@betterborg/cli 0.0.1 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BetterBorg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ BetterBorg CLI
2
+ Copyright 2026 BetterBorg
3
+
4
+ This product includes software developed by BetterBorg
5
+ (https://github.com/betterborg).
6
+
7
+ BetterBorg CLI is distributed under the MIT License. See LICENSE.
package/bin/borg.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ "use strict";
4
+
5
+ const metadata = require("../package.json");
6
+ const { main, reportFailure } = require("../lib/launcher");
7
+
8
+ main(process.argv.slice(2), { version: metadata.version }).catch(reportFailure);
@@ -0,0 +1,421 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const fs = require("node:fs");
5
+ const os = require("node:os");
6
+ const path = require("node:path");
7
+ const { spawn, spawnSync } = require("node:child_process");
8
+
9
+ const REPOSITORY = "betterborg/betterborg-cli";
10
+ const FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
11
+ const SIGNAL_EXIT_CODES = { SIGHUP: 129, SIGINT: 130, SIGTERM: 143 };
12
+
13
+ function targetFor(platform, architecture) {
14
+ const operatingSystems = { darwin: "darwin", linux: "linux" };
15
+ const architectures = { arm64: "arm64", x64: "x86_64" };
16
+ const operatingSystem = operatingSystems[platform];
17
+ const targetArchitecture = architectures[architecture];
18
+ if (!operatingSystem || !targetArchitecture) {
19
+ return null;
20
+ }
21
+ return `borg-${operatingSystem}-${targetArchitecture}`;
22
+ }
23
+
24
+ function translateVersionArguments(arguments_) {
25
+ if (
26
+ arguments_.length === 1 &&
27
+ (arguments_[0] === "--version" || arguments_[0] === "-V")
28
+ ) {
29
+ return ["version"];
30
+ }
31
+ return [...arguments_];
32
+ }
33
+
34
+ function executableNames(name, platform, environment) {
35
+ if (platform !== "win32") {
36
+ return [name];
37
+ }
38
+ const extensions = (environment.PATHEXT || ".EXE;.CMD;.BAT;.COM")
39
+ .split(";")
40
+ .filter(Boolean);
41
+ return [name, ...extensions.map((extension) => `${name}${extension}`)];
42
+ }
43
+
44
+ function samePath(left, right, platform) {
45
+ if (platform === "win32") {
46
+ return left.toLowerCase() === right.toLowerCase();
47
+ }
48
+ return left === right;
49
+ }
50
+
51
+ function isWindowsCommandScript(command, platform) {
52
+ return platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
53
+ }
54
+
55
+ const WINDOWS_SHELL_META_CHARACTERS = /([()\][%!^"`<>&|;, *?])/g;
56
+
57
+ function escapeWindowsCommand(command) {
58
+ return command.replace(WINDOWS_SHELL_META_CHARACTERS, "^$1");
59
+ }
60
+
61
+ function escapeWindowsArgument(argument) {
62
+ let escaped = String(argument)
63
+ .replace(/(\\*)"/g, '$1$1\\"')
64
+ .replace(/(\\*)$/, "$1$1");
65
+ escaped = `"${escaped}"`;
66
+ return escaped.replace(WINDOWS_SHELL_META_CHARACTERS, "^$1");
67
+ }
68
+
69
+ function commandInvocation(command, arguments_, options, dependencies) {
70
+ if (!isWindowsCommandScript(command, dependencies.platform)) {
71
+ return { command, arguments: arguments_, options };
72
+ }
73
+ if ([command, ...arguments_].some((value) => /[\r\n]/.test(value))) {
74
+ throw new Error(
75
+ "Windows command shims cannot safely forward paths or arguments containing line breaks",
76
+ );
77
+ }
78
+
79
+ const shell =
80
+ dependencies.environment.ComSpec ||
81
+ dependencies.environment.COMSPEC ||
82
+ "cmd.exe";
83
+ const shellCommand = [
84
+ escapeWindowsCommand(command),
85
+ ...arguments_.map(escapeWindowsArgument),
86
+ ].join(" ");
87
+ return {
88
+ command: shell,
89
+ arguments: ["/d", "/s", "/v:off", "/c", `"${shellCommand}"`],
90
+ options: { ...options, windowsVerbatimArguments: true },
91
+ };
92
+ }
93
+
94
+ function launcherExecutables(dependencies) {
95
+ if (!dependencies.launcherPath) {
96
+ return [];
97
+ }
98
+ const executables = [dependencies.launcherPath];
99
+ let directory = dependencies.pathModule.dirname(dependencies.launcherPath);
100
+ while (dependencies.pathModule.dirname(directory) !== directory) {
101
+ if (
102
+ dependencies.pathModule.basename(directory).toLowerCase() ===
103
+ "node_modules"
104
+ ) {
105
+ const shimDirectories = [
106
+ dependencies.pathModule.join(directory, ".bin"),
107
+ ];
108
+ if (dependencies.platform === "win32") {
109
+ shimDirectories.push(dependencies.pathModule.dirname(directory));
110
+ }
111
+ const names =
112
+ dependencies.platform === "win32"
113
+ ? ["borg", "borg.cmd", "borg.ps1"]
114
+ : ["borg"];
115
+ for (const shimDirectory of shimDirectories) {
116
+ for (const name of names) {
117
+ executables.push(dependencies.pathModule.resolve(shimDirectory, name));
118
+ }
119
+ }
120
+ }
121
+ directory = dependencies.pathModule.dirname(directory);
122
+ }
123
+ return executables;
124
+ }
125
+
126
+ function executableOnPath(name, dependencies, excludedPaths = []) {
127
+ const {
128
+ environment,
129
+ fileSystem,
130
+ pathModule,
131
+ platform,
132
+ pathDelimiter,
133
+ } = dependencies;
134
+ const pathValue = environment.PATH || environment.Path || "";
135
+ for (const directory of pathValue.split(pathDelimiter)) {
136
+ if (!directory) {
137
+ continue;
138
+ }
139
+ for (const executableName of executableNames(name, platform, environment)) {
140
+ const candidate = pathModule.resolve(directory, executableName);
141
+ try {
142
+ fileSystem.accessSync(candidate, fileSystem.constants.X_OK);
143
+ const resolvedCandidate = fileSystem.realpathSync(candidate);
144
+ if (
145
+ !excludedPaths.some((excludedPath) =>
146
+ samePath(resolvedCandidate, excludedPath, platform),
147
+ )
148
+ ) {
149
+ return candidate;
150
+ }
151
+ } catch {
152
+ // A PATH entry that is missing or not executable is not a candidate.
153
+ }
154
+ }
155
+ }
156
+ return null;
157
+ }
158
+
159
+ function installedCli(version, dependencies) {
160
+ const candidate = executableOnPath(
161
+ "borg",
162
+ dependencies,
163
+ launcherExecutables(dependencies),
164
+ );
165
+ if (!candidate) {
166
+ return null;
167
+ }
168
+ const invocation = commandInvocation(
169
+ candidate,
170
+ ["version"],
171
+ {
172
+ encoding: "utf8",
173
+ stdio: ["ignore", "pipe", "ignore"],
174
+ timeout: 5000,
175
+ },
176
+ dependencies,
177
+ );
178
+ const completed = dependencies.spawnSync(
179
+ invocation.command,
180
+ invocation.arguments,
181
+ invocation.options,
182
+ );
183
+ if (
184
+ completed.status === 0 &&
185
+ completed.stdout.trim() === `borg ${version}`
186
+ ) {
187
+ return candidate;
188
+ }
189
+ return null;
190
+ }
191
+
192
+ function digest(pathname, fileSystem = fs) {
193
+ return crypto
194
+ .createHash("sha256")
195
+ .update(fileSystem.readFileSync(pathname))
196
+ .digest("hex");
197
+ }
198
+
199
+ function verifiedBinary(binaryPath, checksumPath, target, fileSystem = fs) {
200
+ try {
201
+ const checksum = fileSystem.readFileSync(checksumPath, "utf8");
202
+ const match = checksum.match(/^([a-f0-9]{64}) ([^\r\n]+)\n$/);
203
+ return Boolean(
204
+ match &&
205
+ match[2] === target &&
206
+ digest(binaryPath, fileSystem) === match[1],
207
+ );
208
+ } catch {
209
+ return false;
210
+ }
211
+ }
212
+
213
+ async function downloadToFile(url, destination) {
214
+ const response = await fetch(url, { redirect: "follow" });
215
+ if (!response.ok) {
216
+ throw new Error(`download returned HTTP ${response.status} for ${url}`);
217
+ }
218
+ const content = Buffer.from(await response.arrayBuffer());
219
+ fs.writeFileSync(destination, content, { flag: "wx" });
220
+ }
221
+
222
+ function defaultCacheDirectory(version, dependencies) {
223
+ const root = dependencies.environment.XDG_CACHE_HOME
224
+ ? dependencies.pathModule.resolve(dependencies.environment.XDG_CACHE_HOME)
225
+ : dependencies.pathModule.join(dependencies.homeDirectory, ".cache");
226
+ return dependencies.pathModule.join(root, "betterborg", "cli", version);
227
+ }
228
+
229
+ async function cachedRelease(version, target, dependencies) {
230
+ const directory =
231
+ dependencies.cacheDirectory || defaultCacheDirectory(version, dependencies);
232
+ const binaryPath = dependencies.pathModule.join(directory, target);
233
+ const checksumPath = dependencies.pathModule.join(directory, `${target}.sha256`);
234
+ if (
235
+ verifiedBinary(binaryPath, checksumPath, target, dependencies.fileSystem)
236
+ ) {
237
+ dependencies.fileSystem.chmodSync(binaryPath, 0o755);
238
+ return binaryPath;
239
+ }
240
+
241
+ dependencies.fileSystem.mkdirSync(directory, { recursive: true, mode: 0o700 });
242
+ const nonce = dependencies.randomBytes(8).toString("hex");
243
+ const temporaryBinary = `${binaryPath}.${nonce}.tmp`;
244
+ const temporaryChecksum = `${checksumPath}.${nonce}.tmp`;
245
+ const releaseRoot = `https://github.com/${REPOSITORY}/releases/download/v${version}`;
246
+ try {
247
+ await dependencies.download(`${releaseRoot}/${target}`, temporaryBinary);
248
+ await dependencies.download(
249
+ `${releaseRoot}/${target}.sha256`,
250
+ temporaryChecksum,
251
+ );
252
+ if (
253
+ !verifiedBinary(
254
+ temporaryBinary,
255
+ temporaryChecksum,
256
+ target,
257
+ dependencies.fileSystem,
258
+ )
259
+ ) {
260
+ throw new Error(`downloaded ${target} failed SHA-256 verification`);
261
+ }
262
+ dependencies.fileSystem.chmodSync(temporaryBinary, 0o755);
263
+ dependencies.fileSystem.renameSync(temporaryBinary, binaryPath);
264
+ dependencies.fileSystem.renameSync(temporaryChecksum, checksumPath);
265
+ return binaryPath;
266
+ } finally {
267
+ dependencies.fileSystem.rmSync(temporaryBinary, { force: true });
268
+ dependencies.fileSystem.rmSync(temporaryChecksum, { force: true });
269
+ }
270
+ }
271
+
272
+ function withDefaults(overrides = {}) {
273
+ let launcherPath = null;
274
+ try {
275
+ launcherPath = fs.realpathSync(process.argv[1]);
276
+ } catch {
277
+ // Tests and unusual embeddings may not have a filesystem entry in argv[1].
278
+ }
279
+ return {
280
+ cacheDirectory: null,
281
+ download: downloadToFile,
282
+ environment: process.env,
283
+ fileSystem: fs,
284
+ homeDirectory: os.homedir(),
285
+ launcherPath,
286
+ pathDelimiter: path.delimiter,
287
+ pathModule: path,
288
+ platform: process.platform,
289
+ architecture: process.arch,
290
+ process,
291
+ randomBytes: crypto.randomBytes,
292
+ spawn,
293
+ spawnSync,
294
+ ...overrides,
295
+ };
296
+ }
297
+
298
+ async function resolveCli(version, overrides = {}) {
299
+ const dependencies = withDefaults(overrides);
300
+ const installed = installedCli(version, dependencies);
301
+ if (installed) {
302
+ return { command: installed, argumentsPrefix: [], source: "installed" };
303
+ }
304
+
305
+ const target = targetFor(dependencies.platform, dependencies.architecture);
306
+ let releaseFailure = null;
307
+ if (target) {
308
+ try {
309
+ const binary = await cachedRelease(version, target, dependencies);
310
+ return { command: binary, argumentsPrefix: [], source: "release" };
311
+ } catch (error) {
312
+ releaseFailure = error instanceof Error ? error.message : String(error);
313
+ }
314
+ }
315
+
316
+ const uvx = executableOnPath("uvx", dependencies);
317
+ if (uvx) {
318
+ return {
319
+ command: uvx,
320
+ argumentsPrefix: ["--from", `betterborg==${version}`, "borg"],
321
+ source: "uvx",
322
+ };
323
+ }
324
+
325
+ const targetDescription = target
326
+ ? `could not install the ${target} release${releaseFailure ? ` (${releaseFailure})` : ""}`
327
+ : `no standalone release supports ${dependencies.platform}/${dependencies.architecture}`;
328
+ throw new Error(
329
+ `${targetDescription}, and uvx is not on PATH. Install uv from https://docs.astral.sh/uv/ or install betterborg==${version} so borg is on PATH.`,
330
+ );
331
+ }
332
+
333
+ function launch(resolved, arguments_, overrides = {}) {
334
+ const dependencies = withDefaults(overrides);
335
+ return new Promise((resolve, reject) => {
336
+ let settled = false;
337
+ let child;
338
+ try {
339
+ const invocation = commandInvocation(
340
+ resolved.command,
341
+ [...resolved.argumentsPrefix, ...arguments_],
342
+ { stdio: "inherit" },
343
+ dependencies,
344
+ );
345
+ child = dependencies.spawn(
346
+ invocation.command,
347
+ invocation.arguments,
348
+ invocation.options,
349
+ );
350
+ } catch (error) {
351
+ reject(error);
352
+ return;
353
+ }
354
+
355
+ const handlers = new Map(
356
+ FORWARDED_SIGNALS.map((signal) => [
357
+ signal,
358
+ () => {
359
+ child.kill(signal);
360
+ },
361
+ ]),
362
+ );
363
+ for (const [signal, handler] of handlers) {
364
+ dependencies.process.on(signal, handler);
365
+ }
366
+ const cleanup = () => {
367
+ for (const [signal, handler] of handlers) {
368
+ dependencies.process.removeListener(signal, handler);
369
+ }
370
+ };
371
+
372
+ child.once("error", (error) => {
373
+ if (settled) return;
374
+ settled = true;
375
+ cleanup();
376
+ reject(new Error(`could not start BetterBorg CLI: ${error.message}`));
377
+ });
378
+ child.once("close", (code, signal) => {
379
+ if (settled) return;
380
+ settled = true;
381
+ cleanup();
382
+ if (signal) {
383
+ if (typeof dependencies.process.kill === "function") {
384
+ dependencies.process.kill(dependencies.process.pid, signal);
385
+ } else {
386
+ dependencies.process.exitCode = SIGNAL_EXIT_CODES[signal] || 1;
387
+ }
388
+ } else {
389
+ dependencies.process.exitCode = code === null ? 1 : code;
390
+ }
391
+ resolve();
392
+ });
393
+ });
394
+ }
395
+
396
+ async function main(arguments_, overrides = {}) {
397
+ if (!overrides.version) {
398
+ throw new Error("npm package version metadata is missing");
399
+ }
400
+ const resolved = await resolveCli(overrides.version, overrides);
401
+ await launch(resolved, translateVersionArguments(arguments_), overrides);
402
+ }
403
+
404
+ function reportFailure(error, dependencies = {}) {
405
+ const logger = dependencies.console || console;
406
+ const processLike = dependencies.process || process;
407
+ const message = error instanceof Error ? error.message : String(error);
408
+ logger.error(`borg: ${message}`);
409
+ processLike.exitCode = 1;
410
+ }
411
+
412
+ module.exports = {
413
+ cachedRelease,
414
+ launch,
415
+ main,
416
+ reportFailure,
417
+ resolveCli,
418
+ targetFor,
419
+ translateVersionArguments,
420
+ verifiedBinary,
421
+ };
package/package.json CHANGED
@@ -1,14 +1,33 @@
1
1
  {
2
2
  "name": "@betterborg/cli",
3
- "version": "0.0.1",
4
- "description": "Placeholder reserving @betterborg/cli. The first real release is 0.1.0.",
3
+ "version": "0.1.0",
4
+ "description": "Installer and launcher for the BetterBorg CLI",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/betterborg/betterborg-cli.git",
9
9
  "directory": "npm"
10
10
  },
11
- "homepage": "https://github.com/betterborg/betterborg-cli",
12
- "publishConfig": { "access": "public" },
13
- "files": ["README.md"]
11
+ "homepage": "https://github.com/betterborg/betterborg-cli#readme",
12
+ "bugs": "https://github.com/betterborg/betterborg-cli/issues",
13
+ "type": "commonjs",
14
+ "bin": {
15
+ "borg": "bin/borg.js"
16
+ },
17
+ "files": [
18
+ "LICENSE",
19
+ "NOTICE",
20
+ "bin",
21
+ "lib"
22
+ ],
23
+ "engines": {
24
+ "node": ">=18"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "lint": "node --check bin/borg.js && node --check lib/launcher.js && node --check test/launcher.test.js",
31
+ "test": "node --test test/launcher.test.js"
32
+ }
14
33
  }
package/README.md DELETED
@@ -1,11 +0,0 @@
1
- # @betterborg/cli
2
-
3
- Placeholder reserving this package name. It contains no code.
4
-
5
- The first published release is `0.1.0`. Install that instead:
6
-
7
- ```bash
8
- npx --yes @betterborg/cli
9
- ```
10
-
11
- See [betterborg/betterborg-cli](https://github.com/betterborg/betterborg-cli).