|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +// Postinstall script for the `bt` CLI binary. |
| 4 | +// |
| 5 | +// The native binary ships in a per-platform `@braintrust/bt-*` package listed |
| 6 | +// in `optionalDependencies`; npm/pnpm install only the one matching the host. |
| 7 | +// If a package manager is run with `--no-optional`, `--ignore-optional`, or |
| 8 | +// `--omit=optional`, none of those packages get installed and `bt` would be |
| 9 | +// unusable. As a workaround, we manually fetch the matching tarball from the |
| 10 | +// npm registry and extract the binary so the launcher can find it. |
| 11 | + |
| 12 | +const fs = require("node:fs"); |
| 13 | +const https = require("node:https"); |
| 14 | +const path = require("node:path"); |
| 15 | +const zlib = require("node:zlib"); |
| 16 | + |
| 17 | +const helper = require("./bt-helper"); |
| 18 | +const pkg = require("../package.json"); |
| 19 | + |
| 20 | +if (process.env.BT_SKIP_DOWNLOAD === "1") { |
| 21 | + console.log( |
| 22 | + "bt: skipping post-install binary download because BT_SKIP_DOWNLOAD=1 is set.", |
| 23 | + ); |
| 24 | + process.exit(0); |
| 25 | +} |
| 26 | + |
| 27 | +const { packageName, subpath } = helper.getDistributionForThisPlatform(); |
| 28 | + |
| 29 | +if (packageName === undefined) { |
| 30 | + // Don't fail the install; the launcher will surface the unsupported-platform |
| 31 | + // error if/when the user actually tries to run `bt`. |
| 32 | + console.error( |
| 33 | + `bt: no prebuilt binary available for ${process.platform}-${process.arch}; the bt CLI will not be available.`, |
| 34 | + ); |
| 35 | + process.exit(0); |
| 36 | +} |
| 37 | + |
| 38 | +try { |
| 39 | + require.resolve(`${packageName}/${subpath}`); |
| 40 | + // Optional dependency was installed successfully. Nothing to do. |
| 41 | + process.exit(0); |
| 42 | +} catch (e) { |
| 43 | + // Fall through to the manual download path below. |
| 44 | + console.log( |
| 45 | + `bt: failed to locate the "${packageName}" package after installation. |
| 46 | +
|
| 47 | +This can happen if you use an option to disable optional dependencies during installation, like "--no-optional", "--ignore-optional", or "--omit=optional". The "braintrust" package uses the "optionalDependencies" package.json feature to install the correct bt binary for your platform and operating system. This post-install script will now try to work around that by manually downloading the bt binary from the npm registry. If this fails, you need to remove the "--no-optional", "--ignore-optional", and "--omit=optional" flags for bt to work.`, |
| 48 | + ); |
| 49 | +} |
| 50 | + |
| 51 | +const version = (pkg.optionalDependencies || {})[packageName]; |
| 52 | +if (!version) { |
| 53 | + // Don't fail the parent install: the SDK works without `bt`, and the |
| 54 | + // launcher errors clearly if it's actually invoked. |
| 55 | + console.error( |
| 56 | + `bt: cannot determine which version of "${packageName}" to download — it is not listed in the "braintrust" package's optionalDependencies. The bt CLI will not be available; the rest of the braintrust SDK is unaffected.`, |
| 57 | + ); |
| 58 | + process.exit(0); |
| 59 | +} |
| 60 | + |
| 61 | +function fetchBuffer(url, redirectsRemaining = 5) { |
| 62 | + return new Promise((resolve, reject) => { |
| 63 | + https |
| 64 | + .get(url, (response) => { |
| 65 | + const { statusCode = 0, headers } = response; |
| 66 | + if (statusCode >= 200 && statusCode < 300) { |
| 67 | + const chunks = []; |
| 68 | + response.on("data", (chunk) => chunks.push(chunk)); |
| 69 | + response.on("end", () => resolve(Buffer.concat(chunks))); |
| 70 | + response.on("error", reject); |
| 71 | + return; |
| 72 | + } |
| 73 | + if ( |
| 74 | + statusCode >= 300 && |
| 75 | + statusCode < 400 && |
| 76 | + headers.location && |
| 77 | + redirectsRemaining > 0 |
| 78 | + ) { |
| 79 | + response.resume(); |
| 80 | + fetchBuffer(headers.location, redirectsRemaining - 1).then( |
| 81 | + resolve, |
| 82 | + reject, |
| 83 | + ); |
| 84 | + return; |
| 85 | + } |
| 86 | + response.resume(); |
| 87 | + reject( |
| 88 | + new Error( |
| 89 | + `npm registry responded with status code ${statusCode} when downloading ${url}`, |
| 90 | + ), |
| 91 | + ); |
| 92 | + }) |
| 93 | + .on("error", reject); |
| 94 | + }); |
| 95 | +} |
| 96 | + |
| 97 | +// Extracts a single file from an uncompressed tar archive. Tar archives are |
| 98 | +// organized in 512-byte blocks: a header block (file name in bytes 0-99, |
| 99 | +// file size in bytes 124-135 as an octal string) followed by data blocks |
| 100 | +// padded out to the next multiple of 512. |
| 101 | +function extractFileFromTarball(tarball, target) { |
| 102 | + let offset = 0; |
| 103 | + while (offset + 512 <= tarball.length) { |
| 104 | + const header = tarball.subarray(offset, offset + 512); |
| 105 | + offset += 512; |
| 106 | + const fileName = header.toString("utf-8", 0, 100).replace(/\0.*/g, ""); |
| 107 | + if (!fileName) break; |
| 108 | + const fileSize = parseInt( |
| 109 | + header.toString("utf-8", 124, 136).replace(/\0.*/g, ""), |
| 110 | + 8, |
| 111 | + ); |
| 112 | + if (fileName === target) { |
| 113 | + return tarball.subarray(offset, offset + fileSize); |
| 114 | + } |
| 115 | + offset = (offset + fileSize + 511) & ~511; |
| 116 | + } |
| 117 | + return null; |
| 118 | +} |
| 119 | + |
| 120 | +async function downloadFallback() { |
| 121 | + // npm tarball URLs look like: |
| 122 | + // https://registry.npmjs.org/<scope>/<name>/-/<name>-<version>.tgz |
| 123 | + // where <name> is the unscoped package name. |
| 124 | + const tarballName = packageName.split("/").pop(); |
| 125 | + const url = `https://registry.npmjs.org/${packageName}/-/${tarballName}-${version}.tgz`; |
| 126 | + console.log(`bt: downloading ${packageName}@${version} from ${url}`); |
| 127 | + |
| 128 | + const gzipped = await fetchBuffer(url); |
| 129 | + const tarball = zlib.gunzipSync(gzipped); |
| 130 | + const binary = extractFileFromTarball(tarball, `package/${subpath}`); |
| 131 | + |
| 132 | + if (!binary) { |
| 133 | + throw new Error( |
| 134 | + `could not find "package/${subpath}" inside ${packageName}@${version} tarball`, |
| 135 | + ); |
| 136 | + } |
| 137 | + |
| 138 | + const fallbackBinaryPath = helper.getFallbackBinaryPath(); |
| 139 | + fs.mkdirSync(path.dirname(fallbackBinaryPath), { recursive: true }); |
| 140 | + fs.writeFileSync(fallbackBinaryPath, binary); |
| 141 | + fs.chmodSync(fallbackBinaryPath, 0o755); |
| 142 | + console.log(`bt: installed fallback binary at ${fallbackBinaryPath}`); |
| 143 | +} |
| 144 | + |
| 145 | +downloadFallback().catch((err) => { |
| 146 | + // Don't fail the parent install: airgapped/proxied CI may not reach the |
| 147 | + // npm registry, and the SDK works without `bt`. |
| 148 | + console.error( |
| 149 | + `bt: failed to download fallback binary for ${packageName}@${version}: ${err.message} |
| 150 | +The bt CLI will not be available; the rest of the braintrust SDK is unaffected.`, |
| 151 | + ); |
| 152 | + process.exit(0); |
| 153 | +}); |
0 commit comments