CoolFace
Apppublic

Ejdjdososs/fable-ai

sourceHugging Facemitupdated 3mo agoView on Hugging Face
0likes
install.js286 linesDownload Raw Back to esbuild
1"use strict";2var __create = Object.create;3var __defProp = Object.defineProperty;4var __getOwnPropDesc = Object.getOwnPropertyDescriptor;5var __getOwnPropNames = Object.getOwnPropertyNames;6var __getProtoOf = Object.getPrototypeOf;7var __hasOwnProp = Object.prototype.hasOwnProperty;8var __copyProps = (to, from, except, desc) => {9  if (from && typeof from === "object" || typeof from === "function") {10    for (let key of __getOwnPropNames(from))11      if (!__hasOwnProp.call(to, key) && key !== except)12        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });13  }14  return to;15};16var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(17  // If the importer is in node compatibility mode or this is not an ESM18  // file that has been converted to a CommonJS file using a Babel-19  // compatible transform (i.e. "__esModule" has not been set), then set20  // "default" to the CommonJS "module.exports" for node compatibility.21  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,22  mod23));24 25// lib/npm/node-platform.ts26var fs = require("fs");27var os = require("os");28var path = require("path");29var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;30var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";31var knownWindowsPackages = {32  "win32 arm64 LE": "@esbuild/win32-arm64",33  "win32 ia32 LE": "@esbuild/win32-ia32",34  "win32 x64 LE": "@esbuild/win32-x64"35};36var knownUnixlikePackages = {37  "aix ppc64 BE": "@esbuild/aix-ppc64",38  "android arm64 LE": "@esbuild/android-arm64",39  "darwin arm64 LE": "@esbuild/darwin-arm64",40  "darwin x64 LE": "@esbuild/darwin-x64",41  "freebsd arm64 LE": "@esbuild/freebsd-arm64",42  "freebsd x64 LE": "@esbuild/freebsd-x64",43  "linux arm LE": "@esbuild/linux-arm",44  "linux arm64 LE": "@esbuild/linux-arm64",45  "linux ia32 LE": "@esbuild/linux-ia32",46  "linux mips64el LE": "@esbuild/linux-mips64el",47  "linux ppc64 LE": "@esbuild/linux-ppc64",48  "linux riscv64 LE": "@esbuild/linux-riscv64",49  "linux s390x BE": "@esbuild/linux-s390x",50  "linux x64 LE": "@esbuild/linux-x64",51  "linux loong64 LE": "@esbuild/linux-loong64",52  "netbsd x64 LE": "@esbuild/netbsd-x64",53  "openbsd x64 LE": "@esbuild/openbsd-x64",54  "sunos x64 LE": "@esbuild/sunos-x64"55};56var knownWebAssemblyFallbackPackages = {57  "android arm LE": "@esbuild/android-arm",58  "android x64 LE": "@esbuild/android-x64"59};60function pkgAndSubpathForCurrentPlatform() {61  let pkg;62  let subpath;63  let isWASM = false;64  let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;65  if (platformKey in knownWindowsPackages) {66    pkg = knownWindowsPackages[platformKey];67    subpath = "esbuild.exe";68  } else if (platformKey in knownUnixlikePackages) {69    pkg = knownUnixlikePackages[platformKey];70    subpath = "bin/esbuild";71  } else if (platformKey in knownWebAssemblyFallbackPackages) {72    pkg = knownWebAssemblyFallbackPackages[platformKey];73    subpath = "bin/esbuild";74    isWASM = true;75  } else {76    throw new Error(`Unsupported platform: ${platformKey}`);77  }78  return { pkg, subpath, isWASM };79}80function downloadedBinPath(pkg, subpath) {81  const esbuildLibDir = path.dirname(require.resolve("esbuild"));82  return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);83}84 85// lib/npm/node-install.ts86var fs2 = require("fs");87var os2 = require("os");88var path2 = require("path");89var zlib = require("zlib");90var https = require("https");91var child_process = require("child_process");92var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;93var toPath = path2.join(__dirname, "bin", "esbuild");94var isToPathJS = true;95function validateBinaryVersion(...command) {96  command.push("--version");97  let stdout;98  try {99    stdout = child_process.execFileSync(command.shift(), command, {100      // Without this, this install script strangely crashes with the error101      // "EACCES: permission denied, write" but only on Ubuntu Linux when node is102      // installed from the Snap Store. This is not a problem when you download103      // the official version of node. The problem appears to be that stderr104      // (i.e. file descriptor 2) isn't writable?105      //106      // More info:107      // - https://snapcraft.io/ (what the Snap Store is)108      // - https://nodejs.org/dist/ (download the official version of node)109      // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035110      //111      stdio: "pipe"112    }).toString().trim();113  } catch (err) {114    if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {115      let os3 = "this version of macOS";116      try {117        os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();118      } catch {119      }120      throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.121 122The Go compiler (which esbuild relies on) no longer supports ${os3},123which means the "esbuild" binary executable can't be run. You can either:124 125  * Update your version of macOS to one that the Go compiler supports126  * Use the "esbuild-wasm" package instead of the "esbuild" package127  * Build esbuild yourself using an older version of the Go compiler128`);129    }130    throw err;131  }132  if (stdout !== versionFromPackageJSON) {133    throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);134  }135}136function isYarn() {137  const { npm_config_user_agent } = process.env;138  if (npm_config_user_agent) {139    return /\byarn\//.test(npm_config_user_agent);140  }141  return false;142}143function fetch(url) {144  return new Promise((resolve, reject) => {145    https.get(url, (res) => {146      if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)147        return fetch(res.headers.location).then(resolve, reject);148      if (res.statusCode !== 200)149        return reject(new Error(`Server responded with ${res.statusCode}`));150      let chunks = [];151      res.on("data", (chunk) => chunks.push(chunk));152      res.on("end", () => resolve(Buffer.concat(chunks)));153    }).on("error", reject);154  });155}156function extractFileFromTarGzip(buffer, subpath) {157  try {158    buffer = zlib.unzipSync(buffer);159  } catch (err) {160    throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);161  }162  let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");163  let offset = 0;164  subpath = `package/${subpath}`;165  while (offset < buffer.length) {166    let name = str(offset, 100);167    let size = parseInt(str(offset + 124, 12), 8);168    offset += 512;169    if (!isNaN(size)) {170      if (name === subpath) return buffer.subarray(offset, offset + size);171      offset += size + 511 & ~511;172    }173  }174  throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);175}176function installUsingNPM(pkg, subpath, binPath) {177  const env = { ...process.env, npm_config_global: void 0 };178  const esbuildLibDir = path2.dirname(require.resolve("esbuild"));179  const installDir = path2.join(esbuildLibDir, "npm-install");180  fs2.mkdirSync(installDir);181  try {182    fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");183    child_process.execSync(184      `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,185      { cwd: installDir, stdio: "pipe", env }186    );187    const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);188    fs2.renameSync(installedBinPath, binPath);189  } finally {190    try {191      removeRecursive(installDir);192    } catch {193    }194  }195}196function removeRecursive(dir) {197  for (const entry of fs2.readdirSync(dir)) {198    const entryPath = path2.join(dir, entry);199    let stats;200    try {201      stats = fs2.lstatSync(entryPath);202    } catch {203      continue;204    }205    if (stats.isDirectory()) removeRecursive(entryPath);206    else fs2.unlinkSync(entryPath);207  }208  fs2.rmdirSync(dir);209}210function applyManualBinaryPathOverride(overridePath) {211  const pathString = JSON.stringify(overridePath);212  fs2.writeFileSync(toPath, `#!/usr/bin/env node213require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });214`);215  const libMain = path2.join(__dirname, "lib", "main.js");216  const code = fs2.readFileSync(libMain, "utf8");217  fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};218${code}`);219}220function maybeOptimizePackage(binPath) {221  if (os2.platform() !== "win32" && !isYarn()) {222    const tempPath = path2.join(__dirname, "bin-esbuild");223    try {224      fs2.linkSync(binPath, tempPath);225      fs2.renameSync(tempPath, toPath);226      isToPathJS = false;227      fs2.unlinkSync(tempPath);228    } catch {229    }230  }231}232async function downloadDirectlyFromNPM(pkg, subpath, binPath) {233  const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;234  console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);235  try {236    fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));237    fs2.chmodSync(binPath, 493);238  } catch (e) {239    console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);240    throw e;241  }242}243async function checkAndPreparePackage() {244  if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {245    if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {246      console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);247    } else {248      applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);249      return;250    }251  }252  const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();253  let binPath;254  try {255    binPath = require.resolve(`${pkg}/${subpath}`);256  } catch (e) {257    console.error(`[esbuild] Failed to find package "${pkg}" on the file system258 259This can happen if you use the "--no-optional" flag. The "optionalDependencies"260package.json feature is used by esbuild to install the correct binary executable261for your current platform. This install script will now attempt to work around262this. If that fails, you need to remove the "--no-optional" flag to use esbuild.263`);264    binPath = downloadedBinPath(pkg, subpath);265    try {266      console.error(`[esbuild] Trying to install package "${pkg}" using npm`);267      installUsingNPM(pkg, subpath, binPath);268    } catch (e2) {269      console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);270      try {271        await downloadDirectlyFromNPM(pkg, subpath, binPath);272      } catch (e3) {273        throw new Error(`Failed to install package "${pkg}"`);274      }275    }276  }277  maybeOptimizePackage(binPath);278}279checkAndPreparePackage().then(() => {280  if (isToPathJS) {281    validateBinaryVersion(process.execPath, toPath);282  } else {283    validateBinaryVersion(toPath);284  }285});286