### Extension Runner Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Demonstrates how to use the ExtensionRunner obtained from webExt.cmd.run(). It shows starting an extension, reloading it, and performing cleanup. ```javascript const runner = await webExt.cmd.run({ sourceDir: './src', shouldExitProgram: false, }); console.log(runner.getName()); // "Firefox Desktop Extension Runner" // Later, reload extension after code changes await runner.reloadAllExtensions(); // Cleanup when done await runner.exit(); ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Example of a .web-ext-config.json file showing build, run, and sign configurations. API keys are referenced using environment variable syntax. ```json { "build": { "ignoreFiles": ["tests/**", "*.md"], "artifactsDir": "./dist" }, "run": { "firefox": "/path/to/firefox", "sourceDir": "./src" }, "sign": { "apiKey": "${AMO_API_KEY}", "apiSecret": "${AMO_API_SECRET}", "channel": "unlisted" } } ``` -------------------------------- ### Sign Command Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Illustrates the usage of the webExt.cmd.sign() function for signing an extension. The example shows how to retrieve the path to the generated signed XPI file. ```javascript const result = await webExt.cmd.sign({ sourceDir: './src', apiKey: 'key', apiSecret: 'secret', channel: 'unlisted', }); console.log(result.downloadedFilePath); // "./web-ext-artifacts/my-ext-1.0.0.xpi" ``` -------------------------------- ### Full Program Execution Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-program.md This example demonstrates setting global options, defining a command with its arguments, and executing the program with error handling. It shows a complete workflow from program initialization to command execution. ```javascript import { Program } from 'web-ext'; import { consoleStream } from 'web-ext/util/logger'; async function main() { const program = new Program(process.argv.slice(2)); program .setGlobalOptions({ verbose: { describe: 'Verbose logging', type: 'boolean', default: false, }, }) .command( 'run', 'Run the extension', async (argv) => { console.log('Running from', argv.sourceDir); return { success: true }; }, { 'source-dir': { describe: 'Source directory', type: 'string', demandOption: true, }, } ); try { const result = await program.execute({ shouldExitProgram: true, logStream: consoleStream, getVersion: () => '10.3.0', }); console.log('Success:', result); } catch (error) { console.error('Error:', error.message); process.exit(1); } } main(); ``` -------------------------------- ### JavaScript Configuration Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Example of a .web-ext-config.js file demonstrating build, run, and sign options. API keys and secrets are expected to be set as environment variables. ```javascript module.exports = { build: { ignoreFiles: ['tests/**', '*.md'], artifactsDir: './dist', }, run: { firefox: '/path/to/firefox', sourceDir: './src', }, sign: { apiKey: process.env.AMO_API_KEY, apiSecret: process.env.AMO_API_SECRET, channel: 'unlisted', }, }; ``` -------------------------------- ### Install Dependencies and Build from Source Source: https://github.com/mozilla/web-ext/blob/master/README.md Installs project dependencies and builds the web-ext command from its source code. Requires Node.js and npm. ```bash git clone https://github.com/mozilla/web-ext.git cd web-ext npm ci npm run build ``` -------------------------------- ### Install web-ext Globally Source: https://github.com/mozilla/web-ext/blob/master/README.md Installs the web-ext command-line tool globally on your machine. Ensure you have Node.js LTS installed. ```bash npm install --global web-ext ``` -------------------------------- ### Install web-ext using Homebrew Source: https://github.com/mozilla/web-ext/blob/master/README.md Installs the web-ext command-line tool using the Homebrew package manager. This is an unofficial method maintained by the community. ```sh brew install web-ext ``` -------------------------------- ### Build Command Configuration Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Example .web-ext-config.js snippet for the build command, specifying source directory, artifact output directory, files to ignore, and a custom filename template. ```javascript // .web-ext-config.js module.exports = { build: { sourceDir: './src', artifactsDir: './dist/output', ignoreFiles: [ 'tests/**', '**/*.test.js', '**/*.md', 'node_modules/**', '.git/**', ], filename: '{name}-v{version}.xpi', }, }; ``` -------------------------------- ### Start Development Environment Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Continuously build, run tests, and check for JavaScript syntax problems during development. ```bash npm start ``` -------------------------------- ### Build Command Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Demonstrates how to use the webExt.cmd.build() function to package an extension. It shows how to access the resulting extension path and manifest data. ```javascript const result = await webExt.cmd.build({ sourceDir: './src', artifactsDir: './dist', }); console.log(result.extensionPath); // "./dist/my-ext-1.0.0.zip" console.log(result.manifestData.name); // "My Extension" ``` -------------------------------- ### Link web-ext to Node Installation Source: https://github.com/mozilla/web-ext/blob/master/README.md Links the locally built web-ext command to your Node.js installation, allowing it to be run from any directory. ```bash npm link ``` -------------------------------- ### Install web-ext as a Dev Dependency Source: https://github.com/mozilla/web-ext/blob/master/README.md Installs web-ext as a development dependency for your project. This helps manage the version used by your team. ```bash npm install --save-dev web-ext ``` -------------------------------- ### Get Validated Manifest Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-manifest.md Demonstrates how to read and validate a manifest.json file from an extension directory using `getValidatedManifest`. Includes error handling for `InvalidManifest` errors. ```javascript import getValidatedManifest from 'web-ext/util/manifest'; try { const manifest = await getValidatedManifest('./src'); console.log('Extension:', manifest.name); console.log('Version:', manifest.version); console.log('ID:', manifest.browser_specific_settings?.gecko?.id); } catch (error) { if (error instanceof InvalidManifest) { console.error('Fix your manifest:', error.message); } throw error; } ``` -------------------------------- ### Example WebExtConfig Configuration Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Demonstrates a typical configuration for `.web-ext-config.js`, specifying files to ignore during build, the artifacts directory, and paths for Firefox and its profile for running the extension. ```javascript module.exports = { build: { ignoreFiles: ['tests/**', '*.md'], artifactsDir: './dist', }, run: { firefox: '/Applications/Firefox.app/Contents/MacOS/firefox', firefoxProfile: './test-profile', }, sign: { apiKey: process.env.AMO_API_KEY, apiSecret: process.env.AMO_API_SECRET, channel: 'unlisted', }, }; ``` -------------------------------- ### Get web-ext Help Source: https://github.com/mozilla/web-ext/blob/master/README.md Displays the help message for the web-ext command, showing available subcommands and options. ```bash web-ext --help ``` -------------------------------- ### Open Documentation Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Open the web-ext documentation in your default browser. This is a convenient way to access help and guides. ```javascript webExt.cmd.docs(params, options?) ``` -------------------------------- ### Logger Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-utilities.md Demonstrates how to create and use a logger instance, including enabling verbose logging and logging messages at different levels. ```javascript import { createLogger, consoleStream } from 'web-ext/util/logger'; // Enable verbose logging consoleStream.makeVerbose(); // Create logger for module const log = createLogger(import.meta.url); log.info('Extension running'); log.debug('Detailed debug info'); log.error('An error occurred'); ``` -------------------------------- ### Manifest Data Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md An example of a manifest object conforming to the ManifestData interface. This demonstrates how to specify extension details and browser-specific settings. ```javascript const manifest = { name: "My Extension", version: "1.0.0", manifest_version: 3, browser_specific_settings: { gecko: { id: "my-ext@example.com", strict_min_version: "115.0", } }, }; ``` -------------------------------- ### Example Run Configuration Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Configure the 'run' command for development, specifying source directory, target browser, Firefox executable path, profile settings, and preferences. Use this to customize how your extension is launched and reloaded during development. ```javascript // .web-ext-config.js module.exports = { run: { sourceDir: './src', target: ['firefox-desktop'], firefox: '/Applications/Firefox.app/Contents/MacOS/firefox', firefoxProfile: './test-profile', keepProfileChanges: false, pref: [ 'devtools.console.contentMessages=true', 'extensions.debug.logging=true', ], browserConsole: true, devtools: false, noReload: false, ignoreFiles: ['tests/**', '*.md'], }, }; ``` -------------------------------- ### Example web-ext Build Configuration with Ignore Files Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Configuration for the 'build' command, specifying source directory and an extensive list of glob patterns for files to ignore during the build process. ```javascript module.exports = { build: { sourceDir: './src', ignoreFiles: [ // Testing files 'tests/**', '**/*.test.js', '**/*.spec.js', // Documentation '*.md', 'docs/**', // Configuration '.eslintrc*', '.prettierrc*', 'jest.config.js', // Build artifacts 'dist/**', '*.zip', '*.xpi', // Dependencies 'node_modules/**', // Version control '.git/**', '.gitignore', // IDE '.vscode/**', '.idea/**', ], }, }; ``` -------------------------------- ### Listing ADB Devices Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Shows how to retrieve a list of connected Android devices using the `listADBDevices()` function and access their information. ```javascript const devices = await listADBDevices(); // [{ id: 'emulator-5554', type: 'device' }, ...] ``` -------------------------------- ### UsageError: Missing Signing Credentials Examples Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md Two examples of UsageError related to signing operations, highlighting the need to provide a channel and API key when signing extensions. ```text UsageError: You must specify a channel ``` ```text UsageError: apiKey is required for signing ``` -------------------------------- ### Instantiate Program Class Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-program.md Create a new instance of the Program class, optionally providing command-line arguments and options like the absolute package directory. The example shows how to execute the program after instantiation. ```javascript import { Program } from 'web-ext'; const program = new Program( ['run', '--source-dir', './src'], { absolutePackageDir: process.cwd() } ); await program.execute(); ``` -------------------------------- ### Build web-ext (Development) Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Builds a new version of the libraries used by the ./bin/web-ext command, placing new files in the ./dist/ directory. This is done automatically by 'npm start'. ```bash npm run build ``` -------------------------------- ### Run All Application Tests Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Execute the entire test suite once. This command is slower than 'npm start' as it does not use caching and runs functional tests. ```bash npm test ``` -------------------------------- ### JwtApiAuth Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-utilities.md Shows how to instantiate JwtApiAuth with API credentials and retrieve the authorization header for API requests. ```javascript const auth = new JwtApiAuth({ apiKey: 'your-api-key', apiSecret: 'your-api-secret', }); const authHeader = await auth.getAuthHeader(); // Use in API request: Authorization: {authHeader} ``` -------------------------------- ### Execute a CLI Command with Options Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Example of executing the 'build' command with options like 'asNeeded' and 'sourceDir'. Option keys are converted from hyphenated to camelCase. ```javascript commands .build({ asNeeded: true, sourceDir: './src/extension' }) .then((result) => { // ... }); ``` -------------------------------- ### Android Development: Setup and Run Extension Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/README.md This snippet shows how to set up and run an extension on an Android device. It requires listing available ADB devices and Firefox APKs, then creating an extension runner configured for Android. ```javascript import { listADBDevices, listADBFirefoxAPKs } from 'web-ext/util/adb'; import { createExtensionRunner } from 'web-ext'; const devices = await listADBDevices(); const apks = await listADBFirefoxAPKs(devices[0]); const runner = await createExtensionRunner({ target: 'firefox-android', params: { extensions: [{ sourceDir: './src' }], adbDevice: devices[0], firefoxApk: apks[0], }, }); await runner.run(); ``` -------------------------------- ### UsageError: Source Path Not Found Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md Illustrates a common build failure scenario where a UsageError is thrown because the specified source directory does not exist. ```text UsageError: sourceDir does not exist: /path/to/src ``` -------------------------------- ### JSON with Comments Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-manifest.md Illustrates how manifest files can include comments, which are stripped before parsing. ```json { // This is a comment "name": "My Extension", /* This is also a comment */ "version": "1.0.0" } ``` -------------------------------- ### Run Extension Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-runners.md Start the browser instance and load the extension(s) by calling the `run` method on the runner. The browser will be ready for remote control after this method returns. ```javascript const runner = await createExtensionRunner({...}); await runner.run(); console.log('Extension is now running'); ``` -------------------------------- ### ConsoleStream.startCapturing Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Starts capturing logs. Method of the ConsoleStream class. ```APIDOC ## ConsoleStream.startCapturing ### Description Starts capturing logs. ### Method Instance method of ConsoleStream. ### Returns - **void** ### Export Path `src/util/logger.js` → `lib/util/logger.js` ``` -------------------------------- ### Manifest Structure with Localization and Default Locale Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-manifest.md An example manifest.json file demonstrating the use of localized strings for 'name' and 'description', along with the 'default_locale' property. ```javascript { "name": "__MSG_appName__", "version": "1.0.0", "manifest_version": 3, "default_locale": "en_US" } ``` -------------------------------- ### MultiExtensionRunner Run Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Start running all registered extensions managed by the MultiExtensionRunner. This method initiates the extension execution process. ```javascript async run() ``` -------------------------------- ### Create and Use Firefox Desktop Runner Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-runners.md Example of creating a Firefox Desktop runner, loading extensions, running the browser, and performing actions like reloading and exiting. ```javascript import { createExtensionRunner } from 'web-ext'; const runner = await createExtensionRunner({ target: 'firefox-desktop', params: { extensions: [ { sourceDir: './extension1', manifestData: {} }, { sourceDir: './extension2', manifestData: {} }, ], firefoxBinary: '/Applications/Firefox.app/Contents/MacOS/firefox', profilePath: './firefox-profile', customPrefs: { 'devtools.console.contentMessages': true, 'extensions.debug.logging': true, }, browserConsole: true, devtools: false, }, }); await runner.run(); console.log(`Running: ${runner.getName()}`); // Reload after file changes await runner.reloadAllExtensions(); // Exit when done await runner.exit(); ``` -------------------------------- ### Example web-ext Sign Configuration Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Configuration for the 'sign' command in a .web-ext-config.js file. It specifies source directory, API credentials, channel, and other signing-related options. ```javascript // .web-ext-config.js module.exports = { sign: { sourceDir: './src', apiKey: process.env.AMO_API_KEY, apiSecret: process.env.AMO_API_SECRET, channel: 'unlisted', amoBaseUrl: 'https://addons.mozilla.org/api/v5/', artifactsDir: './signed-xpis', timeout: 900000, approvalTimeout: 3600000, // 1 hour }, }; ``` -------------------------------- ### Manifest with Localization Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-manifest.md Shows how manifest property values can reference localized strings using `__MSG_name__` syntax. Localization is resolved during the build process. ```json { "name": "__MSG_appName__", "description": "__MSG_appDescription__" } ``` -------------------------------- ### Example Lint Configuration Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Configure the 'lint' command to specify the source directory, files to ignore, and output format. Use this to automate the validation of your extension's code and manifest. ```javascript // .web-ext-config.js module.exports = { lint: { sourceDir: './src', ignoreFiles: ['tests/**'], output: 'json', warningsAsErrors: false, }, }; ``` -------------------------------- ### cmd.sign() Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Signs a WebExtension for installation on Firefox through Mozilla's AMO service. Requires API credentials and specifies the distribution channel. ```APIDOC ## cmd.sign() ### Description Sign a WebExtension for installation on Firefox through Mozilla's AMO service. Requires API credentials and specifies the distribution channel. ### Parameters #### Path Parameters - **sourceDir** (string) - Required - Path to extension source directory - **apiKey** (string) - Required - AMO API key - **apiSecret** (string) - Required - AMO API secret - **channel** (string) - Required - Distribution channel: 'listed' or 'unlisted' #### Query Parameters - **amoBaseUrl** (string) - Optional - AMO API base URL - **apiProxy** (string) - Optional - HTTP proxy for API requests - **artifactsDir** (string) - Optional - Directory for signed extension - **ignoreFiles** (string[]) - Optional - File patterns to ignore - **timeout** (number) - Optional - Validation timeout in milliseconds - **approvalTimeout** (number) - Optional - Approval timeout in milliseconds - **amoMetadata** (string) - Optional - Path to JSON file with AMO metadata - **uploadSourceCode** (boolean) - Optional - Upload extension source code - **webextVersion** (string) - Optional - web-ext version string for User-Agent ### Options Parameter #### Options - **build** (function) - Optional - Custom builder - **preValidatedManifest** (object) - Optional - Pre-validated manifest object - **submitAddon** (function) - Optional - Custom submission function - **asyncFsReadFile** (function) - Optional - Custom file reader ### Return Type ```javascript { id: string, downloadedFilePath: string, startupScript: string, } ``` ### Throws - UsageError: Invalid configuration or extension - WebExtError: AMO API or network errors ### Example ```javascript const result = await webExt.cmd.sign({ sourceDir: './src', apiKey: 'your-api-key', apiSecret: 'your-api-secret', channel: 'unlisted', artifactsDir: './dist', }); console.log(`Signed extension at: ${result.downloadedFilePath}`); ``` ``` -------------------------------- ### SignResult Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Represents the result returned from `cmd.sign()` or `signAddon()`, including the extension ID, the path to the downloaded signed XPI, and installation script content. ```APIDOC ## SignResult ### Description Result returned from `cmd.sign()` or `signAddon()`. ### Fields - **id** (string) - Extension ID from AMO - **downloadedFilePath** (string) - Path to signed XPI file - **startupScript** (string) - Installation script content ### Example ```javascript { "id": "my-ext@example.com", "downloadedFilePath": "./web-ext-artifacts/my-ext-1.0.0.xpi", "startupScript": "// Installation script content..." } ``` ``` -------------------------------- ### Set Environment Variables for web-ext Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Example of setting environment variables for web-ext commands. This is useful for configuring API keys, source directories, and browser paths. ```bash export WEB_EXT_SOURCE_DIR=./src export WEB_EXT_FIREFOX=/Applications/Firefox.app/Contents/MacOS/firefox export WEB_EXT_API_KEY=your-api-key export WEB_EXT_API_SECRET=your-api-secret web-ext run ``` -------------------------------- ### Sign Add-on with Development API Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Example command to sign a web extension using the development API. It requires specifying the API key, secret, and the base URL for the development API. ```bash web-ext sign --api-key user:123 --api-secret abc1234 \ --amo-base-url https://addons-dev.allizom.org/api/v5/ ``` -------------------------------- ### Get Manifest ID Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-manifest.md Demonstrates how to extract the extension ID from manifest data using `getManifestId`. It logs the ID if found, or a message indicating it will be auto-generated for MV2. ```javascript import getValidatedManifest, { getManifestId } from 'web-ext/util/manifest'; const manifest = await getValidatedManifest('./src'); const id = getManifestId(manifest); if (id) { console.log('Extension ID:', id); } else { console.log('No ID specified (will be auto-generated for MV2)'); } ``` -------------------------------- ### Define a New CLI Command Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Example of defining a new command 'build' for the web-ext CLI using yargs. It includes the command name, description, callback, and available options. ```javascript program.command( 'build', 'Create a web extension package from source', commands.build, { 'as-needed': { describe: 'Watch for file changes and re-build as needed', type: 'boolean', }, }, ); ``` -------------------------------- ### UsageError: Insufficient Arguments for Ignore Files Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md Represents a UsageError encountered when the --ignore-files command-line argument is used without providing any patterns to ignore. ```text UsageError: Not enough arguments following: ignore-files ``` -------------------------------- ### Run Command with Manifest Validation Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-manifest.md The `run` command validates the extension's manifest. It uses the manifest's ID for installation and resolves localized names if necessary. ```javascript const runner = await webExt.cmd.run({ sourceDir: './src' }); // Internally: // 1. Validates manifest for extension // 2. Uses ID from manifest for installation // 3. Resolves localized names if needed ``` -------------------------------- ### Commit Message with Scope Example Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md An example of a commit message using scopes to specify the affected part of the project. This format is useful for more granular tracking. ```git feat(dysfunctioner): Added --quiet option ``` -------------------------------- ### Using onlyInstancesOf to Handle UsageError Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md An example demonstrating the use of the onlyInstancesOf utility function to specifically catch and handle UsageError exceptions during a web-ext command execution. Other error types are re-thrown. ```javascript import { onlyInstancesOf, UsageError } from 'web-ext'; await webExt.cmd.run(params) .catch(onlyInstancesOf(UsageError, (error) => { console.error('User error:', error.message); // If error is NOT UsageError, this handler is not called // and the error is re-thrown })) .catch((error) => { // Catches non-UsageError exceptions console.error('Other error:', error.message); }); ``` -------------------------------- ### Commit Message Examples Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Examples of commit messages following the Angular style semantic convention. Use these to ensure clarity and enable automatic changelog generation. ```git feat: Added a systematic dysfunctioner ``` ```git fix: Fixed hang in systematic dysfunctioner ``` ```git docs: Improved contributor docs ``` ```git style: Added no-console linting, cleaned up code ``` ```git refactor: Split out dysfunctioner for testability ``` ```git perf: Systematic dysfunctioner is now 2x faster ``` ```git test: Added more tests for systematic dysfunctioner ``` ```git chore: Upgraded yargs to 3.x.x ``` -------------------------------- ### main Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-program.md Executes web-ext as a standalone program. This is the entry point used when running from the command line. ```APIDOC ## main(programArgv?, options?) ### Description Executes web-ext as a standalone program. This is the entry point used when running from the command line. ### Method async function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **programArgv** (string[]) - Optional - Command arguments. Defaults to `process.argv.slice(2)`. - **options** (object) - Optional - Configuration options for the program execution. - **options.absolutePackageDir** (string) - Optional - The absolute path to the package directory. Defaults to `process.cwd()`. - **options.shouldExitProgram** (boolean) - Optional - Determines if the process should exit upon completion. Defaults to `true`. - **options.systemProcess** (object) - Optional - The process object to use. Defaults to `process`. - **options.logStream** (ConsoleStream) - Optional - The stream to use for logging. Defaults to `consoleStream`. ### Request Example ```javascript import { main } from 'web-ext'; // Run web-ext with arguments await main(['build', '--source-dir', './src']); ``` ### Response #### Success Response - **any** - The result of the web-ext command execution. #### Response Example ```javascript // Example response depends on the command executed ``` ### Error Handling Errors are thrown as exceptions. ``` -------------------------------- ### AMO API Error: Validation Failed Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md An example of an error returned from the AMO (addons.mozilla.org) API during the signing process, indicating that the submitted file failed validation. ```text Error: Validation failed: {"errors": ["Invalid file"]} ``` -------------------------------- ### Build a WebExtension Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Use cmd.build() to package a WebExtension into a zip/xpi file. Specify the source directory and optionally customize ignored files, output directory, and filename. ```javascript webExt.cmd.build({ sourceDir: './extension-src', ignoreFiles: ['*.tmp', '.git'], artifactsDir: './dist', filename: '{name}-{version}.xpi', }); ``` -------------------------------- ### MultiExtensionRunner.getName Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Gets the name of the MultiExtensionRunner. Method of the MultiExtensionRunner class. ```APIDOC ## MultiExtensionRunner.getName ### Description Gets the name of the MultiExtensionRunner. ### Method Instance method of MultiExtensionRunner. ### Returns - **string** ### File `src/extension-runners/index.js` ``` -------------------------------- ### Creating and Using a File Filter Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Demonstrates how to create a file filter using `createFileFilter` with specified source and ignore patterns, and how to check if a file should be included in the build. ```javascript const filter = createFileFilter({ sourceDir: './src', ignoreFiles: ['tests/**', '*.test.js', 'node_modules/**'], }); if (filter.wantFile('src/index.js')) { // Include this file in build } ``` -------------------------------- ### Dump Configuration using CLI Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/configuration.md Command to display the effective configuration for web-ext, including options from command-line arguments, environment variables, and configuration files. ```bash web-ext dump-config --source-dir ./src ``` -------------------------------- ### Start Log Capturing Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-utilities.md Initiates the capturing of log messages, preventing them from being written to standard output. ```javascript startCapturing(): void ``` -------------------------------- ### Programmatic Execution of web-ext Commands Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-program.md Demonstrates how to invoke the `main` function with build arguments to execute web-ext commands programmatically. This is an alternative to using the CLI. ```javascript import { main } from 'web-ext'; // Run web-ext with arguments await main(['build', '--source-dir', './src']); // Or from CLI // Command: web-ext build --source-dir ./src ``` -------------------------------- ### Build Extension Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Use the build command to package your extension into a .zip or .xpi file. This is useful for distribution. ```javascript webExt.cmd.build(params, options?) ``` -------------------------------- ### Check web-ext and environment versions Source: https://github.com/mozilla/web-ext/blob/master/ISSUE_TEMPLATE.md Run this command to display the versions of Node.js, npm, and web-ext. This helps in diagnosing compatibility issues. ```bash node --version && npm --version && web-ext --version ``` -------------------------------- ### webExt.cmd.build() Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/README.md Packages the extension into a zip or xpi file. It takes an options object and returns a Promise that resolves with a BuildResult. ```APIDOC ## webExt.cmd.build() ### Description Packages the extension into a zip or xpi file. It takes an options object and returns a Promise that resolves with a BuildResult. ### Method `await` ### Parameters #### Request Body - **sourceDir** (string) - Required - The path to the extension's source directory. - **artifactsDir** (string) - Optional - The directory where the built extension will be saved. ### Response #### Success Response - **extensionPath** (string) - The path to the generated extension file. ### Request Example ```json { "sourceDir": "./src", "artifactsDir": "./dist" } ``` ### Response Example ```json { "extensionPath": "./dist/my-extension.zip" } ``` ``` -------------------------------- ### ConsoleStream Start Capturing Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Begin capturing log messages sent to the ConsoleStream. This is useful for testing or analyzing logs. ```javascript startCapturing() ``` -------------------------------- ### Example Usage of ExtensionRunnerReloadResult Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Demonstrates how to iterate through reload results and log success or failure messages based on the presence of a reloadError. ```javascript const results = await runner.reloadAllExtensions(); for (const result of results) { if (result.reloadError) { console.error(`Reload failed in ${result.runnerName}: ${result.reloadError.message}`); } else { console.log(`${result.runnerName} reloaded successfully`); } } ``` -------------------------------- ### JwtApiAuth Get Auth Header Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Retrieve the JWT authentication header. This header is required for making authenticated API requests. ```javascript getAuthHeader() ``` -------------------------------- ### Run a WebExtension Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Use cmd.run() to launch a WebExtension in a browser. Configure source directory, browser path, and input handling. The promise resolves with a runner object for managing the extension's lifecycle. ```javascript import webExt from 'web-ext'; webExt.cmd.run({ sourceDir: './extension-src', firefox: '/path/to/firefox', noInput: false, }, { shouldExitProgram: false, }).then((runner) => { console.log(`Running: ${runner.getName()}`); // Extension is now running }); ``` -------------------------------- ### ADBUtils Get Current User Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Retrieve the current user ID on a specified Android device. This can be useful for user-specific operations. ```javascript getCurrentUser(deviceId) ``` -------------------------------- ### webExt.cmd.docs() Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/README.md Opens the web-ext documentation in the default browser. It returns a Promise. ```APIDOC ## webExt.cmd.docs() ### Description Opens the web-ext documentation in the default browser. It returns a Promise. ### Method `await` ### Request Example ```json {} ``` ``` -------------------------------- ### Client Constructor Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Creates an instance of the Client for submitting addons. This is a class imported from 'web-ext/util/submit-addon'. ```APIDOC ## Client ### Description Provides methods for submitting and managing addons via the API. ### Constructor - **constructor(options)**: Initializes a Client instance. - **options**: Type not specified. Required. ### Export Path `src/util/submit-addon.js` → `lib/util/submit-addon.js` ``` -------------------------------- ### InvalidManifest Error Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md Shows an InvalidManifest error that occurs during the build process, typically due to syntax errors in the manifest.json file. ```text InvalidManifest: Error parsing manifest.json: Unexpected token ``` -------------------------------- ### cmd.build() Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Builds a WebExtension into a zip or xpi file. It can pre-load manifest data, control build completion messages, and use custom file watchers or filters. ```APIDOC ## cmd.build() ### Description Builds a WebExtension into a zip or xpi file. It can pre-load manifest data, control build completion messages, and use custom file watchers or filters. ### Parameters #### Path Parameters - **sourceDir** (string) - Required - Path to extension source directory #### Query Parameters - **artifactsDir** (string) - Optional - Directory to save built extension - **filename** (string) - Optional - Filename for the built extension ### Options Parameter #### Options - **manifestData** (object) - Optional - Pre-loaded manifest to use instead of reading from disk - **showReadyMessage** (boolean) - Optional - Log build completion message - **sourceWatcher** (object) - Optional - Custom file watcher - **fileFilterCreator** (function) - Optional - Custom file filter factory ### Return Type ```javascript { extensionPath: string, // Path to built extension zip/xpi manifestData: object, // Manifest content } ``` ### Example ```javascript const result = await webExt.cmd.build({ sourceDir: './src', artifactsDir: './dist', filename: 'my-ext-{version}.xpi', }); console.log(`Built extension at: ${result.extensionPath}`); ``` ``` -------------------------------- ### Manifest Structure with Firefox-Specific Settings Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-manifest.md Example of a manifest.json file including Firefox-specific settings like 'id' and 'strict_min_version' within 'browser_specific_settings.gecko'. ```javascript { "name": "My Extension", "version": "1.0.0", "manifest_version": 3, "browser_specific_settings": { "gecko": { "id": "my-extension@example.com", "strict_min_version": "115.0" } } } ``` -------------------------------- ### ADBUtils Get Current User Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-utilities.md Retrieves the current user ID on an Android device. Throws a WebExtError if the user ID cannot be determined. ```javascript async getCurrentUser(deviceId: string): Promise ``` -------------------------------- ### Open WebExtension Documentation Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Opens the web-ext documentation in the default browser. Enable verbose logging for additional output. ```javascript await webExt.cmd.docs({ verbose: true }); ``` -------------------------------- ### main Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md The main entry point function for the web-ext program. ```APIDOC ## main ### Description The main entry point function for the web-ext program. ### Method Not specified (assumed to be a function call within the web-ext library). ### Parameters - **programArgv**: Type not specified. Optional. - **options**: Type not specified. Optional. ### Returns - **Promise** ### File `src/program.js` ``` -------------------------------- ### Build Extension with CLI Arguments Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/README.md Build an extension using the web-ext CLI, specifying source and artifact directories via command-line arguments. ```bash web-ext build --source-dir ./src --artifacts-dir ./dist ``` -------------------------------- ### Add a Command Option to CLI Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Example of adding a new option '--file-path' with an alias 'fp' to the 'run' command using yargs. ```javascript program // other commands... .command('run', 'Run the web extension', commands.run, { // other options... 'file-path': { describe: 'An absolute file path.', alias: ['fp'], demandOption: false, requiresArg: true, type: 'string', }, }); ``` -------------------------------- ### Build Extension with Configuration File Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/README.md Configure web-ext build options by creating a JavaScript configuration file (e.g., .web-ext-config.js). ```javascript module.exports = { build: { sourceDir: './src', artifactsDir: './dist', }, }; ``` -------------------------------- ### cmd.docs() Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Opens the web-ext documentation in the default browser. Supports enabling verbose logging. ```APIDOC ## cmd.docs() ### Description Open the web-ext documentation in the default browser. Supports enabling verbose logging. ### Parameters #### Path Parameters - **verbose** (boolean) - Optional - Enable verbose logging ### Return Type Promise that resolves when documentation is opened. ### Example ```javascript await webExt.cmd.docs({ verbose: true }); ``` ``` -------------------------------- ### Build web-ext (Production) Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Creates a production build of web-ext using the NODE_ENV variable. ```bash NODE_ENV=production npm run build ``` -------------------------------- ### Get Runner Name Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-runners.md Retrieve the human-readable name of the current runner using the `getName` method. This is useful for logging or identifying the active browser environment. ```javascript const name = runner.getName(); console.log(`Running on: ${name}`); ``` -------------------------------- ### Sign Addon Directly using Internal Module Source: https://github.com/mozilla/web-ext/blob/master/README.md Use the internal signAddon utility to submit an XPI file for signing. This is an internal API and webExt.cmd.sign is recommended. ```js import { signAddon } from 'web-ext/util/submit-addon'; signAddon({ // NOTE: Please set userAgentString to a custom one of your choice. userAgentString: 'YOUR-CUSTOM-USERAGENT', apiKey, apiSecret, amoBaseUrl: 'https://addons.mozilla.org/api/v5/', id: 'extension-id@example.com', xpiPath: pathToExtension, savedUploadUuidPath: '.amo-upload-uuid', channel: 'unlisted', }); ``` -------------------------------- ### Integration with web-ext Commands Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-program.md Shows how the program module integrates with the command system by importing default commands. Commands are typically lazy-loaded. ```javascript import defaultCommands from './cmd/index.js'; // Commands are lazy-loaded: // defaultCommands.run() // defaultCommands.build() // defaultCommands.lint() // defaultCommands.sign() // defaultCommands.docs() // defaultCommands.dumpConfig() ``` -------------------------------- ### Generate Continuous Coverage Reports Source: https://github.com/mozilla/web-ext/blob/master/CONTRIBUTING.md Generate coverage reports continuously while editing files by setting the COVERAGE environment variable to 'y' when starting the development server. ```bash COVERAGE=y npm start ``` -------------------------------- ### SignResult Interface Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/types.md Defines the structure of the result returned from cmd.sign() or signAddon(). It contains the extension ID, the path to the signed XPI file, and installation script content. ```typescript interface SignResult { id: string, downloadedFilePath: string, startupScript: string, } ``` -------------------------------- ### cmd.build() Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Builds a WebExtension into a zip/xpi package. This method is useful for packaging extensions for distribution or deployment. ```APIDOC ## cmd.build() ### Description Build a WebExtension into a zip/xpi package. ### Signature ```javascript async build(params, options = {}) ``` ### Parameters #### Params - **params.sourceDir** (string) - Required - Path to extension source directory - **params.ignoreFiles** (string[]) - Optional - File patterns to ignore when building. Defaults to `[]` - **params.artifactsDir** (string) - Optional - Directory for build artifacts - **params.overwriteDest** (boolean) - Optional - Overwrite existing artifacts. Defaults to `false` - **params.filename** (string) - Optional - Output filename template. Supports `{name}` and `{version}` interpolation. Defaults to `'{name}-{version}.zip'` - **params.verbose** (boolean) - Optional - Enable verbose logging. Defaults to `false` ``` -------------------------------- ### AMO API Error: Approval Timeout Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md An error indicating that the approval process for an extension on AMO has timed out, suggesting a potential issue with the submission or review. ```text Error: Approval timeout exceeded ``` -------------------------------- ### UsageError: Missing Extension ID Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md A UsageError indicating that an extension ID is required in the manifest.json file for signing purposes, particularly for Manifest V3 extensions. ```text UsageError: An extension ID must be specified in the manifest.json file. ``` -------------------------------- ### Run Extension with Options Source: https://github.com/mozilla/web-ext/blob/master/README.md Execute the 'web-ext run' command with specified options for Firefox executable, source directory, and program exit behavior. ```js import webExt from 'web-ext'; webExt.cmd .run( { // These are command options derived from their CLI conterpart. // In this example, --source-dir is specified as sourceDir. firefox: '/path/to/Firefox-executable', sourceDir: '/path/to/your/extension/source/', }, { // These are non CLI related options for each function. // You need to specify this one so that your NodeJS application // can continue running after web-ext is finished. shouldExitProgram: false, }, ) .then((extensionRunner) => { // The command has finished. Each command resolves its // promise with a different value. console.log(extensionRunner); // You can do a few things like: // extensionRunner.reloadAllExtensions(); // extensionRunner.exit(); }); ``` -------------------------------- ### UsageError: Unexpected Watch File Type Example Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/errors.md This UsageError occurs when an invalid type is provided for the --watch-file option, indicating that the input value is not recognized. ```text UsageError: Unexpected watchFile type ``` -------------------------------- ### Build Extension with Environment Variables Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/README.md Configure web-ext build options using environment variables for source and artifact directories. ```bash export WEB_EXT_SOURCE_DIR=./src export WEB_EXT_ARTIFACTS_DIR=./dist web-ext build ``` -------------------------------- ### Program Constructor Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-program.md Initializes a new Program instance. It can parse provided arguments or use default process arguments and set an absolute package directory. ```APIDOC ## Program Constructor ### Description Initializes a new Program instance. It can parse provided arguments or use default process arguments and set an absolute package directory. ### Signature ```javascript constructor(argv?: string[], options?: { absolutePackageDir?: string }) ``` ### Parameters #### Parameters - **argv** (string[]) - Optional - Command arguments to parse. Defaults to `process.argv.slice(2)`. - **options.absolutePackageDir** (string) - Optional - Absolute path to package directory. Defaults to `process.cwd()`. ### Example ```javascript import { Program } from 'web-ext'; const program = new Program( ['run', '--source-dir', './src'], { absolutePackageDir: process.cwd() } ); await program.execute(); ``` ``` -------------------------------- ### List ADB Firefox APKs Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-index.md Find installed Firefox APKs on a specified Android device using ADB. This utility is helpful for deploying extensions to Android devices. ```javascript listADBFirefoxAPKs(deviceId, adbBin?) ``` -------------------------------- ### Build WebExtension Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-commands.md Builds a WebExtension from a source directory. Specify output artifacts directory and filename pattern. The result includes the path to the built extension. ```javascript const result = await webExt.cmd.build({ sourceDir: './src', artifactsDir: './dist', filename: 'my-ext-{version}.xpi', }); console.log(`Built extension at: ${result.extensionPath}`); ``` -------------------------------- ### listADBFirefoxAPKs Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-utilities.md Lists all installed Firefox APK packages on a specified Android device. Requires the device ID obtained from `listADBDevices()` and can optionally take a path to the ADB binary. ```APIDOC ## listADBFirefoxAPKs ### Description Lists all installed Firefox APK packages on a device. ### Method `async listADBFirefoxAPKs(deviceId: string, adbBin?: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **deviceId** (string) - Required - Android device ID from `listADBDevices()`. - **adbBin** (string) - Optional - Path to adb binary; auto-detected if omitted. ### Response #### Success Response (200) - **Promise** (string[]) - Array of Firefox APK package names. ### Throws - `UsageError` if adb executable not found. ### Example ```javascript import { listADBDevices, listADBFirefoxAPKs } from 'web-ext/util/adb'; const devices = await listADBDevices(); const apks = await listADBFirefoxAPKs(devices[0]); console.log('Firefox APKs:', apks); ``` ``` -------------------------------- ### List ADB Firefox APKs Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/api-reference-utilities.md Lists all installed Firefox APK packages on a specified Android device. Requires the device ID and optionally the adb binary path. ```javascript async listADBFirefoxAPKs(deviceId: string, adbBin?: string): Promise ``` ```javascript import { listADBDevices, listADBFirefoxAPKs } from 'web-ext/util/adb'; const devices = await listADBDevices(); const apks = await listADBFirefoxAPKs(devices[0]); console.log('Firefox APKs:', apks); // Output: ['org.mozilla.firefox', 'org.mozilla.firefox_beta'] ``` -------------------------------- ### Sign Extension using web-ext cmd Source: https://github.com/mozilla/web-ext/blob/master/README.md Request a signed XPI for an extension source directory using the webExt.cmd.sign method. Requires API credentials and a custom user agent string. ```js webExt.cmd.sign({ // NOTE: Please set userAgentString to a custom one of your choice. userAgentString: 'YOUR-CUSTOM-USERAGENT', apiKey, apiSecret, amoBaseUrl: 'https://addons.mozilla.org/api/v5/', sourceDir: ..., channel: 'unlisted', ... }); ``` -------------------------------- ### webExt.cmd.run() Source: https://github.com/mozilla/web-ext/blob/master/_autodocs/README.md Executes the extension in a specified browser. It returns a Promise that resolves with an ExtensionRunner instance. ```APIDOC ## webExt.cmd.run() ### Description Executes the extension in a specified browser. It returns a Promise that resolves with an ExtensionRunner instance. ### Method `await` ### Parameters #### Request Body - **sourceDir** (string) - Required - The path to the extension's source directory. - **firefox** (string) - Optional - The path to the Firefox executable. - **shouldExitProgram** (boolean) - Optional - If true, the program will exit after the runner is created. ### Response #### Success Response - **runner.getName()** (string) - Returns the name of the runner. ### Request Example ```json { "sourceDir": "./src", "firefox": "/path/to/firefox", "shouldExitProgram": false } ``` ### Response Example ```json "Firefox Desktop" ``` ```