### Prebuildify Prebuilt File Examples Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuildify.md Provides examples of prebuilt binary filenames within the prebuilds directory, showing variations for different platforms, architectures, and Node-API support. ```plaintext sqlite3/prebuilds/linux-x64/ electron.abi91.node # Electron 91 electron.napi.node # Node-API variant sqlite3/prebuilds/linux-arm64/ electron.abi91.armv8.node # Electron 91 node.napi.armv8.node # Node-API variant sqlite3/prebuilds/darwin-arm64/ electron.napi.armv8.node # Electron on Apple Silicon ``` -------------------------------- ### CLI Command Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/configuration.md This is a basic example of how to invoke the electron-rebuild command-line tool. It demonstrates the general syntax for passing options. ```bash electron-rebuild [OPTIONS] ``` -------------------------------- ### NodePreGyp Usage Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Provides a practical example of how to use the NodePreGyp class. It demonstrates importing the class, creating an instance, checking if the tool is used, and attempting to find a prebuilt module. ```typescript import { NodePreGyp } from '@electron/rebuild'; const npmPreGyp = new NodePreGyp(rebuilder, '/app/node_modules/node-sqlite3'); if (await npmPreGyp.usesTool()) { const found = await npmPreGyp.findPrebuiltModule(); if (found) { console.log('Prebuilt installed via node-pre-gyp'); } } ``` -------------------------------- ### Install Build Dependencies for Node-gyp Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md If 'node-gyp failed to rebuild', ensure you have the necessary build tools installed. Refer to the node-gyp installation guide for specifics. ```bash Refer to https://github.com/nodejs/node-gyp#installation ``` -------------------------------- ### Prebuildify Directory Structure Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuildify.md Illustrates the expected directory structure for prebuildify prebuilt binaries within a module. ```plaintext {module}/ prebuilds/ {platform}-{nativeArch}/ electron.napi.{ext} # Node-API variant node.napi.{ext} # Node-API variant electron.abi{ABI}.{ext} # ABI-specific variant ``` -------------------------------- ### NodeAPI Usage Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-api.md Demonstrates how to use the NodeAPI class to check Electron's Node-API support, get its version, and find a compatible NAPI version for a native module. ```typescript import { NodeAPI } from '@electron/rebuild'; const api = new NodeAPI('sqlite3', '35.0.0'); // Ensure Electron supports Node-API at all api.ensureElectronSupport(); // Get Electron's NAPI version const electronNapi = api.getVersionForElectron(); console.log(`Electron 35 supports Node-API v${electronNapi}`); // Module supports NAPI 3, 4, 5 but Electron only supports up to 4 const compatible = api.getNapiVersion([3, 4, 5]); console.log(`Using Node-API v${compatible}`); // Outputs: 4 ``` -------------------------------- ### Install electron-rebuild Globally Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md Install the electron-rebuild package globally for command-line access from any directory. ```bash npm install -g @electron/rebuild ``` -------------------------------- ### Prebuilt Module Directory Structure Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Illustrates the expected directory structure for prebuilt modules, showing the placement of platform-specific binary files. ```plaintext {module}/ prebuilds/ {platform}-{arch}/ electron-{ABI}.node sqlite3/prebuilds/linux-x64/electron-91.node ``` -------------------------------- ### PrebuildInstall Usage Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Demonstrates how to instantiate and use the PrebuildInstall class to check if a module uses prebuild-install and attempt to find a prebuilt module. ```typescript import { PrebuildInstall } from '@electron/rebuild'; const installer = new PrebuildInstall(rebuilder, '/app/node_modules/sqlite3'); if (await installer.usesTool()) { const found = await installer.findPrebuiltModule(); console.log(`Prebuilt found: ${found}`); } ``` -------------------------------- ### Example Usage of locateElectronModule Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/electron-locator.md Shows how to import and use `locateElectronModule` to find the Electron path, read its package.json, and log the version. This example assumes `readPackageJson` is available. ```typescript import { locateElectronModule } from '@electron/rebuild'; const electronPath = await locateElectronModule( '/workspace', // projectRootPath process.cwd() // startDir ); if (electronPath) { const pkg = await readPackageJson(electronPath); console.log(`Found Electron v${pkg.version} at ${electronPath}`); } else { console.error('Electron not installed'); } ``` -------------------------------- ### Prebuildify Usage Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuildify.md Demonstrates how to instantiate and use the Prebuildify class to check for prebuilt modules in a project. ```typescript import { Prebuildify } from '@electron/rebuild'; const prebuildify = new Prebuildify(rebuilder, '/app/node_modules/sqlite3'); if (await prebuildify.usesTool()) { const found = await prebuildify.findPrebuiltModule(); if (found) { console.log('Found compatible prebuildify prebuilt'); } } ``` -------------------------------- ### Error Example: Electron No Node-API Support Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-api.md Example error message when the target Electron version does not support Node-API. ```text Native module 'sqlite3' requires Node-API but Electron v13.0.0 does not support Node-API ``` -------------------------------- ### findNodePreGypInstallModule() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Attempts to use node-pre-gyp to download a prebuilt binary. Returns true if the prebuilt was successfully installed. This method may write metadata and cache module state. ```APIDOC ## findNodePreGypInstallModule() ### Description Attempts to use node-pre-gyp to download a prebuilt binary. Returns true if the prebuilt was successfully installed. This method may write metadata and cache module state. ### Method ```typescript async findNodePreGypInstallModule(cacheKey: string): Promise ``` ### Parameters #### Path Parameters - **cacheKey** (string) - Required - Cache key for storing result ### Returns - `Promise` - `true` if prebuilt was successfully installed ``` -------------------------------- ### Install @electron/rebuild as a development dependency Source: https://github.com/electron/rebuild/blob/main/README.md Install the package as a dev dependency using npm. ```sh npm install --save-dev @electron/rebuild ``` -------------------------------- ### findPrebuildInstallModule() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Attempts to use prebuild-install to download a prebuilt binary. Returns true if the prebuilt was successfully installed. This method may write metadata and cache module state. ```APIDOC ## findPrebuildInstallModule() ### Description Attempts to use prebuild-install to download a prebuilt binary. Returns true if the prebuilt was successfully installed. This method may write metadata and cache module state. ### Method ```typescript async findPrebuildInstallModule(cacheKey: string): Promise ``` ### Parameters #### Path Parameters - **cacheKey** (string) - Required - Cache key for storing result ### Returns - `Promise` - `true` if prebuilt was successfully installed ``` -------------------------------- ### Error Example: No Compatible Node-API Version Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-api.md Example error message when no compatible Node-API version can be found between the module and Electron. ```text Native module 'sqlite3' supports Node-API versions 6, 7, 8 but Electron v14.0.0 only supports Node-API v5 ``` -------------------------------- ### NativeModule Usage Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/native-module.md Demonstrates how to instantiate and use the NativeModule class to retrieve module information like version, NAPI versions, and dependency presence. ```typescript const module = new NativeModule(rebuilder, '/app/node_modules/sqlite3'); const version = await module.packageJSONField('version'); const napiVersions = await module.getSupportedNapiVersions(); const hasNodePreGyp = await module.findPackageInDependencies('node-pre-gyp'); console.log(`Module: ${module.moduleName}`); console.log(`Version: ${version}`); console.log(`NAPI versions: ${napiVersions}`); console.log(`Uses node-pre-gyp: ${!!hasNodePreGyp}`); ``` -------------------------------- ### Install electron-rebuild Locally (Command Not Found) Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md If you receive a 'command not found' error, install electron-rebuild locally in your project. ```bash npm install @electron/rebuild ``` -------------------------------- ### Hash Tree Generation Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/cache.md Illustrates the structure of a recursive hash tree generated by the snapshot algorithm, showing files and their corresponding SHA256 hashes. ```typescript { "src/": { "module.cc": "sha256hash", "module.h": "sha256hash", "headers/": { "electron.h": "sha256hash" } }, "binding.gyp": "sha256hash" } ``` -------------------------------- ### Get Platform URL Prefix Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/clang-fetcher.md Determines the Chromium CDN URL prefix for downloading clang based on the host operating system and architecture. For example, it maps 'linux' and 'x64' to 'Linux_x64'. ```typescript function getPlatformUrlPrefix(hostOS: string, hostArch: string): string ``` -------------------------------- ### Locate Prebuild-Install Executable Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Asynchronously finds the absolute path to the prebuild-install executable script. It searches parent directories starting from the module path. ```typescript async locateBinary(): Promise ``` -------------------------------- ### Node-API Support Configuration Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Shows the JSON structure within a module's package.json that declares support for Node-API versions, enabling the use of the highest compatible NAPI version. ```json { "binary": { "napi_versions": [1, 2, 3] } } ``` -------------------------------- ### Example package.json Binary Field Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-gyp.md Illustrates the structure of the 'binary' field in package.json, used to configure native module build paths and names, including NAPI version compatibility. ```json { "binary": { "module_path": "./build/{configuration}", "module_name": "sqlite3", "napi_versions": [1, 2, 3] } } ``` -------------------------------- ### Install Electron to Resolve Version Error Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md If you encounter an 'Unable to find electron's version number' error, ensure Electron is installed in your project. ```bash npm install electron ``` -------------------------------- ### Usage Example: Rebuilding a Native Module Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Demonstrates how to instantiate and use the ModuleRebuilder to rebuild a native module. Ensure necessary imports and configuration are in place. ```typescript import { ModuleRebuilder } from '@electron/rebuild'; const rebuilder = new ModuleRebuilder(rebuilderConfig, '/app/node_modules/native-module'); const cacheKey = 'abc123def456'; const success = await rebuilder.rebuild(cacheKey); if (success) { console.log('Module rebuilt successfully'); } ``` -------------------------------- ### Rebuild with Lifecycle Event Handling Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/rebuild.md This example shows how to use the rebuild function with additional configuration options and how to listen to lifecycle events for detailed progress updates. It uses 'await' to wait for the rebuild to complete. ```typescript import { rebuild } from '@electron/rebuild'; // Listen to lifecycle events const rebuilder = rebuild({ buildPath: '/app', electronVersion: '35.1.5', arch: 'x64', force: true }); rebuilder.lifecycle.on('modules-found', (modules) => { console.log(`Building ${modules.length} modules: ${modules.join(', ')}`); }); rebuilder.lifecycle.on('module-done', (moduleName) => { console.log(`Finished: ${moduleName}`); }); await rebuilder; ``` -------------------------------- ### Execute Node-Pre-Gyp Command Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Executes the node-pre-gyp command with the provided path to the binary and specific flags for installation or updates. Supports fallback-to-build and architecture-specific updates. ```typescript async run(nodePreGypPath: string): Promise ``` -------------------------------- ### Rerun electron-rebuild after installing npm packages (Windows) Source: https://github.com/electron/rebuild/blob/main/README.md Execute the electron-rebuild command from your npm bin directory on Windows. ```sh .\node_modules\.bin\electron-rebuild.cmd ``` -------------------------------- ### uname() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/utilities.md Executes the `uname -m` command to get system architecture. Returns the trimmed output of `uname -m`. ```APIDOC ## uname() ### Description Executes the `uname -m` command to get system architecture. ### Returns - `string` - Trimmed output of `uname -m`. ### Examples - `x86_64` → returns `"x86_64"` - `aarch64` → returns `"aarch64"` - `armv7l` → returns `"armv7l"` ``` -------------------------------- ### Invoke electron-rebuild from Shell (Local) Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md Run the locally installed electron-rebuild executable directly from your project's shell. ```bash ./node_modules/.bin/electron-rebuild ``` -------------------------------- ### Get Clang Environment Variables Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/clang-fetcher.md Prepares environment variables and arguments for using Electron's clang compiler. Use this to set up your build environment before invoking node-gyp. ```typescript async function getClangEnvironmentVars( electronVersion: string, targetArch: string ): Promise<{ env: Record; args: string[] }> ``` ```typescript { CC: "/home/user/.electron-gyp/35.0.0-clang/bin/clang" --sysroot /path/to/sysroot, CXX: "/home/user/.electron-gyp/35.0.0-clang/bin/clang++" --sysroot /path/to/sysroot } ``` ```typescript import { getClangEnvironmentVars } from '@electron/rebuild'; const { env, args } = await getClangEnvironmentVars('35.0.0', 'x64'); // In node-gyp build: Object.assign(process.env, env); const nodeGypArgs = [...args, ...otherArgs]; ``` -------------------------------- ### getProjectRootPath() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/search-module.md Determines the root directory of a project by searching for common lock files (`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`) while traversing up the directory tree from a given starting point. If no lock file is found, it returns the starting directory. ```APIDOC ## getProjectRootPath() ### Description Determines the root directory of a project by searching for common lock files (`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`) while traversing up the directory tree from a given starting point. If no lock file is found, it returns the starting directory. ### Method ```typescript async function getProjectRootPath(cwd: string): Promise ``` ### Parameters #### Path Parameters - **cwd** (string) - Yes - Starting directory ### Returns `Promise` — Absolute path to project root ### Detection Strategy Searches for lock files in order: 1. `yarn.lock` (Yarn) 2. `package-lock.json` (npm) 3. `pnpm-lock.yaml` (pnpm) Searches up directory tree and returns the directory containing the first lock file found. If no lock file found, returns `cwd` unchanged. ### Example ```typescript // In /workspace/packages/app const root = await getProjectRootPath(process.cwd()); // Returns: /workspace (directory containing yarn.lock) // In standalone project const root = await getProjectRootPath('/myapp'); // Returns: /myapp (directory containing package-lock.json) ``` ``` -------------------------------- ### Markdown Structure for Configuration/Types Files Source: https://github.com/electron/rebuild/blob/main/_autodocs/STRUCTURE.md Shows the standard format for markdown files detailing configuration options or type definitions, including title, option/type name, definition, details, and examples. ```markdown # Title ## Option/Type Name ```typescript definition ``` ### Details | Name | Type | Required | Default | Description | ### Behavior ### Example ```typescript // Usage ``` ``` -------------------------------- ### Basic Auto-Detection Rebuild Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md Automatically detects the installed Electron version and rebuilds all native modules. This is the simplest way to use the tool. ```bash electron-rebuild ``` -------------------------------- ### locateBinary() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/utilities.md Walks up the directory tree to locate a binary or file relative to a starting path. Returns the absolute path if found, otherwise null. ```APIDOC ## locateBinary(basePath: string, suffix: string): Promise ### Description Walks up directory tree to locate a binary/file. ### Parameters - `basePath` (string) - Starting directory - `suffix` (string) - Relative path to search for ### Returns - `Promise` - Absolute path to found file, or `null` ### Behavior 1. Starts at `basePath` 2. Checks if `{basePath}/{suffix}` exists 3. If not, moves to parent directory 4. Repeats until found or reached filesystem root ### Example ```typescript // Find node_modules/node-gyp/bin/node-gyp relative to module const binPath = await locateBinary( '/app/node_modules/sqlite3', 'node_modules/node-gyp/bin/node-gyp' ); // Returns: '/app/node_modules/node-gyp/bin/node-gyp' ``` ``` -------------------------------- ### Get System Architecture Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/utilities.md Executes the `uname -m` command to retrieve the system architecture. Returns the trimmed output. ```typescript function uname(): string ``` -------------------------------- ### Rerun electron-rebuild after installing npm packages (macOS/Linux) Source: https://github.com/electron/rebuild/blob/main/README.md Execute the electron-rebuild command from your npm bin directory on macOS or Linux. ```sh $(npm bin)/electron-rebuild ``` -------------------------------- ### ModuleWalker Usage Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-walker.md Demonstrates how to instantiate and use the ModuleWalker class to find modules to rebuild. It initializes the walker, walks the modules, retrieves node_modules paths, and logs the modules to rebuild. ```typescript const walker = new ModuleWalker( '/app', '/app', // projectRootPath ['prod', 'optional'], new Set(), null // process all modules ); await walker.walkModules(); const nodeModulesPaths = await walker.nodeModulesPaths; for (const nodePath of nodeModulesPaths) { await walker.findAllModulesIn(nodePath); } console.log('Modules to rebuild:', walker.modulesToRebuild); ``` -------------------------------- ### Monorepo Support with getProjectRootPath Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/electron-locator.md Shows how `locateElectronModule` works in a monorepo context by first obtaining the project root path using `getProjectRootPath` and then passing it to `locateElectronModule` to find a shared Electron installation. ```typescript // In /workspace/packages/app const root = await getProjectRootPath(process.cwd()); // /workspace const electronPath = await locateElectronModule(root); // Finds shared Electron ``` -------------------------------- ### Get Clang Download URL Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/clang-fetcher.md Constructs the full download URL for a specific clang package. It combines the CDN prefix, package file name, version, and platform details. ```typescript function getClangDownloadURL( packageFile: string, packageVersion: string, hostOS: string, hostArch: string ): string ``` -------------------------------- ### CLI Integration for Electron Path Detection Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/electron-locator.md Illustrates how the CLI uses `locateElectronModule` to determine the Electron module path, falling back to a provided directory if necessary. It then imports the package.json to get the version. ```typescript // From src/cli.ts const electronModulePath = argv['electron-prebuilt-dir'] ? path.resolve(process.cwd(), argv['electron-prebuilt-dir']) : await locateElectronModule(projectRootPath); if (!electronModulePath) { throw new Error(`Unable to find electron's version number...`); } const pkg = await import(`file://${electronModulePath}/package.json`); electronVersion = pkg.default.version; ``` -------------------------------- ### Get Electron Node-API Version Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-api.md Retrieves the Node-API version number supported by the target Electron version. For example, returns 7 for Electron 31+. ```typescript getVersionForElectron(): number ``` -------------------------------- ### Markdown Structure for API Reference Files Source: https://github.com/electron/rebuild/blob/main/_autodocs/STRUCTURE.md Illustrates the expected format for API reference markdown files, including sections for title, description, class/function details, parameters, returns, behavior, properties/methods, examples, and source information. ```markdown # Title Short description. ## Class/Function Name ```typescript signature() ``` ### Parameters/Constructor Parameters | Name | Type | Required | Default | Description | ### Returns Type and description. ### Behavior/Process 1. Step by step 2. How it works 3. Error conditions ### Properties/Methods | Name | Type | Description | ### Examples ```typescript // Usage examples ``` ### Source - File: src/... - Lines: X–Y ``` -------------------------------- ### Determine Project Root Path Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/search-module.md Identifies the project's root directory by searching for common lock files (`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`) upwards from a given directory. If no lock file is found, it returns the starting directory. ```typescript async function getProjectRootPath(cwd: string): Promise ``` ```typescript // In /workspace/packages/app const root = await getProjectRootPath(process.cwd()); // Returns: /workspace (directory containing yarn.lock) // In standalone project const root = await getProjectRootPath('/myapp'); // Returns: /myapp (directory containing package-lock.json) ``` -------------------------------- ### Execute Prebuild-Install Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Executes the prebuild-install script with the provided path and appropriate configuration arguments for the target runtime (Node-API or Electron). ```typescript async run(prebuildInstallPath: string): Promise ``` -------------------------------- ### PrebuildInstall Class Methods Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md This section outlines the methods available on the PrebuildInstall class for managing prebuilt binaries. ```APIDOC ## Class: PrebuildInstall Manages prebuilt binary downloads using prebuild-install. ### Constructor ```typescript constructor(rebuilder: IRebuilder, modulePath: string) ``` Inherits from `NativeModule`. ### Methods #### usesTool() Checks if the module uses prebuild-install. ```typescript async usesTool(): Promise ``` **Returns:** `true` if `prebuild-install` is a dependency of the module #### findPrebuiltModule() Attempts to download and install a prebuilt binary using prebuild-install. ```typescript async findPrebuiltModule(): Promise ``` **Returns:** `true` if a prebuilt was successfully found and installed, `false` otherwise **Behavior:** 1. Locates the prebuild-install binary 2. Executes it via `run()` with appropriate arguments 3. Catches errors; rethrows if they relate to Node-API compatibility 4. Returns false if binary not found or execution fails **Throws:** Error if module requires Node-API but Electron version doesn't support it #### prebuiltModuleExists() Checks if a prebuild-install-generated binary exists on disk. ```typescript async prebuiltModuleExists(): Promise ``` **Returns:** `true` if binary exists at: ``` {modulePath}/prebuilds/{platform}-{arch}/electron-{ABI}.node ``` **Example path:** `/app/node_modules/sqlite3/prebuilds/linux-x64/electron-91.node` #### locateBinary() Finds the prebuild-install executable. ```typescript async locateBinary(): Promise ``` **Returns:** Absolute path to `node_modules/prebuild-install/bin.js` or `null` **Process:** 1. Checks if `prebuild-install` is a dependency 2. Uses `locateBinary()` utility to search parent directories for the binary 3. Starts from module path and walks up #### run() Executes prebuild-install with appropriate configuration. ```typescript async run(prebuildInstallPath: string): Promise ``` **Parameters:** - `prebuildInstallPath` — Absolute path to prebuild-install script **Executes:** ``` node {prebuild-shim.js} {prebuildInstallPath} --arch={arch} --platform={platform} --tag-prefix={prebuildTagPrefix} [--runtime=napi --target={napiVersion}] OR [--runtime=electron --target={electronVersion}] ``` **The prebuild-shim wrapper:** - Interacts with prebuild-install via its CLI - Passes Node-API or Electron runtime configuration based on module support - Captures exit codes and errors #### getPrebuildInstallRuntimeArgs() Determines runtime arguments for prebuild-install. ```typescript async getPrebuildInstallRuntimeArgs(): Promise ``` **Returns:** - If module supports Node-API: `['--runtime=napi', '--target={napiVersion}']` - Otherwise: `['--runtime=electron', '--target={electronVersion}']` **Process:** 1. Checks `binary.napi_versions` in module's package.json 2. Selects compatible NAPI version if present 3. Falls back to Electron runtime configuration ``` -------------------------------- ### Prebuilt Binary Handlers Source: https://github.com/electron/rebuild/blob/main/_autodocs/README.md Integrates with various tools for handling prebuilt binaries, including `prebuild-install`, `node-pre-gyp`, and `prebuildify`. ```APIDOC ## Prebuilt Binary Handlers ### Description This section details the components responsible for interacting with prebuilt binary packages for native Node.js modules. The tool prioritizes using prebuilt binaries to speed up the build process and reduce the need for compilation. ### Supported Handlers - **`PrebuildInstall`**: Integrates with the `prebuild-install` tool to download prebuilt binaries from GitHub releases. - **`NodePreGyp`**: Integrates with `node-pre-gyp`, a popular tool for managing prebuilt binaries, often used as a fallback to compilation. - **`Prebuildify`**: Supports modules that use `prebuildify` for distributing pre-compiled binaries, typically found in a `prebuilds/` directory within the module. ### Order of Preference The rebuild process attempts to use these handlers in a specific order, generally prioritizing `prebuildify`, then `prebuild-install`, followed by `node-pre-gyp`, and finally falling back to `node-gyp` compilation. ``` -------------------------------- ### Use Electron's Clang and Build from Source Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md Configure the build process to use Electron's bundled clang compiler and always build native modules from source, skipping prebuilt downloads. This ensures compatibility with Electron's specific toolchain. ```bash electron-rebuild --use-electron-clang --build-from-source ``` -------------------------------- ### Source Build with Clang Source: https://github.com/electron/rebuild/blob/main/_autodocs/configuration.md Configure a build from source using Clang by setting 'buildFromSource' and 'useElectronClang' to true. Specify the build path and Electron version. ```typescript await rebuild({ buildPath: '/app', electronVersion: '35.0.0', buildFromSource: true, useElectronClang: true }); ``` -------------------------------- ### replaceExistingNativeModule() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Copies the built .node file to a prebuilt binary location. It searches the build directory for .node files and, if found and `disablePreGypCopy` is not set, creates the necessary directory structure and copies the file. ```APIDOC ## replaceExistingNativeModule() ### Description Copies the built .node file to a prebuilt binary location. It searches the build directory for .node files and, if found and `disablePreGypCopy` is not set, creates the necessary directory structure and copies the file. ### Method ```typescript async replaceExistingNativeModule(): Promise ``` ### Returns - `Promise` ``` -------------------------------- ### ModuleRebuilder findNodePreGypInstallModule Method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Attempts to download a prebuilt binary using node-pre-gyp. Writes metadata and caches the module state if enabled. ```typescript async findNodePreGypInstallModule(cacheKey: string): Promise ``` -------------------------------- ### ModuleRebuilder findPrebuildInstallModule Method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Attempts to download a prebuilt binary using prebuild-install. Writes metadata and caches the module state if enabled. ```typescript async findPrebuildInstallModule(cacheKey: string): Promise ``` -------------------------------- ### Get Node Architecture Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuildify.md Resolves the module's configured architecture using Node.js configuration variables, handling ARM version differences. ```typescript const nodeArch = getNodeArch(arch, process.config.variables as ConfigVariables) ``` -------------------------------- ### Find Prebuilt Module Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuildify.md Asynchronously searches for and validates a compatible prebuilt binary for the module. Returns true if found, false otherwise. ```typescript async findPrebuiltModule(): Promise ``` -------------------------------- ### Check for Prebuilt Binary Existence Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Asynchronously checks if a prebuilt binary file, generated by prebuild-install, exists on the disk at the expected location. ```typescript async prebuiltModuleExists(): Promise ``` -------------------------------- ### Determine Prebuild-Install Runtime Arguments Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuild-install.md Asynchronously determines the correct runtime arguments for prebuild-install based on whether the module supports Node-API or relies on the Electron runtime. ```typescript async getPrebuildInstallRuntimeArgs(): Promise ``` -------------------------------- ### Fallback to Build Explanation Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Describes the fallback-to-build mechanism in node-pre-gyp, where it first attempts to download a prebuilt binary and then builds from source upon failure. This ensures compatibility with new Electron versions. ```plaintext With --fallback-to-build flag, node-pre-gyp will: 1. Attempt to download prebuilt binary 2. On failure, build from source This allows graceful degradation for newly released Electron versions without prebuilts. ``` -------------------------------- ### Locate Electron Module Function Signature Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/electron-locator.md This is the TypeScript signature for the `locateElectronModule` function. It can optionally accept a project root path and a starting directory for the search. ```typescript async function locateElectronModule( projectRootPath?: string | undefined, startDir?: string | undefined ): Promise ``` -------------------------------- ### prebuildInstallNativeModuleExists() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Checks if a prebuild-install-generated binary exists in the expected location. ```APIDOC ## prebuildInstallNativeModuleExists() ### Description Checks if a prebuild-install-generated binary exists in the expected location. ### Method ```typescript async prebuildInstallNativeModuleExists(): Promise ``` ### Returns - `Promise` - `true` if prebuilt binary found in expected location ``` -------------------------------- ### Get Supported NAPI Versions Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/native-module.md Extracts supported Node-API versions from the 'binary.napi_versions' field in the module's package.json. Returns an array of numbers or undefined. ```typescript async getSupportedNapiVersions(): Promise ``` -------------------------------- ### Find all node_modules Directories Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/search-module.md Locates all `node_modules` directories by traversing up the directory tree from a starting point. This is particularly useful for understanding the structure of monorepos with nested `node_modules`. ```typescript async function searchForNodeModules( cwd: string, rootPath?: string ): Promise ``` ```typescript const paths = await searchForNodeModules('/workspace/packages/app/src'); // May return: // [ // '/workspace/packages/app/node_modules', // '/workspace/node_modules' // ] ``` -------------------------------- ### rebuildModule() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-gyp.md Executes the node-gyp rebuild process for a native module. This method includes validation, environment setup, argument generation, and process forking to compile the module. ```APIDOC ## Method: rebuildModule() Executes the node-gyp rebuild process. ```typescript async rebuildModule(): Promise ``` **Throws:** - `Error` if attempting to cross-compile (i.e., `rebuilder.platform !== process.platform`) - Error output to console if module path contains spaces **Behavior:** 1. Validates that target platform matches host platform (no cross-compilation) 2. Sets up environment variables (including clang if `useElectronClang` is enabled) 3. Generates build arguments via `buildArgs()` 4. Forks worker process to run node-gyp in module directory 5. Streams stdout/stderr and waits for completion 6. Rejects if exit code is non-zero ``` -------------------------------- ### Specify Electron Version for Rebuild Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md Rebuild native modules for a specific Electron version, regardless of the currently installed version. Useful for testing or targeting a particular release. ```bash electron-rebuild --version 35.0.0 ``` -------------------------------- ### rebuild() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Main method that executes the rebuild workflow for a module. It attempts to find prebuilt modules first, then falls back to building from source using node-gyp if necessary. Returns true if rebuild succeeded or prebuilt was found, false otherwise. ```APIDOC ## rebuild() ### Description Main method that executes the rebuild workflow for a module. It attempts to find prebuilt modules first, then falls back to building from source using node-gyp if necessary. Returns true if rebuild succeeded or prebuilt was found, false otherwise. ### Method ```typescript async rebuild(cacheKey: string): Promise ``` ### Parameters #### Path Parameters - **cacheKey** (string) - Required - Hash key for caching (from `generateCacheKey()`) ### Returns - `Promise` - `true` if rebuild succeeded or prebuilt was found, `false` otherwise ``` -------------------------------- ### Prebuildify Class Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/prebuildify.md Manages prebuilt binaries from the prebuildify tool for Electron modules. ```APIDOC ## Class: Prebuildify Extends `NativeModule` to handle modules built with prebuildify. ### Constructor ```typescript constructor(rebuilder: IRebuilder, modulePath: string) ``` Inherits from `NativeModule`. ### Methods #### usesTool() Checks if the module uses prebuildify. ```typescript async usesTool(): Promise ``` **Returns:** `true` if `prebuildify` is a dev dependency of the module #### findPrebuiltModule() Checks for and validates a prebuildify prebuilt binary. ```typescript async findPrebuiltModule(): Promise ``` **Returns:** `true` if a compatible prebuilt module exists, `false` otherwise **Behavior:** 1. Checks if `prebuilds/` directory exists 2. Resolves the module's native architecture 3. Determines the correct filename extension based on architecture 4. Searches for compatible prebuilt binaries in precedence order: - `electron.napi.{ext}` (Node-API) - `node.napi.{ext}` (Node-API) - `electron.abi{ABI}.{ext}` (ABI-specific) 5. Validates Node-API support if found 6. Returns false if none match **Throws:** Error if Node-API prebuilt found but Electron doesn't support Node-API ### Helper Functions #### determineNativePrebuildArch() ```typescript function determineNativePrebuildArch(arch: string): string ``` **Parameters:** - `arch` — Node.js architecture string **Returns:** Native build architecture **Mapping:** - `armv7l` → `arm` - All others → unchanged **Used for:** Matching prebuilt directory names #### determineNativePrebuildExtension() ```typescript function determineNativePrebuildExtension(arch: string): string ``` **Parameters:** - `arch` — Node.js architecture string **Returns:** File extension after the last `.` **Mapping:** - `arm64` → `armv8.node` - `armv7l` → `armv7.node` - All others → `node` **Examples:** - x64: `module.node` - arm64: `module.armv8.node` - armv7l: `module.armv7.node` ``` -------------------------------- ### NodeAPI Constructor Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-api.md Initializes a new NodeAPI instance to manage compatibility checks for a specific module and Electron version. ```APIDOC ## NodeAPI Constructor ### Description Initializes a new NodeAPI instance to manage compatibility checks for a specific module and Electron version. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```typescript constructor(moduleName: string, electronVersion: string) ``` ### Parameters - **moduleName** (string) - Required - Name of the module (for error messages) - **electronVersion** (string) - Required - Version of Electron being targeted ``` -------------------------------- ### Locate Binary File in Directory Tree Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/utilities.md Walks up the directory tree starting from `basePath` to locate a file specified by `suffix`. Returns the absolute path or `null` if not found. ```typescript // Find node_modules/node-gyp/bin/node-gyp relative to module const binPath = await locateBinary( '/app/node_modules/sqlite3', 'node_modules/node-gyp/bin/node-gyp' ); // Returns: '/app/node_modules/node-gyp/bin/node-gyp' ``` -------------------------------- ### Get macOS SDK Root Path Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/clang-fetcher.md Retrieves the macOS SDK root path by checking the SDKROOT environment variable or executing xcrun. Returns the trimmed output. ```typescript function getSDKRoot(): string ``` -------------------------------- ### Get Compatible Node-API Version Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-api.md Selects the highest Node-API version that is compatible with both the module and the target Electron version. Requires an array of NAPI versions supported by the module. ```typescript getNapiVersion(moduleNapiVersions: number[]): number ``` -------------------------------- ### Disable Pre-gyp Copy Step Source: https://github.com/electron/rebuild/blob/main/_autodocs/cli.md Skip the step where `.node` files are copied to prebuilt locations. This can be useful in specific build pipeline configurations. ```bash electron-rebuild --disable-pre-gyp-copy ``` -------------------------------- ### Fallback Import Meta Resolve Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/electron-locator.md Demonstrates using `import.meta.resolve()` as a fallback mechanism to locate Electron's package.json, useful for globally installed or unusually located Electron packages. ```typescript import.meta.resolve('electron/package.json') ``` -------------------------------- ### walkModules() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-walker.md Walks the dependency tree from package.json to identify production, optional, and dev dependencies. It populates the internal state based on the module types specified during initialization. ```APIDOC ## walkModules() ### Description Walks the dependency tree from `package.json` to identify production, optional, and dev dependencies. It populates the internal state based on the module types specified during initialization. ### Method ```typescript async walkModules(): Promise ``` ### Behavior 1. Reads `package.json` from `buildPath` 2. Collects dependency keys based on `types` 3. Searches for each module in the module hierarchy 4. Recursively marks transitive dependencies as production dependencies ``` -------------------------------- ### Configure Caching for Faster Rebuilds Source: https://github.com/electron/rebuild/blob/main/_autodocs/configuration.md Enable and configure the experimental caching system for faster local rebuilds by specifying 'useCache' and 'cachePath'. ```typescript rebuild({ buildPath: '/app', electronVersion: '35.0.0', useCache: true, cachePath: '/tmp/electron-rebuild-cache' }) ``` -------------------------------- ### alreadyBuiltByRebuild() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-rebuilder.md Checks if the module was previously built by this tool by verifying the existence of a `.forge-meta` file with matching metadata. ```APIDOC ## alreadyBuiltByRebuild() ### Description Checks if the module was previously built by this tool by verifying the existence of a `.forge-meta` file with matching metadata. ### Method ```typescript async alreadyBuiltByRebuild(): Promise ``` ### Returns - `Promise` - `true` if `.forge-meta` file exists with matching `metaData` ``` -------------------------------- ### Detect Binary Architecture Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Demonstrates using the 'read-binary-file-arch' utility to detect a binary's architecture by reading its header (ELF/Mach-O/PE). This is done without executing the binary. ```typescript const moduleArch = await readBinaryFileArch(modulePath) ``` -------------------------------- ### ModuleWalker walkModules Method Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-walker.md Walks the dependency tree starting from the project's package.json to identify production, optional, and dev dependencies. It recursively marks transitive dependencies as production dependencies. ```typescript async walkModules(): Promise ``` -------------------------------- ### getClangEnvironmentVars Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/clang-fetcher.md Prepares environment variables and arguments for using Electron's clang compiler. It handles downloading the necessary clang version if not already cached and configures platform-specific flags. ```APIDOC ## getClangEnvironmentVars ### Description Prepares environment variables and arguments for using Electron's clang. ### Method Signature ```typescript async function getClangEnvironmentVars( electronVersion: string, targetArch: string ): Promise<{ env: Record; args: string[] }> ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Description | |---|---|---| | electronVersion | `string` | Target Electron version (e.g., "35.0.0") | | targetArch | `string` | Target CPU architecture (x64, arm64, etc.) | ### Returns Object with two properties: - `env: Record` — Environment variables to set - `args: string[]` — Extra node-gyp arguments ### Environment Variables Returned **All platforms:** - `CC` — C compiler path with platform-specific flags - `CXX` — C++ compiler path with platform-specific flags **Example values:** ```typescript { CC: '"/home/user/.electron-gyp/35.0.0-clang/bin/clang" --sysroot /path/to/sysroot', CXX: '"/home/user/.electron-gyp/35.0.0-clang/bin/clang++" --sysroot /path/to/sysroot' } ``` ### Platform-Specific Arguments **macOS:** - Adds `isysroot` flag with SDK root from `xcrun` or `SDKROOT` env var - Enables compatibility with Apple's system frameworks **Windows:** - Returns array with MSBuild properties: - `/p:CLToolExe=clang-cl.exe` - `/p:CLToolPath={clangDir}` **Linux:** - Downloads and uses sysroot from `downloadLinuxSysroot()` - Adds `--sysroot {path}` to compiler flags ### Process 1. Calls `downloadClangVersion()` to fetch clang if needed 2. Determines platform-specific flags and arguments 3. Returns compiler paths with platform-specific configuration ### Example ```typescript import { getClangEnvironmentVars } from '@electron/rebuild'; const { env, args } = await getClangEnvironmentVars('35.0.0', 'x64'); // In node-gyp build: Object.assign(process.env, env); const nodeGypArgs = [...args, ...otherArgs]; ``` ``` -------------------------------- ### Check if Binary Needs Updating Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Privately checks if the installed binary's architecture differs from the target architecture specified in the rebuilder. Defaults to true if the existing binary's architecture cannot be determined. ```typescript private async shouldUpdateBinary(nodePreGypPath: string): Promise ``` -------------------------------- ### Production Build Configuration Source: https://github.com/electron/rebuild/blob/main/_autodocs/configuration.md Configure a production build by specifying the build path, Electron version, and target platform/architecture. Set 'force' to false to skip if already built. ```typescript await rebuild({ buildPath: '/app', electronVersion: '35.0.0', arch: 'x64', platform: 'linux', force: false, // Skip if already built mode: 'parallel' }); ``` -------------------------------- ### RebuildResult Type Definition and Usage Example Source: https://github.com/electron/rebuild/blob/main/_autodocs/types.md Defines the return type of the rebuild() function, which is a Promise combined with a lifecycle EventEmitter. This allows for both asynchronous waiting and real-time event listening during the rebuild process. ```typescript type RebuildResult = Promise & { lifecycle: EventEmitter } ``` ```typescript const rebuilder = rebuild({ buildPath, electronVersion }); // Use as a promise await rebuilder; // OR listen to events rebuilder.lifecycle.on('modules-found', (modules) => { console.log(`Found ${modules.length} modules`); }); // Both simultaneously rebuilder.lifecycle.on('module-done', (name) => console.log(name)); await rebuilder; ``` -------------------------------- ### findAllModulesIn() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/module-walker.md Recursively scans a `node_modules` directory and populates the `modulesToRebuild` list. It handles symlinks, scoped packages, and nested dependencies. ```APIDOC ## findAllModulesIn() ### Description Recursively scans a `node_modules` directory and populates the `modulesToRebuild` list. It handles symlinks, scoped packages, and nested dependencies. ### Method ```typescript async findAllModulesIn(nodeModulesPath: string, prefix?: string): Promise ``` ### Parameters #### Path Parameters - **nodeModulesPath** (string) - Required - Absolute path to a `node_modules` directory - **prefix** (string) - Optional - Module name prefix (for scoped packages like `@scope/`) ### Behavior 1. Resolves symlinks to avoid processing duplicates 2. Skips `.bin` directory 3. Checks if each module is in production dependencies 4. Handles scoped packages (e.g., `@babel/core`) 5. Recursively processes nested `node_modules` ``` -------------------------------- ### searchForNodeModules() Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/search-module.md Finds all `node_modules` directories by traversing up the directory tree from a specified starting point. It can optionally stop searching at a defined project root path and is useful for identifying nested `node_modules` in monorepos. ```APIDOC ## searchForNodeModules() ### Description Finds all `node_modules` directories by traversing up the directory tree from a specified starting point. It can optionally stop searching at a defined project root path and is useful for identifying nested `node_modules` in monorepos. ### Method ```typescript async function searchForNodeModules( cwd: string, rootPath?: string ): Promise ``` ### Parameters #### Path Parameters - **cwd** (string) - Yes - Starting directory for search - **rootPath** (string) - No - Project root path; search stops here ### Returns `Promise` — Array of absolute paths to `node_modules` directories ### Behavior 1. Walks up from `cwd` to root (or `rootPath`) 2. For each directory, checks if `node_modules/` exists 3. Returns all found `node_modules` paths 4. Useful for monorepos with nested `node_modules` ### Example ```typescript const paths = await searchForNodeModules('/workspace/packages/app/src'); // May return: // [ // '/workspace/packages/app/node_modules', // '/workspace/node_modules' // ] ``` ``` -------------------------------- ### Execute npm script for rebuilding modules Source: https://github.com/electron/rebuild/blob/main/README.md Run the configured npm script to rebuild modules. ```sh npm run rebuild ``` -------------------------------- ### Get Node-Pre-Gyp Runtime Arguments Source: https://github.com/electron/rebuild/blob/main/_autodocs/api-reference/node-pre-gyp.md Determines the correct runtime arguments for node-pre-gyp based on whether the module supports Node-API. Returns an empty array for NAPI modules or Electron-specific arguments otherwise. ```typescript async getNodePreGypRuntimeArgs(): Promise ```