import { readFile, writeFile, mkdir, mkdtemp, rename, rm, access } from 'node:fs/promises'; import { createWriteStream, createReadStream } from 'node:fs'; import { pipeline } from 'node:stream/promises'; import { Readable, Transform } from 'node:stream'; import { createHash } from 'node:crypto'; import { spawn, spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; import { createServer } from 'node:http'; // Node 24 can honor the user's existing proxy without exposing its credentials. if ((process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy || process.env.http_proxy) && process.allowedNodeEnvironmentFlags.has('--use-env-proxy') && !process.execArgv.includes('--use-env-proxy')) { const rerun = spawnSync(process.execPath, ['--use-env-proxy', fileURLToPath(import.meta.url)], { stdio: 'inherit', env: process.env }); process.exit(rerun.status ?? 1); } const root = path.dirname(fileURLToPath(import.meta.url)); const config = JSON.parse(await readFile(path.join(root, 'launch.json'), 'utf8')); const app = path.join(root, 'app'); const stamp = path.join(root, '.npmstart-ready.json'); const major = Number(process.versions.node.split('.')[0]); if (major < 22 || (major === 22 && Number(process.versions.node.split('.')[1]) < 12)) { console.error('Please install Node.js 22.12+ or 24 LTS first: https://nodejs.org/en/download'); process.exit(1); } if (!/^[\w.-]+\/[\w.-]+$/.test(config.repo) || !/^[a-f0-9]{40}$/.test(config.commit) || !/^[a-f0-9]{64}$/.test(config.sha256)) throw new Error('Invalid pinned source manifest.'); const exists = async value => { try { await access(value); return true; } catch { return false; } }; let child; let server; let stopping = false; for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { stopping = true; child?.kill(signal); if (server) server.close(() => process.exit(0)); else if (!child) process.exit(0); }); function run(command, args, cwd = app, env = {}) { return new Promise((resolve, reject) => { if (stopping) return reject(new Error('Stopped.')); // All command names and arguments come from the pinned manifest, never form input. child = spawn(command, args, { cwd, env: { ...process.env, ...env }, stdio: 'inherit', shell: process.platform === 'win32' }); child.on('error', reject); child.on('exit', (code, signal) => { child = undefined; if (stopping) { process.exitCode = 0; resolve(); } else if (code === 0) resolve(); else reject(new Error(command + ' exited with ' + (signal || code) + '. See the terminal output above.')); }); }); } console.log('\n' + config.name + ' · npmstart launch pack'); console.log('Official source: https://github.com/' + config.repo + '/tree/' + config.commit); console.log('First run downloads the pinned source and dependencies. No model API key is used.'); console.log('Your working copy is kept in app/. Existing files are never replaced.\n'); try { const npx = 'npx'; if (!await exists(app)) { const staging = await mkdtemp(path.join(root, '.npmstart-download-')); try { const archive = path.join(staging, 'source.tar.gz'); const destination = path.join(staging, 'app'); await mkdir(destination); const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 180000); try { const response = await fetch('https://codeload.github.com/' + config.repo + '/tar.gz/' + config.commit, { signal: controller.signal }); if (!response.ok || !response.body) throw new Error('Source download failed: HTTP ' + response.status); let total = 0; const bound = new Transform({ transform(chunk, encoding, callback) { total += chunk.length; callback(total > 512 * 1024 * 1024 ? new Error('Source archive exceeds 512 MiB.') : null, chunk); } }); await pipeline(Readable.fromWeb(response.body), bound, createWriteStream(archive)); } finally { clearTimeout(timeout); } const hash = createHash('sha256'); for await (const chunk of createReadStream(archive)) hash.update(chunk); if (hash.digest('hex') !== config.sha256) throw new Error('Source checksum mismatch. The download was not extracted. Get a fresh verified pack from npmstart.com.'); await run('tar', ['-xzf', archive, '--strip-components=1', '-C', destination], root); await rename(destination, app); } finally { await rm(staging, { recursive: true, force: true }); } } const previous = await exists(stamp) ? JSON.parse(await readFile(stamp, 'utf8')) : null; if (previous && previous.commit !== config.commit) throw new Error('The app folder belongs to another source revision. Keep your changes and extract this pack into a new folder.'); if (!previous || previous.nodeMajor !== major || !await exists(path.join(app, 'node_modules'))) { console.log('Installing the original pinned toolchain and dependencies…'); await run(npx, ['--yes', config.manager, ...config.install], app, config.env); for (const args of config.prepare || []) await run(npx, ['--yes', config.manager, ...args], app, config.env); await writeFile(stamp, JSON.stringify({ commit: config.commit, nodeMajor: major })); } if (!stopping) { console.log('\nOpen: ' + config.localUrl + '\nStop: Ctrl+C\n'); if (config.serve) { const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.woff2': 'font/woff2', '.wasm': 'application/wasm' }; server = createServer(async (request, response) => { try { if (!['GET', 'HEAD'].includes(request.method)) { response.writeHead(405); response.end(); return; } const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); const parts = pathname.split('/'); if (parts.some(part => part === '..' || part.startsWith('.')) || pathname.includes('\\') || pathname.includes('\0')) throw new Error('Invalid path'); const filename = path.join(app, pathname.endsWith('/') ? pathname + 'index.html' : pathname); if (!filename.startsWith(app + path.sep)) throw new Error('Invalid path'); await access(filename); response.writeHead(200, { 'Content-Type': mime[path.extname(filename)] || 'application/octet-stream', 'X-Content-Type-Options': 'nosniff' }); if (request.method === 'HEAD') response.end(); else createReadStream(filename).on('error', () => response.destroy()).pipe(response); } catch { response.writeHead(404); response.end('Not found'); } }); server.on('error', error => { console.error('Local server could not start: ' + error.message); process.exitCode = 1; }); server.listen(config.serve.port, '127.0.0.1'); } else await run(npx, ['--yes', config.manager, ...config.start], app, config.env); } } catch (error) { console.error('\nStartup did not complete: ' + error.message); console.error('Check Node.js, GitHub/npm connectivity, available disk space and the original error above.'); console.error('A system tar command is required. On Windows, use a current Windows 10/11 terminal.'); console.error('If you use an HTTP proxy, on Node 24 you can try NODE_USE_ENV_PROXY=1 (set it in your terminal).'); console.error('Help: https://npmstart.com/projects/' + config.id); process.exitCode = 1; }