Files
New-CrossSound-Computer/scripts/prefetch-electron.js
2026-10-11 07:55:36 -07:00

190 lines
8.4 KiB
JavaScript
Executable File

#!/usr/bin/env node
'use strict'
// Download the Electron binary BEFORE electron-forge starts, so the download is
// actually VISIBLE.
//
// Why: forge runs packaging under a listr2 spinner UI that owns the terminal.
// @electron/get's own progress bar (a) only appears after a 30 second delay and
// (b) is immediately wiped by the spinner's next frame — so pulling the ~130 MB
// castLabs +wvcus Electron looks like the build froze on "Packaging application"
// for several minutes with no output at all. Downloading it here fills
// @electron/get's cache (keyed on the download URL, so forge finds the exact same
// file) and forge's own download step becomes a no-op.
//
// Usage: node scripts/prefetch-electron.js [darwin|win32|linux] [--arch=arm64|x64|universal]
// (defaults: host platform + host arch, matching electron-packager)
// Never fails the build: a broken prefetch just falls through to forge, which
// downloads the file itself (silently, as before).
const path = require('path')
// Silence @electron/get's own delayed progress bar so it can't fight with ours.
// GotDownloader only skips it when quiet is set AND this env var is present.
process.env.ELECTRON_GET_NO_PROGRESS = '1'
const PLATFORMS = ['win32', 'darwin', 'linux']
const argv = process.argv.slice(2)
const platform = argv.find((a) => !a.startsWith('-')) || process.platform
if (!PLATFORMS.includes(platform)) {
console.error(`prefetch-electron: unknown platform "${platform}" — expected one of ${PLATFORMS.join(', ')}`)
process.exit(1)
}
// electron-packager defaults to the HOST arch when --arch isn't given, so match
// that. `universal` (macOS) is stitched from a real x64 + arm64 build, so both
// zips have to be on disk.
const archArg = (argv.find((a) => a.startsWith('--arch=')) || '').slice('--arch='.length) || process.env.CS_ARCH || ''
const archs = archArg === 'universal'
? ['x64', 'arm64']
: (archArg || process.arch).split(',').map((a) => a.trim()).filter(Boolean)
function humanBytes(n) {
if (!n && n !== 0) return '?'
const mb = n / 1024 / 1024
return mb >= 1024 ? `${(mb / 1024).toFixed(2)} GB` : `${mb.toFixed(1)} MB`
}
function humanTime(seconds) {
if (!isFinite(seconds) || seconds < 0) return '--:--'
const m = Math.floor(seconds / 60)
const s = Math.floor(seconds % 60)
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
}
// A single self-rewriting line on a TTY; plain 10%-step lines when the output is
// a log file or CI (where \r just produces one giant unreadable line).
function makeReporter(label) {
const tty = Boolean(process.stdout.isTTY)
const start = Date.now()
let lastPaint = 0
let lastStep = -1
let sawAnyProgress = false
const paint = (transferred, total, percent, final) => {
const elapsed = (Date.now() - start) / 1000
const speed = elapsed > 0 ? transferred / elapsed : 0
const eta = speed > 0 && total ? (total - transferred) / speed : Infinity
const pct = Math.round((percent || 0) * 100)
if (tty) {
const width = 28
const filled = Math.min(width, Math.round((width * pct) / 100))
const bar = `${'█'.repeat(filled)}${'░'.repeat(width - filled)}`
const line = ` ${bar} ${String(pct).padStart(3)}% ${humanBytes(transferred)} / ${humanBytes(total)} ${humanBytes(speed)}/s ETA ${humanTime(eta)}`
// Pad to clear leftovers from a previous, longer frame.
process.stdout.write(`\r${line.padEnd(90)}`)
if (final) process.stdout.write('\n')
} else {
const step = Math.floor(pct / 10)
if (final || step > lastStep) {
lastStep = step
console.log(` [prefetch] ${label}: ${pct}% (${humanBytes(transferred)} / ${humanBytes(total)}, ${humanBytes(speed)}/s)`)
}
}
}
return {
get sawAnyProgress() {
return sawAnyProgress
},
onProgress(progress) {
const total = progress.total || 0
const transferred = progress.transferred || 0
// The checksum file (SHASUMS256.txt) comes through this same callback — and
// on a cache HIT it's the ONLY thing that downloads. It's a couple of KB, so
// anything under a megabyte is not the Electron zip: ignore it, both to keep
// the bar clean and so a cache hit still reports as "already cached".
// (Guard on transferred too, in case the server sends no content-length.)
if (total ? total < 1024 * 1024 : transferred < 1024 * 1024) return
sawAnyProgress = true
const now = Date.now()
if (now - lastPaint < 120 && (progress.percent || 0) < 1) return
lastPaint = now
paint(transferred, total, progress.percent || 0, false)
},
finish(bytes) {
if (!sawAnyProgress) return
paint(bytes, bytes, 1, true)
},
}
}
// Absolute path of the artifact if it's already sitting in @electron/get's cache,
// else null — resolved WITHOUT touching the network.
// The cache directory is a sha256 of the download URL, so the only honest way to
// find it is to build the URL exactly the way @electron/get does. These two
// modules are internal (no public "is it cached?" API), hence the try/catch: if a
// future @electron/get moves them we just return null and fall back to
// downloadArtifact, which cache-hits anyway — one wasted checksum request, not a
// broken build.
async function findInCache(details) {
try {
const artifactUtils = require('@electron/get/dist/cjs/artifact-utils')
const { Cache } = require('@electron/get/dist/cjs/Cache')
// downloadArtifact() normalizes the version (adds the leading `v`) BEFORE it
// derives the file name, so do the same or the name won't match.
const normalized = { ...details, version: artifactUtils.getArtifactVersion(details) }
const url = await artifactUtils.getArtifactRemoteURL(normalized)
return await new Cache(details.cacheRoot).getPathForFileInCache(url, artifactUtils.getArtifactFileName(normalized))
} catch (e) {
return null
}
}
async function main() {
const { downloadArtifact } = require('@electron/get')
const { version } = require('electron/package.json')
// Single source of truth for the castLabs mirror — forge.config.js. Using the
// same options guarantees the same download URL, which is what @electron/get
// hashes into the cache directory name, so forge gets a cache HIT.
const forgeConfig = require(path.resolve(__dirname, '..', 'forge.config.js'))
const download = (forgeConfig.packagerConfig && forgeConfig.packagerConfig.download) || {}
for (const arch of archs) {
const details = { ...download, version, platform, arch, artifactName: 'electron' }
const fileName = `electron-v${version}-${platform}-${arch}.zip`
console.log(`[prefetch] Electron ${version} — ${platform}/${arch}`)
// Already downloaded? Then do NOTHING — no network at all. Worth the extra
// probe because downloadArtifact() re-fetches SHASUMS256.txt even on a cache
// hit (it's deliberately never cached), so without this every mac/win build
// would still make a network round trip — and stall on a flaky or offline
// connection — just to be told the zip is already there. Skipping that check
// loses nothing: forge runs the same validated download right after us and
// would catch a corrupt cached zip itself.
const cached = await findInCache(details)
if (cached) {
console.log(`[prefetch] ${path.basename(cached)} already cached (${humanBytes(require('fs').statSync(cached).size)}) — nothing to do`)
continue
}
const reporter = makeReporter(fileName)
const startedAt = Date.now()
const zipPath = await downloadArtifact({
...details,
downloadOptions: {
...(download.downloadOptions || {}),
quiet: true,
getProgressCallback: (progress) => reporter.onProgress(progress),
},
})
const bytes = require('fs').statSync(zipPath).size
reporter.finish(bytes)
if (reporter.sawAnyProgress) {
console.log(`[prefetch] downloaded ${fileName} (${humanBytes(bytes)}) in ${humanTime((Date.now() - startedAt) / 1000)} → ${zipPath}`)
} else {
console.log(`[prefetch] ${fileName} already cached (${humanBytes(bytes)}) — skipping download`)
}
}
console.log('[prefetch] Electron ready — handing over to electron-forge\n')
}
main().catch((err) => {
// A prefetch failure must never break packaging: forge will just download the
// binary itself the old (silent) way, or fail with its own clearer error.
console.warn(`[prefetch] skipped: ${(err && err.message) || err}`)
})