### Commander.js Command Definitions and Actions Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/commander/Readme.md This comprehensive example defines multiple commands ('setup', 'exec', and a catch-all '*') with options, descriptions, and action handlers. It also shows how to use aliases and attach help listeners to specific 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); ``` -------------------------------- ### Install Source Map Support with Options Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/source-map-support/README.md Installs source-map-support with custom options. This example shows how to disable the default uncaught exception handler by passing `{ handleUncaughtExceptions: false }` to the install function. This is useful if you have your own exception handling mechanism. ```javascript require('source-map-support').install({ handleUncaughtExceptions: false }); ``` -------------------------------- ### Install buffer-from package Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/buffer-from/readme.md This command installs the 'buffer-from' package as a project dependency using npm. ```sh npm install --save buffer-from ``` -------------------------------- ### Installing Tapable Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tapable/README.md This command shows how to install the tapable package as a project dependency using npm. It is a common step for projects that utilize tapable for their plugin system. ```shell npm install --save tapable ``` -------------------------------- ### Install Dependencies and Run Tests (npm) Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md This command installs project dependencies using npm and then executes the test suite. It's a common way to verify code integrity and functionality before or after making changes. ```shell npm install && npm test ``` -------------------------------- ### Install detect-libc using npm Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/detect-libc/README.md This command installs the 'detect-libc' Node.js module. It is a prerequisite for using the module in your project. ```sh npm install detect-libc ``` -------------------------------- ### Install @jridgewell/trace-mapping Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@jridgewell/trace-mapping/README.md Installs the @jridgewell/trace-mapping package using npm. This is the first step to using the library in your project. ```sh npm install @jridgewell/trace-mapping ``` -------------------------------- ### Picomatch Scan with Tokens Example (JavaScript) Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md Demonstrates how to use the .scan method with the 'tokens' option enabled to get a detailed breakdown of a glob pattern. It shows the structure of the returned object, including prefix, input, glob segments, and tokenized parts. ```javascript const picomatch = require('picomatch'); const result = picomatch.scan('!./foo/*.js', { tokens: true }); console.log(result); // { // prefix: '!./', // input: '!./foo/*.js', // start: 3, // base: 'foo', // glob: '*.js', // isBrace: false, // isBracket: false, // isGlob: true, // isExtglob: false, // isGlobstar: false, // negated: true, // maxDepth: 2, // tokens: [ // { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, // { value: 'foo', depth: 1, isGlob: false }, // { value: '*.js', depth: 1, isGlob: true } // ], // slashes: [ 2, 6 ], // parts: [ 'foo', '*.js' ] // } ``` -------------------------------- ### Install @jridgewell/sourcemap-codec Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@jridgewell/sourcemap-codec/README.md Installs the sourcemap-codec package using npm. This is the first step to using the encoding and decoding functionalities. ```bash npm install @jridgewell/sourcemap-codec ``` -------------------------------- ### Install Picomatch using npm Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md This snippet shows how to install the picomatch package using npm. It's a standard command for adding JavaScript libraries to a project. ```sh npm install --save picomatch ``` -------------------------------- ### Minipass Stream Examples Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/minipass/README.md Illustrates various ways to use Minipass streams, including promise-based operations, data collection, and iteration. ```APIDOC ## Minipass Stream Examples ### Description This section provides practical examples of how to use Minipass streams for common tasks. ### Simple "Are You Done Yet" Promise ```javascript mp.promise().then( () => { // stream is finished }, er => { // stream emitted an error } ) ``` ### Collecting All Data ```javascript mp.collect().then(all => { // 'all' is an array of all the data emitted. // If an encoding was specified, the result will be an array of strings. // Otherwise, it will be an array of buffers or objects. // In an async function, you can use: // const data = await stream.collect() }) ``` ### Collecting into a Single Blob ```javascript mp.concat().then(onebigchunk => { // 'onebigchunk' is a string if the stream had an encoding set, or a buffer otherwise. // This method concatenates all data into a single chunk. }) ``` ### Synchronous Iteration ```javascript const mp = new Minipass({ objectMode: true }) pm.write('a') pm.write('b') for (let letter of mp) { console.log(letter) // Output: a, b } pm.write('c') pm.write('d') for (let letter of mp) { console.log(letter) // Output: c, d } pm.write('e') pm.end() for (let letter of mp) { console.log(letter) // Output: e } for (let letter of mp) { console.log(letter) // Output: (nothing) } // Note: Synchronous iteration ends when currently available data is consumed. // For objectMode streams, chunks are yielded as written. // In string/buffer mode, data is concatenated unless multiple writes occur in the same tick. ``` ### Asynchronous Iteration ```javascript const mp = new Minipass({ encoding: 'utf8' }) // Example data source let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // Consume data with asynchronous iteration async function consume() { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // Expected output: 'foo\n' logged 5 times, followed by 'ok' ``` ### Subclassing for Custom Behavior (Logger Example) ```javascript class Logger extends Minipass { write(chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end(chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } // Example usage: someSource.pipe(new Logger()).pipe(someDest) ``` ``` -------------------------------- ### Install @ampproject/remapping Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@ampproject/remapping/README.md Installs the @ampproject/remapping package using npm. This is the first step to using the library in your project. ```sh npm install @ampproject/remapping ``` -------------------------------- ### Install @jridgewell/set-array using npm Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@jridgewell/set-array/README.md This command installs the @jridgewell/set-array package using npm. It is a prerequisite for using the library in your project. ```sh npm install @jridgewell/set-array ``` -------------------------------- ### onMatch Callback Example (JavaScript) Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md Demonstrates the 'onMatch' option, which allows you to execute a callback function every time a pattern matches. The callback receives an object containing details about the match. ```javascript const picomatch = require('picomatch'); const onMatch = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onMatch }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` -------------------------------- ### Combined Terser Minify Options Example Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/terser/README.md This JavaScript example demonstrates a combination of Terser's `minify` options, including `toplevel`, `compress` with `global_defs` and `passes`, and `format` with `preamble`. ```javascript var code = { "file1.js": "function add(first, second) { return first + second; }", "file2.js": "console.log(add(1 + 2, 3 + 4));" }; var options = { toplevel: true, compress: { global_defs: { "@console.log": "alert" }, passes: 2 }, format: { preamble: "/* minified */" } }; var result = await minify(code, options); console.log(result.code); ``` -------------------------------- ### Basic magic-string usage for string manipulation and sourcemap generation Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/magic-string/README.md This JavaScript example demonstrates the core functionality of magic-string. It shows how to initialize a MagicString instance, perform updates, prepend/append content, and generate a sourcemap. The example also includes writing the modified string and its sourcemap to files. ```javascript import MagicString from 'magic-string'; import fs from 'fs'; const s = new MagicString('problems = 99'); s.update(0, 8, 'answer'); s.toString(); // 'answer = 99' s.update(11, 13, '42'); // character indices always refer to the original string s.toString(); // 'answer = 42' s.prepend('var ').append(';'); // most methods are chainable s.toString(); // 'var answer = 42;' const map = s.generateMap({ source: 'source.js', file: 'converted.js.map', includeContent: true, }); // generates a v3 sourcemap fs.writeFileSync('converted.js', s.toString()); fs.writeFileSync('converted.js.map', map.toString()); ``` -------------------------------- ### Node.js Core Stream Buffering Example Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/minipass/README.md Demonstrates how Node.js core streams with PassThrough can lead to significant buffering and event deferrals when writing data larger than the highWaterMark. This example illustrates the potential for performance degradation due to intermediate buffering. ```javascript const { PassThrough } = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` -------------------------------- ### Custom String Formatting for Matching (JavaScript) Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md Shows how to use the 'format' option to preprocess strings before matching. This example defines a function to strip leading './' from paths, allowing for more flexible matching. ```javascript const picomatch = require('picomatch'); // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')); //=> true ``` -------------------------------- ### Basic Minification with Terser API Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/terser/README.md This JavaScript example shows the basic usage of the asynchronous `minify` function from Terser. It takes code as a string and options, returning the minified code and source map. ```javascript var code = "function add(first, second) { return first + second; }"; var result = await minify(code, { sourceMap: true }); console.log(result.code); // minified output: function add(n,d){return n+d} console.log(result.map); // source map ``` -------------------------------- ### onIgnore Callback Example (JavaScript) Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md Illustrates the 'onIgnore' option, which triggers a callback function when a pattern is ignored due to the 'ignore' option. The callback provides details about the ignored match. ```javascript const picomatch = require('picomatch'); const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` -------------------------------- ### Get Tarball Filenames using JavaScript Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tar/README.md An example derived from 'tar tf my-tarball.tgz' to specifically retrieve a list of filenames from a tar archive. It uses the 'onReadEntry' callback to collect entry paths into an array. ```javascript const getEntryFilenames = async tarballFilename => { const filenames = [] await tar.t({ file: tarballFilename, onReadEntry: entry => filenames.push(entry.path), }) return filenames } ``` -------------------------------- ### Build Documentation with Verb (npm) Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md This command installs the 'verbose/verb' package globally along with the 'verb-generate-readme' plugin, and then executes the 'verb' command to generate the project's README file. This process relies on a specific readme template (.verb.md) and is managed by the Verb tool. ```shell npm install -g verbose/verb#dev verb-generate-readme && verb ``` -------------------------------- ### Initializing a SyncHook Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tapable/README.md Demonstrates the basic initialization of a SyncHook. Hooks are initialized with an optional array of argument names as strings, which helps in documenting and potentially validating the arguments passed to the hooks. ```javascript const hook = new SyncHook(["arg1", "arg2", "arg3"]); ``` -------------------------------- ### Get Source Map Module Reference Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/source-map/README.md Provides examples for obtaining a reference to the source-map module in different JavaScript environments, including Node.js, browsers, and Firefox developer tools. ```javascript // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` -------------------------------- ### Usage Examples for buffer-from Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/buffer-from/readme.md Demonstrates various ways to use the buffer-from function, including creating Buffers from arrays, ArrayBuffer views, strings, and other Buffers. It shows how to specify byte offsets and lengths when working with ArrayBuffers. ```javascript const bufferFrom = require('buffer-from') console.log(bufferFrom([1, 2, 3, 4])) //=> const arr = new Uint8Array([1, 2, 3, 4]) console.log(bufferFrom(arr.buffer, 1, 2)) //=> console.log(bufferFrom('test', 'utf8')) //=> const buf = bufferFrom('test') console.log(bufferFrom(buf)) //=> ``` -------------------------------- ### Adjusting string offset with MagicString Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/magic-string/README.md This TypeScript example shows how to modify the `offset` property of a MagicString instance. Changing the offset affects how subsequent operations like `slice`, `update`, and others interpret character indices, allowing for adjustments to the perceived start of the string. ```typescript const s = new MagicString('hello world', { offset: 0 }); s.offset = 6; s.slice() === 'world'; ``` -------------------------------- ### Install magic-string via npm Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/magic-string/README.md This command installs the magic-string package using npm, making it available for use in Node.js projects. It's a direct installation command. ```bash npm i magic-string ``` -------------------------------- ### Passing Options to createJiti Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/jiti/README.md Shows how to pass options, such as 'debug', when initializing a jiti instance. ```javascript const jiti = createJiti(import.meta.url, { debug: true }); ``` -------------------------------- ### Create Tarball with Gzip to File using JavaScript Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tar/README.md Mimics 'tar cz files and folders > my-tarball.tgz'. This example creates a gzipped tarball from specified files and folders and pipes the output to a file. It demonstrates the use of the 'c' alias for create and the 'z' alias for gzip. ```javascript // if you're familiar with the tar(1) cli flags, this can be nice import * as tar from 'tar' tar.c( { // 'z' is alias for 'gzip' option z: }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` -------------------------------- ### Install @jridgewell/source-map Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@jridgewell/source-map/README.md Installs the @jridgewell/source-map package using npm. This is the primary step to include the library in your project. ```sh npm install @jridgewell/source-map ``` -------------------------------- ### Output Help Without Exiting using Commander.js Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/commander/Readme.md This example demonstrates how to use the `.outputHelp()` method to display help information without exiting the program. It includes an optional callback to modify the help text before display, such as coloring it red. ```javascript var program = require('commander'); var colors = require('colors'); program .version('0.1.0') .command('getstream [url]', 'get stream URL') .parse(process.argv); if (!process.argv.slice(2).length) { program.outputHelp(make_red); } function make_red(txt) { return colors.red(txt); //display the help text in red on the console } ``` -------------------------------- ### Install @jridgewell/resolve-uri Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@jridgewell/resolve-uri/README.md Installs the @jridgewell/resolve-uri package using npm. This is the first step to using the package in your project. ```sh npm install @jridgewell/resolve-uri ``` -------------------------------- ### Basic Usage of Picomatch Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md Demonstrates the fundamental usage of picomatch. It imports the library, creates a matcher function for '*.js' files, and then uses this function to test various strings. ```javascript const pm = require('picomatch'); const isMatch = pm('*.js'); console.log(isMatch('abcd')); //=> false console.log(isMatch('a.js')); //=> true console.log(isMatch('a.md')); //=> false console.log(isMatch('a/b.js')); //=> false ``` -------------------------------- ### Tapping a SyncHook with Arguments Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tapable/README.md Demonstrates tapping a SyncHook that expects arguments. The provided plugin function receives these arguments, allowing it to react to specific data, such as a new speed value. ```javascript myCar.hooks.accelerate.tap("LoggerPlugin", (newSpeed) => console.log(`Accelerating to ${newSpeed}`) ); ``` -------------------------------- ### Install @jridgewell/gen-mapping Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@jridgewell/gen-mapping/README.md Install the gen-mapping package using npm. This package is used for generating source maps. ```sh npm install @jridgewell/gen-mapping ``` -------------------------------- ### Create and Use HookMap (JavaScript) Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tapable/README.md Illustrates the usage of HookMap, a utility for managing a map of hooks where each key corresponds to a specific hook instance. This allows for dynamic creation and retrieval of hooks based on keys, facilitating organized management of multiple related hooks. ```javascript const keyedHook = new HookMap((key) => new SyncHook(["arg"])); ``` ```javascript keyedHook.for("some-key").tap("MyPlugin", (arg) => { /* ... */ }); keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => { /* ... */ }); keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => { /* ... */ }); ``` ```javascript const hook = keyedHook.get("some-key"); if (hook !== undefined) { hook.callAsync("arg", (err) => { /* ... */ }); } ``` -------------------------------- ### Generate Source Map with Existing Content Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/terser/README.md This example demonstrates how to generate a source map when you already have the content of the original source map. The `sourceMap.content` option takes the source map content as a string, allowing the minifier to process and combine it. ```javascript var result = await minify({"compiled.js": "compiled code"}, { sourceMap: { content: "content from compiled.js.map", url: "minified.js.map" } }); // same as before, it returns `code` and `map` ``` -------------------------------- ### Instantiate SourceMapConsumer Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/source-map-js/README.md Demonstrates how to create a SourceMapConsumer instance by passing raw source map data. The consumer can then be used to query information about the original source positions. ```javascript var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); ``` -------------------------------- ### Basic Usage of tinyglobby Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tinyglobby/README.md Demonstrates how to import and use the `glob` and `globSync` functions from the tinyglobby library for finding files based on patterns. It shows examples of including and excluding files, and specifying the current working directory. ```javascript import { glob, globSync } from 'tinyglobby'; await glob(['files/*.ts', '!**/*.d.ts'], { cwd: 'src' }); globSync(['src/**/*.ts'], { ignore: ['**/*.d.ts'] }); ``` -------------------------------- ### Asynchronous Directory Creation with mkdirp Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/mkdirp/readme.markdown Demonstrates how to create directories recursively using the asynchronous Promise-based API of mkdirp. It logs the first directory that was created. This method is suitable for non-blocking operations. ```javascript // hybrid module, import or require() both work import { mkdirp } from 'mkdirp' // or: const { mkdirp } = require('mkdirp') // return value is a Promise resolving to the first directory created mkdirp('/tmp/foo/bar/baz').then(made => console.log(`made directories, starting with ${made}`) ) ``` -------------------------------- ### Install enhanced-resolve using npm or Yarn Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/enhanced-resolve/README.md This snippet shows how to install the enhanced-resolve package using either npm or Yarn package managers. It's a prerequisite for using the library. ```shell # npm npm install enhanced-resolve # or Yarn yarn add enhanced-resolve ``` -------------------------------- ### Picomatch API: Creating a Matcher Function Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/picomatch/README.md Illustrates how to use the main `picomatch` function to create a matcher. This function accepts glob patterns and options, returning a specialized matching function. The example shows matching strings against a pattern that excludes files ending in '.a'. ```javascript const picomatch = require('picomatch'); // picomatch(glob[, options]); const isMatch = picomatch('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` -------------------------------- ### Install fsevents Node.js Package Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/fsevents/README.md Installs the fsevents Node.js package using npm. This is the first step to using native FSEvents access in your project. ```sh npm install fsevents ``` -------------------------------- ### Install source-map-support via npm Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/source-map-support/README.md This command installs the 'source-map-support' package using npm, making it available for use in your Node.js project. It is a prerequisite for enabling source map support. ```bash $ npm install source-map-support ``` -------------------------------- ### Create Gzipped Tarball using JavaScript Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tar/README.md Replicates the 'tar czf my-tarball.tgz files and folders' command. This example shows how to create a gzipped tarball with a specified file name and includes files and folders. It utilizes the 'create' function from the 'tar' module. ```javascript import { create } from 'tar' create( { gzip: , file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` -------------------------------- ### Debug Property Name Mangling Output Example Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/terser/README.md This JavaScript code snippet shows an example of how property names are mangled when the `--mangle-props debug` option is used. The mangled names retain a readable prefix and suffix. ```javascript var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_); ``` -------------------------------- ### Terser Minify Error Handling Example Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/terser/README.md This JavaScript example shows how to handle potential errors during the Terser `minify` operation using a try-catch block. It demonstrates how to access error details like message, filename, line, and column. ```javascript try { const result = await minify({"foo.js" : "if (0) else console.log(1);"}); // Do something with result } catch (error) { const { message, filename, line, col, pos } = error; // Do something with error } ``` -------------------------------- ### Install fdir using npm or Yarn Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/fdir/README.md This snippet shows how to install the fdir package using either npm or Yarn package managers. fdir is a NodeJS module for directory crawling. ```sh npm i fdir ``` ```sh yarn add fdir ``` -------------------------------- ### Install Source Map Support Specifying Environment Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/source-map-support/README.md Installs source-map-support and explicitly sets the execution environment. This is useful in environments where the module might misinterpret the environment (e.g., browser emulation). You can set it to 'node' or 'browser'. ```javascript require('source-map-support').install({ environment: 'node' }); ``` -------------------------------- ### Run CoffeeScript Demo with Source Map Support Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/source-map-support/README.md Demonstrates how to compile and run a CoffeeScript file that utilizes source map support. It requires installing dependencies and then compiling and executing the JavaScript output. The output shows an error traceback with source map information. ```coffeescript require('source-map-support').install() foo = -> bar = -> throw new Error 'this is a demo' bar() foo() ``` ```sh $ npm install source-map-support coffeescript $ node_modules/.bin/coffee --map --compile demo.coffee $ node demo.js ``` -------------------------------- ### CLI Usage of jiti Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/jiti/README.md Demonstrates how to use the jiti CLI to run a script with TypeScript and native ESM support. ```bash npx jiti ./index.ts ``` -------------------------------- ### TypeScript Custom Event Stream Example Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/minipass/README.md Demonstrates how to create a custom stream in TypeScript by extending Minipass and defining custom events. This example shows a NDJSONStream that emits a 'jsonError' event when JSON stringification fails. It highlights type safety for emitted event arguments. ```typescript import { Minipass } from 'minipass' // a NDJSON stream that emits 'jsonError' when it can't stringify export interface Events extends Minipass.Events { jsonError: [e: Error] } export class NDJSONStream extends Minipass { constructor() { super({ objectMode: true }) } // data is type `any` because that's WType write(data, encoding, cb) { try { const json = JSON.stringify(data) return super.write(json + '\n', encoding, cb) } catch (er) { if (!er instanceof Error) { er = Object.assign(new Error('json stringify failed'), { cause: er, }) } // trying to emit with something OTHER than an error will // fail, because we declared the event arguments type. this.emit('jsonError', er) } } } const s = new NDJSONStream() s.on('jsonError', e => { // here, TS knows that e is an Error }) ``` -------------------------------- ### Install Source Map Support with Custom Source Map Retrieval Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/source-map-support/README.md Installs source-map-support and provides a custom function to retrieve source maps. The `retrieveSourceMap` callback allows for alternative loading strategies, such as reading from the filesystem or using an in-memory cache, as demonstrated with `fs.readFileSync`. ```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; } }); ``` -------------------------------- ### Programmatic Initialization of jiti Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/jiti/README.md Shows how to initialize a jiti instance programmatically in both ESM and CommonJS environments. ```javascript // ESM import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); // CommonJS (deprecated) const { createJiti } = require("jiti"); const jiti = createJiti(__filename); ``` -------------------------------- ### Usage of SetArray in JavaScript Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/@jridgewell/set-array/README.md Demonstrates how to use the SetArray, get, put, and pop functions. It shows adding elements, retrieving their indices, and removing elements. The 'put' function adds an element and returns its index, while 'get' retrieves the index of an existing element. 'pop' removes the last element. ```javascript 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' ]); ``` -------------------------------- ### Synchronous Directory Creation with mkdirp Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/mkdirp/readme.markdown Illustrates the synchronous way to create directories recursively using mkdirp. This method blocks the event loop until the operation is complete and returns the first directory that was created. Use with caution in performance-sensitive applications. ```javascript import { mkdirp } from 'mkdirp' // return value is the first directory created const made = mkdirp.sync('/tmp/foo/bar/baz') console.log(`made directories, starting with ${made}`) ``` -------------------------------- ### Generate Evenly Spaced Numbers (TypeScript) Source: https://context7.com/mmilanta/probable-spork-web/llms.txt A utility function that generates an array of evenly spaced numbers between a start and stop value, with a specified gap. This is essential for creating smooth curves in probability visualizations. It takes start, stop, and gap values, returning an array of numbers. ```typescript import { linspace } from './loadAlgo'; // Generate points for plotting const probPoints = linspace(0, 1, 0.01); // Returns: [0, 0.01, 0.02, ..., 0.99, 1] const lengthPoints = linspace(0, 12, 0.5); // Returns: [0, 0.5, 1, 1.5, ..., 11.5, 12] // Use for optimality curve (y = x^2) const fairnessRange = linspace(0, 15, 0.1); const optimalityCurve = fairnessRange.map(x => ({ x, y: x * x })); // Creates parabola points for the conjectured bound ``` -------------------------------- ### Tar WriteEntry.Tar Constructor Options Source: https://github.com/mmilanta/probable-spork-web/blob/main/node_modules/tar/README.md Specifies the options for the tar.WriteEntry.Tar constructor, which creates entries from an existing tar.ReadEntry. It supports similar options to tar.WriteEntry regarding portability, path preservation, strict error handling, and warning callbacks. ```javascript constructor(readEntry, options) { // Options: // - portable: Omit system-specific metadata (ctime, atime, uid, gid, uname, gname, dev, ino, nlink). // - preservePaths: Allow absolute paths (defaults to stripping '/'). // - strict: Treat warnings as errors (defaults to false). // - onwarn: Callback function for warnings (code, message, data). // - noMtime: Omit writing mtime values (prevents mtime-based features). } ```