@futurelastic/colab-handbook 1.12.0 → 1.13.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +243 -213
- package/README.vi.md +246 -186
- package/audit/audit.mjs +193 -10
- package/package.json +6 -1
- package/templates/README.md +30 -2
- package/templates/ci-laravel.yml +102 -21
- package/templates/ci-node.yml +61 -3
- package/templates/ci-python.yml +52 -3
- package/templates/deploy-adapter-portainer.mjs +206 -0
- package/templates/deploy-container-run.mjs +368 -0
- package/templates/deploy-container.yml +219 -0
- package/templates/dist-refs.yml +6 -0
- package/templates/docs-lint.mjs +1 -1
- package/templates/npx-launcher.mjs +118 -20
- package/templates/npx-service.mjs +828 -0
- package/templates/release-auto.yml +341 -32
- package/tools/colab +1691 -254
- package/tools/lib/adopt.js +373 -14
- package/tools/lib/branch-name.js +29 -1
- package/tools/lib/ci-cure.js +522 -31
- package/tools/lib/ci-grant.js +289 -22
- package/tools/lib/ci-wait.js +203 -0
- package/tools/lib/claim-comments.js +13 -64
- package/tools/lib/claim-identity.js +4 -7
- package/tools/lib/codec/claim.d.ts +41 -0
- package/tools/lib/codec/claim.js +151 -0
- package/tools/lib/codec/decision.d.ts +29 -0
- package/tools/lib/codec/decision.js +81 -0
- package/tools/lib/codec/grants.d.ts +82 -0
- package/tools/lib/codec/grants.js +268 -0
- package/tools/lib/codec/hold.d.ts +26 -0
- package/tools/lib/codec/hold.js +152 -0
- package/tools/lib/codec/index.d.ts +21 -0
- package/tools/lib/codec/index.js +32 -0
- package/tools/lib/codec/labels.d.ts +65 -0
- package/tools/lib/codec/labels.js +716 -0
- package/tools/lib/codec/markers.d.ts +35 -0
- package/tools/lib/codec/markers.js +138 -0
- package/tools/lib/codec/release.d.ts +17 -0
- package/tools/lib/codec/release.js +69 -0
- package/tools/lib/codec/samples.json +762 -0
- package/tools/lib/codeowners.js +68 -4
- package/tools/lib/container-close.js +38 -0
- package/tools/lib/cure-diff.js +198 -9
- package/tools/lib/decision-record.js +15 -39
- package/tools/lib/docs-only.js +15 -1
- package/tools/lib/exposure-shape.js +42 -8
- package/tools/lib/git.js +303 -42
- package/tools/lib/group-labels.js +65 -0
- package/tools/lib/install-check.js +14 -8
- package/tools/lib/install-route.js +139 -0
- package/tools/lib/instruction-file.js +1 -0
- package/tools/lib/labels.js +22 -647
- package/tools/lib/local-adopt.js +8 -4
- package/tools/lib/migration-grant.js +206 -104
- package/tools/lib/place.js +2 -2
- package/tools/lib/release-cut.js +199 -25
- package/tools/lib/release-finalize.js +111 -23
- package/tools/lib/release-policy.js +130 -22
- package/tools/lib/release-runner.js +125 -0
- package/tools/lib/release-tag.js +3 -1
- package/tools/lib/scratch-dirs.js +106 -0
- package/tools/lib/ship-batch.js +36 -1
- package/tools/lib/stamp.js +7 -0
- package/tools/lib/tracker-fake.js +195 -0
- package/tools/lib/tracker-github.js +106 -0
- package/tools/lib/tracker-scenarios.json +206 -0
- package/tools/lib/tracker.js +64 -0
- package/tools/lib/tree-green.js +88 -0
- package/tools/lib/util.js +17 -1
- package/tools/lib/verify-runs.js +104 -0
- package/tools/lib/wake.js +8 -90
- package/tools/lib/workflow-triggers.js +48 -0
|
@@ -0,0 +1,828 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// npx service manager — TEMPLATE. Copy me into your repo NEXT TO your copy of npx-launcher.mjs
|
|
3
|
+
// (e.g. `colab template npx-service.mjs --dest bin/service.mjs` and
|
|
4
|
+
// `colab template npx-launcher.mjs --dest bin/npx-launcher.mjs`) and point your root
|
|
5
|
+
// package.json's `bin` at THIS copy. YOU OWN THE COPY.
|
|
6
|
+
//
|
|
7
|
+
// WHAT IT IS FOR. CONVENTIONS.md §6, *Services over npx* (#465): a tool that runs as a per-machine
|
|
8
|
+
// service (a dashboard, a daemon, a JS app a launch agent serves) installs, updates and rolls back
|
|
9
|
+
// through three verbs, and never runs from npx's cache:
|
|
10
|
+
//
|
|
11
|
+
// npx github:<org>/<repo>#vX.Y.Z init [--channel next|stable] [--health-url URL]
|
|
12
|
+
// [--auto-update <interval> | --no-auto-update]
|
|
13
|
+
// <tool> update [--check] [--version vX.Y.Z] [--channel next|stable]
|
|
14
|
+
// <tool> rollback
|
|
15
|
+
// <tool> status
|
|
16
|
+
// <tool> uninstall [--purge]
|
|
17
|
+
//
|
|
18
|
+
// Anything else on the command line is the tool's own: it runs the CURRENT version's payload.
|
|
19
|
+
//
|
|
20
|
+
// LAYOUT (every path per user, none inside the package npx unpacked):
|
|
21
|
+
//
|
|
22
|
+
// $XDG_DATA_HOME/<tool>/ (default ~/.local/share/<tool>, macOS too — no spaces in a plist)
|
|
23
|
+
// vX.Y.Z/pkg/ the package at that version (an npm prefix: node_modules/<name>/…)
|
|
24
|
+
// vX.Y.Z/<os>-<arch>/<tool> KIND 'binary' only — exactly where npx-launcher.mjs installs it
|
|
25
|
+
// vX.Y.Z/app/ KIND 'dist' only — the prebuilt app, unpacked from its tarball
|
|
26
|
+
// current -> vX.Y.Z the launch agent and the shim go THROUGH this link, so an update
|
|
27
|
+
// previous -> vW.Y.Z or a rollback is one atomic rename, never a rewritten unit
|
|
28
|
+
// $XDG_CONFIG_HOME/<tool>/ (0700) install.json {origin, channel, healthUrl?} + YOUR config
|
|
29
|
+
// and secrets — never in the package, the install dir or the unit
|
|
30
|
+
// $XDG_STATE_HOME/<tool>/ (0700) logs, update.lock, your runtime state
|
|
31
|
+
// ~/.local/bin/<tool> a small sh shim: the verbs above → this file at `current`,
|
|
32
|
+
// anything else → the current payload
|
|
33
|
+
//
|
|
34
|
+
// UPDATE IS A TRANSACTION. The new version is installed side by side FIRST (a failed fetch or
|
|
35
|
+
// build changes nothing), then `current` is pointed at it and the service restarted. If the
|
|
36
|
+
// health check fails, `current` is pointed back, the service restarted again, and the command
|
|
37
|
+
// exits 1 — "switched back". `rollback` is the same switch to `previous`; run it twice to toggle.
|
|
38
|
+
//
|
|
39
|
+
// A CHANNEL IS RESOLVED TO A VERSION, never installed as one. `update` asks the origin (same git,
|
|
40
|
+
// same URL as npx used, so the same credentials) for the channel branch's tip and the release tag
|
|
41
|
+
// on it — `stable` → the highest final, `next` → the highest release tag — and installs exactly
|
|
42
|
+
// that `vX.Y.Z`. A tip with no release tag refuses. `update --version vX.Y.Z` pins: later
|
|
43
|
+
// `update`s report "pinned" until `--channel` is given again.
|
|
44
|
+
//
|
|
45
|
+
// HEALTH. With a health URL (install.json, env <TOOL>_HEALTH_URL, or HEALTH_URL below): poll it
|
|
46
|
+
// until a 2xx body reports the version just switched to. Without one: the service manager must
|
|
47
|
+
// report the service running after a settle period. <TOOL>_HEALTH_TIMEOUT_MS overrides the wait.
|
|
48
|
+
//
|
|
49
|
+
// THREE KINDS. 'binary': a compiled tool; the service runs the binary from the platform's dist ref.
|
|
50
|
+
// 'package': a JS app that runs from its package (built by `prepare` if it needs building).
|
|
51
|
+
// 'dist': a JS app whose build cannot run on the target (#470) — the release ships its output
|
|
52
|
+
// prebuilt as ONE tarball (DIST_FILE) in the platform-neutral dist ref refs/tags/dist/vX.Y.Z/any
|
|
53
|
+
// (templates/dist-refs.yml with `platforms: any`, `bin: <DIST_FILE>`). It is fetched and verified
|
|
54
|
+
// against that ref's SHA256SUMS exactly as the launcher fetches a binary, then unpacked into
|
|
55
|
+
// vX.Y.Z/app/, and the service runs app/ENTRY with node. The package itself is still installed
|
|
56
|
+
// beside it (vX.Y.Z/pkg/) because this manager lives there. Build the tarball with its files at
|
|
57
|
+
// the top level: `tar -czf <DIST_FILE> -C <build-output-dir> .` — an absolute or `..` entry is
|
|
58
|
+
// refused before anything is unpacked.
|
|
59
|
+
//
|
|
60
|
+
// AUTO-UPDATE (#471) is a timer that runs the same `update`, never a second mechanism. Opt in with
|
|
61
|
+
// `init --auto-update 6h` (seconds, or a number with s/m/h/d; at least 60s), opt out with
|
|
62
|
+
// `init --no-auto-update`; AUTO_UPDATE below sets the default for a first init. macOS: a second
|
|
63
|
+
// launchd agent (<label>.update) with StartInterval. Linux: a systemd user <unit>-update.service
|
|
64
|
+
// (oneshot) plus <unit>-update.timer. Its output goes to update.out.log / update.err.log in the
|
|
65
|
+
// state dir. A pinned install's timer runs and changes nothing ("pinned"), as `update` does.
|
|
66
|
+
//
|
|
67
|
+
// UNINSTALL (#472) unloads the timer and the service, deletes their unit files, the shim (only if
|
|
68
|
+
// this template wrote it) and the whole data dir — every installed version. The config and state
|
|
69
|
+
// dirs stay, so a later init picks up the same config; `--purge` deletes them too.
|
|
70
|
+
//
|
|
71
|
+
// SERVICE MANAGERS. macOS: a launchd agent in ~/Library/LaunchAgents (bootstrap, kickstart -k).
|
|
72
|
+
// Linux: a systemd user unit in $XDG_CONFIG_HOME/systemd/user (enable --now, restart). A Linux
|
|
73
|
+
// service that must outlive the login session needs `loginctl enable-linger` — `init` prints it,
|
|
74
|
+
// never runs it. <TOOL>_SERVICE_MANAGER=none skips the manager entirely (a container, a unit you
|
|
75
|
+
// manage yourself). Windows is refused.
|
|
76
|
+
//
|
|
77
|
+
// Node >= 18, zero dependencies; needs `git` (and `npm` for `update`; `tar` for KIND 'dist'). The unit carries only the
|
|
78
|
+
// LOCATIONS of config and state (<TOOL>_CONFIG_DIR, <TOOL>_STATE_DIR) — never a secret value.
|
|
79
|
+
|
|
80
|
+
import { spawnSync } from 'node:child_process';
|
|
81
|
+
import {
|
|
82
|
+
chmodSync, closeSync, cpSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync,
|
|
83
|
+
renameSync, rmSync, symlinkSync, writeFileSync, writeSync, realpathSync,
|
|
84
|
+
} from 'node:fs';
|
|
85
|
+
import { homedir } from 'node:os';
|
|
86
|
+
import { basename, dirname, join, relative, resolve } from 'node:path';
|
|
87
|
+
import { fileURLToPath } from 'node:url';
|
|
88
|
+
// EDIT: the path of YOUR copy of templates/npx-launcher.mjs, relative to this file.
|
|
89
|
+
import * as launcher from './npx-launcher.mjs';
|
|
90
|
+
|
|
91
|
+
// ---- EDIT POINTS ----------------------------------------------------------------------------
|
|
92
|
+
// 'binary': a compiled tool shipped as dist refs (templates/dist-refs.yml); the service runs the
|
|
93
|
+
// binary npx-launcher.mjs installs. 'package': a JS app; the service runs ENTRY with node.
|
|
94
|
+
// 'dist': a prebuilt JS app shipped as ONE tarball in the dist ref `dist/vX.Y.Z/any`; the
|
|
95
|
+
// service runs app/ENTRY with node (THREE KINDS, above).
|
|
96
|
+
const KIND = 'binary';
|
|
97
|
+
// The launchd label / systemd unit name. null = `local.<tool>` (launchd) and `<tool>` (systemd).
|
|
98
|
+
const LABEL = null;
|
|
99
|
+
// Arguments the service is started with (KIND 'binary': the binary's; 'package': ENTRY's).
|
|
100
|
+
const SERVICE_ARGS = ['serve'];
|
|
101
|
+
// KIND 'package': the file node runs, relative to the package root. KIND 'dist': relative to the
|
|
102
|
+
// unpacked tarball's root.
|
|
103
|
+
const ENTRY = 'server.mjs';
|
|
104
|
+
// KIND 'dist': the tarball's name inside the `any` dist ref. null = `<tool>.tgz`.
|
|
105
|
+
const DIST_FILE = null;
|
|
106
|
+
// The auto-update interval a FIRST init uses when no --auto-update/--no-auto-update is given
|
|
107
|
+
// (e.g. '6h'), or null for none. Re-running init keeps whatever the install already records.
|
|
108
|
+
const AUTO_UPDATE = null;
|
|
109
|
+
// A URL reporting the running version (e.g. http://127.0.0.1:8080/version), or null.
|
|
110
|
+
const HEALTH_URL = null;
|
|
111
|
+
// How many versions to keep side by side (current and previous are never pruned).
|
|
112
|
+
const KEEP = 3;
|
|
113
|
+
// The verbs this file owns. They shadow the tool's own subcommands of the same names — rename
|
|
114
|
+
// them here (e.g. 'self-update') if your tool already has an `update`.
|
|
115
|
+
const VERBS = { init: 'init', update: 'update', rollback: 'rollback', status: 'status', uninstall: 'uninstall' };
|
|
116
|
+
// ----------------------------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
119
|
+
const DIST_PLAT = 'any';
|
|
120
|
+
const SHIM_MARK = 'npx-service.mjs, #465';
|
|
121
|
+
|
|
122
|
+
/** Every per-user location, from the environment. Pure. */
|
|
123
|
+
export function paths({ env, home, tool }) {
|
|
124
|
+
const data = env.XDG_DATA_HOME || join(home, '.local', 'share');
|
|
125
|
+
const config = env.XDG_CONFIG_HOME || join(home, '.config');
|
|
126
|
+
const state = env.XDG_STATE_HOME || join(home, '.local', 'state');
|
|
127
|
+
return {
|
|
128
|
+
root: join(data, tool),
|
|
129
|
+
config: join(config, tool),
|
|
130
|
+
state: join(state, tool),
|
|
131
|
+
shim: join(home, '.local', 'bin', tool),
|
|
132
|
+
systemdDir: join(config, 'systemd', 'user'),
|
|
133
|
+
launchAgents: join(home, 'Library', 'LaunchAgents'),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function envPrefix(tool) {
|
|
138
|
+
return tool.toUpperCase().replace(/[^A-Z0-9]/g, '_');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** `<tool> update --check --channel next` → { verb, flags, rest }. Pure. */
|
|
142
|
+
export function parseArgs(argv) {
|
|
143
|
+
const flags = {};
|
|
144
|
+
const rest = [];
|
|
145
|
+
for (let i = 0; i < argv.length; i++) {
|
|
146
|
+
const a = argv[i];
|
|
147
|
+
const m = a.match(/^--(check|purge|no-auto-update|version|channel|health-url|auto-update)(?:=(.*))?$/);
|
|
148
|
+
if (!m) { rest.push(a); continue; }
|
|
149
|
+
const key = m[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
150
|
+
if (['check', 'purge', 'noAutoUpdate'].includes(key)) { flags[key] = true; continue; }
|
|
151
|
+
const v = m[2] !== undefined ? m[2] : argv[++i];
|
|
152
|
+
if (v === undefined) return { error: `--${m[1]} needs a value` };
|
|
153
|
+
flags[key] = v;
|
|
154
|
+
}
|
|
155
|
+
return { flags, rest };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** `6h` / `30m` / `1d` / `900s` / `900` → seconds; anything else, or under 60s, → null. Pure. */
|
|
159
|
+
export function parseInterval(s) {
|
|
160
|
+
const m = String(s ?? '').trim().match(/^(\d+)\s*([smhd]?)$/i);
|
|
161
|
+
if (!m) return null;
|
|
162
|
+
const n = Number(m[1]) * { '': 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2].toLowerCase()];
|
|
163
|
+
return n >= 60 ? n : null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Seconds → the shortest exact `Nd` / `Nh` / `Nm` / `Ns`. Pure. */
|
|
167
|
+
export function formatInterval(sec) {
|
|
168
|
+
for (const [u, n] of [['d', 86400], ['h', 3600], ['m', 60]]) if (sec % n === 0) return `${sec / n}${u}`;
|
|
169
|
+
return `${sec}s`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** A git URL npm will install from. */
|
|
173
|
+
export function npmSpec(origin, version) {
|
|
174
|
+
let o = origin;
|
|
175
|
+
if (o.startsWith('/')) o = `git+file://${o}`;
|
|
176
|
+
else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(o) && !o.startsWith('git+')) o = `git+${o}`;
|
|
177
|
+
return `${o}#${version}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Same rule as templates/deploy-container-run.mjs: the version as a whole token, `v` optional. */
|
|
181
|
+
export function reportsVersion(body, version) {
|
|
182
|
+
const v = String(version).replace(/^v/, '').replace(/\./g, '\\.');
|
|
183
|
+
return new RegExp(`(?<![0-9.])v?${v}(?![0-9]|\\.[0-9])`).test(String(body || ''));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function shq(s) {
|
|
187
|
+
return `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function xml(s) {
|
|
191
|
+
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** What the service runs — always through `current`, never through npx's cache. Pure. */
|
|
195
|
+
export function unitSpec({ kind = KIND, tool, name, root, state, config, execPath, plat, envPath, label = LABEL, args = SERVICE_ARGS, entry = ENTRY }) {
|
|
196
|
+
const cur = join(root, 'current');
|
|
197
|
+
const programArgs = kind === 'binary'
|
|
198
|
+
? [join(cur, plat, tool), ...args]
|
|
199
|
+
: kind === 'dist'
|
|
200
|
+
? [execPath, join(cur, 'app', entry), ...args]
|
|
201
|
+
: [execPath, join(cur, 'pkg', 'node_modules', name, entry), ...args];
|
|
202
|
+
const P = envPrefix(tool);
|
|
203
|
+
return {
|
|
204
|
+
label: label || `local.${tool}`,
|
|
205
|
+
unitName: `${label || tool}.service`,
|
|
206
|
+
programArgs,
|
|
207
|
+
env: { [`${P}_CONFIG_DIR`]: config, [`${P}_STATE_DIR`]: state, PATH: envPath },
|
|
208
|
+
logOut: join(state, `${tool}.out.log`),
|
|
209
|
+
logErr: join(state, `${tool}.err.log`),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function renderLaunchd(spec) {
|
|
214
|
+
const args = spec.programArgs.map((a) => ` <string>${xml(a)}</string>`).join('\n');
|
|
215
|
+
const env = Object.entries(spec.env).filter(([, v]) => v).map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`).join('\n');
|
|
216
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
217
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
218
|
+
<plist version="1.0">
|
|
219
|
+
<dict>
|
|
220
|
+
<key>Label</key>
|
|
221
|
+
<string>${xml(spec.label)}</string>
|
|
222
|
+
<key>ProgramArguments</key>
|
|
223
|
+
<array>
|
|
224
|
+
${args}
|
|
225
|
+
</array>
|
|
226
|
+
<key>EnvironmentVariables</key>
|
|
227
|
+
<dict>
|
|
228
|
+
${env}
|
|
229
|
+
</dict>
|
|
230
|
+
${spec.startInterval ? ` <key>StartInterval</key>
|
|
231
|
+
<integer>${Number(spec.startInterval)}</integer>
|
|
232
|
+
<key>RunAtLoad</key>
|
|
233
|
+
<false/>` : ` <key>RunAtLoad</key>
|
|
234
|
+
<true/>
|
|
235
|
+
<key>KeepAlive</key>
|
|
236
|
+
<true/>`}
|
|
237
|
+
<key>StandardOutPath</key>
|
|
238
|
+
<string>${xml(spec.logOut)}</string>
|
|
239
|
+
<key>StandardErrorPath</key>
|
|
240
|
+
<string>${xml(spec.logErr)}</string>
|
|
241
|
+
</dict>
|
|
242
|
+
</plist>
|
|
243
|
+
`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function renderSystemd(spec) {
|
|
247
|
+
const q = (a) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(a) ? a : `"${String(a).replace(/(["\\])/g, '\\$1')}"`);
|
|
248
|
+
const env = Object.entries(spec.env).filter(([, v]) => v).map(([k, v]) => `Environment=${q(`${k}=${v}`)}`).join('\n');
|
|
249
|
+
return `[Unit]
|
|
250
|
+
Description=${spec.label}
|
|
251
|
+
|
|
252
|
+
[Service]
|
|
253
|
+
ExecStart=${spec.programArgs.map(q).join(' ')}
|
|
254
|
+
${env}
|
|
255
|
+
Restart=on-failure
|
|
256
|
+
StandardOutput=append:${spec.logOut}
|
|
257
|
+
StandardError=append:${spec.logErr}
|
|
258
|
+
|
|
259
|
+
[Install]
|
|
260
|
+
WantedBy=default.target
|
|
261
|
+
`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** The auto-update timer's oneshot service: runs `update` once, then exits. Pure. */
|
|
265
|
+
export function renderSystemdOneshot(spec) {
|
|
266
|
+
return renderSystemd(spec)
|
|
267
|
+
.replace(/^Restart=on-failure\n/m, '')
|
|
268
|
+
.replace(/^\[Service\]$/m, '[Service]\nType=oneshot')
|
|
269
|
+
.replace(/\n\[Install\]\nWantedBy=default\.target\n$/, '\n');
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function renderSystemdTimer(spec) {
|
|
273
|
+
return `[Unit]
|
|
274
|
+
Description=${spec.label} (timer)
|
|
275
|
+
|
|
276
|
+
[Timer]
|
|
277
|
+
OnBootSec=${spec.startInterval}s
|
|
278
|
+
OnUnitActiveSec=${spec.startInterval}s
|
|
279
|
+
Unit=${spec.unitName}
|
|
280
|
+
|
|
281
|
+
[Install]
|
|
282
|
+
WantedBy=timers.target
|
|
283
|
+
`;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The auto-update timer's spec: `<this manager at current> update`, every `interval` seconds,
|
|
288
|
+
* with the same XDG bases the install was made under (a launchd/systemd job does not inherit the
|
|
289
|
+
* shell's), so the update it runs finds the same install. Pure.
|
|
290
|
+
*/
|
|
291
|
+
export function timerSpec({ spec, tool, name, p, execPath, serviceRel, interval, verbs = VERBS }) {
|
|
292
|
+
const base = spec.unitName.replace(/\.service$/, '');
|
|
293
|
+
return {
|
|
294
|
+
label: `${spec.label}.update`,
|
|
295
|
+
unitName: `${base}-update.service`,
|
|
296
|
+
timerName: `${base}-update.timer`,
|
|
297
|
+
startInterval: interval,
|
|
298
|
+
programArgs: [execPath, join(p.root, 'current', 'pkg', 'node_modules', name, serviceRel), verbs.update],
|
|
299
|
+
env: {
|
|
300
|
+
...spec.env,
|
|
301
|
+
XDG_DATA_HOME: dirname(p.root), XDG_CONFIG_HOME: dirname(p.config), XDG_STATE_HOME: dirname(p.state),
|
|
302
|
+
},
|
|
303
|
+
logOut: join(p.state, 'update.out.log'),
|
|
304
|
+
logErr: join(p.state, 'update.err.log'),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The timer's unit files and the manager's argv to load / unload it. Pure. */
|
|
309
|
+
export function timerCommands(platform, { uid, tspec, p }) {
|
|
310
|
+
if (platform === 'darwin') {
|
|
311
|
+
const unitPath = join(p.launchAgents, `${tspec.label}.plist`);
|
|
312
|
+
const target = `gui/${uid}/${tspec.label}`;
|
|
313
|
+
return {
|
|
314
|
+
files: [[unitPath, renderLaunchd(tspec)]],
|
|
315
|
+
load: [['launchctl', 'bootout', target, '?'], ['launchctl', 'bootstrap', `gui/${uid}`, unitPath]],
|
|
316
|
+
unload: [['launchctl', 'bootout', target, '?']],
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
files: [[join(p.systemdDir, tspec.unitName), renderSystemdOneshot(tspec)], [join(p.systemdDir, tspec.timerName), renderSystemdTimer(tspec)]],
|
|
321
|
+
load: [['systemctl', '--user', 'daemon-reload'], ['systemctl', '--user', 'enable', '--now', tspec.timerName]],
|
|
322
|
+
unload: [['systemctl', '--user', 'disable', '--now', tspec.timerName, '?']],
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The unit file's path and the manager's argv for each step. Pure. */
|
|
327
|
+
export function managerCommands(platform, { uid, spec, p }) {
|
|
328
|
+
if (platform === 'darwin') {
|
|
329
|
+
const unitPath = join(p.launchAgents, `${spec.label}.plist`);
|
|
330
|
+
const target = `gui/${uid}/${spec.label}`;
|
|
331
|
+
return {
|
|
332
|
+
unitPath,
|
|
333
|
+
render: renderLaunchd,
|
|
334
|
+
load: [['launchctl', 'bootout', target, '?'], ['launchctl', 'bootstrap', `gui/${uid}`, unitPath]],
|
|
335
|
+
unload: [['launchctl', 'bootout', target, '?']],
|
|
336
|
+
forget: [],
|
|
337
|
+
restart: [['launchctl', 'kickstart', '-k', target]],
|
|
338
|
+
status: ['launchctl', 'print', target],
|
|
339
|
+
running: (r) => r.status === 0 && /\bstate = running\b/.test(r.stdout || ''),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
const unitPath = join(p.systemdDir, spec.unitName);
|
|
343
|
+
return {
|
|
344
|
+
unitPath,
|
|
345
|
+
render: renderSystemd,
|
|
346
|
+
load: [['systemctl', '--user', 'daemon-reload'], ['systemctl', '--user', 'enable', '--now', spec.unitName]],
|
|
347
|
+
unload: [['systemctl', '--user', 'disable', '--now', spec.unitName, '?']],
|
|
348
|
+
forget: [['systemctl', '--user', 'daemon-reload', '?']],
|
|
349
|
+
restart: [['systemctl', '--user', 'restart', spec.unitName]],
|
|
350
|
+
status: ['systemctl', '--user', 'is-active', spec.unitName],
|
|
351
|
+
running: (r) => r.status === 0,
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** The ~/.local/bin shim: verbs → this manager at `current`; anything else → the payload. Pure. */
|
|
356
|
+
export function renderShim({ kind = KIND, root, tool, name, plat, execPath, entry = ENTRY, verbs = VERBS, serviceRel }) {
|
|
357
|
+
const cur = `"$ROOT/current"`;
|
|
358
|
+
const manager = `${cur}/pkg/node_modules/${name}/${serviceRel}`;
|
|
359
|
+
const payload = kind === 'binary'
|
|
360
|
+
? `exec ${cur}/${plat}/${tool} "$@"`
|
|
361
|
+
: kind === 'dist'
|
|
362
|
+
? `exec ${shq(execPath)} ${cur}/app/${entry} "$@"`
|
|
363
|
+
: `exec ${shq(execPath)} ${cur}/pkg/node_modules/${name}/${entry} "$@"`;
|
|
364
|
+
return `#!/bin/sh
|
|
365
|
+
# Written by \`${tool} ${verbs.init}\` (${SHIM_MARK}). Re-run init to rewrite it.
|
|
366
|
+
ROOT=${shq(root)}
|
|
367
|
+
case "\${1:-}" in
|
|
368
|
+
${Object.values(verbs).join('|')}) exec ${shq(execPath)} ${manager} "$@" ;;
|
|
369
|
+
esac
|
|
370
|
+
${payload}
|
|
371
|
+
`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// ---- filesystem -------------------------------------------------------------------------------
|
|
375
|
+
|
|
376
|
+
function readJson(p) {
|
|
377
|
+
try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export function readInstall(p) {
|
|
381
|
+
return readJson(join(p.config, 'install.json'));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function writeInstall(p, rec) {
|
|
385
|
+
mkdirSync(p.config, { recursive: true, mode: 0o700 });
|
|
386
|
+
const f = join(p.config, 'install.json');
|
|
387
|
+
writeFileSync(`${f}.tmp`, `${JSON.stringify(rec, null, 2)}\n`, { mode: 0o600 });
|
|
388
|
+
renameSync(`${f}.tmp`, f);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export function readLink(root, name) {
|
|
392
|
+
try { return basename(readlinkSync(join(root, name))); } catch { return null; }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Point `root/name` at `version`, atomically (symlink beside it, then rename over it). */
|
|
396
|
+
export function pointTo(root, name, version) {
|
|
397
|
+
const tmp = join(root, `.${name}.${process.pid}`);
|
|
398
|
+
rmSync(tmp, { force: true });
|
|
399
|
+
symlinkSync(version, tmp);
|
|
400
|
+
renameSync(tmp, join(root, name));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function installedVersions(root) {
|
|
404
|
+
let names = [];
|
|
405
|
+
try { names = readdirSync(root); } catch { return []; }
|
|
406
|
+
return names.filter((n) => launcher.VERSION_RE.test(n)).sort(launcher.compareVersions);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Remove all but `keep` newest versions, never `current` or `previous`. Returns what went. */
|
|
410
|
+
export function prune(root, keep = KEEP) {
|
|
411
|
+
const all = installedVersions(root);
|
|
412
|
+
const pinned = new Set([readLink(root, 'current'), readLink(root, 'previous')]);
|
|
413
|
+
const newest = new Set(all.slice(-keep));
|
|
414
|
+
const gone = all.filter((v) => !pinned.has(v) && !newest.has(v));
|
|
415
|
+
for (const v of gone) rmSync(join(root, v), { recursive: true, force: true });
|
|
416
|
+
return gone;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** One update at a time per user: an O_EXCL lock file holding the pid; a dead holder is stale. */
|
|
420
|
+
export function withLock(stateDir, fn) {
|
|
421
|
+
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
422
|
+
const lock = join(stateDir, 'update.lock');
|
|
423
|
+
let fd;
|
|
424
|
+
try { fd = openSync(lock, 'wx'); } catch {
|
|
425
|
+
const pid = Number(String(readFileSync(lock, 'utf8')).trim());
|
|
426
|
+
let alive = false;
|
|
427
|
+
try { process.kill(pid, 0); alive = true; } catch (e) { alive = e.code === 'EPERM'; }
|
|
428
|
+
if (alive) throw new Error(`another update is running (pid ${pid}; ${lock})`);
|
|
429
|
+
rmSync(lock, { force: true });
|
|
430
|
+
fd = openSync(lock, 'wx');
|
|
431
|
+
}
|
|
432
|
+
writeSync(fd, `${process.pid}\n`);
|
|
433
|
+
closeSync(fd);
|
|
434
|
+
const done = () => rmSync(lock, { force: true });
|
|
435
|
+
let out;
|
|
436
|
+
try { out = fn(); } catch (e) { done(); throw e; }
|
|
437
|
+
if (out && typeof out.then === 'function') return out.finally(done);
|
|
438
|
+
done();
|
|
439
|
+
return out;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// ---- the transaction --------------------------------------------------------------------------
|
|
443
|
+
|
|
444
|
+
function ctl(io, steps) {
|
|
445
|
+
for (const s of steps) {
|
|
446
|
+
const tolerant = s[s.length - 1] === '?';
|
|
447
|
+
const argv = tolerant ? s.slice(0, -1) : s;
|
|
448
|
+
const r = io.run(argv[0], argv.slice(1));
|
|
449
|
+
if (r.status !== 0 && !tolerant) throw new Error(`${argv.join(' ')} failed: ${(r.stderr || r.stdout || '').trim()}`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Is `version` the one serving? Health URL if there is one, else the manager's own answer. */
|
|
454
|
+
export async function healthy({ version, url, mgr, io }) {
|
|
455
|
+
const until = io.now() + io.timing.timeoutMs;
|
|
456
|
+
if (!url) {
|
|
457
|
+
if (!mgr) return true; // no manager, no URL: nothing to ask
|
|
458
|
+
await io.sleep(io.timing.settleMs);
|
|
459
|
+
return mgr.running(io.run(mgr.status[0], mgr.status.slice(1)));
|
|
460
|
+
}
|
|
461
|
+
for (;;) {
|
|
462
|
+
try {
|
|
463
|
+
const res = await io.fetch(url);
|
|
464
|
+
const body = await res.text();
|
|
465
|
+
if (res.ok && reportsVersion(body, version)) return true;
|
|
466
|
+
} catch { /* not up yet */ }
|
|
467
|
+
if (io.now() >= until) return false;
|
|
468
|
+
await io.sleep(io.timing.pollMs);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Point `current` at `to`, restart, check; on failure point back, restart, report. */
|
|
473
|
+
export async function switchTo({ to, root, mgr, url, io }) {
|
|
474
|
+
const from = readLink(root, 'current');
|
|
475
|
+
pointTo(root, 'current', to);
|
|
476
|
+
if (mgr) ctl(io, mgr.restart);
|
|
477
|
+
if (await healthy({ version: to, url, mgr, io })) {
|
|
478
|
+
if (from && from !== to) pointTo(root, 'previous', from);
|
|
479
|
+
return { ok: true, from, to };
|
|
480
|
+
}
|
|
481
|
+
if (!from || from === to) return { ok: false, from, to, back: false };
|
|
482
|
+
pointTo(root, 'current', from);
|
|
483
|
+
if (mgr) ctl(io, mgr.restart);
|
|
484
|
+
const backHealthy = await healthy({ version: from, url, mgr, io });
|
|
485
|
+
return { ok: false, from, to, back: true, backHealthy };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Is `root/version` a complete install for this kind? */
|
|
489
|
+
function complete({ root, version, kind, name, tool, plat, entry = ENTRY }) {
|
|
490
|
+
const v = join(root, version);
|
|
491
|
+
if (!existsSync(join(v, 'pkg', 'node_modules', name, 'package.json'))) return false;
|
|
492
|
+
if (kind === 'dist') return existsSync(join(v, 'app', entry));
|
|
493
|
+
return kind !== 'binary' || existsSync(join(v, plat, tool));
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** A tarball listing → the first entry that would land outside its target dir, or null. Pure. */
|
|
497
|
+
export function unsafeEntry(listing) {
|
|
498
|
+
for (const e of String(listing || '').split('\n').map((l) => l.trim()).filter(Boolean)) {
|
|
499
|
+
if (e.startsWith('/') || e.split('/').includes('..')) return e;
|
|
500
|
+
}
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** KIND 'dist': fetch + verify the tarball from `dist/<version>/any`, unpack it into `dir`. */
|
|
505
|
+
export function installDist({ origin, version, dir, file, entry = ENTRY, io }) {
|
|
506
|
+
const tgz = launcher.fetchDistFile({ origin, version, plat: DIST_PLAT, file, dest: join(dirname(dir), `.${file}`), mode: 0o644 });
|
|
507
|
+
try {
|
|
508
|
+
const ls = io.run('tar', ['-tzf', tgz]);
|
|
509
|
+
if (ls.status !== 0) throw new Error(`${file} in dist/${version}/${DIST_PLAT} is not a gzip tarball: ${(ls.stderr || '').trim()}`);
|
|
510
|
+
const bad = unsafeEntry(ls.stdout);
|
|
511
|
+
if (bad) throw new Error(`${file} in dist/${version}/${DIST_PLAT} has an entry outside its root (${bad}) — refusing to unpack it`);
|
|
512
|
+
mkdirSync(dir, { recursive: true });
|
|
513
|
+
const x = io.run('tar', ['-xzf', tgz, '-C', dir]);
|
|
514
|
+
if (x.status !== 0) throw new Error(`could not unpack ${file}: ${(x.stderr || '').trim()}`);
|
|
515
|
+
} finally { rmSync(tgz, { force: true }); }
|
|
516
|
+
if (!existsSync(join(dir, entry))) throw new Error(`${version}: ${file} has no ${entry} at its top level`);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Install `version` side by side, into a temp dir renamed into place — a failure leaves nothing
|
|
521
|
+
* behind. `fromPkg` (init) copies the package npx already unpacked; otherwise npm fetches it.
|
|
522
|
+
*/
|
|
523
|
+
export function installVersion({ kind = KIND, version, origin, root, name, tool, plat, fromPkg, entry = ENTRY, distFile, io }) {
|
|
524
|
+
if (complete({ root, version, kind, name, tool, plat, entry })) return join(root, version);
|
|
525
|
+
mkdirSync(root, { recursive: true });
|
|
526
|
+
const tmp = join(root, `.install-${version}-${process.pid}`);
|
|
527
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
528
|
+
try {
|
|
529
|
+
const pkg = join(tmp, 'pkg');
|
|
530
|
+
if (fromPkg) {
|
|
531
|
+
cpSync(fromPkg, pkg, { recursive: true, dereference: false });
|
|
532
|
+
} else {
|
|
533
|
+
mkdirSync(pkg, { recursive: true });
|
|
534
|
+
const r = io.run('npm', ['install', '--prefix', pkg, '--omit=dev', '--no-audit', '--no-fund', npmSpec(origin, version)]);
|
|
535
|
+
if (r.status !== 0) throw new Error(`npm could not install ${version}: ${(r.stderr || r.stdout || '').trim()}`);
|
|
536
|
+
}
|
|
537
|
+
if (!existsSync(join(pkg, 'node_modules', name, 'package.json'))) throw new Error(`${version}: the package did not land at node_modules/${name}`);
|
|
538
|
+
if (kind === 'binary') {
|
|
539
|
+
launcher.install({ origin, version, plat, exe: tool, dir: join(tmp, plat) });
|
|
540
|
+
}
|
|
541
|
+
if (kind === 'dist') {
|
|
542
|
+
installDist({ origin, version, dir: join(tmp, 'app'), file: distFile || `${tool}.tgz`, entry, io });
|
|
543
|
+
}
|
|
544
|
+
rmSync(join(root, version), { recursive: true, force: true });
|
|
545
|
+
renameSync(tmp, join(root, version));
|
|
546
|
+
return join(root, version);
|
|
547
|
+
} catch (e) {
|
|
548
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
549
|
+
throw e;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function context(opts, io) {
|
|
554
|
+
const tool = opts.tool;
|
|
555
|
+
const p = paths({ env: io.env, home: io.home, tool });
|
|
556
|
+
const P = envPrefix(tool);
|
|
557
|
+
const plat = launcher.platformKey();
|
|
558
|
+
const spec = unitSpec({
|
|
559
|
+
kind: opts.kind, tool, name: opts.name, root: p.root, state: p.state, config: p.config,
|
|
560
|
+
execPath: io.execPath, plat, envPath: io.env.PATH, label: opts.label, args: opts.args, entry: opts.entry,
|
|
561
|
+
});
|
|
562
|
+
const managed = io.env[`${P}_SERVICE_MANAGER`] !== 'none';
|
|
563
|
+
const mgr = managed ? managerCommands(io.platform, { uid: io.uid, spec, p }) : null;
|
|
564
|
+
// The timer's unit files are known whatever the interval (uninstall and opt-out remove them).
|
|
565
|
+
const tspec = timerSpec({ spec, tool, name: opts.name, p, execPath: io.execPath, serviceRel: opts.serviceRel || 'service.mjs', interval: 0 });
|
|
566
|
+
const timer = managed ? timerCommands(io.platform, { uid: io.uid, tspec, p }) : null;
|
|
567
|
+
return { tool, p, P, plat, spec, mgr, timer, tspec };
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function healthUrl(rec, P, io, flags = {}) {
|
|
571
|
+
return flags.healthUrl || io.env[`${P}_HEALTH_URL`] || (rec && rec.healthUrl) || HEALTH_URL;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function readText(f) {
|
|
575
|
+
try { return readFileSync(f, 'utf8'); } catch { return null; }
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function writeUnit(c, io, rec) {
|
|
579
|
+
if (!c.mgr) return false;
|
|
580
|
+
const text = c.mgr.render(c.spec);
|
|
581
|
+
if (readText(c.mgr.unitPath) !== text) {
|
|
582
|
+
mkdirSync(dirname(c.mgr.unitPath), { recursive: true });
|
|
583
|
+
writeFileSync(c.mgr.unitPath, text);
|
|
584
|
+
ctl(io, c.mgr.load);
|
|
585
|
+
}
|
|
586
|
+
writeTimer(c, io, rec && rec.autoUpdate);
|
|
587
|
+
return true;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** Write (and load) the auto-update timer for `interval` seconds — or remove it when falsy. */
|
|
591
|
+
function writeTimer(c, io, interval) {
|
|
592
|
+
if (!c.timer) return;
|
|
593
|
+
if (!interval) { removeTimer(c, io); return; }
|
|
594
|
+
const t = timerCommands(io.platform, { uid: io.uid, tspec: { ...c.tspec, startInterval: interval }, p: c.p });
|
|
595
|
+
if (t.files.every(([f, text]) => readText(f) === text)) return;
|
|
596
|
+
for (const [f, text] of t.files) { mkdirSync(dirname(f), { recursive: true }); writeFileSync(f, text); }
|
|
597
|
+
ctl(io, t.load);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Unload the timer and delete its unit files, if any are there. Returns the files removed. */
|
|
601
|
+
function removeTimer(c, io) {
|
|
602
|
+
if (!c.timer) return [];
|
|
603
|
+
const present = c.timer.files.map(([f]) => f).filter((f) => existsSync(f));
|
|
604
|
+
if (!present.length) return [];
|
|
605
|
+
ctl(io, c.timer.unload);
|
|
606
|
+
for (const f of present) rmSync(f, { force: true });
|
|
607
|
+
ctl(io, c.mgr.forget);
|
|
608
|
+
return present;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* One verb. opts: { tool, name, kind, pkgDir, serviceRel, label, args, entry, distFile }. Returns an exit code.
|
|
613
|
+
* Every refusal happens before anything is written.
|
|
614
|
+
*/
|
|
615
|
+
export async function run(verb, argv, opts, io) {
|
|
616
|
+
try {
|
|
617
|
+
return await runVerb(verb, argv, opts, io);
|
|
618
|
+
} catch (e) {
|
|
619
|
+
io.err(e.message);
|
|
620
|
+
return 1;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
async function runVerb(verb, argv, opts, io) {
|
|
625
|
+
if (io.platform === 'win32') { io.err('services are not supported on Windows by this template'); return 1; }
|
|
626
|
+
const a = parseArgs(argv);
|
|
627
|
+
if (a.error) { io.err(a.error); return 1; }
|
|
628
|
+
const { flags } = a;
|
|
629
|
+
if (flags.channel && !launcher.CHANNELS.includes(flags.channel)) { io.err(`--channel must be one of ${launcher.CHANNELS.join(', ')}`); return 1; }
|
|
630
|
+
if (flags.version && !launcher.VERSION_RE.test(flags.version)) { io.err(`--version must be vX.Y.Z or vX.Y.Z-rc.N (got ${flags.version})`); return 1; }
|
|
631
|
+
if (flags.autoUpdate !== undefined && !parseInterval(flags.autoUpdate)) { io.err(`--auto-update must be seconds, or a number with s/m/h/d, at least 60s (got ${flags.autoUpdate})`); return 1; }
|
|
632
|
+
if (flags.autoUpdate !== undefined && flags.noAutoUpdate) { io.err('--auto-update and --no-auto-update contradict each other'); return 1; }
|
|
633
|
+
const kind = opts.kind || KIND;
|
|
634
|
+
const c = context({ ...opts, kind }, io);
|
|
635
|
+
const rec = readInstall(c.p);
|
|
636
|
+
const inst = { kind, name: opts.name, tool: c.tool, plat: c.plat, entry: opts.entry, distFile: opts.distFile, io };
|
|
637
|
+
|
|
638
|
+
if (verb === VERBS.status) {
|
|
639
|
+
if (!rec) { io.err(`not installed — run \`npx <origin>#vX.Y.Z ${VERBS.init}\``); return 1; }
|
|
640
|
+
io.out([
|
|
641
|
+
`current: ${readLink(c.p.root, 'current') || '—'}`,
|
|
642
|
+
`previous: ${readLink(c.p.root, 'previous') || '—'}`,
|
|
643
|
+
`channel: ${rec.channel}`,
|
|
644
|
+
`origin: ${rec.origin}`,
|
|
645
|
+
`versions: ${installedVersions(c.p.root).join(' ') || '—'}`,
|
|
646
|
+
`unit: ${c.mgr ? c.mgr.unitPath : '(no service manager)'}`,
|
|
647
|
+
`auto-update: ${rec.autoUpdate ? `every ${formatInterval(rec.autoUpdate)}` : 'off'}`,
|
|
648
|
+
`node: ${io.execPath}`,
|
|
649
|
+
].join('\n'));
|
|
650
|
+
return 0;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
if (verb === VERBS.uninstall) return uninstall(c, flags, io);
|
|
654
|
+
|
|
655
|
+
if (verb === VERBS.init) {
|
|
656
|
+
const pkg = readJson(join(opts.pkgDir, 'package.json')) || {};
|
|
657
|
+
const t = launcher.resolveTarget({ env: io.env, pkgDir: opts.pkgDir, pkg });
|
|
658
|
+
if (t.error) { io.err(t.error); return 1; }
|
|
659
|
+
if (!t.version) {
|
|
660
|
+
const ch = launcher.resolveChannel({ origin: t.origin, channel: t.channel, at: t.sha, run: io.git });
|
|
661
|
+
if (ch.error) { io.err(ch.error); return 1; }
|
|
662
|
+
t.version = ch.version;
|
|
663
|
+
}
|
|
664
|
+
const npxRoot = launcher.installerRoot(opts.pkgDir, opts.name);
|
|
665
|
+
if (!npxRoot) { io.err(`run init through npx: \`npx <origin>#${t.version} ${VERBS.init}\` (no installing project above ${opts.pkgDir})`); return 1; }
|
|
666
|
+
return withLock(c.p.state, async () => {
|
|
667
|
+
installVersion({ ...inst, version: t.version, origin: t.origin, root: c.p.root, fromPkg: npxRoot });
|
|
668
|
+
const record = rec || { origin: t.origin, channel: flags.channel || t.channel || 'stable' };
|
|
669
|
+
if (flags.channel) record.channel = flags.channel;
|
|
670
|
+
if (flags.healthUrl) record.healthUrl = flags.healthUrl;
|
|
671
|
+
if (!rec && AUTO_UPDATE && parseInterval(AUTO_UPDATE)) record.autoUpdate = parseInterval(AUTO_UPDATE);
|
|
672
|
+
if (flags.autoUpdate !== undefined) record.autoUpdate = parseInterval(flags.autoUpdate);
|
|
673
|
+
if (flags.noAutoUpdate) delete record.autoUpdate;
|
|
674
|
+
writeInstall(c.p, record);
|
|
675
|
+
mkdirSync(c.p.state, { recursive: true, mode: 0o700 });
|
|
676
|
+
mkdirSync(dirname(c.p.shim), { recursive: true });
|
|
677
|
+
writeFileSync(c.p.shim, renderShim({ kind, root: c.p.root, tool: c.tool, name: opts.name, plat: c.plat, execPath: io.execPath, entry: opts.entry, serviceRel: opts.serviceRel }), { mode: 0o755 });
|
|
678
|
+
chmodSync(c.p.shim, 0o755);
|
|
679
|
+
const first = !readLink(c.p.root, 'current');
|
|
680
|
+
if (first) pointTo(c.p.root, 'current', t.version); // the unit must find something at load
|
|
681
|
+
writeUnit(c, io, record);
|
|
682
|
+
const s = first
|
|
683
|
+
? { ok: await healthy({ version: t.version, url: healthUrl(record, c.P, io), mgr: c.mgr, io }), to: t.version }
|
|
684
|
+
: await switchTo({ to: t.version, root: c.p.root, mgr: c.mgr, url: healthUrl(record, c.P, io), io });
|
|
685
|
+
if (!s.ok) {
|
|
686
|
+
if (first && c.mgr) { removeTimer(c, io); ctl(io, c.mgr.unload); }
|
|
687
|
+
io.err(first ? `${t.version} installed but not healthy — service unloaded; see ${c.p.state}` : `${t.version} not healthy — switched back to ${s.from}`);
|
|
688
|
+
return 1;
|
|
689
|
+
}
|
|
690
|
+
io.out(`${c.tool} ${t.version} installed and running (channel ${record.channel}); shim ${c.p.shim}`);
|
|
691
|
+
if (record.autoUpdate) io.out(c.timer ? `auto-update: \`${VERBS.update}\` every ${formatInterval(record.autoUpdate)}; log ${c.tspec.logOut}` : 'auto-update recorded, but no service manager is in use — no timer written');
|
|
692
|
+
if (io.platform === 'linux' && c.mgr) io.out(`to keep it running after logout: loginctl enable-linger ${io.env.USER || '$USER'}`);
|
|
693
|
+
return 0;
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
if (verb !== VERBS.update && verb !== VERBS.rollback) { io.err(`unknown verb ${verb}`); return 1; }
|
|
698
|
+
if (!rec) { io.err(`not installed — run \`npx <origin>#vX.Y.Z ${VERBS.init}\` first`); return 1; }
|
|
699
|
+
const cur = readLink(c.p.root, 'current');
|
|
700
|
+
const url = healthUrl(rec, c.P, io);
|
|
701
|
+
|
|
702
|
+
if (verb === VERBS.rollback) {
|
|
703
|
+
const prev = readLink(c.p.root, 'previous');
|
|
704
|
+
if (!prev || !existsSync(join(c.p.root, prev))) { io.err('nothing to roll back to — no previous version'); return 1; }
|
|
705
|
+
return withLock(c.p.state, async () => {
|
|
706
|
+
const s = await switchTo({ to: prev, root: c.p.root, mgr: c.mgr, url, io });
|
|
707
|
+
if (!s.ok) { io.err(`${prev} not healthy — switched back to ${s.from}`); return 1; }
|
|
708
|
+
io.out(`rolled back: ${s.from} -> ${prev}`);
|
|
709
|
+
return 0;
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// update
|
|
714
|
+
let target;
|
|
715
|
+
let channel = rec.channel;
|
|
716
|
+
if (flags.version) { target = flags.version; channel = 'pinned'; } else {
|
|
717
|
+
if (flags.channel) channel = flags.channel;
|
|
718
|
+
if (channel === 'pinned') { io.out(`pinned at ${cur} — \`${VERBS.update} --channel stable|next\` to follow a channel again`); return 0; }
|
|
719
|
+
const r = launcher.resolveChannel({ origin: rec.origin, channel, run: io.git });
|
|
720
|
+
if (r.error) { io.err(r.error); return 1; }
|
|
721
|
+
target = r.version;
|
|
722
|
+
}
|
|
723
|
+
if (flags.check) {
|
|
724
|
+
io.out(target === cur ? `up to date: ${cur}` : `update available: ${cur} -> ${target} (${channel})`);
|
|
725
|
+
return 0;
|
|
726
|
+
}
|
|
727
|
+
return withLock(c.p.state, async () => {
|
|
728
|
+
if (channel !== rec.channel) writeInstall(c.p, { ...rec, channel });
|
|
729
|
+
if (target === cur) { io.out(`up to date: ${cur}`); return 0; }
|
|
730
|
+
try {
|
|
731
|
+
installVersion({ ...inst, version: target, origin: rec.origin, root: c.p.root });
|
|
732
|
+
} catch (e) { io.err(`${e.message}\nnothing switched — still on ${cur}`); return 1; }
|
|
733
|
+
writeUnit(c, io, rec);
|
|
734
|
+
const s = await switchTo({ to: target, root: c.p.root, mgr: c.mgr, url, io });
|
|
735
|
+
if (!s.ok) { io.err(`${target} not healthy — switched back to ${s.from}${s.backHealthy ? '' : ' (which is not reporting healthy either)'}`); return 1; }
|
|
736
|
+
const gone = prune(c.p.root);
|
|
737
|
+
io.out(`updated: ${s.from} -> ${target} (${channel})${gone.length ? `; pruned ${gone.join(' ')}` : ''}`);
|
|
738
|
+
return 0;
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* Unload and delete the timer and the service unit, the shim (only one this template wrote) and
|
|
744
|
+
* the data dir. Config and state stay unless `--purge`. Safe to re-run: what is gone is skipped.
|
|
745
|
+
*/
|
|
746
|
+
function uninstall(c, flags, io) {
|
|
747
|
+
const shimText = readText(c.p.shim);
|
|
748
|
+
const ours = shimText !== null && shimText.includes(SHIM_MARK);
|
|
749
|
+
const unit = c.mgr && existsSync(c.mgr.unitPath);
|
|
750
|
+
const timerFiles = c.timer ? c.timer.files.map(([f]) => f).filter((f) => existsSync(f)) : [];
|
|
751
|
+
const data = existsSync(c.p.root);
|
|
752
|
+
const keep = [c.p.config, c.p.state].filter((d) => existsSync(d));
|
|
753
|
+
if (!ours && !unit && !timerFiles.length && !data && !(flags.purge && keep.length)) {
|
|
754
|
+
io.out(`nothing to uninstall — no ${c.tool} install found`);
|
|
755
|
+
return 0;
|
|
756
|
+
}
|
|
757
|
+
const removed = [];
|
|
758
|
+
const work = () => {
|
|
759
|
+
removed.push(...removeTimer(c, io));
|
|
760
|
+
if (unit) {
|
|
761
|
+
ctl(io, c.mgr.unload);
|
|
762
|
+
rmSync(c.mgr.unitPath, { force: true });
|
|
763
|
+
ctl(io, c.mgr.forget);
|
|
764
|
+
removed.push(c.mgr.unitPath);
|
|
765
|
+
}
|
|
766
|
+
if (ours) { rmSync(c.p.shim, { force: true }); removed.push(c.p.shim); }
|
|
767
|
+
if (data) { rmSync(c.p.root, { recursive: true, force: true }); removed.push(c.p.root); }
|
|
768
|
+
};
|
|
769
|
+
// Under the update lock, so a timer-started update cannot install into what is being deleted.
|
|
770
|
+
if (existsSync(c.p.state)) withLock(c.p.state, work); else work();
|
|
771
|
+
if (flags.purge) {
|
|
772
|
+
for (const d of keep) { rmSync(d, { recursive: true, force: true }); removed.push(d); }
|
|
773
|
+
}
|
|
774
|
+
io.out(`${c.tool} uninstalled. removed:\n${removed.map((r) => ` ${r}`).join('\n')}`);
|
|
775
|
+
if (shimText !== null && !ours) io.out(`left ${c.p.shim} in place — this template did not write it`);
|
|
776
|
+
if (!flags.purge && keep.length) io.out(`kept (config and state; \`${VERBS.uninstall} --purge\` deletes them):\n${keep.map((d) => ` ${d}`).join('\n')}`);
|
|
777
|
+
return 0;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
export function defaultIo(env = process.env) {
|
|
781
|
+
return {
|
|
782
|
+
env,
|
|
783
|
+
platform: process.platform,
|
|
784
|
+
uid: typeof process.getuid === 'function' ? process.getuid() : 0,
|
|
785
|
+
home: env.HOME || homedir(),
|
|
786
|
+
execPath: process.execPath,
|
|
787
|
+
run: (cmd, args) => spawnSync(cmd, args, { encoding: 'utf8', env }),
|
|
788
|
+
git: (args) => spawnSync('git', args, { encoding: 'utf8', env }),
|
|
789
|
+
fetch: (url) => fetch(url),
|
|
790
|
+
now: () => Date.now(),
|
|
791
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
792
|
+
timing: { timeoutMs: 60000, pollMs: 1000, settleMs: 3000 },
|
|
793
|
+
out: (s) => process.stdout.write(`${s}\n`),
|
|
794
|
+
err: (s) => process.stderr.write(`npx-service: ${s}\n`),
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
async function main(argv) {
|
|
799
|
+
const pkgDir = launcher.packageRoot(here);
|
|
800
|
+
const pkg = (pkgDir && readJson(join(pkgDir, 'package.json'))) || {};
|
|
801
|
+
const name = pkg.name;
|
|
802
|
+
if (!name) { process.stderr.write('npx-service: cannot find this package\'s package.json\n'); return 1; }
|
|
803
|
+
const tool = name.replace(/^@[^/]+\//, '');
|
|
804
|
+
const verb = argv[0];
|
|
805
|
+
if (!Object.values(VERBS).includes(verb)) {
|
|
806
|
+
// Not ours: the tool's own command line, run from the CURRENT install — never from npx's cache.
|
|
807
|
+
if (KIND === 'binary') return launcher.main(argv, here);
|
|
808
|
+
let entry = join(pkgDir, ENTRY);
|
|
809
|
+
if (KIND === 'dist') {
|
|
810
|
+
// The prebuilt app is not in the package — it exists only in an install.
|
|
811
|
+
entry = join(paths({ env: process.env, home: process.env.HOME || homedir(), tool }).root, 'current', 'app', ENTRY);
|
|
812
|
+
if (!existsSync(entry)) { process.stderr.write(`npx-service: ${tool} is not installed — run \`npx <origin>#vX.Y.Z ${VERBS.init}\` first\n`); return 1; }
|
|
813
|
+
}
|
|
814
|
+
const r = spawnSync(process.execPath, [entry, ...argv], { stdio: 'inherit' });
|
|
815
|
+
return r.status ?? 1;
|
|
816
|
+
}
|
|
817
|
+
const io = defaultIo(process.env);
|
|
818
|
+
const ms = Number(process.env[`${envPrefix(tool)}_HEALTH_TIMEOUT_MS`]);
|
|
819
|
+
if (ms) io.timing.timeoutMs = ms;
|
|
820
|
+
return run(verb, argv.slice(1), { tool, name, kind: KIND, pkgDir, distFile: DIST_FILE, serviceRel: relative(pkgDir, fileURLToPath(import.meta.url)) }, io);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
function isEntry() {
|
|
824
|
+
try { return realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; }
|
|
825
|
+
}
|
|
826
|
+
if (process.argv[1] && isEntry()) {
|
|
827
|
+
main(process.argv.slice(2)).then((code) => process.exit(code));
|
|
828
|
+
}
|