|
| 1 | +import { pkgAndBinForCurrentPlatform } from './node-platform'; |
| 2 | + |
| 3 | +import fs = require('fs'); |
| 4 | +import os = require('os'); |
| 5 | +import path = require('path'); |
| 6 | +import child_process = require('child_process'); |
| 7 | + |
| 8 | +declare const ESBUILD_VERSION: string; |
| 9 | +const toPath = path.join(__dirname, 'bin', 'esbuild'); |
| 10 | + |
| 11 | +function validateBinaryVersion(binaryPath: string): void { |
| 12 | + const stdout = child_process.execFileSync(binaryPath, ['--version']).toString().trim(); |
| 13 | + if (stdout !== ESBUILD_VERSION) { |
| 14 | + throw new Error(`Expected ${JSON.stringify(ESBUILD_VERSION)} but got ${JSON.stringify(stdout)}`); |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +function isYarn2OrAbove(): boolean { |
| 19 | + const { npm_config_user_agent } = process.env; |
| 20 | + if (npm_config_user_agent) { |
| 21 | + const match = npm_config_user_agent.match(/yarn\/(\d+)/); |
| 22 | + if (match && match[1]) { |
| 23 | + return parseInt(match[1], 10) >= 2; |
| 24 | + } |
| 25 | + } |
| 26 | + return false; |
| 27 | +} |
| 28 | + |
| 29 | +// This package contains a "bin/esbuild" JavaScript file that finds and runs |
| 30 | +// the appropriate binary executable. However, this means that running the |
| 31 | +// "esbuild" command runs another instance of "node" which is way slower than |
| 32 | +// just running the binary executable directly. |
| 33 | +// |
| 34 | +// Here we optimize for this by replacing the JavaScript file with the binary |
| 35 | +// executable at install time. This optimization does not work on Windows |
| 36 | +// because on Windows the binary executable must be called "esbuild.exe" |
| 37 | +// instead of "esbuild". This also doesn't work with Yarn 2+ because the Yarn |
| 38 | +// developers don't think binary modules should be used. See this thread for |
| 39 | +// details: https://github.com/yarnpkg/berry/issues/882. This optimization also |
| 40 | +// doesn't apply when npm's "--ignore-scripts" flag is used since in that case |
| 41 | +// this install script will not be run. |
| 42 | +if (os.platform() !== 'win32' && !isYarn2OrAbove()) { |
| 43 | + const { bin } = pkgAndBinForCurrentPlatform(); |
| 44 | + try { |
| 45 | + fs.unlinkSync(toPath); |
| 46 | + fs.linkSync(bin, toPath); |
| 47 | + } catch (e) { |
| 48 | + // Ignore errors here since this optimization is optional |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// Verify that the binary is the correct version |
| 53 | +validateBinaryVersion(toPath); |
0 commit comments