@git.zone/cli 8.11.0 → 9.0.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.
Files changed (64) hide show
  1. package/assets/templates/{asset_deno_binary_installer → asset_binary_installer}/install.sh +134 -40
  2. package/assets/templates/{asset_deno_binary_postinstall → asset_binary_postinstall}/bin/wrapper.js +13 -4
  3. package/assets/templates/asset_binary_postinstall/scripts/install-binary.js +211 -0
  4. package/assets/templates/asset_binary_release_gitea/.gitea/workflows/release.yml +194 -0
  5. package/assets/templates/asset_binary_release_gitea/scripts/gitzone-binary-release.d.mts +29 -0
  6. package/assets/templates/asset_binary_release_gitea/scripts/gitzone-binary-release.mjs +168 -0
  7. package/assets/templates/asset_tspack_release_gitea/.gitea/workflows/release.yml +7 -4
  8. package/dist_ts/00_commitinfo_data.js +2 -2
  9. package/dist_ts/helpers.managedassets.d.ts +44 -0
  10. package/dist_ts/helpers.managedassets.js +166 -0
  11. package/dist_ts/helpers.ownerscopes.d.ts +3 -15
  12. package/dist_ts/helpers.ownerscopes.js +4 -16
  13. package/dist_ts/helpers.packagefiles.d.ts +2 -1
  14. package/dist_ts/helpers.packagefiles.js +7 -4
  15. package/dist_ts/helpers.sealedrelease.js +3 -3
  16. package/dist_ts/helpers.tssea.d.ts +11 -0
  17. package/dist_ts/helpers.tssea.js +81 -0
  18. package/dist_ts/helpers.workflow.d.ts +0 -3
  19. package/dist_ts/helpers.workflow.js +7 -19
  20. package/dist_ts/index.d.ts +1 -1
  21. package/dist_ts/index.js +2 -2
  22. package/dist_ts/mod_commit/mod.helpers.d.ts +8 -21
  23. package/dist_ts/mod_commit/mod.helpers.js +32 -83
  24. package/dist_ts/mod_commit/mod.ui.js +1 -5
  25. package/dist_ts/mod_config/index.js +41 -33
  26. package/dist_ts/mod_format/formatters/assets.formatter.js +57 -93
  27. package/dist_ts/mod_format/formatters/packagejson.formatter.js +3 -3
  28. package/dist_ts/mod_format/index.js +30 -11
  29. package/dist_ts/mod_format/interfaces.format.js +1 -2
  30. package/dist_ts/mod_release/helpers.releasepreparation.d.ts +6 -14
  31. package/dist_ts/mod_release/helpers.releasepreparation.js +27 -53
  32. package/dist_ts/mod_release/index.js +9 -10
  33. package/dist_ts/mod_services/classes.serviceconfiguration.d.ts +2 -2
  34. package/dist_ts/mod_services/classes.serviceoptions.d.ts +2 -2
  35. package/dist_ts/plugins.d.ts +3 -1
  36. package/dist_ts/plugins.js +4 -2
  37. package/package.json +3 -2
  38. package/readme.md +69 -63
  39. package/ts/00_commitinfo_data.ts +1 -1
  40. package/ts/helpers.managedassets.ts +215 -0
  41. package/ts/helpers.ownerscopes.ts +3 -15
  42. package/ts/helpers.packagefiles.ts +6 -3
  43. package/ts/helpers.sealedrelease.ts +2 -2
  44. package/ts/helpers.tssea.ts +102 -0
  45. package/ts/helpers.workflow.ts +6 -28
  46. package/ts/index.ts +1 -1
  47. package/ts/mod_commit/mod.helpers.ts +33 -94
  48. package/ts/mod_commit/mod.ui.ts +0 -4
  49. package/ts/mod_config/index.ts +47 -35
  50. package/ts/mod_format/formatters/assets.formatter.ts +62 -109
  51. package/ts/mod_format/formatters/packagejson.formatter.ts +2 -2
  52. package/ts/mod_format/index.ts +36 -10
  53. package/ts/mod_format/interfaces.format.ts +0 -1
  54. package/ts/mod_release/helpers.releasepreparation.ts +36 -69
  55. package/ts/mod_release/index.ts +6 -16
  56. package/ts/mod_services/classes.serviceconfiguration.ts +2 -2
  57. package/ts/mod_services/classes.serviceoptions.ts +2 -2
  58. package/ts/plugins.ts +4 -0
  59. package/assets/templates/asset_deno_binary_postinstall/scripts/install-binary.js +0 -123
  60. package/assets/templates/asset_deno_binary_release_gitea/.gitea/workflows/release.yml +0 -154
  61. package/assets/templates/multienv/deno.json +0 -8
  62. package/dist_ts/mod_format/formatters/deno.formatter.d.ts +0 -18
  63. package/dist_ts/mod_format/formatters/deno.formatter.js +0 -175
  64. package/ts/mod_format/formatters/deno.formatter.ts +0 -219
@@ -1,5 +1,5 @@
1
1
  #!/bin/bash
2
- # Managed by @git.zone/cli from assets/templates/asset_deno_binary_installer. Do not edit by hand.
2
+ # Managed by @git.zone/cli from assets/templates/asset_binary_installer. Do not edit by hand.
3
3
 
4
4
  set -euo pipefail
5
5
 
@@ -227,7 +227,7 @@ detect_binary_name() {
227
227
 
228
228
  case "${os_name}-${arch_name}" in
229
229
  {{#each binary.targets}}
230
- {{os}}-{{arch}}) echo "{{assetName}}" ;;
230
+ {{os}}-{{arch}}) echo "{{name}}" ;;
231
231
  {{/each}}
232
232
  *)
233
233
  echo "Error: Unsupported platform: ${os_name}-${arch_name}" >&2
@@ -266,6 +266,7 @@ echo ""
266
266
  TEMP_DIR=$(mktemp -d)
267
267
  SOURCE_DIR="$TEMP_DIR/source"
268
268
  BACKUP_DIR=""
269
+ INSTALL_REPLACED=0
269
270
  SERVICE_WAS_RUNNING=0
270
271
  SERVICE_STOPPED=0
271
272
  SYSTEMD_AVAILABLE=0
@@ -278,7 +279,7 @@ trap cleanup_temp EXIT
278
279
 
279
280
  if command -v systemctl >/dev/null 2>&1; then
280
281
  SYSTEMD_AVAILABLE=1
281
- for service_name in "${SERVICE_NAMES[@]}"; do
282
+ for service_name in ${SERVICE_NAMES[@]+"${SERVICE_NAMES[@]}"}; do
282
283
  if systemctl is-active --quiet "$service_name" 2>/dev/null; then
283
284
  SERVICE_WAS_RUNNING=1
284
285
  break
@@ -290,11 +291,26 @@ if [[ -n "$PRIMARY_PRESERVE_PATH" && -e "$PRIMARY_PRESERVE_PATH" ]]; then
290
291
  PRESERVE_PATH_EXISTS=1
291
292
  fi
292
293
 
294
+ # Puts the moved-aside installation back, or removes an incomplete first installation.
293
295
  restore_previous_installation() {
294
- if [[ -n "$BACKUP_DIR" && -d "$BACKUP_DIR" ]]; then
296
+ if [[ $INSTALL_REPLACED -ne 1 ]]; then
297
+ return 0
298
+ fi
299
+ if [[ -z "$BACKUP_DIR" ]]; then
300
+ echo "Removing the incomplete installation at $INSTALL_DIR"
301
+ rm -rf "$INSTALL_DIR" || true
302
+ if [[ "$(readlink "$BIN_DIR/{{cliName}}" 2>/dev/null || true)" == "$INSTALL_DIR/"* ]]; then
303
+ rm -f "$BIN_DIR/{{cliName}}" || true
304
+ fi
305
+ return 0
306
+ fi
307
+ if [[ -d "$BACKUP_DIR" ]]; then
295
308
  echo "Restoring previous installation from $BACKUP_DIR..."
296
309
  rm -rf "$INSTALL_DIR" || true
297
- mv "$BACKUP_DIR" "$INSTALL_DIR" || true
310
+ if ! mv "$BACKUP_DIR" "$INSTALL_DIR"; then
311
+ echo "Error: could not restore $BACKUP_DIR to $INSTALL_DIR; restore it by hand" >&2
312
+ return 1
313
+ fi
298
314
  if [[ -f "$INSTALL_DIR/{{binary.installFileName}}" ]]; then
299
315
  mkdir -p "$BIN_DIR" || true
300
316
  ln -sf "$INSTALL_DIR/{{binary.installFileName}}" "$BIN_DIR/{{cliName}}" || true
@@ -309,15 +325,31 @@ restore_previous_installation() {
309
325
 
310
326
  restart_previous_service_on_error() {
311
327
  if [[ $SERVICE_STOPPED -eq 1 && $SYSTEMD_AVAILABLE -eq 1 && -n "$SERVICE_RESTART_NAME" ]]; then
312
- echo "Installation failed after stopping {{displayName}}; restarting previous service..."
313
- systemctl start "$SERVICE_RESTART_NAME" || true
328
+ echo "Restarting the previous service: $SERVICE_RESTART_NAME"
329
+ if ! systemctl restart "$SERVICE_RESTART_NAME"; then
330
+ echo "Error: the previous service $SERVICE_RESTART_NAME did not restart; check: systemctl status $SERVICE_RESTART_NAME" >&2
331
+ return 1
332
+ fi
314
333
  fi
315
334
  }
316
335
 
317
- handle_install_error() {
336
+ # Every failure after the current installation was touched ends here: put it back, restart it, exit 1.
337
+ abort_update() {
318
338
  trap - ERR
319
- restore_previous_installation
320
- restart_previous_service_on_error
339
+ echo "Error: $1" >&2
340
+ local restored=0
341
+ restore_previous_installation || restored=1
342
+ restart_previous_service_on_error || restored=1
343
+ if [[ $restored -eq 0 ]]; then
344
+ echo "Error: {{displayName}} $VERSION was not installed; the previous state is restored" >&2
345
+ else
346
+ echo "Error: {{displayName}} $VERSION was not installed, and the previous installation could not be fully restored" >&2
347
+ fi
348
+ exit 1
349
+ }
350
+
351
+ handle_install_error() {
352
+ abort_update "the {{displayName}} installation failed"
321
353
  }
322
354
  trap handle_install_error ERR
323
355
 
@@ -325,11 +357,11 @@ stop_service_if_running() {
325
357
  if [[ $SYSTEMD_AVAILABLE -ne 1 ]]; then
326
358
  return
327
359
  fi
328
- for service_name in "${SERVICE_NAMES[@]}"; do
360
+ for service_name in ${SERVICE_NAMES[@]+"${SERVICE_NAMES[@]}"}; do
329
361
  if systemctl is-active --quiet "$service_name" 2>/dev/null; then
330
362
  echo "Stopping service: $service_name"
331
- systemctl stop "$service_name"
332
363
  SERVICE_STOPPED=1
364
+ systemctl stop "$service_name" || abort_update "could not stop the service $service_name"
333
365
  fi
334
366
  done
335
367
  }
@@ -339,7 +371,7 @@ remove_legacy_services() {
339
371
  return
340
372
  fi
341
373
  local needs_reload=0
342
- for service_name in "${LEGACY_SERVICE_NAMES[@]}"; do
374
+ for service_name in ${LEGACY_SERVICE_NAMES[@]+"${LEGACY_SERVICE_NAMES[@]}"}; do
343
375
  if systemctl is-enabled --quiet "$service_name" 2>/dev/null \
344
376
  || systemctl is-active --quiet "$service_name" 2>/dev/null \
345
377
  || systemctl is-failed --quiet "$service_name" 2>/dev/null \
@@ -365,12 +397,62 @@ remove_legacy_services() {
365
397
  }
366
398
 
367
399
  move_previous_installation() {
368
- mkdir -p "$(dirname "$INSTALL_DIR")"
400
+ mkdir -p "$(dirname "$INSTALL_DIR")" || abort_update "could not create the parent directory of $INSTALL_DIR"
369
401
  if [[ -d "$INSTALL_DIR" ]]; then
370
402
  BACKUP_DIR="${INSTALL_DIR}.previous.$$"
371
403
  echo "Moving previous installation to $BACKUP_DIR"
372
- mv "$INSTALL_DIR" "$BACKUP_DIR"
404
+ mv "$INSTALL_DIR" "$BACKUP_DIR" || abort_update "could not move $INSTALL_DIR aside"
405
+ fi
406
+ INSTALL_REPLACED=1
407
+ }
408
+
409
+ sha256_of() {
410
+ local digest
411
+ if command -v sha256sum >/dev/null 2>&1; then
412
+ digest=$(sha256sum "$1")
413
+ elif command -v shasum >/dev/null 2>&1; then
414
+ digest=$(shasum -a 256 "$1")
415
+ else
416
+ echo "Error: neither sha256sum nor shasum is available to verify the download" >&2
417
+ exit 1
418
+ fi
419
+ echo "${digest%% *}"
420
+ }
421
+
422
+ # Refuses the download unless SHA256SUMS.txt of the release lists it with the same digest.
423
+ verify_release_checksum() {
424
+ local file="$1"
425
+ local name="$2"
426
+ local sums_url="${GITEA_BASE_URL}/${GITEA_REPO}/releases/download/${VERSION}/SHA256SUMS.txt"
427
+ local sums_file="$TEMP_DIR/SHA256SUMS.txt"
428
+ local expected=""
429
+ local actual
430
+ local sum
431
+ local entry
432
+
433
+ echo "Downloading checksums: $sums_url"
434
+ if ! curl -fsSL "$sums_url" -o "$sums_file"; then
435
+ echo "Error: could not download $sums_url; refusing to install an unverified binary" >&2
436
+ exit 1
437
+ fi
438
+ while read -r sum entry; do
439
+ if [[ "${entry#\*}" == "$name" ]]; then
440
+ expected="$sum"
441
+ break
442
+ fi
443
+ done < "$sums_file"
444
+ if [[ -z "$expected" ]]; then
445
+ echo "Error: SHA256SUMS.txt of $VERSION has no entry for $name; refusing to install it" >&2
446
+ exit 1
373
447
  fi
448
+ actual=$(sha256_of "$file")
449
+ if [[ "$actual" != "$expected" ]]; then
450
+ echo "Error: checksum mismatch for $name of $VERSION; refusing to install it" >&2
451
+ echo " expected: $expected" >&2
452
+ echo " actual: $actual" >&2
453
+ exit 1
454
+ fi
455
+ echo "Checksum verified: $name"
374
456
  }
375
457
 
376
458
  install_release_binary() {
@@ -383,21 +465,29 @@ install_release_binary() {
383
465
  temp_file="$TEMP_DIR/$binary_name"
384
466
 
385
467
  echo "Downloading {{displayName}} binary: $download_url"
386
- curl -fSL "$download_url" -o "$temp_file"
468
+ if ! curl -fSL "$download_url" -o "$temp_file"; then
469
+ echo "Error: could not download $download_url; the current installation is untouched" >&2
470
+ exit 1
471
+ fi
472
+ verify_release_checksum "$temp_file" "$binary_name"
387
473
  chmod 0755 "$temp_file"
388
474
 
475
+ # The new binary must run before the current installation is touched.
389
476
  echo "Validating downloaded binary..."
390
- "$temp_file" --version >/dev/null
477
+ if ! "$temp_file" --version >/dev/null; then
478
+ echo "Error: the downloaded {{displayName}} $VERSION binary failed '--version'; the current installation is untouched" >&2
479
+ exit 1
480
+ fi
391
481
 
392
482
  stop_service_if_running
393
483
  move_previous_installation
394
484
 
395
485
  echo "Installing binary to $INSTALL_DIR"
396
- mkdir -p "$INSTALL_DIR"
397
- install -m 0755 "$temp_file" "$INSTALL_DIR/{{binary.installFileName}}"
398
-
399
- mkdir -p "$BIN_DIR"
400
- ln -sf "$INSTALL_DIR/{{binary.installFileName}}" "$BIN_DIR/{{cliName}}"
486
+ mkdir -p "$INSTALL_DIR" \
487
+ && install -m 0755 "$temp_file" "$INSTALL_DIR/{{binary.installFileName}}" \
488
+ && mkdir -p "$BIN_DIR" \
489
+ && ln -sf "$INSTALL_DIR/{{binary.installFileName}}" "$BIN_DIR/{{cliName}}" \
490
+ || abort_update "could not install the binary to $INSTALL_DIR"
401
491
  }
402
492
 
403
493
  {{#if installer.source.enabled}}
@@ -409,8 +499,10 @@ install_source_build() {
409
499
  echo "Cloning {{displayName}} source from $REPO_URL ($VERSION)..."
410
500
  git clone --depth 1 --branch "$VERSION" "$REPO_URL" "$SOURCE_DIR"
411
501
 
502
+ # The build and its check must pass before the current installation is touched.
412
503
  echo "Building {{displayName}} from source..."
413
504
  (
505
+ trap 'echo "Error: building or checking {{displayName}} $VERSION from source failed; the current installation is untouched" >&2' ERR
414
506
  cd "$SOURCE_DIR"
415
507
  {{#each installer.source.commands}}
416
508
  {{{this}}}
@@ -422,13 +514,17 @@ install_source_build() {
422
514
  move_previous_installation
423
515
 
424
516
  echo "Installing source build to $INSTALL_DIR"
425
- mv "$SOURCE_DIR" "$INSTALL_DIR"
426
- {{#each installer.source.executableFiles}}
427
- chmod 0755 "$INSTALL_DIR/{{this}}"
428
- {{/each}}
429
-
430
- mkdir -p "$BIN_DIR"
431
- ln -sf "$INSTALL_DIR/{{installer.source.executable}}" "$BIN_DIR/{{cliName}}"
517
+ mv "$SOURCE_DIR" "$INSTALL_DIR" || abort_update "could not install the source build to $INSTALL_DIR"
518
+ # Every listed executable must exist in the build: a missing one is a configuration or build defect.
519
+ for executable_file in{{#each installer.source.executableFiles}} "{{this}}"{{/each}}; do
520
+ if [[ ! -f "$INSTALL_DIR/$executable_file" ]]; then
521
+ abort_update "the source build has no $executable_file, which installer.modes.source.executableFiles lists"
522
+ fi
523
+ chmod 0755 "$INSTALL_DIR/$executable_file" || abort_update "could not make $INSTALL_DIR/$executable_file executable"
524
+ done
525
+ mkdir -p "$BIN_DIR" \
526
+ && ln -sf "$INSTALL_DIR/{{installer.source.executable}}" "$BIN_DIR/{{cliName}}" \
527
+ || abort_update "could not link $BIN_DIR/{{cliName}}"
432
528
  }
433
529
 
434
530
  {{/if}}
@@ -448,28 +544,21 @@ fi
448
544
  echo "Symlink created: $BIN_DIR/{{cliName}}"
449
545
 
450
546
  {{#each installer.ensureDirs}}
451
- mkdir -p "{{this}}"
547
+ mkdir -p "{{this}}" || abort_update "could not create {{this}}"
452
548
  {{/each}}
453
549
 
454
550
  if ! "$BIN_DIR/{{cliName}}" --version >/dev/null; then
455
- echo "Error: Installed {{displayName}} CLI failed validation"
456
- restore_previous_installation
457
- restart_previous_service_on_error
458
- exit 1
459
- fi
460
-
461
- if [[ -n "$BACKUP_DIR" && -d "$BACKUP_DIR" ]]; then
462
- rm -rf "$BACKUP_DIR"
551
+ abort_update "the installed {{displayName}} CLI failed '--version'"
463
552
  fi
464
553
 
465
554
  if [[ $SERVICE_WAS_RUNNING -eq 1 && $SYSTEMD_AVAILABLE -eq 1 ]]; then
466
555
  {{#if installer.service.hasRefreshCommand}}
467
556
  echo "Refreshing systemd service..."
468
- {{{installer.service.refreshCommand}}}
557
+ {{{installer.service.refreshCommand}}} || abort_update "refreshing the service failed: {{{installer.service.refreshCommand}}}"
469
558
  {{/if}}
470
559
  if [[ -n "$SERVICE_RESTART_NAME" ]]; then
471
560
  echo "Restarting service: $SERVICE_RESTART_NAME"
472
- systemctl restart "$SERVICE_RESTART_NAME"
561
+ systemctl restart "$SERVICE_RESTART_NAME" || abort_update "the service $SERVICE_RESTART_NAME did not restart with {{displayName}} $VERSION"
473
562
  SERVICE_STOPPED=0
474
563
  echo "Service restarted successfully."
475
564
  echo ""
@@ -478,6 +567,11 @@ fi
478
567
 
479
568
  trap - ERR
480
569
 
570
+ # The backup goes only once the new installation runs.
571
+ if [[ -n "$BACKUP_DIR" && -d "$BACKUP_DIR" ]]; then
572
+ rm -rf "$BACKUP_DIR"
573
+ fi
574
+
481
575
  echo "================================================"
482
576
  echo " {{displayName}} Installation Complete!"
483
577
  echo "================================================"
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- // Managed by @git.zone/cli from assets/templates/asset_deno_binary_postinstall. Do not edit by hand.
2
+ // Managed by @git.zone/cli from assets/templates/asset_binary_postinstall. Do not edit by hand.
3
3
 
4
- import { arch, platform } from 'node:os';
4
+ import { arch, constants, platform } from 'node:os';
5
5
  import { existsSync } from 'node:fs';
6
6
  import { dirname, join } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
@@ -11,7 +11,7 @@ const __filename = fileURLToPath(import.meta.url);
11
11
  const __dirname = dirname(__filename);
12
12
  const BINARY_MAP = new Map([
13
13
  {{#each binary.targets}}
14
- ['{{nodeKey}}', '{{assetName}}'],
14
+ ['{{nodeKey}}', '{{name}}'],
15
15
  {{/each}}
16
16
  ]);
17
17
 
@@ -34,4 +34,13 @@ if (result.error) {
34
34
  console.error(result.error.message);
35
35
  process.exit(1);
36
36
  }
37
- process.exit(result.status ?? 0);
37
+ if (result.signal) {
38
+ // Die of the same signal, so callers see what ended the binary. Node ignores some signals
39
+ // (SIGPIPE) and starts its inspector on SIGUSR1; those end with the shell convention 128 + n.
40
+ if (result.signal !== 'SIGUSR1') {
41
+ process.removeAllListeners(result.signal);
42
+ process.kill(process.pid, result.signal);
43
+ }
44
+ process.exit(128 + (constants.signals[result.signal] ?? 0));
45
+ }
46
+ process.exit(result.status ?? 1);
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env node
2
+ // Managed by @git.zone/cli from assets/templates/asset_binary_postinstall. Do not edit by hand.
3
+
4
+ import { arch, platform } from 'node:os';
5
+ import { createHash } from 'node:crypto';
6
+ import { chmodSync, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
7
+ import { dirname, join, resolve, sep } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import https from 'node:https';
10
+ import process from 'node:process';
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = dirname(__filename);
14
+
15
+ const REPO_BASE = '{{{repository.baseUrl}}}';
16
+ const PACKAGE_ROOT = resolve(__dirname, '..');
17
+ const VERSION = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8')).version;
18
+ const RELEASE_BASE = `${REPO_BASE}/releases/download/v${VERSION}`;
19
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
20
+ const MAX_REDIRECTS = 10;
21
+ /** Connecting and every silence while transferring. */
22
+ const IDLE_TIMEOUT_MS = 30_000;
23
+ /** The whole transfer of one file, redirects included. */
24
+ const DEADLINE_MS = 15 * 60_000;
25
+ const MAX_CHECKSUMS_BYTES = 1024 * 1024;
26
+ const BINARY_MAP = new Map([
27
+ {{#each binary.targets}}
28
+ ['{{nodeKey}}', '{{name}}'],
29
+ {{/each}}
30
+ ]);
31
+
32
+ /**
33
+ * npm, pnpm, Yarn and Bun place every installed package, local or global, inside a
34
+ * node_modules directory. Outside one, this is the project's own checkout (development
35
+ * or a release build), whose binaries the project builds itself and whose version is
36
+ * not released yet.
37
+ */
38
+ function isInstalledAsDependency() {
39
+ return PACKAGE_ROOT.split(sep).includes('node_modules');
40
+ }
41
+
42
+ function getBinaryInfo() {
43
+ const key = `${platform()}:${arch()}`;
44
+ const binaryName = BINARY_MAP.get(key);
45
+ if (!binaryName) {
46
+ return { supported: false, key, platform: platform(), arch: arch() };
47
+ }
48
+ return { supported: true, key, binaryName, platform: platform(), arch: arch() };
49
+ }
50
+
51
+ /**
52
+ * GETs an HTTPS URL, following redirects, and passes the 200 response to `consume`. Fails on any other
53
+ * status, a non-HTTPS redirect, more than MAX_REDIRECTS hops, IDLE_TIMEOUT_MS of silence or DEADLINE_MS overall.
54
+ */
55
+ function fetchHttps(url, consume) {
56
+ return new Promise((resolvePromise, rejectPromise) => {
57
+ const chain = [];
58
+ let request;
59
+ let settled = false;
60
+ const finish = (error, value) => {
61
+ if (settled) return;
62
+ settled = true;
63
+ clearTimeout(deadline);
64
+ if (error) {
65
+ request?.destroy();
66
+ rejectPromise(error);
67
+ } else {
68
+ resolvePromise(value);
69
+ }
70
+ };
71
+ const deadline = setTimeout(
72
+ () => finish(new Error(`no complete answer within ${DEADLINE_MS / 60_000} minutes from ${chain.join(' -> ')}`)),
73
+ DEADLINE_MS,
74
+ );
75
+ const get = (target) => {
76
+ chain.push(target);
77
+ if (chain.length > MAX_REDIRECTS + 1) {
78
+ finish(new Error(`more than ${MAX_REDIRECTS} redirects: ${chain.join(' -> ')}`));
79
+ return;
80
+ }
81
+ if (new URL(target).protocol !== 'https:') {
82
+ finish(new Error(`refusing a non-HTTPS URL: ${chain.join(' -> ')}`));
83
+ return;
84
+ }
85
+ const current = https.get(target, { timeout: IDLE_TIMEOUT_MS }, (response) => {
86
+ const location = response.headers.location;
87
+ if (REDIRECT_STATUSES.has(response.statusCode) && location) {
88
+ response.resume();
89
+ let next;
90
+ try {
91
+ next = new URL(location, target).href;
92
+ } catch {
93
+ finish(new Error(`invalid redirect location ${JSON.stringify(location)} from ${target}`));
94
+ return;
95
+ }
96
+ get(next);
97
+ return;
98
+ }
99
+ if (response.statusCode !== 200) {
100
+ response.resume();
101
+ finish(new Error(`HTTP ${response.statusCode} ${response.statusMessage ?? ''}`.trim() + ` from ${target}`));
102
+ return;
103
+ }
104
+ consume(response).then((value) => finish(undefined, value), (error) => finish(error));
105
+ });
106
+ request = current;
107
+ current.on('timeout', () => {
108
+ current.destroy(new Error(`no data for ${IDLE_TIMEOUT_MS / 1000} s from ${target}`));
109
+ });
110
+ // A redirect's finished request no longer decides the outcome.
111
+ current.on('error', (error) => {
112
+ if (request === current) finish(error);
113
+ });
114
+ };
115
+ get(url);
116
+ });
117
+ }
118
+
119
+ /** The SHA-256 SHA256SUMS.txt of the release lists for `name`. */
120
+ async function expectedDigest(name) {
121
+ const sums = await fetchHttps(`${RELEASE_BASE}/SHA256SUMS.txt`, async (response) => {
122
+ let text = '';
123
+ for await (const chunk of response) {
124
+ text += chunk;
125
+ if (text.length > MAX_CHECKSUMS_BYTES) throw new Error('SHA256SUMS.txt exceeds 1 MiB');
126
+ }
127
+ return text;
128
+ });
129
+ for (const line of sums.split(/\r?\n/)) {
130
+ const match = /^([0-9a-fA-F]{64})\s+\*?(.+?)\s*$/.exec(line);
131
+ if (match && match[2] === name) return match[1].toLowerCase();
132
+ }
133
+ throw new Error(`SHA256SUMS.txt of v${VERSION} has no entry for ${name}`);
134
+ }
135
+
136
+ /** Downloads `url` next to `destination`, verifies its SHA-256 and only then moves it into place. */
137
+ async function downloadVerified(url, destination, digest) {
138
+ const partial = `${destination}.download-${process.pid}`;
139
+ try {
140
+ const actual = await fetchHttps(url, (response) => new Promise((resolveDigest, rejectDigest) => {
141
+ const hash = createHash('sha256');
142
+ const file = createWriteStream(partial, { mode: 0o600 });
143
+ response.on('data', (chunk) => hash.update(chunk));
144
+ response.on('error', rejectDigest);
145
+ file.on('error', rejectDigest);
146
+ file.on('finish', () => resolveDigest(hash.digest('hex')));
147
+ response.pipe(file);
148
+ }));
149
+ if (actual !== digest) {
150
+ throw new Error(`checksum mismatch: SHA256SUMS.txt lists ${digest}, the download is ${actual}`);
151
+ }
152
+ renameSync(partial, destination);
153
+ } finally {
154
+ rmSync(partial, { force: true });
155
+ }
156
+ }
157
+
158
+ async function main() {
159
+ if (!isInstalledAsDependency()) {
160
+ console.log('{{displayName}}: skipping the binary download in the project\'s own install (not inside node_modules).');
161
+ return;
162
+ }
163
+
164
+ console.log('===========================================');
165
+ console.log(' {{displayName}} - Binary Installation');
166
+ console.log('===========================================');
167
+ console.log('');
168
+
169
+ const binaryInfo = getBinaryInfo();
170
+ if (!binaryInfo.supported) {
171
+ console.error(`Error: Unsupported platform/architecture: ${binaryInfo.platform}/${binaryInfo.arch}`);
172
+ console.error('Supported platforms: {{binary.supportedPlatformText}}');
173
+ process.exit(1);
174
+ }
175
+
176
+ const binariesDir = join(__dirname, '..', '{{{npmWrapper.binariesDir}}}');
177
+ if (!existsSync(binariesDir)) {
178
+ mkdirSync(binariesDir, { recursive: true });
179
+ }
180
+
181
+ const binaryPath = join(binariesDir, binaryInfo.binaryName);
182
+ if (existsSync(binaryPath)) {
183
+ console.log('Binary already exists, skipping download');
184
+ } else {
185
+ const releaseUrl = `${RELEASE_BASE}/${binaryInfo.binaryName}`;
186
+ let failedUrl = `${RELEASE_BASE}/SHA256SUMS.txt`;
187
+ try {
188
+ const digest = await expectedDigest(binaryInfo.binaryName);
189
+ failedUrl = releaseUrl;
190
+ console.log(`Downloading from: ${releaseUrl}`);
191
+ await downloadVerified(releaseUrl, binaryPath, digest);
192
+ } catch (error) {
193
+ console.error(`Error: Failed to install the {{displayName}} ${VERSION} binary for ${binaryInfo.key}`);
194
+ console.error(` URL: ${failedUrl}`);
195
+ console.error(` Cause: ${error.message}`);
196
+ process.exit(1);
197
+ }
198
+ console.log(`Checksum verified: ${binaryInfo.binaryName}`);
199
+ }
200
+
201
+ if (binaryInfo.platform !== 'win32') {
202
+ chmodSync(binaryPath, 0o755);
203
+ }
204
+
205
+ console.log('{{displayName}} installation completed successfully.');
206
+ }
207
+
208
+ main().catch((error) => {
209
+ console.error(`Installation failed: ${error.message}`);
210
+ process.exit(1);
211
+ });