### Setup pkg Project with Yarn Source: https://github.com/vercel/pkg/wiki/Developers Instructions for cloning the pkg repository, installing dependencies using Yarn, and linking the project globally and within a local application. This setup allows for testing customized versions of pkg. ```bash git clone https://github.com/vercel/pkg.git cd pkg # install deps and build project (see `prepare` script) yarn install # link pkg globally yarn link # link pkg inside your app cd ../my-test-app yarn link pkg ``` -------------------------------- ### pkg Build Command Example Source: https://github.com/vercel/pkg/blob/main/README.md A command-line example demonstrating how to use `pkg` to create an executable. This specifies the entry point, target platform, and output file name. ```bash pkg app.js --target host --output app.exe ``` -------------------------------- ### JavaScript: Function demonstrating module and path operations Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt A JavaScript function 'hellee' that encapsulates calls to 'require.resolve', 'require', and 'path.join'. It serves as an example of how these core Node.js/JavaScript functionalities might be used within a function context, including variations in argument types. ```javascript function hellee(a, b, c) { require.resolve(); /***/ require.resolve("barbos1"); /***/ require.resolve(`barbos1`); /***/ require.resolve(`barbos1`, `must-exclude1`); /***/ require.resolve("barbos1", "must-exclude1"); /***/ require.resolve("barbos1", "may-exclude1"); /***/ require.resolve("barbos1", "unknown1"); require(); /***/ require("barbos2"); /***/ require(`barbos2`); /***/ require(`barbos2`, `must-exclude2`); /***/ require("barbos2", "must-exclude2"); /***/ require("barbos2", "may-exclude2"); /***/ require("barbos2", "unknown2"); path.join(); path.join(__dirname); /***/ path.join(__dirname, "file"); /***/ path.join(__dirname, `file`); // TODO path.join(__dirname + "/file"); return { result: a + b - c }; } ``` -------------------------------- ### JavaScript: Demonstrate require with various arguments Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Shows different ways to use the 'require' function in JavaScript, including calls with string literals, template literals, and optional arguments. 'require' is used to import modules. The examples cover basic module loading and passing additional arguments. ```javascript /***/ require("barbos2"); /***/ require(`barbos2`); /***/ require(`barbos2`, `must-exclude2`); /***/ require("barbos2", "must-exclude2"); /***/ require("barbos2", "may-exclude2"); /***/ require("barbos2", "unknown2"); ``` -------------------------------- ### JavaScript: Illustrate path.join usage Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Demonstrates the 'path.join' method for concatenating path segments in JavaScript. Examples include joining with '__dirname' and string literals or template literals. This is a common utility for constructing file paths reliably across different operating systems. ```javascript /***/ path.join(__dirname, "file"); /***/ path.join(__dirname, `file`); ``` -------------------------------- ### pkg Dictionary Configuration Example Source: https://github.com/vercel/pkg/wiki/Developers Illustrates the structure of a `dictionary` file used within the pkg project for patching Node.js modules. It shows how to define globs for scripts and assets, and how to specify code patches for specific files. ```js 'use strict'; module.exports = { pkg: { scripts: ['lib/middleware/*.js'], assets: [ 'lib/public/**/*', ], patches: { 'lib/bunyan.js': ["mv = require('mv' + '');", "mv = require('mv');"], 'graceful-fs.js': [ { do: 'prepend' }, 'if ((function() { var version = require('./package.json').version; var major = parseInt(version.split('.')[0]); if (major < 4) { module.exports = require('fs'); return true; } })(); return; ', ], }, deployFiles: [['prebuilds', 'prebuilds', 'directory']], }, }; ``` -------------------------------- ### Install pkg CLI Source: https://github.com/vercel/pkg/blob/main/README.md Installs the pkg command-line interface globally using npm. This makes the `pkg` command available in your terminal for packaging Node.js projects. ```bash npm install -g pkg ``` -------------------------------- ### JavaScript: Demonstrate require.resolve with various arguments Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Illustrates the usage of 'require.resolve' in JavaScript, showcasing calls with string literals, template literals, and different argument combinations. This function is used to find the absolute path of a module. The examples highlight how arguments like module names and options are passed. ```javascript /***/ require.resolve("barbos1"); /***/ require.resolve(`barbos1`); /***/ require.resolve(`barbos1`, `must-exclude1`); /***/ require.resolve("barbos1", "must-exclude1"); /***/ require.resolve("barbos1", "may-exclude1"); /***/ require.resolve("barbos1", "unknown1"); ``` -------------------------------- ### JavaScript: Function demonstrating try-catch with module/path operations Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt This JavaScript function 'helleeTry' demonstrates the use of try-catch blocks around 'require.resolve', 'require', and 'path.join' calls. It shows how to handle potential errors during module resolution or path operations, making the code more robust. ```javascript function helleeTry(a, b, c) { try { require.resolve(); } catch (_) {} /***/ try { require.resolve("barbos1"); } catch (_) {} /***/ try { require.resolve(`barbos1`); } catch (_) {} /***/ try { require.resolve(`barbos1`, `must-exclude1`); } catch (_) {} /***/ try { require.resolve("barbos1", "must-exclude1"); } catch (_) {} /***/ try { require.resolve("barbos1", "may-exclude1"); } catch (_) {} /***/ try { require.resolve("barbos1", "unknown1"); } catch (_) {} try { require(); } catch (_) {} /***/ try { require("barbos2"); } catch (_) {} /***/ try { require(`barbos2`); } catch (_) {} /***/ try { require(`barbos2`, `must-exclude2`); } catch (_) {} /***/ try { require("barbos2", "must-exclude2"); } catch (_) {} /***/ try { require("barbos2", "may-exclude2"); } catch (_) {} /***/ try { require("barbos2", "unknown2"); } catch (_) {} try { path.join(); } catch (_) {} try { path.join(__dirname); } catch (_) {} /***/ try { path.join(__dirname, "file"); } catch (_) {} // TODO path.join(__dirname + "/file"); return { result: a + b - c }; } ``` -------------------------------- ### JavaScript: Nested function demonstrating module/path operations Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt The 'helluu' function contains a nested function that executes 'require.resolve', 'require', and 'path.join' calls. This example illustrates scoping and how these operations can be performed within inner functions, including scenarios where 'require' and 'path' might be locally shadowed. ```javascript function helluu(a, b, c) { return { result: function() { var require = {}; var path = {}; require.resolve(); /***/ require.resolve("barbos1"); /***/ require.resolve(`barbos1`); /***/ require.resolve(`barbos1`, `must-exclude1`); /***/ require.resolve("barbos1", "must-exclude1"); /***/ require.resolve("barbos1", "may-exclude1"); /***/ require.resolve("barbos1", "unknown1"); require(); /***/ require("barbos2"); /***/ require(`barbos2`); /***/ require(`barbos2`, `must-exclude2`); /***/ require("barbos2", "must-exclude2"); /***/ require("barbos2", "may-exclude2"); /***/ require("barbos2", "unknown2"); path.join(); path.join(__dirname); /***/ path.join(__dirname, "file"); /***/ path.join(__dirname, `file`); // TODO path.join(__dirname + "/file"); return { result: a + b - c }; } } } ``` -------------------------------- ### JavaScript: Nested try-catch function with module/path operations Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt This 'helluuTry' function features a nested function that uses try-catch blocks around 'require.resolve', 'require', and 'path.join' calls. It demonstrates error handling within nested scopes, showing how to gracefully manage potential issues during module loading or path manipulation. ```javascript function helluuTry(a, b, c) { return { result: function() { var require = {}; var path = {}; try { require.resolve(); } catch (_) {} /***/ try { require.resolve("barbos1"); } catch (_) {} /***/ try { require.resolve(`barbos1`); } catch (_) {} /***/ try { require.resolve(`barbos1`, `must-exclude1`); } catch (_) {} /***/ try { require.resolve("barbos1", "must-exclude1"); } catch (_) {} /***/ try { require.resolve("barbos1", "may-exclude1"); } catch (_) {} /***/ try { require.resolve("barbos1", "unknown1"); } catch (_) {} try { require(); } catch (_) {} /***/ try { require("barbos2"); } catch (_) {} /***/ try { require(`barbos2`); } catch (_) {} /***/ try { require(`barbos2`, `must-exclude2`); } catch (_) {} /***/ try { require("barbos2", "must-exclude2"); } catch (_) {} /***/ try { require("barbos2", "may-exclude2"); } catch (_) {} /***/ try { require("barbos2", "unknown2"); } catch (_) {} try { path.join(); } catch (_) {} try { path.join(__dirname); } catch (_) {} /***/ try { path.join(__dirname, "file"); } catch (_) {} /***/ try { path.join(__dirname, `file`); } catch (_) {} // TODO path.join(__dirname + "/file"); return { result: a + b - c }; } } } ``` -------------------------------- ### JavaScript: Infinity and Negative Infinity constants Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Defines standard JavaScript constants for positive infinity ('INFINITY') and negative infinity ('NEGATIVE_INFINITY'). These are special numeric values representing values beyond the maximum representable finite number. ```javascript var INFINITY = 1 / 0; var NEGATIVE_INFINITY = -1 / 0; ``` -------------------------------- ### JavaScript: Utility pattern for object property iteration Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt This snippet demonstrates a common JavaScript pattern for iterating over object properties using a 'for...in' loop with a 'hasProp' check. It includes an 'enumeration' label for labeled 'continue' statements, often used for clarity in complex loops. ```javascript var inheritedDataKeys = (function() { var obj = {}; function hasProp(o, k) { return true; } enumeration: for (var key in obj) { if (!hasProp.call(obj, key)) { continue enumeration; } } })(); ``` -------------------------------- ### JavaScript: Array of group names with intentional comma Source: https://github.com/vercel/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt An array named 'group_names' containing string identifiers. It includes an intentional comma before the first element, which results in the first element being 'undefined' or empty, a common pattern for specific indexing or enumeration schemes. ```javascript var group_names = [ , 'whitespace' // INTENTIONAL COMMA! , 'terminator' , 'string' , 'comment' , 'identifier' , 'preprocess' , 'operator' , 'invalid' ]; ``` -------------------------------- ### Snapshot Filesystem Path Comparison Source: https://github.com/vercel/pkg/blob/main/README.md Illustrates how various path-related variables differ between a standard Node.js environment and a pkg-packaged executable. This helps understand file access within the snapshot filesystem. ```text | value | with `node` | packaged | comments | | ----------------------------- | --------------- | ------------------------ | ------------------------------ | | __filename | /project/app.js | /snapshot/project/app.js | | | __dirname | /project | /snapshot/project | | | process.cwd() | /project | /deploy | suppose the app is called ... | | process.execPath | /usr/bin/nodejs | /deploy/app-x64 | `app-x64` and run in `/deploy` | | process.argv[0] | /usr/bin/nodejs | /deploy/app-x64 | | | process.argv[1] | /project/app.js | /snapshot/project/app.js | | | process.pkg.entrypoint | undefined | /snapshot/project/app.js | | | process.pkg.defaultEntrypoint | undefined | /snapshot/project/app.js | | | require.main.filename | /project/app.js | /snapshot/project/app.js | | ``` -------------------------------- ### pkg Project Structure Overview Source: https://github.com/vercel/pkg/wiki/Developers Provides a high-level view of the pkg project's directory structure. It lists the main folders, indicating their general purpose within the project's architecture. ```bash pkg ├── dictionary ├── examples ├── lib ├── prelude └── test ``` -------------------------------- ### PKG Command-Line Options Source: https://github.com/vercel/pkg/blob/main/README.md Common command-line flags for the Vercel PKG tool to control build behavior, such as disabling bytecode compilation, building from source, and applying compression. ```bash pkg --no-bytecode app.js ``` ```bash pkg --build app.js ``` ```bash pkg --compress Brotli app.js ``` ```bash pkg -C GZip app.js ``` -------------------------------- ### PKG Environment Variables and Usage Source: https://github.com/vercel/pkg/blob/main/README.md Configuration options for PKG via environment variables and how packaged applications are invoked. Includes cache path, ignore tags, and job count for builds. ```APIDOC Environment Variables: PKG_CACHE_PATH: Description: Used to specify a custom path for node binaries cache folder. Default is ~/.pkg-cache PKG_IGNORE_TAG: Description: Allows to ignore additional folder created on PKG_CACHE_PATH matching pkg-fetch version MAKE_JOB_COUNT: Description: Allow configuring number of processes used for compiling Usage Examples: # 1 - Using export export PKG_CACHE_PATH=/my/cache pkg app.js # 2 - Passing it before the script PKG_CACHE_PATH=/my/cache pkg app.js Packaged App Usage: Command line call to packaged app './app a b' is equivalent to 'node app.js a b' ``` -------------------------------- ### pkg Command-Line Interface Source: https://github.com/vercel/pkg/blob/main/README.md The `pkg` CLI tool allows packaging Node.js projects into single executable files. It supports cross-compilation, asset embedding, and various configuration options for creating distributable applications. The entrypoint can be a file, package.json, or a directory. ```APIDOC pkg [options] The `pkg` command packages a Node.js project into a single executable file. : The entrypoint of your project. This can be: - Path to entry file (e.g., `index.js`). Packaged app behaves like `node /path/app.js`. - Path to `package.json`. `pkg` follows the `bin` property as the entry file. - Path to directory. `pkg` looks for `package.json` in the directory. Options: -h, --help output usage information -v, --version output pkg version -t, --targets comma-separated list of targets (e.g., `node16-linux-arm64`, `node18-win-x64`). -c, --config package.json or any json file with top-level config. --options bake v8 options into executable to run with them on (e.g., `--options "expose-gc,max-heap-size=34"`). -o, --output output file name or template for several files. --out-path path to save output one or more executables. -d, --debug show more information during packaging process [off]. -b, --build don't download prebuilt base binaries, build them. --public speed up and disclose the sources of top-level project. --public-packages force specified packages to be considered public (e.g., `--public-packages "packageA,packageB"` or `--public-packages "*"`). --no-bytecode skip bytecode generation and include source files as plain js. --no-native-build skip native addons build. --no-signature skip signature of the final executable on macos. --no-dict comma-separated list of packages names to ignore dictionaries. Use `--no-dict *` to disable all dictionaries. -C, --compress [default=None] compression algorithm = Brotli or GZip (e.g., `--compress GZip`). Examples: # Makes executables for Linux, macOS and Windows $ pkg index.js # Takes package.json from cwd and follows 'bin' entry $ pkg . # Makes executable for particular target machine $ pkg -t node16-win-arm64 index.js # Makes executables for target machines of your choice $ pkg -t node16-linux,node18-linux,node16-win index.js # Bakes '--expose-gc' and '--max-heap-size=34' into executable $ pkg --options "expose-gc,max-heap-size=34" index.js # Consider packageA and packageB to be public $ pkg --public-packages "packageA,packageB" index.js # Consider all packages to be public $ pkg --public-packages "*" index.js # Bakes '--expose-gc' into executable $ pkg --options expose-gc index.js # reduce size of the data packed inside the executable with GZip $ pkg --compress GZip index.js ``` -------------------------------- ### Detecting Assets with path.join Source: https://github.com/vercel/pkg/blob/main/README.md Demonstrates how pkg automatically detects and packages files specified as assets when using `path.join` with a string literal argument. This can bypass the need for explicit `pkg` configuration. ```javascript path.join(__dirname, '../path/to/asset') ``` -------------------------------- ### pkg API: Executing Package Builds Source: https://github.com/vercel/pkg/blob/main/README.md Shows how to use the `pkg` module programmatically to execute build commands. It returns a promise that resolves after the packaging process is complete. ```javascript const { exec } = require('pkg'); async function buildPackage() { try { await exec(['app.js', '--target', 'host', '--output', 'app.exe']); console.log('Package built successfully!'); // Further actions with app.exe } catch (error) { console.error('Package build failed:', error); } } ``` -------------------------------- ### pkg Configuration in package.json Source: https://github.com/vercel/pkg/blob/main/README.md Manually specify files and build configurations for pkg within your project's package.json. This includes glob patterns for scripts and assets, target platforms, and output paths. ```json { "pkg": { "scripts": "build/**/*.js", "assets": "views/**/*", "targets": [ "node14-linux-arm64" ], "outputPath": "dist" } } ``` ```json { "pkg": { "assets": [ "assets/**/*", "images/**/*" ] } } ``` -------------------------------- ### pkg Command-Line Options for Output Source: https://github.com/vercel/pkg/blob/main/README.md Control the output location and naming of executables generated by pkg. Use --output for a single executable or --out-path for multiple target executables. ```shell pkg app.js --output my-app ``` ```shell pkg app.js --out-path ./builds ``` -------------------------------- ### pkg stepPatch Function Logic Source: https://github.com/vercel/pkg/wiki/Developers Details the `stepPatch` function from `lib/walker.js`, which applies code patches to files. It explains how the function handles different patch types, including string replacement, prepending, appending, and erasing code, based on the patch configuration. ```js stepPatch(record) { const patch = this.patches[record.file]; if (!patch) return; let body = record.body.toString('utf8'); for (let i = 0; i < patch.length; i += 2) { if (typeof patch[i] === 'object') { if (patch[i].do === 'erase') { body = patch[i + 1]; } else if (patch[i].do === 'prepend') { body = patch[i + 1] + body; } else if (patch[i].do === 'append') { body += patch[i + 1]; } } else if (typeof patch[i] === 'string') { const esc = patch[i].replace(/[.*+?^${}()|[]\\]/g, '\\$&'); const regexp = new RegExp(esc, 'g'); body = body.replace(regexp, patch[i + 1]); } } record.body = body; } ``` -------------------------------- ### Iterate Object Keys in JavaScript Source: https://github.com/vercel/pkg/blob/main/test/test-79-npm/babel-core/babel-core.txt This snippet demonstrates how to iterate over the keys of a JavaScript object using `Object.keys()` and the `some()` method. It logs each key to the console. This is a common pattern for inspecting object properties. ```javascript let p = process; Object.keys(p).some((key) => { console.log(key); }); ``` -------------------------------- ### pkg Command-Line Options for Debugging Source: https://github.com/vercel/pkg/blob/main/README.md Enable verbose logging during the packaging process by passing the --debug flag to pkg. This is useful for troubleshooting issues with file packaging or build steps. ```shell pkg app.js --debug ``` -------------------------------- ### Explore pkg Virtual File System in Debug Mode Source: https://github.com/vercel/pkg/blob/main/README.md When building executables with the `--debug` flag, pkg allows inspection of the embedded virtual file system and symlink table by setting the `DEBUG_PKG` environment variable. This is useful for verifying file inclusion and symlink handling. Note: Do not use `--debug` in production. ```bash pkg --debug app.js -o output DEBUG_PKG=1 output ``` ```powershell pkg --debug app.js -o output.exe set DEBUG_PKG=1 output.exe ``` -------------------------------- ### Generate HTML Table from Data Source: https://github.com/vercel/pkg/blob/main/test/test-79-npm/checklist.htm This snippet iterates through a data object (assumed to be `table`), extracts keys and values to build an HTML table string. It generates column headers by processing keys, replacing specific substrings for display. Data cells are populated, and styling (background and text color) is applied conditionally based on cell content like 'ok', 'nop', 'n/a', or 'error'. Finally, the complete HTML table is set as the innerHTML of the document body. ```javascript var add = ''; var columns = []; add = add + ''; add = add + ''; Object.keys(table).forEach(function (row_key) { var row = table[row_key]; Object.keys(row).forEach(function (cell_key) { if (columns.indexOf(cell_key) < 0) { var narrow = cell_key .replace(/\//g, '
') .replace(/win32/g, 'win') .replace(/linux/g, 'lnx') .replace(/darwin/g, 'dwn'); add = add + ''; columns.push(cell_key); } }); }); add = add + ''; Object.keys(table).forEach(function (row_key) { var row = table[row_key]; add = add + ''; add = add + ''; columns.forEach(function (column) { var cell = row[column]; if (typeof cell === 'undefined') cell = 'n/a'; cell = cell.split(',')[0]; cell = cell.replace(/error/g, 'err'); var bcolor = 'red'; var fcolor = 'white'; if (cell === 'ok') bcolor = 'green'; if (cell === 'nop') bcolor = 'blue'; if (cell === 'n/a') { cell = 'n/a'; bcolor = 'white'; fcolor = 'black'; } var style = 'background-color:' + bcolor; style = style + ';color:' + fcolor; add = add + "'; }); add = add + ''; }); add = add + '
' + narrow + '
' + row_key + '" + cell + '
'; document.body.innerHTML = add; ``` -------------------------------- ### Troubleshoot NODE_OPTIONS Conflict with pkg Source: https://github.com/vercel/pkg/blob/main/README.md This section addresses an error where `require(...).internalModuleStat` is not a function, often caused by `NODE_OPTIONS` environment variables conflicting with pkg. It provides instructions on how to check for these variables on Unix-like systems. ```bash printenv | grep NODE ``` -------------------------------- ### Export String Value Source: https://github.com/vercel/pkg/blob/main/test/test-50-node-modules-tree/node_modules/test-y-fish-O/node_modules/test-y-fish-O/index.txt This snippet demonstrates exporting a string literal from a Node.js module. It utilizes the `module.exports` syntax, which is standard in CommonJS environments for making module content available to other modules. The exported value is a simple string. ```javascript module.exports = "test-y-fish-O-subpackage"; ``` -------------------------------- ### Vercel PKG Module Export Source: https://github.com/vercel/pkg/blob/main/test/test-50-package-json/test-y-resolve-B.txt This snippet shows a basic JavaScript module export for the /vercel/pkg project. It exports a string value, typical for Node.js modules. ```javascript module.exports = "test-y-resolve-B"; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.