### Installation and Basic Usage Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@isaacs/cliui/node_modules/ansi-styles/readme.md Instructions on how to install the ansi-styles package and a basic example of its usage for styling text. ```APIDOC ## Installation ```sh npm install ansi-styles ``` ## Basic Usage ```js import styles from 'ansi-styles'; console.log(`${styles.green.open}Hello world!${styles.green.close}`); ``` ``` -------------------------------- ### Yocto-Queue Installation and Usage Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/yocto-queue/readme.md Instructions on how to install and basic usage examples for the yocto-queue package. ```APIDOC ## Installation ```bash $ npm install yocto-queue ``` ## Usage Example ```javascript const Queue = require('yocto-queue'); const queue = new Queue(); queue.enqueue('item1'); queue.enqueue('item2'); console.log(queue.size); // Output: 2 console.log(...queue); // Output: 'item1 item2' console.log(queue.dequeue()); // Output: 'item1' console.log(queue.dequeue()); // Output: 'item2' ``` ``` -------------------------------- ### Install verb and verb-generate-readme Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/is-extglob/README.md Install the necessary tools globally to generate documentation. This is part of the project's development setup. ```sh $ npm install -g verb verb-generate-readme && verb ``` -------------------------------- ### Glob Installation and Basic Usage Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/glob/README.md Instructions on how to install the glob library using npm and a basic example of its asynchronous usage. ```APIDOC ## Installation Install with npm ``` npm i glob ``` ## Basic Usage ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ``` -------------------------------- ### Hookified Setup Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/qified/node_modules/hookified/README.md The base setup required for all Hookified examples. It involves importing Hookified, extending it, and instantiating the class. ```javascript import { Hookified } from 'hookified'; class MyClass extends Hookified { constructor(options) { super(options); } } const myClass = new MyClass(); ``` -------------------------------- ### JSON5 Development Setup Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/json5/README.md Clone the repository, install dependencies, and set up your development environment for contributing to JSON5. ```sh git clone https://github.com/json5/json5 cd json5 npm install ``` -------------------------------- ### Install and Use UAParser.js in Node.js Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/ua-parser-js/readme.md Installation command and example of using the library within an HTTP server. Note that device information is unavailable in Node.js. ```sh $ npm install ua-parser-js ``` ```js var http = require('http'); var parser = require('ua-parser-js'); http.createServer(function (req, res) { // get user-agent header var ua = parser(req.headers['user-agent']); // write the result as response res.end(JSON.stringify(ua, null, ' ')); }) .listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); ``` -------------------------------- ### End-to-End Example with Keyv and Redis Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/keyv/README.md Demonstrates basic Keyv operations (set, get, delete, clear) using the Redis adapter. Shows setting values with and without expiration. ```javascript import Keyv from 'keyv'; import KeyvRedis from '@keyv/redis'; const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379'); const keyv = new Keyv({ store: keyvRedis }); await keyv.set('foo', 'expires in 1 second', 1000); // true await keyv.set('foo', 'never expires'); // true await keyv.get('foo'); // 'never expires' await keyv.delete('foo'); // true await keyv.clear(); // undefined ``` -------------------------------- ### Setup Standalone Proxy Server with Latency Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/http-proxy/README.md This example shows how to introduce latency to proxied requests. It simulates a delay before forwarding the request to the target server. Requires 'http' and 'http-proxy' modules. ```javascript var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with latency // var proxy = httpProxy.createProxyServer(); // // Create your server that makes an operation that waits a while // and then proxies the request // http.createServer(function (req, res) { // This simulates an operation that takes 500ms to execute setTimeout(function () { proxy.web(req, res, { target: 'http://localhost:9008' }); }, 500); }).listen(8008); // // Create your target server // http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(9008); ``` -------------------------------- ### Install Keyv Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/flat-cache/node_modules/keyv/README.md Install Keyv using npm. This command installs the core Keyv package. ```bash npm install --save keyv ``` -------------------------------- ### Basic Optionator Setup and Usage Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/eslint/node_modules/optionator/README.md Demonstrates how to initialize Optionator with custom settings for options, prepend/append text, and then parse command-line arguments. Includes logic to display help if the 'help' option is present. ```javascript var optionator = require('optionator')({ prepend: 'Usage: cmd [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'displays help' }, { option: 'count', alias: 'c', type: 'Int', description: 'number of things', example: 'cmd --count 2' }] }); var options = optionator.parseArgv(process.argv); if (options.help) { console.log(optionator.generateHelp()); } ... ``` -------------------------------- ### Initialize a Connect Application Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/connect/README.md A complete example demonstrating how to set up a Connect app with compression, session management, body parsing, and a basic response handler. ```javascript var connect = require('connect'); var http = require('http'); var app = connect(); // gzip/deflate outgoing responses var compression = require('compression'); app.use(compression()); // store session state in browser cookie var cookieSession = require('cookie-session'); app.use(cookieSession({ keys: ['secret1', 'secret2'] })); // parse urlencoded request bodies into req.body var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: false})); // respond to all requests app.use(function(req, res){ res.end('Hello from Connect!\n'); }); //create node.js http server and listen on port http.createServer(app).listen(3000); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/chromedevtools/devtools-frontend/blob/main/inspector_overlay/README.md Command to initiate a local web server for testing overlay UI without bundling. ```bash python -m SimpleHTTPServer 8000 ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/chromedevtools/devtools-frontend/blob/main/scripts/component_docs/README.md Start a local HTTP server in the output directory to view the generated documentation. ```bash python3 -m http.server 8000 ``` -------------------------------- ### Quickstart Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/micromatch/README.md Basic usage examples for micromatch. ```APIDOC ## Quickstart ```js const micromatch = require('micromatch'); // micromatch(list, patterns[, options]); ``` The [main export](#micromatch) takes a list of strings and one or more glob patterns: ```js console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz'] console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux'] ``` Use [.isMatch()](#ismatch) to for boolean matching: ```js console.log(micromatch.isMatch('foo', 'f*')) //=> true console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true ``` [Switching](#switching-to-micromatch) from minimatch and multimatch is easy! ``` -------------------------------- ### Setup Basic Stand-alone Proxy Server Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/http-proxy/README.md Set up a basic stand-alone proxy server by creating a proxy instance with a target and then invoking the `listen` method on the proxy instance. A target server is also created for demonstration. ```javascript var http = require('http'), httpProxy = require('http-proxy'); // // Create your proxy server and set the target in the options. // httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†) // // Create your target server // http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(9000); ``` -------------------------------- ### new Keyv([uri], [options]) Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/flat-cache/node_modules/keyv/README.md Initializes a new Keyv instance with optional connection URI and configuration settings. ```APIDOC ## new Keyv([uri], [options]) ### Description Returns a new Keyv instance. The instance is an EventEmitter that emits an 'error' event if the storage adapter connection fails. ### Parameters #### Path Parameters - **uri** (String) - Optional - The connection string URI. #### Request Body - **options** (Object) - Optional - Configuration object passed to the storage adapter. - **options.namespace** (String) - Optional - Namespace for the current instance. Default: 'keyv'. - **options.ttl** (Number) - Optional - Default Time-To-Live. Can be overridden on .set(). ### Request Example const keyv = new Keyv('redis://localhost', { namespace: 'my-app', ttl: 5000 }); ``` -------------------------------- ### Defining Commands with Options and Actions Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/commander/Readme.md Define commands with descriptions, options, and associated actions. This snippet demonstrates setting up 'setup' and 'exec' commands, including aliases and custom help for commands. ```javascript var program = require('commander'); program .version('0.1.0') .option('-C, --chdir ', 'change the working directory') .option('-c, --config ', 'set config path. defaults to ./deploy.conf') .option('-T, --no-tests', 'ignore test hook'); program .command('setup [env]') .description('run setup commands for all envs') .option("-s, --setup_mode [mode]", "Which setup mode to use") .action(function(env, options){ var mode = options.setup_mode || "normal"; env = env || 'all'; console.log('setup for %s env(s) with %s mode', env, mode); }); program .command('exec ') .alias('ex') .description('execute the given remote cmd') .option("-e, --exec_mode ", "Which exec mode to use") .action(function(cmd, options){ console.log('exec "%s" using %s mode', cmd, options.exec_mode); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ deploy exec sequential'); console.log(' $ deploy exec async'); }); program .command('*') .action(function(env){ console.log('deploying "%s"', env); }); program.parse(process.argv); ``` -------------------------------- ### Deep Filter Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@nodelib/fs.walk/README.md Provides an example of a `deepFilter` function that prevents the traversal from entering directories whose paths start with `node_modules`. ```typescript // Skip all directories that starts with `node_modules` const filter: DeepFilterFunction = (entry) => !entry.path.startsWith('node_modules'); ``` -------------------------------- ### Installation and Usage Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/eslint/node_modules/eslint-visitor-keys/README.md Instructions on how to install and import the eslint-visitor-keys package into your project. ```APIDOC ## Installation Use npm to install: ```bash $ npm install eslint-visitor-keys ``` ### Requirements - Node.js `^18.18.0`, `^20.9.0`, or `>=21.1.0` ## Usage To use in an ESM file: ```js import * as evk from "eslint-visitor-keys" ``` To use in a CommonJS file: ```js const evk = require("eslint-visitor-keys") ``` ``` -------------------------------- ### Installation via NPM Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/fast-json-stable-stringify/README.md Command to install the package. ```bash npm install fast-json-stable-stringify ``` -------------------------------- ### Install and Run NPM License Checker Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/license-checker/README.md Install the license-checker globally and run it on a project to see dependency licenses. This is a basic setup for initial use. ```shell npm install -g license-checker mkdir foo cd foo npm install yui-lint license-checker ``` -------------------------------- ### Version Option Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/svgo/node_modules/commander/Readme.md Example of how the version option is displayed when invoked. ```bash $ ./examples/pizza -V 0.0.1 ``` -------------------------------- ### Usage in Node.js Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/treeify/README.md Example of how to use the `asTree` method in a Node.js project after installation. ```APIDOC ## Usage in Node.js Then proceed to use it in your project: ```javascript var treeify = require('treeify'); console.log( treeify.asTree({ apples: 'gala', // ├─ apples: gala oranges: 'mandarin' // └─ oranges: mandarin }, true) ); ``` ``` -------------------------------- ### Initialize Engine.IO Client Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/engine.io/README.md Shows how to include the client library and establish a connection to the server. ```html ``` -------------------------------- ### Install on-finished Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/body-parser/node_modules/on-finished/README.md Use npm to install the module in your project. ```sh $ npm install on-finished ``` -------------------------------- ### Get Executable Path Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/bare-os/README.md Returns the absolute path of the executable that started the process. ```javascript const p = os.execPath() ``` -------------------------------- ### Quick Start: Get MIME Type and Extension Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/mime/README.md Basic usage of the Mime module to get the MIME type from an extension and the extension from a MIME type. This demonstrates the core functionality. ```javascript const mime = require('mime'); mime.getType('txt'); // ⇨ 'text/plain' mime.getExtension('text/plain'); // ⇨ 'txt' ``` -------------------------------- ### Build Component Documentation Source: https://github.com/chromedevtools/devtools-frontend/blob/main/scripts/component_docs/README.md Execute this command to build the component documentation, generating an `index.html` file in the output directory. ```bash autoninja -C out/Default scripts/component_docs ``` -------------------------------- ### Get unquoted attribute value Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/postcss-selector-parser/API.md Examples of retrieving the raw unquoted content from an attribute value. ```css [href=foo] /* foo */ [href='foo'] /* foo */ [href="foo"] /* foo */ [href] /* undefined */ ``` -------------------------------- ### Run Example Code Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/svg-tags/README.md Execute the example JavaScript file using Node.js from the top-level application directory. ```bash $ node ./examples/index.js ``` -------------------------------- ### Installation Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/color-convert/README.md Instructions on how to install the color-convert library using npm. ```APIDOC ## Install ### Description Instructions on how to install the color-convert library using npm. ### Request Example ```console $ npm install color-convert ``` ``` -------------------------------- ### Streamroller Usage and Constructor Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/streamroller/README.md This section covers the basic installation, usage example, and the constructor for creating a RollingFileStream. ```APIDOC ## Installation ```sh npm install streamroller ``` ## Usage Example ```javascript var rollers = require('streamroller'); var stream = new rollers.RollingFileStream('myfile', 1024, 3); stream.write("stuff"); stream.end(); ``` ## Constructor: RollingFileStream This returns a `WritableStream` that manages file rollovers. ### Parameters * **filename** (string) - The base name for the log file. * **maxSize** (integer) - Optional. Defaults to `MAX_SAFE_INTEGER`. The size in bytes that triggers a rollover. * **numBackups** (integer) - Optional. Defaults to `1`. The number of old files to keep (excluding the current active file). * **options** (Object) - Optional. Configuration options for the stream. * **encoding** (string) - Optional. Defaults to `'utf8'`. The encoding for the file. * **mode** (integer) - Optional. Defaults to `0o600`. The file mode (see [node.js file modes](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_modes)). * **flags** (string) - Optional. Defaults to `'a'`. The file system flags (see [node.js file flags](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_file_system_flags)). * **compress** (boolean) - Optional. Defaults to `false`. If true, backup files will be compressed using gzip and have a `.gz` extension. * **keepFileExt** (boolean) - Optional. Defaults to `false`. If true, preserves the file extension when rotating log files (e.g., `file.log` becomes `file.1.log` instead of `file.log.1`). * **fileNameSep** (string) - Optional. Defaults to `'.'`. The separator used when naming backup files (e.g., `abc.log.1` or `abc.1.log` if `keepFileExt` is true). ### Rollover Behavior When the current file being written to reaches or exceeds `maxSize`, the following occurs: 1. The current file is renamed to `filename.1`. 2. A new file is created for writing. Up to `numBackups` old files are maintained. For example, if `numBackups` is 3, the files will be named: ``` filename filename.1 filename.2 filename.3 ``` When `filename` size >= `maxSize`: ``` filename -> filename.1 filename.1 -> filename.2 filename.2 -> filename.3 filename.3 gets overwritten filename is a new file ``` ``` -------------------------------- ### Basic Usage Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/meow/readme.md Demonstrates how to use the meow CLI helper with arguments and flags. ```sh ./foo-app.js unicorns --rainbow ``` ```js #!/usr/bin/env node import meow from 'meow'; import foo from './lib/index.js'; const cli = meow(` Usage $ foo Options --rainbow, -r Include a rainbow Examples $ foo unicorns --rainbow 🌈 unicorns 🌈 `, { importMeta: import.meta, flags: { rainbow: { type: 'boolean', shortFlag: 'r' } } }); /* { input: ['unicorns'], flags: {rainbow: true}, ... } */ foo(cli.input.at(0), cli.flags); ``` -------------------------------- ### Initialize Keyv Instance Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/flat-cache/node_modules/keyv/README.md Create a new Keyv instance. Pass a connection string to automatically load the correct storage adapter. Handle database connection errors using the 'error' event. ```javascript const Keyv = require('keyv'); // One of the following const keyv = new Keyv(); const keyv = new Keyv('redis://user:pass@localhost:6379'); const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname'); const keyv = new Keyv('sqlite://path/to/database.sqlite'); const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname'); const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname'); const keyv = new Keyv('etcd://localhost:2379'); // Handle DB connection errors keyv.on('error', err => console.log('Connection Error', err)); ``` -------------------------------- ### Clean Project Dependencies Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/flat-cache/node_modules/keyv/README.md Removes Yarn and all installed dependencies. After running, you must repeat the setup steps. ```bash yarn clean ``` -------------------------------- ### Use side-channel-map Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/side-channel-map/README.md Basic usage example demonstrating setting, getting, asserting, and deleting values in the side channel. ```js const assert = require('assert'); const getSideChannelMap = require('side-channel-map'); const channel = getSideChannelMap(); const key = {}; assert.equal(channel.has(key), false); assert.throws(() => channel.assert(key), TypeError); channel.set(key, 42); channel.assert(key); // does not throw assert.equal(channel.has(key), true); assert.equal(channel.get(key), 42); channel.delete(key); assert.equal(channel.has(key), false); assert.throws(() => channel.assert(key), TypeError); ``` -------------------------------- ### GET /products/:id Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/cors/README.md An example endpoint demonstrating how to implement asynchronous CORS configuration using a whitelist delegate. ```APIDOC ## GET /products/:id ### Description Retrieves product information with CORS enabled based on a dynamic whitelist check. ### Method GET ### Endpoint /products/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the product. ### Response #### Success Response (200) - **msg** (string) - Confirmation message indicating CORS is enabled for the domain. #### Response Example { "msg": "This is CORS-enabled for a whitelisted domain." } ``` -------------------------------- ### Installation Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md Instructions on how to install the eslint-visitor-keys package using npm. ```APIDOC ## Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] `^20.19.0`, `^22.13.0`, or `>=24` ``` -------------------------------- ### Example package.json structure Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/eslint-plugin-import/docs/rules/no-extraneous-dependencies.md A sample package.json file demonstrating various dependency categories. ```json { "name": "my-project", "...": "...", "dependencies": { "builtin-modules": "^1.1.1", "lodash.cond": "^4.2.0", "lodash.find": "^4.2.0", "pkg-up": "^1.0.0" }, "devDependencies": { "ava": "^0.13.0", "eslint": "^2.4.0", "eslint-plugin-ava": "^1.3.0", "xo": "^0.13.0" }, "optionalDependencies": { "lodash.isarray": "^4.0.0" }, "peerDependencies": { "react": ">=15.0.0 <16.0.0" }, "bundledDependencies": [ "@generated/foo", ] } ``` -------------------------------- ### Install Mocha Type Definitions Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@types/mocha/README.md Use npm to install the @types/mocha package, which provides TypeScript type definitions for the Mocha testing framework. This is useful for projects using TypeScript to get better autocompletion and type checking when writing tests. ```bash npm install --save @types/mocha ``` -------------------------------- ### Run DevTools with Canary Browser Source: https://github.com/chromedevtools/devtools-frontend/blob/main/front_end/models/ai_assistance/README.md Starts the DevTools development server using the Canary browser. Ensure you have Canary installed and configured. ```bash npm start -- --browser=canary ``` -------------------------------- ### Build and test the project Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/fast-levenshtein/README.md Commands to install dependencies and run the build process. ```bash $ npm install -g grunt-cli $ npm install $ npm run build ``` -------------------------------- ### Get Caller File in a Module Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/get-caller-file/README.md This example demonstrates how to use the get-caller-file utility within a Node.js module to determine the invoking file. ```javascript // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` -------------------------------- ### Usage Example for @jridgewell/set-array Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@jridgewell/set-array/README.md Demonstrates how to import and use SetArray, put, get, and pop functions. Ensure you have assert imported for the assertions to work. ```js import { SetArray, get, put, pop } from '@jridgewell/set-array'; const sa = new SetArray(); let index = put(sa, 'first'); assert.strictEqual(index, 0); index = put(sa, 'second'); assert.strictEqual(index, 1); assert.deepEqual(sa.array, [ 'first', 'second' ]); index = get(sa, 'first'); assert.strictEqual(index, 0); pop(sa); index = get(sa, 'second'); assert.strictEqual(index, undefined); assert.deepEqual(sa.array, [ 'first' ]); ``` -------------------------------- ### new Keyv([storage-adapter], [options]) or new Keyv([options]) Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/keyv/README.md Instantiates a new Keyv instance. You can optionally provide a storage adapter and/or configuration options. ```APIDOC ## new Keyv([storage-adapter], [options]) or new Keyv([options]) ### Description Instantiates a new Keyv instance. You can optionally provide a storage adapter and/or configuration options. ### Parameters #### Path Parameters - **storage-adapter** (object) - Optional - The storage adapter to use. - **options** (object) - Optional - Configuration options for Keyv. - **namespace** (string) - Optional - A namespace for the storage. - **ttl** (number) - Optional - Default time-to-live in milliseconds. - **serialize** (function) - Optional - Custom serializer function. - **deserialize** (function) - Optional - Custom deserializer function. - **compression** (boolean|object) - Optional - Enable or configure compression. - **useKeyPrefix** (boolean) - Optional - Use key prefix for storage adapter. - **retry** (object) - Optional - Retry options for storage adapter operations. - **max** (number) - Optional - Maximum number of items in the cache (for memory adapter). - **ttlInterval** (number) - Optional - Interval for cleaning expired items (for memory adapter). - **store** (object) - Optional - The underlying storage instance. ``` -------------------------------- ### Async Usage Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/escalade/readme.md Demonstrates how to use the asynchronous version of escalade to find a 'package.json' file starting from a given input path. The callback logs the current directory and names, and returns the filename when found. Also shows an example of searching for a non-existent file. ```javascript //~> demo.js import { join } from 'path'; import escalade from 'escalade'; const input = join(__dirname, 'demo.js'); // or: const input = __dirname; const pkg = await escalade(input, (dir, names) => { console.log('~> dir:', dir); console.log('~> names:', names); console.log('---'); if (names.includes('package.json')) { // will be resolved into absolute return 'package.json'; } }); //~> dir: /Users/lukeed/oss/escalade/test/fixtures/foobar //~> names: ['demo.js'] //--- //~> dir: /Users/lukeed/oss/escalade/test/fixtures //~> names: ['index.js', 'foobar'] //--- //~> dir: /Users/lukeed/oss/escalade/test //~> names: ['fixtures'] //--- //~> dir: /Users/lukeed/oss/escalade //~> names: ['package.json', 'test'] //--- console.log(pkg); //=> /Users/lukeed/oss/escalade/package.json // Now search for "missing123.txt" // (Assume it doesn't exist anywhere!) const missing = await escalade(input, (dir, names) => { console.log('~> dir:', dir); return names.includes('missing123.txt') && 'missing123.txt'; }); //~> dir: /Users/lukeed/oss/escalade/test/fixtures/foobar //~> dir: /Users/lukeed/oss/escalade/test/fixtures //~> dir: /Users/lukeed/oss/escalade/test //~> dir: /Users/lukeed/oss/escalade //~> dir: /Users/lukeed/oss //~> dir: /Users/lukeed //~> dir: /Users //~> dir: / console.log(missing); //=> undefined ``` -------------------------------- ### Build and Update Documentation Source: https://github.com/chromedevtools/devtools-frontend/blob/main/front_end/third_party/third-party-web/package/lib/markdown/template.md Commands to install dependencies, build the project, and regenerate the README. ```bash # Install `cairo` and dependencies for node-canvas brew install pkg-config cairo pango libpng jpeg giflib # Build the requirements in this repo yarn build # Regenerate the README yarn start ``` -------------------------------- ### Install with Custom Source Map Retrieval Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/source-map-support/README.md Provide a `retrieveSourceMap` callback to customize how source maps are loaded. This example shows caching source maps in memory. ```javascript require('source-map-support').install({ retrieveSourceMap: function(source) { if (source === 'compiled.js') { return { url: 'original.js', map: fs.readFileSync('compiled.js.map', 'utf8') }; } return null; } }); ``` -------------------------------- ### Get Symbol Description Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/get-symbol-description/README.md Import and use the `get-symbol-description` function to test its behavior with different Symbol types. Asserts are used to verify the expected output. ```javascript var getSymbolDescription = require('get-symbol-description'); var assert = require('assert'); assert(getSymbolDescription(Symbol()) === undefined); assert(getSymbolDescription(Symbol('')) === ''); // or `undefined`, if in an engine that lacks name inference from concise method assert(getSymbolDescription(Symbol('foo')) === 'foo'); assert(getSymbolDescription(Symbol.iterator) === 'Symbol.iterator'); ``` -------------------------------- ### Usage Example for side-channel-list Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/side-channel-list/README.md Demonstrates basic usage of the side-channel-list, including setting, getting, asserting, and deleting keys. Ensure keys are deleted to prevent memory leaks. ```js const assert = require('assert'); const getSideChannelList = require('side-channel-list'); const channel = getSideChannelList(); const key = {}; assert.equal(channel.has(key), false); assert.throws(() => channel.assert(key), TypeError); channel.set(key, 42); channel.assert(key); // does not throw assert.equal(channel.has(key), true); assert.equal(channel.get(key), 42); channel.delete(key); assert.equal(channel.has(key), false); assert.throws(() => channel.assert(key), TypeError); ``` -------------------------------- ### Basic Mitt Usage Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/mitt/README.md Demonstrates how to create an emitter instance, listen to events (including wildcard), emit events, clear all handlers, and manage handler references for listening and unlistening. ```javascript import mitt from 'mitt' const emitter = mitt() // listen to an event emitter.on('foo', e => console.log('foo', e) ) // listen to all events emitter.on('*', (type, e) => console.log(type, e) ) // fire an event emitter.emit('foo', { a: 'b' }) // clearing all events emitter.all.clear() // working with handler references: function onFoo() {} emitter.on('foo', onFoo) // listen emitter.off('foo', onFoo) // unlisten ``` -------------------------------- ### Access browser globals Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@eslint/eslintrc/node_modules/globals/readme.md Import the 'globals' package and access the 'browser' property to get a list of browser-specific global identifiers. The output shows examples of these globals and their read-only status. ```js const globals = require('globals'); console.log(globals.browser); /* { addEventListener: false, applicationCache: false, ArrayBuffer: false, atob: false, … } */ ``` -------------------------------- ### Install Dependencies Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/engine.io-parser/Readme.md Commands to navigate to the directory and install dependencies. ```bash cd engine.io-parser npm ci ``` -------------------------------- ### Get and Validate Typed Array Names Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/possible-typed-array-names/README.md Use this snippet to retrieve the list of Typed Array names and assert their validity. Ensure the 'assert' module is available and the 'possible-typed-array-names' package is installed. ```javascript const assert = require('assert'); const names = require('possible-typed-array-names'); assert(Array.isArray(names)); assert(names.every(name => ( typeof name === 'string' && typeof globalThis[name] === 'function' && globalThis[name].name === name ))); ``` -------------------------------- ### Step Option Examples Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/fill-range/README.md Demonstration of the step option with numbers and letters. ```js // numbers console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] // letters console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] ``` -------------------------------- ### Generate Browserslist Query from Electron Major Version (Deprecated) Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/electron-to-chromium/README.md Use the deprecated `electronToBrowserList` function with a major Electron version to get a Browserslist query string. Example uses '1.4'. ```javascript var query = e2c.electronToBrowserList('1.4'); // query is "Chrome >= 53" ``` -------------------------------- ### Convert Chromium Major Version to Electron Major Version Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/electron-to-chromium/README.md Use the `chromiumToElectron` function with a major Chromium version to get the corresponding major Electron version. Example uses '54'. ```javascript var electronVersion = e2c.chromiumToElectron('54'); // electronVersion is "1.4" ``` -------------------------------- ### Install bare-os Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/bare-os/README.md Install the bare-os module using npm. ```bash npm i bare-os ``` -------------------------------- ### Install source map support programmatically Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/source-map-support/README.md Invoke the install method at the top of your entry file. ```javascript require('source-map-support').install(); ``` -------------------------------- ### Convert Electron Full Version to Chromium Full Version Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/electron-to-chromium/README.md Use the `electronToChromium` function with a full Electron version to get the corresponding full Chromium version. Example uses '1.4.11'. ```javascript var chromeVersion = e2c.electronToChromium('1.4.11'); // chromeVersion is "53.0.2785.143" ``` -------------------------------- ### Convert Electron Major Version to Chromium Major Version Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/electron-to-chromium/README.md Use the `electronToChromium` function with a major Electron version to get the corresponding major Chromium version. Example uses '1.4'. ```javascript var chromeVersion = e2c.electronToChromium('1.4'); // chromeVersion is "53" ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/fill-range/README.md This command installs the necessary project dependencies and executes the unit tests. It's a standard way to verify the project's functionality. ```sh $ npm install && npm test ``` -------------------------------- ### Create Keyv Instance with BigMap Adapter Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@keyv/bigmap/README.md Basic usage of createKeyv to initialize a Keyv instance with BigMap as the storage adapter. Includes examples for set, get, has, delete, and clear operations. ```typescript import { createKeyv } from '@keyv/bigmap'; // Basic usage const keyv = createKeyv(); // Set with TTL (in milliseconds) await keyv.set('user:123', { name: 'Alice', age: 30 }, 60000); // Expires in 60 seconds // Get value const user = await keyv.get('user:123'); console.log(user); // { name: 'Alice', age: 30 } // Check if key exists const exists = await keyv.has('user:123'); // Delete key await keyv.delete('user:123'); // Clear all keys await keyv.clear(); ``` -------------------------------- ### Install to-regex-range Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/to-regex-range/README.md Command to install the library via npm. ```sh $ npm install --save to-regex-range ``` -------------------------------- ### Install @eslint/config-helpers Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@eslint/config-helpers/README.md Install the package using npm, yarn, pnpm, or bun for Node.js environments. For Deno, use the 'deno add' command. ```shell npm install @eslint/config-helpers ``` ```shell yarn add @eslint/config-helpers ``` ```shell pnpm install @eslint/config-helpers ``` ```shell bun add @eslint/config-helpers ``` ```shell deno add @eslint/config-helpers ``` -------------------------------- ### Example Output: Process Arguments Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/yargs-parser/README.md Example of the output when parsing process arguments with '--foo=33 --bar hello'. ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` -------------------------------- ### Convert Chromium Full Version to Electron Full Versions Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/electron-to-chromium/README.md Use the `chromiumToElectron` function with a full Chromium version to get an array of corresponding full Electron versions. Example uses '56.0.2924.87'. ```javascript var electronVersions = e2c.chromiumToElectron('56.0.2924.87'); // electronVersions is ["1.6.3", "1.6.2", "1.6.1", "1.6.0"] ``` -------------------------------- ### Setup Automatic Workspace Folders with Serve Source: https://github.com/chromedevtools/devtools-frontend/blob/main/docs/ecosystem/automatic_workspace_folders.md This bash script sets up the necessary directory and configuration file for automatic workspace folders and starts a local server. It dynamically generates a UUID for the project. ```bash cd /Users/foo/bar mkdir -p .well-known/appspecific echo "{\"workspace\":{\"root\":\"${PWD}\",\"uuid\":\" $(npx --package uuid uuid v4)\"}}" > .well-known/appspecific/com.chrome.devtools.json npx serve ``` -------------------------------- ### Get Visitor Keys for an AST Node Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@stylistic/eslint-plugin/node_modules/eslint-visitor-keys/README.md Retrieve the visitor keys for a given AST node. This utility excludes keys like 'parent', 'leadingComments', 'trailingComments', and properties starting with '_'. It's useful for traversing unknown nodes. ```javascript const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` -------------------------------- ### Installing the plugin Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@web/rollup-plugin-import-meta-assets/README.md Command to install the package as a development dependency. ```bash npm install @web/rollup-plugin-import-meta-assets --save-dev ``` -------------------------------- ### Compile and Run CoffeeScript with Source Maps Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/source-map-support/README.md Install necessary packages, compile the CoffeeScript file with source map support, and run the generated JavaScript file. This setup helps in debugging by providing accurate error locations. ```sh $ npm install source-map-support coffeescript $ node_modules/.bin/coffee --map --compile demo.coffee $ node demo.js ``` -------------------------------- ### Command Line Usage Examples Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/nopt/README.md Demonstrates various command-line invocations and their resulting parsed output objects. ```console $ node my-program.js --foo "blerp" --no-flag { "foo" : "blerp", "flag" : false } $ node my-program.js ---bar 7 --foo "Mr. Hand" --flag { bar: 7, foo: "Mr. Hand", flag: true } $ node my-program.js --foo "blerp" -f -----p { foo: "blerp", flag: true, pick: true } $ node my-program.js -fp --foofoo { foo: "Mr. Foo", flag: true, pick: true } $ node my-program.js --foofoo -- -fp # -- stops the flag parsing. { foo: "Mr. Foo", argv: { remain: ["-fp"] } } $ node my-program.js --blatzk -fp # unknown opts are ok. { blatzk: true, flag: true, pick: true } $ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value { blatzk: 1000, flag: true, pick: true } $ node my-program.js --no-blatzk -fp # unless they start with "no-" { blatzk: false, flag: true, pick: true } $ node my-program.js --baz b/a/z # known paths are resolved. { baz: "/Users/isaacs/b/a/z" } # if Array is one of the types, then it can take many # values, and will always be an array. The other types provided # specify what types are allowed in the list. $ node my-program.js --many1 5 --many1 null --many1 foo { many1: ["5", "null", "foo"] } $ node my-program.js --many2 foo --many2 bar { many2: ["/path/to/foo", "path/to/bar"] } ``` -------------------------------- ### Basic qjobs Usage Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/qjobs/Readme.md Demonstrates how to initialize qjobs, add jobs, and handle various queue events like start, end, jobStart, jobEnd, pause, and unpause. Jobs can be added dynamically, and the queue can be paused and resumed. ```javascript var qjobs = new require('./qjobs'); // My non blocking main job var myjob = function(args,next) { setTimeout(function() { console.log('Do something interesting here',args); next(); },1000); } var q = new qjobs({maxConcurrency:10}); // Let's add 30 job to the queue for (var i = 0; i<30; i++) { q.add(myjob,[i,'test '+i]); } q.on('start',function() { console.log('Starting ...'); }); q.on('end',function() { console.log('... All jobs done'); }); q.on('jobStart',function(args) { console.log('jobStart',args); }); q.on('jobEnd',function(args) { console.log('jobend',args); // If i'm jobId 10, then make a pause of 5 sec if (args._jobId == 10) { q.pause(true); setTimeout(function() { q.pause(false); },5000); } }); q.on('pause',function(since) { console.log('in pause since '+since+' milliseconds'); }); q.on('unpause',function() { console.log('pause end, continu ..'); }); q.run(); //q.abort() will empty jobs list ``` -------------------------------- ### Setup Standalone Proxy Server with Request Header Rewriting Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/http-proxy/README.md This example demonstrates how to proxy requests while modifying outgoing proxy request headers. It uses the 'proxyReq' event to add a custom header before the request is sent to the target. Requires 'http' and 'http-proxy' modules. ```javascript var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with custom application logic // var proxy = httpProxy.createProxyServer({}); // To modify the proxy connection before data is sent, you can listen // for the 'proxyReq' event. When the event is fired, you will receive // the following arguments: (http.ClientRequest proxyReq, http.IncomingMessage req, // http.ServerResponse res, Object options). This mechanism is useful when // you need to modify the proxy request before the proxy connection // is made to the target. // proxy.on('proxyReq', function(proxyReq, req, res, options) { proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); }); var server = http.createServer(function(req, res) { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { target: 'http://127.0.0.1:5050' }); }); console.log("listening on port 5050") server.listen(5050); ``` -------------------------------- ### Install Keyv Storage Adapters Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/keyv/README.md Install optional storage adapters for Keyv, such as Redis, MongoDB, SQLite, and others. ```bash npm install --save @keyv/redis npm install --save @keyv/valkey npm install --save @keyv/mongo npm install --save @keyv/sqlite npm install --save @keyv/postgres npm install --save @keyv/mysql npm install --save @keyv/etcd npm install --save @keyv/memcache npm install --save @keyv/dynamo ``` -------------------------------- ### Basic Usage Example Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/@isaacs/cliui/README.md Demonstrates how to use cliui to create a simple command-line interface with usage information and options. ```APIDOC ## Basic Usage Example ### Description This example shows how to initialize cliui and add rows with text and formatting. ### Method `require('cliui')()` ### Endpoint N/A (Client-side library) ### Request Example ```javascript const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ### Response #### Success Response (200) Outputs the formatted command-line interface to the console. #### Response Example ```shell Usage: $0 [command] [options] Options: -f, --file the file to load. (if this description is long it wraps). [required] ``` ``` -------------------------------- ### Install ESLint JSDoc Plugin Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/eslint-plugin-jsdoc/README.md Install the eslint-plugin-jsdoc. Install globally if ESLint is global, otherwise install locally. ```sh npm install --save-dev eslint-plugin-jsdoc ``` -------------------------------- ### Install get-proto Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/get-proto/README.md Use npm to install the package as a dependency. ```sh npm install --save get-proto ``` -------------------------------- ### Install and Configure ESLint Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/eslint/README.md Use this command to install and configure ESLint for your project. Ensure you have Node.js installed. ```shell npm init @eslint/config@latest ``` -------------------------------- ### Install Storage Adapters Source: https://github.com/chromedevtools/devtools-frontend/blob/main/node_modules/flat-cache/node_modules/keyv/README.md Install optional storage adapters for Keyv, such as Redis, MongoDB, SQLite, PostgreSQL, MySQL, and Etcd. ```bash npm install --save @keyv/redis npm install --save @keyv/mongo npm install --save @keyv/sqlite npm install --save @keyv/postgres npm install --save @keyv/mysql npm install --save @keyv/etcd ```