npm-pkg-lint 4.3.4 → 4.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../node_modules/argparse/lib/sub.js", "../node_modules/argparse/lib/textwrap.js", "../node_modules/argparse/argparse.js", "../node_modules/tmp/lib/tmp.js", "../node_modules/semver/internal/constants.js", "../node_modules/semver/internal/debug.js", "../node_modules/semver/internal/re.js", "../node_modules/semver/internal/parse-options.js", "../node_modules/semver/internal/identifiers.js", "../node_modules/semver/classes/semver.js", "../node_modules/semver/functions/parse.js", "../node_modules/semver/functions/valid.js", "../node_modules/semver/functions/clean.js", "../node_modules/semver/functions/inc.js", "../node_modules/semver/functions/diff.js", "../node_modules/semver/functions/major.js", "../node_modules/semver/functions/minor.js", "../node_modules/semver/functions/patch.js", "../node_modules/semver/functions/prerelease.js", "../node_modules/semver/functions/compare.js", "../node_modules/semver/functions/rcompare.js", "../node_modules/semver/functions/compare-loose.js", "../node_modules/semver/functions/compare-build.js", "../node_modules/semver/functions/sort.js", "../node_modules/semver/functions/rsort.js", "../node_modules/semver/functions/gt.js", "../node_modules/semver/functions/lt.js", "../node_modules/semver/functions/eq.js", "../node_modules/semver/functions/neq.js", "../node_modules/semver/functions/gte.js", "../node_modules/semver/functions/lte.js", "../node_modules/semver/functions/cmp.js", "../node_modules/semver/functions/coerce.js", "../node_modules/semver/internal/lrucache.js", "../node_modules/semver/classes/range.js", "../node_modules/semver/classes/comparator.js", "../node_modules/semver/functions/satisfies.js", "../node_modules/semver/ranges/to-comparators.js", "../node_modules/semver/ranges/max-satisfying.js", "../node_modules/semver/ranges/min-satisfying.js", "../node_modules/semver/ranges/min-version.js", "../node_modules/semver/ranges/valid.js", "../node_modules/semver/ranges/outside.js", "../node_modules/semver/ranges/gtr.js", "../node_modules/semver/ranges/ltr.js", "../node_modules/semver/ranges/intersects.js", "../node_modules/semver/ranges/simplify.js", "../node_modules/semver/ranges/subset.js", "../node_modules/semver/index.js", "../src/index.ts", "../node_modules/kleur/colors.mjs", "../node_modules/@html-validate/stylish/node_modules/text-table/index.js", "../node_modules/@html-validate/stylish/src/stylish.ts", "../node_modules/@html-validate/stylish/src/colors-node.ts", "../node_modules/@html-validate/stylish/src/severity.ts", "../node_modules/@humanwhocodes/momoa/dist/momoa.js", "../node_modules/find-up/index.js", "../node_modules/locate-path/index.js", "../node_modules/p-locate/node_modules/yocto-queue/index.js", "../node_modules/p-locate/node_modules/p-limit/index.js", "../node_modules/p-locate/index.js", "../node_modules/unicorn-magic/node.js", "../src/blacklist/helpers.ts", "../src/blacklist/ava.ts", "../src/blacklist/emacs.ts", "../src/blacklist/eslint.ts", "../src/blacklist/fimbullinter.ts", "../src/blacklist/git.ts", "../src/blacklist/jest.ts", "../src/blacklist/node.ts", "../src/blacklist/prettier.ts", "../src/blacklist/typescript.ts", "../src/blacklist/windows.ts", "../src/blacklist/index.ts", "../src/blacklist.ts", "../src/tarball.ts", "../node_modules/@isaacs/fs-minipass/src/index.ts", "../node_modules/@isaacs/fs-minipass/node_modules/minipass/src/index.ts", "../node_modules/tar/src/create.ts", "../node_modules/tar/src/list.ts", "../node_modules/tar/src/options.ts", "../node_modules/tar/src/make-command.ts", "../node_modules/tar/src/parse.ts", "../node_modules/minizlib/src/index.ts", "../node_modules/minizlib/node_modules/minipass/src/index.ts", "../node_modules/minizlib/src/constants.ts", "../node_modules/tar/src/header.ts", "../node_modules/tar/src/large-numbers.ts", "../node_modules/tar/src/types.ts", "../node_modules/tar/src/pax.ts", "../node_modules/tar/node_modules/minipass/src/index.ts", "../node_modules/tar/src/normalize-windows-path.ts", "../node_modules/tar/src/read-entry.ts", "../node_modules/tar/src/warn-method.ts", "../node_modules/tar/src/strip-trailing-slashes.ts", "../node_modules/tar/src/pack.ts", "../node_modules/tar/src/write-entry.ts", "../node_modules/tar/src/mode-fix.ts", "../node_modules/tar/src/strip-absolute-path.ts", "../node_modules/tar/src/winchars.ts", "../node_modules/tar/node_modules/yallist/src/index.ts", "../node_modules/tar/src/extract.ts", "../node_modules/tar/src/unpack.ts", "../node_modules/tar/src/get-write-flag.ts", "../node_modules/chownr/src/index.ts", "../node_modules/tar/src/mkdir.ts", "../node_modules/tar/src/cwd-error.ts", "../node_modules/tar/src/symlink-error.ts", "../node_modules/tar/src/path-reservations.ts", "../node_modules/tar/src/normalize-unicode.ts", "../node_modules/tar/src/replace.ts", "../node_modules/tar/src/update.ts", "../src/tarball-location.ts", "../src/utils/persistent-cache.ts", "../src/utils/json-location.ts", "../node_modules/nano-spawn/source/context.js", "../node_modules/nano-spawn/source/options.js", "../node_modules/nano-spawn/source/spawn.js", "../node_modules/nano-spawn/source/windows.js", "../node_modules/nano-spawn/source/result.js", "../node_modules/nano-spawn/source/pipe.js", "../node_modules/nano-spawn/source/iterable.js", "../node_modules/nano-spawn/source/index.js", "../src/utils/npm-info.ts", "../src/rules/conflicting-types-typings.ts", "../src/rules/deprecated-dependency.ts", "../src/rules/disallowed-dependency.ts", "../src/rules/exports-types-order.ts", "../src/rules/obsolete-dependency.ts", "../src/rules/outdated-engines.ts", "../src/node-versions.ts", "../src/rules/prefer-types.ts", "../src/rules/shadowed-types.ts", "../src/rules/types-node-matching-engine.ts", "../src/rules/verify-engine-constraint.ts", "../src/validators/validation-error.ts", "../src/validators/non-empty.ts", "../src/validators/present.ts", "../src/validators/type-array.ts", "../src/validators/type-string.ts", "../src/validators/valid-repo-url.ts", "../src/validators/valid-url.ts", "../src/package-json.ts", "../src/shebang.ts", "../src/verify.ts"],
4
- "sourcesContent": ["// Limited implementation of python % string operator, supports only %s and %r for now\n// (other formats are not used here, but may appear in custom templates)\n\n'use strict'\n\nconst { inspect } = require('util')\n\n\nmodule.exports = function sub(pattern, ...values) {\n let regex = /%(?:(%)|(-)?(\\*)?(?:\\((\\w+)\\))?([A-Za-z]))/g\n\n let result = pattern.replace(regex, function (_, is_literal, is_left_align, is_padded, name, format) {\n if (is_literal) return '%'\n\n let padded_count = 0\n if (is_padded) {\n if (values.length === 0) throw new TypeError('not enough arguments for format string')\n padded_count = values.shift()\n if (!Number.isInteger(padded_count)) throw new TypeError('* wants int')\n }\n\n let str\n if (name !== undefined) {\n let dict = values[0]\n if (typeof dict !== 'object' || dict === null) throw new TypeError('format requires a mapping')\n if (!(name in dict)) throw new TypeError(`no such key: '${name}'`)\n str = dict[name]\n } else {\n if (values.length === 0) throw new TypeError('not enough arguments for format string')\n str = values.shift()\n }\n\n switch (format) {\n case 's':\n str = String(str)\n break\n case 'r':\n str = inspect(str)\n break\n case 'd':\n case 'i':\n if (typeof str !== 'number') {\n throw new TypeError(`%${format} format: a number is required, not ${typeof str}`)\n }\n str = String(str.toFixed(0))\n break\n default:\n throw new TypeError(`unsupported format character '${format}'`)\n }\n\n if (padded_count > 0) {\n return is_left_align ? str.padEnd(padded_count) : str.padStart(padded_count)\n } else {\n return str\n }\n })\n\n if (values.length) {\n if (values.length === 1 && typeof values[0] === 'object' && values[0] !== null) {\n // mapping\n } else {\n throw new TypeError('not all arguments converted during string formatting')\n }\n }\n\n return result\n}\n", "// Partial port of python's argparse module, version 3.9.0 (only wrap and fill functions):\n// https://github.com/python/cpython/blob/v3.9.0b4/Lib/textwrap.py\n\n'use strict'\n\n/*\n * Text wrapping and filling.\n */\n\n// Copyright (C) 1999-2001 Gregory P. Ward.\n// Copyright (C) 2002, 2003 Python Software Foundation.\n// Copyright (C) 2020 argparse.js authors\n// Originally written by Greg Ward <gward@python.net>\n\n// Hardcode the recognized whitespace characters to the US-ASCII\n// whitespace characters. The main reason for doing this is that\n// some Unicode spaces (like \\u00a0) are non-breaking whitespaces.\n//\n// This less funky little regex just split on recognized spaces. E.g.\n// \"Hello there -- you goof-ball, use the -b option!\"\n// splits into\n// Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/\nconst wordsep_simple_re = /([\\t\\n\\x0b\\x0c\\r ]+)/\n\nclass TextWrapper {\n /*\n * Object for wrapping/filling text. The public interface consists of\n * the wrap() and fill() methods; the other methods are just there for\n * subclasses to override in order to tweak the default behaviour.\n * If you want to completely replace the main wrapping algorithm,\n * you'll probably have to override _wrap_chunks().\n *\n * Several instance attributes control various aspects of wrapping:\n * width (default: 70)\n * the maximum width of wrapped lines (unless break_long_words\n * is false)\n * initial_indent (default: \"\")\n * string that will be prepended to the first line of wrapped\n * output. Counts towards the line's width.\n * subsequent_indent (default: \"\")\n * string that will be prepended to all lines save the first\n * of wrapped output; also counts towards each line's width.\n * expand_tabs (default: true)\n * Expand tabs in input text to spaces before further processing.\n * Each tab will become 0 .. 'tabsize' spaces, depending on its position\n * in its line. If false, each tab is treated as a single character.\n * tabsize (default: 8)\n * Expand tabs in input text to 0 .. 'tabsize' spaces, unless\n * 'expand_tabs' is false.\n * replace_whitespace (default: true)\n * Replace all whitespace characters in the input text by spaces\n * after tab expansion. Note that if expand_tabs is false and\n * replace_whitespace is true, every tab will be converted to a\n * single space!\n * fix_sentence_endings (default: false)\n * Ensure that sentence-ending punctuation is always followed\n * by two spaces. Off by default because the algorithm is\n * (unavoidably) imperfect.\n * break_long_words (default: true)\n * Break words longer than 'width'. If false, those words will not\n * be broken, and some lines might be longer than 'width'.\n * break_on_hyphens (default: true)\n * Allow breaking hyphenated words. If true, wrapping will occur\n * preferably on whitespaces and right after hyphens part of\n * compound words.\n * drop_whitespace (default: true)\n * Drop leading and trailing whitespace from lines.\n * max_lines (default: None)\n * Truncate wrapped lines.\n * placeholder (default: ' [...]')\n * Append to the last line of truncated text.\n */\n\n constructor(options = {}) {\n let {\n width = 70,\n initial_indent = '',\n subsequent_indent = '',\n expand_tabs = true,\n replace_whitespace = true,\n fix_sentence_endings = false,\n break_long_words = true,\n drop_whitespace = true,\n break_on_hyphens = true,\n tabsize = 8,\n max_lines = undefined,\n placeholder=' [...]'\n } = options\n\n this.width = width\n this.initial_indent = initial_indent\n this.subsequent_indent = subsequent_indent\n this.expand_tabs = expand_tabs\n this.replace_whitespace = replace_whitespace\n this.fix_sentence_endings = fix_sentence_endings\n this.break_long_words = break_long_words\n this.drop_whitespace = drop_whitespace\n this.break_on_hyphens = break_on_hyphens\n this.tabsize = tabsize\n this.max_lines = max_lines\n this.placeholder = placeholder\n }\n\n\n // -- Private methods -----------------------------------------------\n // (possibly useful for subclasses to override)\n\n _munge_whitespace(text) {\n /*\n * _munge_whitespace(text : string) -> string\n *\n * Munge whitespace in text: expand tabs and convert all other\n * whitespace characters to spaces. Eg. \" foo\\\\tbar\\\\n\\\\nbaz\"\n * becomes \" foo bar baz\".\n */\n if (this.expand_tabs) {\n text = text.replace(/\\t/g, ' '.repeat(this.tabsize)) // not strictly correct in js\n }\n if (this.replace_whitespace) {\n text = text.replace(/[\\t\\n\\x0b\\x0c\\r]/g, ' ')\n }\n return text\n }\n\n _split(text) {\n /*\n * _split(text : string) -> [string]\n *\n * Split the text to wrap into indivisible chunks. Chunks are\n * not quite the same as words; see _wrap_chunks() for full\n * details. As an example, the text\n * Look, goof-ball -- use the -b option!\n * breaks into the following chunks:\n * 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',\n * 'use', ' ', 'the', ' ', '-b', ' ', 'option!'\n * if break_on_hyphens is True, or in:\n * 'Look,', ' ', 'goof-ball', ' ', '--', ' ',\n * 'use', ' ', 'the', ' ', '-b', ' ', option!'\n * otherwise.\n */\n let chunks = text.split(wordsep_simple_re)\n chunks = chunks.filter(Boolean)\n return chunks\n }\n\n _handle_long_word(reversed_chunks, cur_line, cur_len, width) {\n /*\n * _handle_long_word(chunks : [string],\n * cur_line : [string],\n * cur_len : int, width : int)\n *\n * Handle a chunk of text (most likely a word, not whitespace) that\n * is too long to fit in any line.\n */\n // Figure out when indent is larger than the specified width, and make\n // sure at least one character is stripped off on every pass\n let space_left\n if (width < 1) {\n space_left = 1\n } else {\n space_left = width - cur_len\n }\n\n // If we're allowed to break long words, then do so: put as much\n // of the next chunk onto the current line as will fit.\n if (this.break_long_words) {\n cur_line.push(reversed_chunks[reversed_chunks.length - 1].slice(0, space_left))\n reversed_chunks[reversed_chunks.length - 1] = reversed_chunks[reversed_chunks.length - 1].slice(space_left)\n\n // Otherwise, we have to preserve the long word intact. Only add\n // it to the current line if there's nothing already there --\n // that minimizes how much we violate the width constraint.\n } else if (!cur_line) {\n cur_line.push(...reversed_chunks.pop())\n }\n\n // If we're not allowed to break long words, and there's already\n // text on the current line, do nothing. Next time through the\n // main loop of _wrap_chunks(), we'll wind up here again, but\n // cur_len will be zero, so the next line will be entirely\n // devoted to the long word that we can't handle right now.\n }\n\n _wrap_chunks(chunks) {\n /*\n * _wrap_chunks(chunks : [string]) -> [string]\n *\n * Wrap a sequence of text chunks and return a list of lines of\n * length 'self.width' or less. (If 'break_long_words' is false,\n * some lines may be longer than this.) Chunks correspond roughly\n * to words and the whitespace between them: each chunk is\n * indivisible (modulo 'break_long_words'), but a line break can\n * come between any two chunks. Chunks should not have internal\n * whitespace; ie. a chunk is either all whitespace or a \"word\".\n * Whitespace chunks will be removed from the beginning and end of\n * lines, but apart from that whitespace is preserved.\n */\n let lines = []\n let indent\n if (this.width <= 0) {\n throw Error(`invalid width ${this.width} (must be > 0)`)\n }\n if (this.max_lines !== undefined) {\n if (this.max_lines > 1) {\n indent = this.subsequent_indent\n } else {\n indent = this.initial_indent\n }\n if (indent.length + this.placeholder.trimStart().length > this.width) {\n throw Error('placeholder too large for max width')\n }\n }\n\n // Arrange in reverse order so items can be efficiently popped\n // from a stack of chucks.\n chunks = chunks.reverse()\n\n while (chunks.length > 0) {\n\n // Start the list of chunks that will make up the current line.\n // cur_len is just the length of all the chunks in cur_line.\n let cur_line = []\n let cur_len = 0\n\n // Figure out which static string will prefix this line.\n let indent\n if (lines) {\n indent = this.subsequent_indent\n } else {\n indent = this.initial_indent\n }\n\n // Maximum width for this line.\n let width = this.width - indent.length\n\n // First chunk on line is whitespace -- drop it, unless this\n // is the very beginning of the text (ie. no lines started yet).\n if (this.drop_whitespace && chunks[chunks.length - 1].trim() === '' && lines.length > 0) {\n chunks.pop()\n }\n\n while (chunks.length > 0) {\n let l = chunks[chunks.length - 1].length\n\n // Can at least squeeze this chunk onto the current line.\n if (cur_len + l <= width) {\n cur_line.push(chunks.pop())\n cur_len += l\n\n // Nope, this line is full.\n } else {\n break\n }\n }\n\n // The current line is full, and the next chunk is too big to\n // fit on *any* line (not just this one).\n if (chunks.length && chunks[chunks.length - 1].length > width) {\n this._handle_long_word(chunks, cur_line, cur_len, width)\n cur_len = cur_line.map(l => l.length).reduce((a, b) => a + b, 0)\n }\n\n // If the last chunk on this line is all whitespace, drop it.\n if (this.drop_whitespace && cur_line.length > 0 && cur_line[cur_line.length - 1].trim() === '') {\n cur_len -= cur_line[cur_line.length - 1].length\n cur_line.pop()\n }\n\n if (cur_line) {\n if (this.max_lines === undefined ||\n lines.length + 1 < this.max_lines ||\n (chunks.length === 0 ||\n this.drop_whitespace &&\n chunks.length === 1 &&\n !chunks[0].trim()) && cur_len <= width) {\n // Convert current line back to a string and store it in\n // list of all lines (return value).\n lines.push(indent + cur_line.join(''))\n } else {\n let had_break = false\n while (cur_line) {\n if (cur_line[cur_line.length - 1].trim() &&\n cur_len + this.placeholder.length <= width) {\n cur_line.push(this.placeholder)\n lines.push(indent + cur_line.join(''))\n had_break = true\n break\n }\n cur_len -= cur_line[-1].length\n cur_line.pop()\n }\n if (!had_break) {\n if (lines) {\n let prev_line = lines[lines.length - 1].trimEnd()\n if (prev_line.length + this.placeholder.length <=\n this.width) {\n lines[lines.length - 1] = prev_line + this.placeholder\n break\n }\n }\n lines.push(indent + this.placeholder.lstrip())\n }\n break\n }\n }\n }\n\n return lines\n }\n\n _split_chunks(text) {\n text = this._munge_whitespace(text)\n return this._split(text)\n }\n\n // -- Public interface ----------------------------------------------\n\n wrap(text) {\n /*\n * wrap(text : string) -> [string]\n *\n * Reformat the single paragraph in 'text' so it fits in lines of\n * no more than 'self.width' columns, and return a list of wrapped\n * lines. Tabs in 'text' are expanded with string.expandtabs(),\n * and all other whitespace characters (including newline) are\n * converted to space.\n */\n let chunks = this._split_chunks(text)\n // not implemented in js\n //if (this.fix_sentence_endings) {\n // this._fix_sentence_endings(chunks)\n //}\n return this._wrap_chunks(chunks)\n }\n\n fill(text) {\n /*\n * fill(text : string) -> string\n *\n * Reformat the single paragraph in 'text' to fit in lines of no\n * more than 'self.width' columns, and return a new string\n * containing the entire wrapped paragraph.\n */\n return this.wrap(text).join('\\n')\n }\n}\n\n\n// -- Convenience interface ---------------------------------------------\n\nfunction wrap(text, options = {}) {\n /*\n * Wrap a single paragraph of text, returning a list of wrapped lines.\n *\n * Reformat the single paragraph in 'text' so it fits in lines of no\n * more than 'width' columns, and return a list of wrapped lines. By\n * default, tabs in 'text' are expanded with string.expandtabs(), and\n * all other whitespace characters (including newline) are converted to\n * space. See TextWrapper class for available keyword args to customize\n * wrapping behaviour.\n */\n let { width = 70, ...kwargs } = options\n let w = new TextWrapper(Object.assign({ width }, kwargs))\n return w.wrap(text)\n}\n\nfunction fill(text, options = {}) {\n /*\n * Fill a single paragraph of text, returning a new string.\n *\n * Reformat the single paragraph in 'text' to fit in lines of no more\n * than 'width' columns, and return a new string containing the entire\n * wrapped paragraph. As with wrap(), tabs are expanded and other\n * whitespace characters converted to space. See TextWrapper class for\n * available keyword args to customize wrapping behaviour.\n */\n let { width = 70, ...kwargs } = options\n let w = new TextWrapper(Object.assign({ width }, kwargs))\n return w.fill(text)\n}\n\n// -- Loosely related functionality -------------------------------------\n\nlet _whitespace_only_re = /^[ \\t]+$/mg\nlet _leading_whitespace_re = /(^[ \\t]*)(?:[^ \\t\\n])/mg\n\nfunction dedent(text) {\n /*\n * Remove any common leading whitespace from every line in `text`.\n *\n * This can be used to make triple-quoted strings line up with the left\n * edge of the display, while still presenting them in the source code\n * in indented form.\n *\n * Note that tabs and spaces are both treated as whitespace, but they\n * are not equal: the lines \" hello\" and \"\\\\thello\" are\n * considered to have no common leading whitespace.\n *\n * Entirely blank lines are normalized to a newline character.\n */\n // Look for the longest leading string of spaces and tabs common to\n // all lines.\n let margin = undefined\n text = text.replace(_whitespace_only_re, '')\n let indents = text.match(_leading_whitespace_re) || []\n for (let indent of indents) {\n indent = indent.slice(0, -1)\n\n if (margin === undefined) {\n margin = indent\n\n // Current line more deeply indented than previous winner:\n // no change (previous winner is still on top).\n } else if (indent.startsWith(margin)) {\n // pass\n\n // Current line consistent with and no deeper than previous winner:\n // it's the new winner.\n } else if (margin.startsWith(indent)) {\n margin = indent\n\n // Find the largest common whitespace between current line and previous\n // winner.\n } else {\n for (let i = 0; i < margin.length && i < indent.length; i++) {\n if (margin[i] !== indent[i]) {\n margin = margin.slice(0, i)\n break\n }\n }\n }\n }\n\n if (margin) {\n text = text.replace(new RegExp('^' + margin, 'mg'), '')\n }\n return text\n}\n\nmodule.exports = { wrap, fill, dedent }\n", "// Port of python's argparse module, version 3.9.0:\n// https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py\n\n'use strict'\n\n// Copyright (C) 2010-2020 Python Software Foundation.\n// Copyright (C) 2020 argparse.js authors\n\n/*\n * Command-line parsing library\n *\n * This module is an optparse-inspired command-line parsing library that:\n *\n * - handles both optional and positional arguments\n * - produces highly informative usage messages\n * - supports parsers that dispatch to sub-parsers\n *\n * The following is a simple usage example that sums integers from the\n * command-line and writes the result to a file::\n *\n * parser = argparse.ArgumentParser(\n * description='sum the integers at the command line')\n * parser.add_argument(\n * 'integers', metavar='int', nargs='+', type=int,\n * help='an integer to be summed')\n * parser.add_argument(\n * '--log', default=sys.stdout, type=argparse.FileType('w'),\n * help='the file where the sum should be written')\n * args = parser.parse_args()\n * args.log.write('%s' % sum(args.integers))\n * args.log.close()\n *\n * The module contains the following public classes:\n *\n * - ArgumentParser -- The main entry point for command-line parsing. As the\n * example above shows, the add_argument() method is used to populate\n * the parser with actions for optional and positional arguments. Then\n * the parse_args() method is invoked to convert the args at the\n * command-line into an object with attributes.\n *\n * - ArgumentError -- The exception raised by ArgumentParser objects when\n * there are errors with the parser's actions. Errors raised while\n * parsing the command-line are caught by ArgumentParser and emitted\n * as command-line messages.\n *\n * - FileType -- A factory for defining types of files to be created. As the\n * example above shows, instances of FileType are typically passed as\n * the type= argument of add_argument() calls.\n *\n * - Action -- The base class for parser actions. Typically actions are\n * selected by passing strings like 'store_true' or 'append_const' to\n * the action= argument of add_argument(). However, for greater\n * customization of ArgumentParser actions, subclasses of Action may\n * be defined and passed as the action= argument.\n *\n * - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,\n * ArgumentDefaultsHelpFormatter -- Formatter classes which\n * may be passed as the formatter_class= argument to the\n * ArgumentParser constructor. HelpFormatter is the default,\n * RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser\n * not to change the formatting for help text, and\n * ArgumentDefaultsHelpFormatter adds information about argument defaults\n * to the help.\n *\n * All other classes in this module are considered implementation details.\n * (Also note that HelpFormatter and RawDescriptionHelpFormatter are only\n * considered public as object names -- the API of the formatter objects is\n * still considered an implementation detail.)\n */\n\nconst SUPPRESS = '==SUPPRESS=='\n\nconst OPTIONAL = '?'\nconst ZERO_OR_MORE = '*'\nconst ONE_OR_MORE = '+'\nconst PARSER = 'A...'\nconst REMAINDER = '...'\nconst _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'\n\n\n// ==================================\n// Utility functions used for porting\n// ==================================\nconst assert = require('assert')\nconst util = require('util')\nconst fs = require('fs')\nconst sub = require('./lib/sub')\nconst path = require('path')\nconst repr = util.inspect\n\nfunction get_argv() {\n // omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.)\n return process.argv.slice(1)\n}\n\nfunction get_terminal_size() {\n return {\n columns: +process.env.COLUMNS || process.stdout.columns || 80\n }\n}\n\nfunction hasattr(object, name) {\n return Object.prototype.hasOwnProperty.call(object, name)\n}\n\nfunction getattr(object, name, value) {\n return hasattr(object, name) ? object[name] : value\n}\n\nfunction setattr(object, name, value) {\n object[name] = value\n}\n\nfunction setdefault(object, name, value) {\n if (!hasattr(object, name)) object[name] = value\n return object[name]\n}\n\nfunction delattr(object, name) {\n delete object[name]\n}\n\nfunction range(from, to, step=1) {\n // range(10) is equivalent to range(0, 10)\n if (arguments.length === 1) [ to, from ] = [ from, 0 ]\n if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') {\n throw new TypeError('argument cannot be interpreted as an integer')\n }\n if (step === 0) throw new TypeError('range() arg 3 must not be zero')\n\n let result = []\n if (step > 0) {\n for (let i = from; i < to; i += step) result.push(i)\n } else {\n for (let i = from; i > to; i += step) result.push(i)\n }\n return result\n}\n\nfunction splitlines(str, keepends = false) {\n let result\n if (!keepends) {\n result = str.split(/\\r\\n|[\\n\\r\\v\\f\\x1c\\x1d\\x1e\\x85\\u2028\\u2029]/)\n } else {\n result = []\n let parts = str.split(/(\\r\\n|[\\n\\r\\v\\f\\x1c\\x1d\\x1e\\x85\\u2028\\u2029])/)\n for (let i = 0; i < parts.length; i += 2) {\n result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : ''))\n }\n }\n if (!result[result.length - 1]) result.pop()\n return result\n}\n\nfunction _string_lstrip(string, prefix_chars) {\n let idx = 0\n while (idx < string.length && prefix_chars.includes(string[idx])) idx++\n return idx ? string.slice(idx) : string\n}\n\nfunction _string_split(string, sep, maxsplit) {\n let result = string.split(sep)\n if (result.length > maxsplit) {\n result = result.slice(0, maxsplit).concat([ result.slice(maxsplit).join(sep) ])\n }\n return result\n}\n\nfunction _array_equal(array1, array2) {\n if (array1.length !== array2.length) return false\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) return false\n }\n return true\n}\n\nfunction _array_remove(array, item) {\n let idx = array.indexOf(item)\n if (idx === -1) throw new TypeError(sub('%r not in list', item))\n array.splice(idx, 1)\n}\n\n// normalize choices to array;\n// this isn't required in python because `in` and `map` operators work with anything,\n// but in js dealing with multiple types here is too clunky\nfunction _choices_to_array(choices) {\n if (choices === undefined) {\n return []\n } else if (Array.isArray(choices)) {\n return choices\n } else if (choices !== null && typeof choices[Symbol.iterator] === 'function') {\n return Array.from(choices)\n } else if (typeof choices === 'object' && choices !== null) {\n return Object.keys(choices)\n } else {\n throw new Error(sub('invalid choices value: %r', choices))\n }\n}\n\n// decorator that allows a class to be called without new\nfunction _callable(cls) {\n let result = { // object is needed for inferred class name\n [cls.name]: function (...args) {\n let this_class = new.target === result || !new.target\n return Reflect.construct(cls, args, this_class ? cls : new.target)\n }\n }\n result[cls.name].prototype = cls.prototype\n // fix default tag for toString, e.g. [object Action] instead of [object Object]\n cls.prototype[Symbol.toStringTag] = cls.name\n return result[cls.name]\n}\n\nfunction _alias(object, from, to) {\n try {\n let name = object.constructor.name\n Object.defineProperty(object, from, {\n value: util.deprecate(object[to], sub('%s.%s() is renamed to %s.%s()',\n name, from, name, to)),\n enumerable: false\n })\n } catch {}\n}\n\n// decorator that allows snake_case class methods to be called with camelCase and vice versa\nfunction _camelcase_alias(_class) {\n for (let name of Object.getOwnPropertyNames(_class.prototype)) {\n let camelcase = name.replace(/\\w_[a-z]/g, s => s[0] + s[2].toUpperCase())\n if (camelcase !== name) _alias(_class.prototype, camelcase, name)\n }\n return _class\n}\n\nfunction _to_legacy_name(key) {\n key = key.replace(/\\w_[a-z]/g, s => s[0] + s[2].toUpperCase())\n if (key === 'default') key = 'defaultValue'\n if (key === 'const') key = 'constant'\n return key\n}\n\nfunction _to_new_name(key) {\n if (key === 'defaultValue') key = 'default'\n if (key === 'constant') key = 'const'\n key = key.replace(/[A-Z]/g, c => '_' + c.toLowerCase())\n return key\n}\n\n// parse options\nlet no_default = Symbol('no_default_value')\nfunction _parse_opts(args, descriptor) {\n function get_name() {\n let stack = new Error().stack.split('\\n')\n .map(x => x.match(/^ at (.*) \\(.*\\)$/))\n .filter(Boolean)\n .map(m => m[1])\n .map(fn => fn.match(/[^ .]*$/)[0])\n\n if (stack.length && stack[0] === get_name.name) stack.shift()\n if (stack.length && stack[0] === _parse_opts.name) stack.shift()\n return stack.length ? stack[0] : ''\n }\n\n args = Array.from(args)\n let kwargs = {}\n let result = []\n let last_opt = args.length && args[args.length - 1]\n\n if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) &&\n (!last_opt.constructor || last_opt.constructor.name === 'Object')) {\n kwargs = Object.assign({}, args.pop())\n }\n\n // LEGACY (v1 compatibility): camelcase\n let renames = []\n for (let key of Object.keys(descriptor)) {\n let old_name = _to_legacy_name(key)\n if (old_name !== key && (old_name in kwargs)) {\n if (key in kwargs) {\n // default and defaultValue specified at the same time, happens often in old tests\n //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key))\n } else {\n kwargs[key] = kwargs[old_name]\n }\n renames.push([ old_name, key ])\n delete kwargs[old_name]\n }\n }\n if (renames.length) {\n let name = get_name()\n deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s',\n name, renames.map(([ a, b ]) => sub('%r -> %r', a, b))))\n }\n // end\n\n let missing_positionals = []\n let positional_count = args.length\n\n for (let [ key, def ] of Object.entries(descriptor)) {\n if (key[0] === '*') {\n if (key.length > 0 && key[1] === '*') {\n // LEGACY (v1 compatibility): camelcase\n let renames = []\n for (let key of Object.keys(kwargs)) {\n let new_name = _to_new_name(key)\n if (new_name !== key && (key in kwargs)) {\n if (new_name in kwargs) {\n // default and defaultValue specified at the same time, happens often in old tests\n //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), new_name))\n } else {\n kwargs[new_name] = kwargs[key]\n }\n renames.push([ key, new_name ])\n delete kwargs[key]\n }\n }\n if (renames.length) {\n let name = get_name()\n deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s',\n name, renames.map(([ a, b ]) => sub('%r -> %r', a, b))))\n }\n // end\n result.push(kwargs)\n kwargs = {}\n } else {\n result.push(args)\n args = []\n }\n } else if (key in kwargs && args.length > 0) {\n throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key))\n } else if (key in kwargs) {\n result.push(kwargs[key])\n delete kwargs[key]\n } else if (args.length > 0) {\n result.push(args.shift())\n } else if (def !== no_default) {\n result.push(def)\n } else {\n missing_positionals.push(key)\n }\n }\n\n if (Object.keys(kwargs).length) {\n throw new TypeError(sub('%s() got an unexpected keyword argument %r',\n get_name(), Object.keys(kwargs)[0]))\n }\n\n if (args.length) {\n let from = Object.entries(descriptor).filter(([ k, v ]) => k[0] !== '*' && v !== no_default).length\n let to = Object.entries(descriptor).filter(([ k ]) => k[0] !== '*').length\n throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given',\n get_name(),\n from === to ? sub('from %s to %s', from, to) : to,\n from === to && to === 1 ? '' : 's',\n positional_count,\n positional_count === 1 ? 'was' : 'were'))\n }\n\n if (missing_positionals.length) {\n let strs = missing_positionals.map(repr)\n if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1]\n let str_joined = strs.join(strs.length === 2 ? '' : ', ')\n throw new TypeError(sub('%s() missing %i required positional argument%s: %s',\n get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined))\n }\n\n return result\n}\n\nlet _deprecations = {}\nfunction deprecate(id, string) {\n _deprecations[id] = _deprecations[id] || util.deprecate(() => {}, string)\n _deprecations[id]()\n}\n\n\n// =============================\n// Utility functions and classes\n// =============================\nfunction _AttributeHolder(cls = Object) {\n /*\n * Abstract base class that provides __repr__.\n *\n * The __repr__ method returns a string in the format::\n * ClassName(attr=name, attr=name, ...)\n * The attributes are determined either by a class-level attribute,\n * '_kwarg_names', or by inspecting the instance __dict__.\n */\n\n return class _AttributeHolder extends cls {\n [util.inspect.custom]() {\n let type_name = this.constructor.name\n let arg_strings = []\n let star_args = {}\n for (let arg of this._get_args()) {\n arg_strings.push(repr(arg))\n }\n for (let [ name, value ] of this._get_kwargs()) {\n if (/^[a-z_][a-z0-9_$]*$/i.test(name)) {\n arg_strings.push(sub('%s=%r', name, value))\n } else {\n star_args[name] = value\n }\n }\n if (Object.keys(star_args).length) {\n arg_strings.push(sub('**%s', repr(star_args)))\n }\n return sub('%s(%s)', type_name, arg_strings.join(', '))\n }\n\n toString() {\n return this[util.inspect.custom]()\n }\n\n _get_kwargs() {\n return Object.entries(this)\n }\n\n _get_args() {\n return []\n }\n }\n}\n\n\nfunction _copy_items(items) {\n if (items === undefined) {\n return []\n }\n return items.slice(0)\n}\n\n\n// ===============\n// Formatting Help\n// ===============\nconst HelpFormatter = _camelcase_alias(_callable(class HelpFormatter {\n /*\n * Formatter for generating usage messages and argument help strings.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n constructor() {\n let [\n prog,\n indent_increment,\n max_help_position,\n width\n ] = _parse_opts(arguments, {\n prog: no_default,\n indent_increment: 2,\n max_help_position: 24,\n width: undefined\n })\n\n // default setting for width\n if (width === undefined) {\n width = get_terminal_size().columns\n width -= 2\n }\n\n this._prog = prog\n this._indent_increment = indent_increment\n this._max_help_position = Math.min(max_help_position,\n Math.max(width - 20, indent_increment * 2))\n this._width = width\n\n this._current_indent = 0\n this._level = 0\n this._action_max_length = 0\n\n this._root_section = this._Section(this, undefined)\n this._current_section = this._root_section\n\n this._whitespace_matcher = /[ \\t\\n\\r\\f\\v]+/g // equivalent to python /\\s+/ with ASCII flag\n this._long_break_matcher = /\\n\\n\\n+/g\n }\n\n // ===============================\n // Section and indentation methods\n // ===============================\n _indent() {\n this._current_indent += this._indent_increment\n this._level += 1\n }\n\n _dedent() {\n this._current_indent -= this._indent_increment\n assert(this._current_indent >= 0, 'Indent decreased below 0.')\n this._level -= 1\n }\n\n _add_item(func, args) {\n this._current_section.items.push([ func, args ])\n }\n\n // ========================\n // Message building methods\n // ========================\n start_section(heading) {\n this._indent()\n let section = this._Section(this, this._current_section, heading)\n this._add_item(section.format_help.bind(section), [])\n this._current_section = section\n }\n\n end_section() {\n this._current_section = this._current_section.parent\n this._dedent()\n }\n\n add_text(text) {\n if (text !== SUPPRESS && text !== undefined) {\n this._add_item(this._format_text.bind(this), [text])\n }\n }\n\n add_usage(usage, actions, groups, prefix = undefined) {\n if (usage !== SUPPRESS) {\n let args = [ usage, actions, groups, prefix ]\n this._add_item(this._format_usage.bind(this), args)\n }\n }\n\n add_argument(action) {\n if (action.help !== SUPPRESS) {\n\n // find all invocations\n let invocations = [this._format_action_invocation(action)]\n for (let subaction of this._iter_indented_subactions(action)) {\n invocations.push(this._format_action_invocation(subaction))\n }\n\n // update the maximum item length\n let invocation_length = Math.max(...invocations.map(invocation => invocation.length))\n let action_length = invocation_length + this._current_indent\n this._action_max_length = Math.max(this._action_max_length,\n action_length)\n\n // add the item to the list\n this._add_item(this._format_action.bind(this), [action])\n }\n }\n\n add_arguments(actions) {\n for (let action of actions) {\n this.add_argument(action)\n }\n }\n\n // =======================\n // Help-formatting methods\n // =======================\n format_help() {\n let help = this._root_section.format_help()\n if (help) {\n help = help.replace(this._long_break_matcher, '\\n\\n')\n help = help.replace(/^\\n+|\\n+$/g, '') + '\\n'\n }\n return help\n }\n\n _join_parts(part_strings) {\n return part_strings.filter(part => part && part !== SUPPRESS).join('')\n }\n\n _format_usage(usage, actions, groups, prefix) {\n if (prefix === undefined) {\n prefix = 'usage: '\n }\n\n // if usage is specified, use that\n if (usage !== undefined) {\n usage = sub(usage, { prog: this._prog })\n\n // if no optionals or positionals are available, usage is just prog\n } else if (usage === undefined && !actions.length) {\n usage = sub('%(prog)s', { prog: this._prog })\n\n // if optionals and positionals are available, calculate usage\n } else if (usage === undefined) {\n let prog = sub('%(prog)s', { prog: this._prog })\n\n // split optionals from positionals\n let optionals = []\n let positionals = []\n for (let action of actions) {\n if (action.option_strings.length) {\n optionals.push(action)\n } else {\n positionals.push(action)\n }\n }\n\n // build full usage string\n let action_usage = this._format_actions_usage([].concat(optionals).concat(positionals), groups)\n usage = [ prog, action_usage ].map(String).join(' ')\n\n // wrap the usage parts if it's too long\n let text_width = this._width - this._current_indent\n if (prefix.length + usage.length > text_width) {\n\n // break usage into wrappable parts\n let part_regexp = /\\(.*?\\)+(?=\\s|$)|\\[.*?\\]+(?=\\s|$)|\\S+/g\n let opt_usage = this._format_actions_usage(optionals, groups)\n let pos_usage = this._format_actions_usage(positionals, groups)\n let opt_parts = opt_usage.match(part_regexp) || []\n let pos_parts = pos_usage.match(part_regexp) || []\n assert(opt_parts.join(' ') === opt_usage)\n assert(pos_parts.join(' ') === pos_usage)\n\n // helper for wrapping lines\n let get_lines = (parts, indent, prefix = undefined) => {\n let lines = []\n let line = []\n let line_len\n if (prefix !== undefined) {\n line_len = prefix.length - 1\n } else {\n line_len = indent.length - 1\n }\n for (let part of parts) {\n if (line_len + 1 + part.length > text_width && line) {\n lines.push(indent + line.join(' '))\n line = []\n line_len = indent.length - 1\n }\n line.push(part)\n line_len += part.length + 1\n }\n if (line.length) {\n lines.push(indent + line.join(' '))\n }\n if (prefix !== undefined) {\n lines[0] = lines[0].slice(indent.length)\n }\n return lines\n }\n\n let lines\n\n // if prog is short, follow it with optionals or positionals\n if (prefix.length + prog.length <= 0.75 * text_width) {\n let indent = ' '.repeat(prefix.length + prog.length + 1)\n if (opt_parts.length) {\n lines = get_lines([prog].concat(opt_parts), indent, prefix)\n lines = lines.concat(get_lines(pos_parts, indent))\n } else if (pos_parts.length) {\n lines = get_lines([prog].concat(pos_parts), indent, prefix)\n } else {\n lines = [prog]\n }\n\n // if prog is long, put it on its own line\n } else {\n let indent = ' '.repeat(prefix.length)\n let parts = [].concat(opt_parts).concat(pos_parts)\n lines = get_lines(parts, indent)\n if (lines.length > 1) {\n lines = []\n lines = lines.concat(get_lines(opt_parts, indent))\n lines = lines.concat(get_lines(pos_parts, indent))\n }\n lines = [prog].concat(lines)\n }\n\n // join lines into usage\n usage = lines.join('\\n')\n }\n }\n\n // prefix with 'usage:'\n return sub('%s%s\\n\\n', prefix, usage)\n }\n\n _format_actions_usage(actions, groups) {\n // find group indices and identify actions in groups\n let group_actions = new Set()\n let inserts = {}\n for (let group of groups) {\n let start = actions.indexOf(group._group_actions[0])\n if (start === -1) {\n continue\n } else {\n let end = start + group._group_actions.length\n if (_array_equal(actions.slice(start, end), group._group_actions)) {\n for (let action of group._group_actions) {\n group_actions.add(action)\n }\n if (!group.required) {\n if (start in inserts) {\n inserts[start] += ' ['\n } else {\n inserts[start] = '['\n }\n if (end in inserts) {\n inserts[end] += ']'\n } else {\n inserts[end] = ']'\n }\n } else {\n if (start in inserts) {\n inserts[start] += ' ('\n } else {\n inserts[start] = '('\n }\n if (end in inserts) {\n inserts[end] += ')'\n } else {\n inserts[end] = ')'\n }\n }\n for (let i of range(start + 1, end)) {\n inserts[i] = '|'\n }\n }\n }\n }\n\n // collect all actions format strings\n let parts = []\n for (let [ i, action ] of Object.entries(actions)) {\n\n // suppressed arguments are marked with None\n // remove | separators for suppressed arguments\n if (action.help === SUPPRESS) {\n parts.push(undefined)\n if (inserts[+i] === '|') {\n delete inserts[+i]\n } else if (inserts[+i + 1] === '|') {\n delete inserts[+i + 1]\n }\n\n // produce all arg strings\n } else if (!action.option_strings.length) {\n let default_value = this._get_default_metavar_for_positional(action)\n let part = this._format_args(action, default_value)\n\n // if it's in a group, strip the outer []\n if (group_actions.has(action)) {\n if (part[0] === '[' && part[part.length - 1] === ']') {\n part = part.slice(1, -1)\n }\n }\n\n // add the action string to the list\n parts.push(part)\n\n // produce the first way to invoke the option in brackets\n } else {\n let option_string = action.option_strings[0]\n let part\n\n // if the Optional doesn't take a value, format is:\n // -s or --long\n if (action.nargs === 0) {\n part = action.format_usage()\n\n // if the Optional takes a value, format is:\n // -s ARGS or --long ARGS\n } else {\n let default_value = this._get_default_metavar_for_optional(action)\n let args_string = this._format_args(action, default_value)\n part = sub('%s %s', option_string, args_string)\n }\n\n // make it look optional if it's not required or in a group\n if (!action.required && !group_actions.has(action)) {\n part = sub('[%s]', part)\n }\n\n // add the action string to the list\n parts.push(part)\n }\n }\n\n // insert things at the necessary indices\n for (let i of Object.keys(inserts).map(Number).sort((a, b) => b - a)) {\n parts.splice(+i, 0, inserts[+i])\n }\n\n // join all the action items with spaces\n let text = parts.filter(Boolean).join(' ')\n\n // clean up separators for mutually exclusive groups\n text = text.replace(/([\\[(]) /g, '$1')\n text = text.replace(/ ([\\])])/g, '$1')\n text = text.replace(/[\\[(] *[\\])]/g, '')\n text = text.replace(/\\(([^|]*)\\)/g, '$1', text)\n text = text.trim()\n\n // return the text\n return text\n }\n\n _format_text(text) {\n if (text.includes('%(prog)')) {\n text = sub(text, { prog: this._prog })\n }\n let text_width = Math.max(this._width - this._current_indent, 11)\n let indent = ' '.repeat(this._current_indent)\n return this._fill_text(text, text_width, indent) + '\\n\\n'\n }\n\n _format_action(action) {\n // determine the required width and the entry label\n let help_position = Math.min(this._action_max_length + 2,\n this._max_help_position)\n let help_width = Math.max(this._width - help_position, 11)\n let action_width = help_position - this._current_indent - 2\n let action_header = this._format_action_invocation(action)\n let indent_first\n\n // no help; start on same line and add a final newline\n if (!action.help) {\n let tup = [ this._current_indent, '', action_header ]\n action_header = sub('%*s%s\\n', ...tup)\n\n // short action name; start on the same line and pad two spaces\n } else if (action_header.length <= action_width) {\n let tup = [ this._current_indent, '', action_width, action_header ]\n action_header = sub('%*s%-*s ', ...tup)\n indent_first = 0\n\n // long action name; start on the next line\n } else {\n let tup = [ this._current_indent, '', action_header ]\n action_header = sub('%*s%s\\n', ...tup)\n indent_first = help_position\n }\n\n // collect the pieces of the action help\n let parts = [action_header]\n\n // if there was help for the action, add lines of help text\n if (action.help) {\n let help_text = this._expand_help(action)\n let help_lines = this._split_lines(help_text, help_width)\n parts.push(sub('%*s%s\\n', indent_first, '', help_lines[0]))\n for (let line of help_lines.slice(1)) {\n parts.push(sub('%*s%s\\n', help_position, '', line))\n }\n\n // or add a newline if the description doesn't end with one\n } else if (!action_header.endsWith('\\n')) {\n parts.push('\\n')\n }\n\n // if there are any sub-actions, add their help as well\n for (let subaction of this._iter_indented_subactions(action)) {\n parts.push(this._format_action(subaction))\n }\n\n // return a single string\n return this._join_parts(parts)\n }\n\n _format_action_invocation(action) {\n if (!action.option_strings.length) {\n let default_value = this._get_default_metavar_for_positional(action)\n let metavar = this._metavar_formatter(action, default_value)(1)[0]\n return metavar\n\n } else {\n let parts = []\n\n // if the Optional doesn't take a value, format is:\n // -s, --long\n if (action.nargs === 0) {\n parts = parts.concat(action.option_strings)\n\n // if the Optional takes a value, format is:\n // -s ARGS, --long ARGS\n } else {\n let default_value = this._get_default_metavar_for_optional(action)\n let args_string = this._format_args(action, default_value)\n for (let option_string of action.option_strings) {\n parts.push(sub('%s %s', option_string, args_string))\n }\n }\n\n return parts.join(', ')\n }\n }\n\n _metavar_formatter(action, default_metavar) {\n let result\n if (action.metavar !== undefined) {\n result = action.metavar\n } else if (action.choices !== undefined) {\n let choice_strs = _choices_to_array(action.choices).map(String)\n result = sub('{%s}', choice_strs.join(','))\n } else {\n result = default_metavar\n }\n\n function format(tuple_size) {\n if (Array.isArray(result)) {\n return result\n } else {\n return Array(tuple_size).fill(result)\n }\n }\n return format\n }\n\n _format_args(action, default_metavar) {\n let get_metavar = this._metavar_formatter(action, default_metavar)\n let result\n if (action.nargs === undefined) {\n result = sub('%s', ...get_metavar(1))\n } else if (action.nargs === OPTIONAL) {\n result = sub('[%s]', ...get_metavar(1))\n } else if (action.nargs === ZERO_OR_MORE) {\n let metavar = get_metavar(1)\n if (metavar.length === 2) {\n result = sub('[%s [%s ...]]', ...metavar)\n } else {\n result = sub('[%s ...]', ...metavar)\n }\n } else if (action.nargs === ONE_OR_MORE) {\n result = sub('%s [%s ...]', ...get_metavar(2))\n } else if (action.nargs === REMAINDER) {\n result = '...'\n } else if (action.nargs === PARSER) {\n result = sub('%s ...', ...get_metavar(1))\n } else if (action.nargs === SUPPRESS) {\n result = ''\n } else {\n let formats\n try {\n formats = range(action.nargs).map(() => '%s')\n } catch (err) {\n throw new TypeError('invalid nargs value')\n }\n result = sub(formats.join(' '), ...get_metavar(action.nargs))\n }\n return result\n }\n\n _expand_help(action) {\n let params = Object.assign({ prog: this._prog }, action)\n for (let name of Object.keys(params)) {\n if (params[name] === SUPPRESS) {\n delete params[name]\n }\n }\n for (let name of Object.keys(params)) {\n if (params[name] && params[name].name) {\n params[name] = params[name].name\n }\n }\n if (params.choices !== undefined) {\n let choices_str = _choices_to_array(params.choices).map(String).join(', ')\n params.choices = choices_str\n }\n // LEGACY (v1 compatibility): camelcase\n for (let key of Object.keys(params)) {\n let old_name = _to_legacy_name(key)\n if (old_name !== key) {\n params[old_name] = params[key]\n }\n }\n // end\n return sub(this._get_help_string(action), params)\n }\n\n * _iter_indented_subactions(action) {\n if (typeof action._get_subactions === 'function') {\n this._indent()\n yield* action._get_subactions()\n this._dedent()\n }\n }\n\n _split_lines(text, width) {\n text = text.replace(this._whitespace_matcher, ' ').trim()\n // The textwrap module is used only for formatting help.\n // Delay its import for speeding up the common usage of argparse.\n let textwrap = require('./lib/textwrap')\n return textwrap.wrap(text, { width })\n }\n\n _fill_text(text, width, indent) {\n text = text.replace(this._whitespace_matcher, ' ').trim()\n let textwrap = require('./lib/textwrap')\n return textwrap.fill(text, { width,\n initial_indent: indent,\n subsequent_indent: indent })\n }\n\n _get_help_string(action) {\n return action.help\n }\n\n _get_default_metavar_for_optional(action) {\n return action.dest.toUpperCase()\n }\n\n _get_default_metavar_for_positional(action) {\n return action.dest\n }\n}))\n\nHelpFormatter.prototype._Section = _callable(class _Section {\n\n constructor(formatter, parent, heading = undefined) {\n this.formatter = formatter\n this.parent = parent\n this.heading = heading\n this.items = []\n }\n\n format_help() {\n // format the indented section\n if (this.parent !== undefined) {\n this.formatter._indent()\n }\n let item_help = this.formatter._join_parts(this.items.map(([ func, args ]) => func.apply(null, args)))\n if (this.parent !== undefined) {\n this.formatter._dedent()\n }\n\n // return nothing if the section was empty\n if (!item_help) {\n return ''\n }\n\n // add the heading if the section was non-empty\n let heading\n if (this.heading !== SUPPRESS && this.heading !== undefined) {\n let current_indent = this.formatter._current_indent\n heading = sub('%*s%s:\\n', current_indent, '', this.heading)\n } else {\n heading = ''\n }\n\n // join the section-initial newline, the heading and the help\n return this.formatter._join_parts(['\\n', heading, item_help, '\\n'])\n }\n})\n\n\nconst RawDescriptionHelpFormatter = _camelcase_alias(_callable(class RawDescriptionHelpFormatter extends HelpFormatter {\n /*\n * Help message formatter which retains any formatting in descriptions.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _fill_text(text, width, indent) {\n return splitlines(text, true).map(line => indent + line).join('')\n }\n}))\n\n\nconst RawTextHelpFormatter = _camelcase_alias(_callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter {\n /*\n * Help message formatter which retains formatting of all help text.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _split_lines(text/*, width*/) {\n return splitlines(text)\n }\n}))\n\n\nconst ArgumentDefaultsHelpFormatter = _camelcase_alias(_callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter {\n /*\n * Help message formatter which adds default values to argument help.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _get_help_string(action) {\n let help = action.help\n // LEGACY (v1 compatibility): additional check for defaultValue needed\n if (!action.help.includes('%(default)') && !action.help.includes('%(defaultValue)')) {\n if (action.default !== SUPPRESS) {\n let defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]\n if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) {\n help += ' (default: %(default)s)'\n }\n }\n }\n return help\n }\n}))\n\n\nconst MetavarTypeHelpFormatter = _camelcase_alias(_callable(class MetavarTypeHelpFormatter extends HelpFormatter {\n /*\n * Help message formatter which uses the argument 'type' as the default\n * metavar value (instead of the argument 'dest')\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _get_default_metavar_for_optional(action) {\n return typeof action.type === 'function' ? action.type.name : action.type\n }\n\n _get_default_metavar_for_positional(action) {\n return typeof action.type === 'function' ? action.type.name : action.type\n }\n}))\n\n\n// =====================\n// Options and Arguments\n// =====================\nfunction _get_action_name(argument) {\n if (argument === undefined) {\n return undefined\n } else if (argument.option_strings.length) {\n return argument.option_strings.join('/')\n } else if (![ undefined, SUPPRESS ].includes(argument.metavar)) {\n return argument.metavar\n } else if (![ undefined, SUPPRESS ].includes(argument.dest)) {\n return argument.dest\n } else {\n return undefined\n }\n}\n\n\nconst ArgumentError = _callable(class ArgumentError extends Error {\n /*\n * An error from creating or using an argument (optional or positional).\n *\n * The string value of this exception is the message, augmented with\n * information about the argument that caused it.\n */\n\n constructor(argument, message) {\n super()\n this.name = 'ArgumentError'\n this._argument_name = _get_action_name(argument)\n this._message = message\n this.message = this.str()\n }\n\n str() {\n let format\n if (this._argument_name === undefined) {\n format = '%(message)s'\n } else {\n format = 'argument %(argument_name)s: %(message)s'\n }\n return sub(format, { message: this._message,\n argument_name: this._argument_name })\n }\n})\n\n\nconst ArgumentTypeError = _callable(class ArgumentTypeError extends Error {\n /*\n * An error from trying to convert a command line string to a type.\n */\n\n constructor(message) {\n super(message)\n this.name = 'ArgumentTypeError'\n }\n})\n\n\n// ==============\n// Action classes\n// ==============\nconst Action = _camelcase_alias(_callable(class Action extends _AttributeHolder(Function) {\n /*\n * Information about how to convert command line strings to Python objects.\n *\n * Action objects are used by an ArgumentParser to represent the information\n * needed to parse a single argument from one or more strings from the\n * command line. The keyword arguments to the Action constructor are also\n * all attributes of Action instances.\n *\n * Keyword Arguments:\n *\n * - option_strings -- A list of command-line option strings which\n * should be associated with this action.\n *\n * - dest -- The name of the attribute to hold the created object(s)\n *\n * - nargs -- The number of command-line arguments that should be\n * consumed. By default, one argument will be consumed and a single\n * value will be produced. Other values include:\n * - N (an integer) consumes N arguments (and produces a list)\n * - '?' consumes zero or one arguments\n * - '*' consumes zero or more arguments (and produces a list)\n * - '+' consumes one or more arguments (and produces a list)\n * Note that the difference between the default and nargs=1 is that\n * with the default, a single value will be produced, while with\n * nargs=1, a list containing a single value will be produced.\n *\n * - const -- The value to be produced if the option is specified and the\n * option uses an action that takes no values.\n *\n * - default -- The value to be produced if the option is not specified.\n *\n * - type -- A callable that accepts a single string argument, and\n * returns the converted value. The standard Python types str, int,\n * float, and complex are useful examples of such callables. If None,\n * str is used.\n *\n * - choices -- A container of values that should be allowed. If not None,\n * after a command-line argument has been converted to the appropriate\n * type, an exception will be raised if it is not a member of this\n * collection.\n *\n * - required -- True if the action must always be specified at the\n * command line. This is only meaningful for optional command-line\n * arguments.\n *\n * - help -- The help string describing the argument.\n *\n * - metavar -- The name to be used for the option's argument with the\n * help string. If None, the 'dest' value will be used as the name.\n */\n\n constructor() {\n let [\n option_strings,\n dest,\n nargs,\n const_value,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n nargs: undefined,\n const: undefined,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n // when this class is called as a function, redirect it to .call() method of itself\n super('return arguments.callee.call.apply(arguments.callee, arguments)')\n\n this.option_strings = option_strings\n this.dest = dest\n this.nargs = nargs\n this.const = const_value\n this.default = default_value\n this.type = type\n this.choices = choices\n this.required = required\n this.help = help\n this.metavar = metavar\n }\n\n _get_kwargs() {\n let names = [\n 'option_strings',\n 'dest',\n 'nargs',\n 'const',\n 'default',\n 'type',\n 'choices',\n 'help',\n 'metavar'\n ]\n return names.map(name => [ name, getattr(this, name) ])\n }\n\n format_usage() {\n return this.option_strings[0]\n }\n\n call(/*parser, namespace, values, option_string = undefined*/) {\n throw new Error('.call() not defined')\n }\n}))\n\n\nconst BooleanOptionalAction = _camelcase_alias(_callable(class BooleanOptionalAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n let _option_strings = []\n for (let option_string of option_strings) {\n _option_strings.push(option_string)\n\n if (option_string.startsWith('--')) {\n option_string = '--no-' + option_string.slice(2)\n _option_strings.push(option_string)\n }\n }\n\n if (help !== undefined && default_value !== undefined) {\n help += ` (default: ${default_value})`\n }\n\n super({\n option_strings: _option_strings,\n dest,\n nargs: 0,\n default: default_value,\n type,\n choices,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace, values, option_string = undefined) {\n if (this.option_strings.includes(option_string)) {\n setattr(namespace, this.dest, !option_string.startsWith('--no-'))\n }\n }\n\n format_usage() {\n return this.option_strings.join(' | ')\n }\n}))\n\n\nconst _StoreAction = _callable(class _StoreAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n nargs,\n const_value,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n nargs: undefined,\n const: undefined,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n if (nargs === 0) {\n throw new TypeError('nargs for store actions must be != 0; if you ' +\n 'have nothing to store, actions such as store ' +\n 'true or store const may be more appropriate')\n }\n if (const_value !== undefined && nargs !== OPTIONAL) {\n throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL))\n }\n super({\n option_strings,\n dest,\n nargs,\n const: const_value,\n default: default_value,\n type,\n choices,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace, values/*, option_string = undefined*/) {\n setattr(namespace, this.dest, values)\n }\n})\n\n\nconst _StoreConstAction = _callable(class _StoreConstAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n const_value,\n default_value,\n required,\n help\n //, metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n const: no_default,\n default: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n super({\n option_strings,\n dest,\n nargs: 0,\n const: const_value,\n default: default_value,\n required,\n help\n })\n }\n\n call(parser, namespace/*, values, option_string = undefined*/) {\n setattr(namespace, this.dest, this.const)\n }\n})\n\n\nconst _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n required,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: false,\n required: false,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n const: true,\n default: default_value,\n required,\n help\n })\n }\n})\n\n\nconst _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n required,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: true,\n required: false,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n const: false,\n default: default_value,\n required,\n help\n })\n }\n})\n\n\nconst _AppendAction = _callable(class _AppendAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n nargs,\n const_value,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n nargs: undefined,\n const: undefined,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n if (nargs === 0) {\n throw new TypeError('nargs for append actions must be != 0; if arg ' +\n 'strings are not supplying the value to append, ' +\n 'the append const action may be more appropriate')\n }\n if (const_value !== undefined && nargs !== OPTIONAL) {\n throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL))\n }\n super({\n option_strings,\n dest,\n nargs,\n const: const_value,\n default: default_value,\n type,\n choices,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace, values/*, option_string = undefined*/) {\n let items = getattr(namespace, this.dest, undefined)\n items = _copy_items(items)\n items.push(values)\n setattr(namespace, this.dest, items)\n }\n})\n\n\nconst _AppendConstAction = _callable(class _AppendConstAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n const_value,\n default_value,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n const: no_default,\n default: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n super({\n option_strings,\n dest,\n nargs: 0,\n const: const_value,\n default: default_value,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace/*, values, option_string = undefined*/) {\n let items = getattr(namespace, this.dest, undefined)\n items = _copy_items(items)\n items.push(this.const)\n setattr(namespace, this.dest, items)\n }\n})\n\n\nconst _CountAction = _callable(class _CountAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n required,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: undefined,\n required: false,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n nargs: 0,\n default: default_value,\n required,\n help\n })\n }\n\n call(parser, namespace/*, values, option_string = undefined*/) {\n let count = getattr(namespace, this.dest, undefined)\n if (count === undefined) {\n count = 0\n }\n setattr(namespace, this.dest, count + 1)\n }\n})\n\n\nconst _HelpAction = _callable(class _HelpAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: SUPPRESS,\n default: SUPPRESS,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n default: default_value,\n nargs: 0,\n help\n })\n }\n\n call(parser/*, namespace, values, option_string = undefined*/) {\n parser.print_help()\n parser.exit()\n }\n})\n\n\nconst _VersionAction = _callable(class _VersionAction extends Action {\n\n constructor() {\n let [\n option_strings,\n version,\n dest,\n default_value,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n version: undefined,\n dest: SUPPRESS,\n default: SUPPRESS,\n help: \"show program's version number and exit\"\n })\n\n super({\n option_strings,\n dest,\n default: default_value,\n nargs: 0,\n help\n })\n this.version = version\n }\n\n call(parser/*, namespace, values, option_string = undefined*/) {\n let version = this.version\n if (version === undefined) {\n version = parser.version\n }\n let formatter = parser._get_formatter()\n formatter.add_text(version)\n parser._print_message(formatter.format_help(), process.stdout)\n parser.exit()\n }\n})\n\n\nconst _SubParsersAction = _camelcase_alias(_callable(class _SubParsersAction extends Action {\n\n constructor() {\n let [\n option_strings,\n prog,\n parser_class,\n dest,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n prog: no_default,\n parser_class: no_default,\n dest: SUPPRESS,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n let name_parser_map = {}\n\n super({\n option_strings,\n dest,\n nargs: PARSER,\n choices: name_parser_map,\n required,\n help,\n metavar\n })\n\n this._prog_prefix = prog\n this._parser_class = parser_class\n this._name_parser_map = name_parser_map\n this._choices_actions = []\n }\n\n add_parser() {\n let [\n name,\n kwargs\n ] = _parse_opts(arguments, {\n name: no_default,\n '**kwargs': no_default\n })\n\n // set prog from the existing prefix\n if (kwargs.prog === undefined) {\n kwargs.prog = sub('%s %s', this._prog_prefix, name)\n }\n\n let aliases = getattr(kwargs, 'aliases', [])\n delete kwargs.aliases\n\n // create a pseudo-action to hold the choice help\n if ('help' in kwargs) {\n let help = kwargs.help\n delete kwargs.help\n let choice_action = this._ChoicesPseudoAction(name, aliases, help)\n this._choices_actions.push(choice_action)\n }\n\n // create the parser and add it to the map\n let parser = new this._parser_class(kwargs)\n this._name_parser_map[name] = parser\n\n // make parser available under aliases also\n for (let alias of aliases) {\n this._name_parser_map[alias] = parser\n }\n\n return parser\n }\n\n _get_subactions() {\n return this._choices_actions\n }\n\n call(parser, namespace, values/*, option_string = undefined*/) {\n let parser_name = values[0]\n let arg_strings = values.slice(1)\n\n // set the parser name if requested\n if (this.dest !== SUPPRESS) {\n setattr(namespace, this.dest, parser_name)\n }\n\n // select the parser\n if (hasattr(this._name_parser_map, parser_name)) {\n parser = this._name_parser_map[parser_name]\n } else {\n let args = {parser_name,\n choices: this._name_parser_map.join(', ')}\n let msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args)\n throw new ArgumentError(this, msg)\n }\n\n // parse all the remaining options into the namespace\n // store any unrecognized options on the object, so that the top\n // level parser can decide what to do with them\n\n // In case this subparser defines new defaults, we parse them\n // in a new namespace object and then update the original\n // namespace for the relevant parts.\n let subnamespace\n [ subnamespace, arg_strings ] = parser.parse_known_args(arg_strings, undefined)\n for (let [ key, value ] of Object.entries(subnamespace)) {\n setattr(namespace, key, value)\n }\n\n if (arg_strings.length) {\n setdefault(namespace, _UNRECOGNIZED_ARGS_ATTR, [])\n getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings)\n }\n }\n}))\n\n\n_SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action {\n constructor(name, aliases, help) {\n let metavar = name, dest = name\n if (aliases.length) {\n metavar += sub(' (%s)', aliases.join(', '))\n }\n super({ option_strings: [], dest, help, metavar })\n }\n})\n\n\nconst _ExtendAction = _callable(class _ExtendAction extends _AppendAction {\n call(parser, namespace, values/*, option_string = undefined*/) {\n let items = getattr(namespace, this.dest, undefined)\n items = _copy_items(items)\n items = items.concat(values)\n setattr(namespace, this.dest, items)\n }\n})\n\n\n// ==============\n// Type classes\n// ==============\nconst FileType = _callable(class FileType extends Function {\n /*\n * Factory for creating file object types\n *\n * Instances of FileType are typically passed as type= arguments to the\n * ArgumentParser add_argument() method.\n *\n * Keyword Arguments:\n * - mode -- A string indicating how the file is to be opened. Accepts the\n * same values as the builtin open() function.\n * - bufsize -- The file's desired buffer size. Accepts the same values as\n * the builtin open() function.\n * - encoding -- The file's encoding. Accepts the same values as the\n * builtin open() function.\n * - errors -- A string indicating how encoding and decoding errors are to\n * be handled. Accepts the same value as the builtin open() function.\n */\n\n constructor() {\n let [\n flags,\n encoding,\n mode,\n autoClose,\n emitClose,\n start,\n end,\n highWaterMark,\n fs\n ] = _parse_opts(arguments, {\n flags: 'r',\n encoding: undefined,\n mode: undefined, // 0o666\n autoClose: undefined, // true\n emitClose: undefined, // false\n start: undefined, // 0\n end: undefined, // Infinity\n highWaterMark: undefined, // 64 * 1024\n fs: undefined\n })\n\n // when this class is called as a function, redirect it to .call() method of itself\n super('return arguments.callee.call.apply(arguments.callee, arguments)')\n\n Object.defineProperty(this, 'name', {\n get() {\n return sub('FileType(%r)', flags)\n }\n })\n this._flags = flags\n this._options = {}\n if (encoding !== undefined) this._options.encoding = encoding\n if (mode !== undefined) this._options.mode = mode\n if (autoClose !== undefined) this._options.autoClose = autoClose\n if (emitClose !== undefined) this._options.emitClose = emitClose\n if (start !== undefined) this._options.start = start\n if (end !== undefined) this._options.end = end\n if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark\n if (fs !== undefined) this._options.fs = fs\n }\n\n call(string) {\n // the special argument \"-\" means sys.std{in,out}\n if (string === '-') {\n if (this._flags.includes('r')) {\n return process.stdin\n } else if (this._flags.includes('w')) {\n return process.stdout\n } else {\n let msg = sub('argument \"-\" with mode %r', this._flags)\n throw new TypeError(msg)\n }\n }\n\n // all other arguments are used as file names\n let fd\n try {\n fd = fs.openSync(string, this._flags, this._options.mode)\n } catch (e) {\n let args = { filename: string, error: e.message }\n let message = \"can't open '%(filename)s': %(error)s\"\n throw new ArgumentTypeError(sub(message, args))\n }\n\n let options = Object.assign({ fd, flags: this._flags }, this._options)\n if (this._flags.includes('r')) {\n return fs.createReadStream(undefined, options)\n } else if (this._flags.includes('w')) {\n return fs.createWriteStream(undefined, options)\n } else {\n let msg = sub('argument \"%s\" with mode %r', string, this._flags)\n throw new TypeError(msg)\n }\n }\n\n [util.inspect.custom]() {\n let args = [ this._flags ]\n let kwargs = Object.entries(this._options).map(([ k, v ]) => {\n if (k === 'mode') v = { value: v, [util.inspect.custom]() { return '0o' + this.value.toString(8) } }\n return [ k, v ]\n })\n let args_str = []\n .concat(args.filter(arg => arg !== -1).map(repr))\n .concat(kwargs.filter(([/*kw*/, arg]) => arg !== undefined)\n .map(([kw, arg]) => sub('%s=%r', kw, arg)))\n .join(', ')\n return sub('%s(%s)', this.constructor.name, args_str)\n }\n\n toString() {\n return this[util.inspect.custom]()\n }\n})\n\n// ===========================\n// Optional and Positional Parsing\n// ===========================\nconst Namespace = _callable(class Namespace extends _AttributeHolder() {\n /*\n * Simple object for storing attributes.\n *\n * Implements equality by attribute names and values, and provides a simple\n * string representation.\n */\n\n constructor(options = {}) {\n super()\n Object.assign(this, options)\n }\n})\n\n// unset string tag to mimic plain object\nNamespace.prototype[Symbol.toStringTag] = undefined\n\n\nconst _ActionsContainer = _camelcase_alias(_callable(class _ActionsContainer {\n\n constructor() {\n let [\n description,\n prefix_chars,\n argument_default,\n conflict_handler\n ] = _parse_opts(arguments, {\n description: no_default,\n prefix_chars: no_default,\n argument_default: no_default,\n conflict_handler: no_default\n })\n\n this.description = description\n this.argument_default = argument_default\n this.prefix_chars = prefix_chars\n this.conflict_handler = conflict_handler\n\n // set up registries\n this._registries = {}\n\n // register actions\n this.register('action', undefined, _StoreAction)\n this.register('action', 'store', _StoreAction)\n this.register('action', 'store_const', _StoreConstAction)\n this.register('action', 'store_true', _StoreTrueAction)\n this.register('action', 'store_false', _StoreFalseAction)\n this.register('action', 'append', _AppendAction)\n this.register('action', 'append_const', _AppendConstAction)\n this.register('action', 'count', _CountAction)\n this.register('action', 'help', _HelpAction)\n this.register('action', 'version', _VersionAction)\n this.register('action', 'parsers', _SubParsersAction)\n this.register('action', 'extend', _ExtendAction)\n // LEGACY (v1 compatibility): camelcase variants\n ;[ 'storeConst', 'storeTrue', 'storeFalse', 'appendConst' ].forEach(old_name => {\n let new_name = _to_new_name(old_name)\n this.register('action', old_name, util.deprecate(this._registry_get('action', new_name),\n sub('{action: \"%s\"} is renamed to {action: \"%s\"}', old_name, new_name)))\n })\n // end\n\n // raise an exception if the conflict handler is invalid\n this._get_handler()\n\n // action storage\n this._actions = []\n this._option_string_actions = {}\n\n // groups\n this._action_groups = []\n this._mutually_exclusive_groups = []\n\n // defaults storage\n this._defaults = {}\n\n // determines whether an \"option\" looks like a negative number\n this._negative_number_matcher = /^-\\d+$|^-\\d*\\.\\d+$/\n\n // whether or not there are any optionals that look like negative\n // numbers -- uses a list so it can be shared and edited\n this._has_negative_number_optionals = []\n }\n\n // ====================\n // Registration methods\n // ====================\n register(registry_name, value, object) {\n let registry = setdefault(this._registries, registry_name, {})\n registry[value] = object\n }\n\n _registry_get(registry_name, value, default_value = undefined) {\n return getattr(this._registries[registry_name], value, default_value)\n }\n\n // ==================================\n // Namespace default accessor methods\n // ==================================\n set_defaults(kwargs) {\n Object.assign(this._defaults, kwargs)\n\n // if these defaults match any existing arguments, replace\n // the previous default on the object with the new one\n for (let action of this._actions) {\n if (action.dest in kwargs) {\n action.default = kwargs[action.dest]\n }\n }\n }\n\n get_default(dest) {\n for (let action of this._actions) {\n if (action.dest === dest && action.default !== undefined) {\n return action.default\n }\n }\n return this._defaults[dest]\n }\n\n\n // =======================\n // Adding argument actions\n // =======================\n add_argument() {\n /*\n * add_argument(dest, ..., name=value, ...)\n * add_argument(option_string, option_string, ..., name=value, ...)\n */\n let [\n args,\n kwargs\n ] = _parse_opts(arguments, {\n '*args': no_default,\n '**kwargs': no_default\n })\n // LEGACY (v1 compatibility), old-style add_argument([ args ], { options })\n if (args.length === 1 && Array.isArray(args[0])) {\n args = args[0]\n deprecate('argument-array',\n sub('use add_argument(%(args)s, {...}) instead of add_argument([ %(args)s ], { ... })', {\n args: args.map(repr).join(', ')\n }))\n }\n // end\n\n // if no positional args are supplied or only one is supplied and\n // it doesn't look like an option string, parse a positional\n // argument\n let chars = this.prefix_chars\n if (!args.length || args.length === 1 && !chars.includes(args[0][0])) {\n if (args.length && 'dest' in kwargs) {\n throw new TypeError('dest supplied twice for positional argument')\n }\n kwargs = this._get_positional_kwargs(...args, kwargs)\n\n // otherwise, we're adding an optional argument\n } else {\n kwargs = this._get_optional_kwargs(...args, kwargs)\n }\n\n // if no default was supplied, use the parser-level default\n if (!('default' in kwargs)) {\n let dest = kwargs.dest\n if (dest in this._defaults) {\n kwargs.default = this._defaults[dest]\n } else if (this.argument_default !== undefined) {\n kwargs.default = this.argument_default\n }\n }\n\n // create the action object, and add it to the parser\n let action_class = this._pop_action_class(kwargs)\n if (typeof action_class !== 'function') {\n throw new TypeError(sub('unknown action \"%s\"', action_class))\n }\n // eslint-disable-next-line new-cap\n let action = new action_class(kwargs)\n\n // raise an error if the action type is not callable\n let type_func = this._registry_get('type', action.type, action.type)\n if (typeof type_func !== 'function') {\n throw new TypeError(sub('%r is not callable', type_func))\n }\n\n if (type_func === FileType) {\n throw new TypeError(sub('%r is a FileType class object, instance of it' +\n ' must be passed', type_func))\n }\n\n // raise an error if the metavar does not match the type\n if ('_get_formatter' in this) {\n try {\n this._get_formatter()._format_args(action, undefined)\n } catch (err) {\n // check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same\n if (err instanceof TypeError && err.message !== 'invalid nargs value') {\n throw new TypeError('length of metavar tuple does not match nargs')\n } else {\n throw err\n }\n }\n }\n\n return this._add_action(action)\n }\n\n add_argument_group() {\n let group = _ArgumentGroup(this, ...arguments)\n this._action_groups.push(group)\n return group\n }\n\n add_mutually_exclusive_group() {\n // eslint-disable-next-line no-use-before-define\n let group = _MutuallyExclusiveGroup(this, ...arguments)\n this._mutually_exclusive_groups.push(group)\n return group\n }\n\n _add_action(action) {\n // resolve any conflicts\n this._check_conflict(action)\n\n // add to actions list\n this._actions.push(action)\n action.container = this\n\n // index the action by any option strings it has\n for (let option_string of action.option_strings) {\n this._option_string_actions[option_string] = action\n }\n\n // set the flag if any option strings look like negative numbers\n for (let option_string of action.option_strings) {\n if (this._negative_number_matcher.test(option_string)) {\n if (!this._has_negative_number_optionals.length) {\n this._has_negative_number_optionals.push(true)\n }\n }\n }\n\n // return the created action\n return action\n }\n\n _remove_action(action) {\n _array_remove(this._actions, action)\n }\n\n _add_container_actions(container) {\n // collect groups by titles\n let title_group_map = {}\n for (let group of this._action_groups) {\n if (group.title in title_group_map) {\n let msg = 'cannot merge actions - two groups are named %r'\n throw new TypeError(sub(msg, group.title))\n }\n title_group_map[group.title] = group\n }\n\n // map each action to its group\n let group_map = new Map()\n for (let group of container._action_groups) {\n\n // if a group with the title exists, use that, otherwise\n // create a new group matching the container's group\n if (!(group.title in title_group_map)) {\n title_group_map[group.title] = this.add_argument_group({\n title: group.title,\n description: group.description,\n conflict_handler: group.conflict_handler\n })\n }\n\n // map the actions to their new group\n for (let action of group._group_actions) {\n group_map.set(action, title_group_map[group.title])\n }\n }\n\n // add container's mutually exclusive groups\n // NOTE: if add_mutually_exclusive_group ever gains title= and\n // description= then this code will need to be expanded as above\n for (let group of container._mutually_exclusive_groups) {\n let mutex_group = this.add_mutually_exclusive_group({\n required: group.required\n })\n\n // map the actions to their new mutex group\n for (let action of group._group_actions) {\n group_map.set(action, mutex_group)\n }\n }\n\n // add all actions to this container or their group\n for (let action of container._actions) {\n group_map.get(action)._add_action(action)\n }\n }\n\n _get_positional_kwargs() {\n let [\n dest,\n kwargs\n ] = _parse_opts(arguments, {\n dest: no_default,\n '**kwargs': no_default\n })\n\n // make sure required is not specified\n if ('required' in kwargs) {\n let msg = \"'required' is an invalid argument for positionals\"\n throw new TypeError(msg)\n }\n\n // mark positional arguments as required if at least one is\n // always required\n if (![OPTIONAL, ZERO_OR_MORE].includes(kwargs.nargs)) {\n kwargs.required = true\n }\n if (kwargs.nargs === ZERO_OR_MORE && !('default' in kwargs)) {\n kwargs.required = true\n }\n\n // return the keyword arguments with no option strings\n return Object.assign(kwargs, { dest, option_strings: [] })\n }\n\n _get_optional_kwargs() {\n let [\n args,\n kwargs\n ] = _parse_opts(arguments, {\n '*args': no_default,\n '**kwargs': no_default\n })\n\n // determine short and long option strings\n let option_strings = []\n let long_option_strings = []\n let option_string\n for (option_string of args) {\n // error on strings that don't start with an appropriate prefix\n if (!this.prefix_chars.includes(option_string[0])) {\n let args = {option: option_string,\n prefix_chars: this.prefix_chars}\n let msg = 'invalid option string %(option)r: ' +\n 'must start with a character %(prefix_chars)r'\n throw new TypeError(sub(msg, args))\n }\n\n // strings starting with two prefix characters are long options\n option_strings.push(option_string)\n if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) {\n long_option_strings.push(option_string)\n }\n }\n\n // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'\n let dest = kwargs.dest\n delete kwargs.dest\n if (dest === undefined) {\n let dest_option_string\n if (long_option_strings.length) {\n dest_option_string = long_option_strings[0]\n } else {\n dest_option_string = option_strings[0]\n }\n dest = _string_lstrip(dest_option_string, this.prefix_chars)\n if (!dest) {\n let msg = 'dest= is required for options like %r'\n throw new TypeError(sub(msg, option_string))\n }\n dest = dest.replace(/-/g, '_')\n }\n\n // return the updated keyword arguments\n return Object.assign(kwargs, { dest, option_strings })\n }\n\n _pop_action_class(kwargs, default_value = undefined) {\n let action = getattr(kwargs, 'action', default_value)\n delete kwargs.action\n return this._registry_get('action', action, action)\n }\n\n _get_handler() {\n // determine function from conflict handler string\n let handler_func_name = sub('_handle_conflict_%s', this.conflict_handler)\n if (typeof this[handler_func_name] === 'function') {\n return this[handler_func_name]\n } else {\n let msg = 'invalid conflict_resolution value: %r'\n throw new TypeError(sub(msg, this.conflict_handler))\n }\n }\n\n _check_conflict(action) {\n\n // find all options that conflict with this option\n let confl_optionals = []\n for (let option_string of action.option_strings) {\n if (hasattr(this._option_string_actions, option_string)) {\n let confl_optional = this._option_string_actions[option_string]\n confl_optionals.push([ option_string, confl_optional ])\n }\n }\n\n // resolve any conflicts\n if (confl_optionals.length) {\n let conflict_handler = this._get_handler()\n conflict_handler.call(this, action, confl_optionals)\n }\n }\n\n _handle_conflict_error(action, conflicting_actions) {\n let message = conflicting_actions.length === 1 ?\n 'conflicting option string: %s' :\n 'conflicting option strings: %s'\n let conflict_string = conflicting_actions.map(([ option_string/*, action*/ ]) => option_string).join(', ')\n throw new ArgumentError(action, sub(message, conflict_string))\n }\n\n _handle_conflict_resolve(action, conflicting_actions) {\n\n // remove all conflicting options\n for (let [ option_string, action ] of conflicting_actions) {\n\n // remove the conflicting option\n _array_remove(action.option_strings, option_string)\n delete this._option_string_actions[option_string]\n\n // if the option now has no option string, remove it from the\n // container holding it\n if (!action.option_strings.length) {\n action.container._remove_action(action)\n }\n }\n }\n}))\n\n\nconst _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer {\n\n constructor() {\n let [\n container,\n title,\n description,\n kwargs\n ] = _parse_opts(arguments, {\n container: no_default,\n title: undefined,\n description: undefined,\n '**kwargs': no_default\n })\n\n // add any missing keyword arguments by checking the container\n setdefault(kwargs, 'conflict_handler', container.conflict_handler)\n setdefault(kwargs, 'prefix_chars', container.prefix_chars)\n setdefault(kwargs, 'argument_default', container.argument_default)\n super(Object.assign({ description }, kwargs))\n\n // group attributes\n this.title = title\n this._group_actions = []\n\n // share most attributes with the container\n this._registries = container._registries\n this._actions = container._actions\n this._option_string_actions = container._option_string_actions\n this._defaults = container._defaults\n this._has_negative_number_optionals =\n container._has_negative_number_optionals\n this._mutually_exclusive_groups = container._mutually_exclusive_groups\n }\n\n _add_action(action) {\n action = super._add_action(action)\n this._group_actions.push(action)\n return action\n }\n\n _remove_action(action) {\n super._remove_action(action)\n _array_remove(this._group_actions, action)\n }\n})\n\n\nconst _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup {\n\n constructor() {\n let [\n container,\n required\n ] = _parse_opts(arguments, {\n container: no_default,\n required: false\n })\n\n super(container)\n this.required = required\n this._container = container\n }\n\n _add_action(action) {\n if (action.required) {\n let msg = 'mutually exclusive arguments must be optional'\n throw new TypeError(msg)\n }\n action = this._container._add_action(action)\n this._group_actions.push(action)\n return action\n }\n\n _remove_action(action) {\n this._container._remove_action(action)\n _array_remove(this._group_actions, action)\n }\n})\n\n\nconst ArgumentParser = _camelcase_alias(_callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) {\n /*\n * Object for parsing command line strings into Python objects.\n *\n * Keyword Arguments:\n * - prog -- The name of the program (default: sys.argv[0])\n * - usage -- A usage message (default: auto-generated from arguments)\n * - description -- A description of what the program does\n * - epilog -- Text following the argument descriptions\n * - parents -- Parsers whose arguments should be copied into this one\n * - formatter_class -- HelpFormatter class for printing help messages\n * - prefix_chars -- Characters that prefix optional arguments\n * - fromfile_prefix_chars -- Characters that prefix files containing\n * additional arguments\n * - argument_default -- The default value for all arguments\n * - conflict_handler -- String indicating how to handle conflicts\n * - add_help -- Add a -h/-help option\n * - allow_abbrev -- Allow long options to be abbreviated unambiguously\n * - exit_on_error -- Determines whether or not ArgumentParser exits with\n * error info when an error occurs\n */\n\n constructor() {\n let [\n prog,\n usage,\n description,\n epilog,\n parents,\n formatter_class,\n prefix_chars,\n fromfile_prefix_chars,\n argument_default,\n conflict_handler,\n add_help,\n allow_abbrev,\n exit_on_error,\n debug, // LEGACY (v1 compatibility), debug mode\n version // LEGACY (v1 compatibility), version\n ] = _parse_opts(arguments, {\n prog: undefined,\n usage: undefined,\n description: undefined,\n epilog: undefined,\n parents: [],\n formatter_class: HelpFormatter,\n prefix_chars: '-',\n fromfile_prefix_chars: undefined,\n argument_default: undefined,\n conflict_handler: 'error',\n add_help: true,\n allow_abbrev: true,\n exit_on_error: true,\n debug: undefined, // LEGACY (v1 compatibility), debug mode\n version: undefined // LEGACY (v1 compatibility), version\n })\n\n // LEGACY (v1 compatibility)\n if (debug !== undefined) {\n deprecate('debug',\n 'The \"debug\" argument to ArgumentParser is deprecated. Please ' +\n 'override ArgumentParser.exit function instead.'\n )\n }\n\n if (version !== undefined) {\n deprecate('version',\n 'The \"version\" argument to ArgumentParser is deprecated. Please use ' +\n \"add_argument(..., { action: 'version', version: 'N', ... }) instead.\"\n )\n }\n // end\n\n super({\n description,\n prefix_chars,\n argument_default,\n conflict_handler\n })\n\n // default setting for prog\n if (prog === undefined) {\n prog = path.basename(get_argv()[0] || '')\n }\n\n this.prog = prog\n this.usage = usage\n this.epilog = epilog\n this.formatter_class = formatter_class\n this.fromfile_prefix_chars = fromfile_prefix_chars\n this.add_help = add_help\n this.allow_abbrev = allow_abbrev\n this.exit_on_error = exit_on_error\n // LEGACY (v1 compatibility), debug mode\n this.debug = debug\n // end\n\n this._positionals = this.add_argument_group('positional arguments')\n this._optionals = this.add_argument_group('optional arguments')\n this._subparsers = undefined\n\n // register types\n function identity(string) {\n return string\n }\n this.register('type', undefined, identity)\n this.register('type', null, identity)\n this.register('type', 'auto', identity)\n this.register('type', 'int', function (x) {\n let result = Number(x)\n if (!Number.isInteger(result)) {\n throw new TypeError(sub('could not convert string to int: %r', x))\n }\n return result\n })\n this.register('type', 'float', function (x) {\n let result = Number(x)\n if (isNaN(result)) {\n throw new TypeError(sub('could not convert string to float: %r', x))\n }\n return result\n })\n this.register('type', 'str', String)\n // LEGACY (v1 compatibility): custom types\n this.register('type', 'string',\n util.deprecate(String, 'use {type:\"str\"} or {type:String} instead of {type:\"string\"}'))\n // end\n\n // add help argument if necessary\n // (using explicit default to override global argument_default)\n let default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0]\n if (this.add_help) {\n this.add_argument(\n default_prefix + 'h',\n default_prefix.repeat(2) + 'help',\n {\n action: 'help',\n default: SUPPRESS,\n help: 'show this help message and exit'\n }\n )\n }\n // LEGACY (v1 compatibility), version\n if (version) {\n this.add_argument(\n default_prefix + 'v',\n default_prefix.repeat(2) + 'version',\n {\n action: 'version',\n default: SUPPRESS,\n version: this.version,\n help: \"show program's version number and exit\"\n }\n )\n }\n // end\n\n // add parent arguments and defaults\n for (let parent of parents) {\n this._add_container_actions(parent)\n Object.assign(this._defaults, parent._defaults)\n }\n }\n\n // =======================\n // Pretty __repr__ methods\n // =======================\n _get_kwargs() {\n let names = [\n 'prog',\n 'usage',\n 'description',\n 'formatter_class',\n 'conflict_handler',\n 'add_help'\n ]\n return names.map(name => [ name, getattr(this, name) ])\n }\n\n // ==================================\n // Optional/Positional adding methods\n // ==================================\n add_subparsers() {\n let [\n kwargs\n ] = _parse_opts(arguments, {\n '**kwargs': no_default\n })\n\n if (this._subparsers !== undefined) {\n this.error('cannot have multiple subparser arguments')\n }\n\n // add the parser class to the arguments if it's not present\n setdefault(kwargs, 'parser_class', this.constructor)\n\n if ('title' in kwargs || 'description' in kwargs) {\n let title = getattr(kwargs, 'title', 'subcommands')\n let description = getattr(kwargs, 'description', undefined)\n delete kwargs.title\n delete kwargs.description\n this._subparsers = this.add_argument_group(title, description)\n } else {\n this._subparsers = this._positionals\n }\n\n // prog defaults to the usage message of this parser, skipping\n // optional arguments and with no \"usage:\" prefix\n if (kwargs.prog === undefined) {\n let formatter = this._get_formatter()\n let positionals = this._get_positional_actions()\n let groups = this._mutually_exclusive_groups\n formatter.add_usage(this.usage, positionals, groups, '')\n kwargs.prog = formatter.format_help().trim()\n }\n\n // create the parsers action and add it to the positionals list\n let parsers_class = this._pop_action_class(kwargs, 'parsers')\n // eslint-disable-next-line new-cap\n let action = new parsers_class(Object.assign({ option_strings: [] }, kwargs))\n this._subparsers._add_action(action)\n\n // return the created parsers action\n return action\n }\n\n _add_action(action) {\n if (action.option_strings.length) {\n this._optionals._add_action(action)\n } else {\n this._positionals._add_action(action)\n }\n return action\n }\n\n _get_optional_actions() {\n return this._actions.filter(action => action.option_strings.length)\n }\n\n _get_positional_actions() {\n return this._actions.filter(action => !action.option_strings.length)\n }\n\n // =====================================\n // Command line argument parsing methods\n // =====================================\n parse_args(args = undefined, namespace = undefined) {\n let argv\n [ args, argv ] = this.parse_known_args(args, namespace)\n if (argv && argv.length > 0) {\n let msg = 'unrecognized arguments: %s'\n this.error(sub(msg, argv.join(' ')))\n }\n return args\n }\n\n parse_known_args(args = undefined, namespace = undefined) {\n if (args === undefined) {\n args = get_argv().slice(1)\n }\n\n // default Namespace built from parser defaults\n if (namespace === undefined) {\n namespace = new Namespace()\n }\n\n // add any action defaults that aren't present\n for (let action of this._actions) {\n if (action.dest !== SUPPRESS) {\n if (!hasattr(namespace, action.dest)) {\n if (action.default !== SUPPRESS) {\n setattr(namespace, action.dest, action.default)\n }\n }\n }\n }\n\n // add any parser defaults that aren't present\n for (let dest of Object.keys(this._defaults)) {\n if (!hasattr(namespace, dest)) {\n setattr(namespace, dest, this._defaults[dest])\n }\n }\n\n // parse the arguments and exit if there are any errors\n if (this.exit_on_error) {\n try {\n [ namespace, args ] = this._parse_known_args(args, namespace)\n } catch (err) {\n if (err instanceof ArgumentError) {\n this.error(err.message)\n } else {\n throw err\n }\n }\n } else {\n [ namespace, args ] = this._parse_known_args(args, namespace)\n }\n\n if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) {\n args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))\n delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)\n }\n\n return [ namespace, args ]\n }\n\n _parse_known_args(arg_strings, namespace) {\n // replace arg strings that are file references\n if (this.fromfile_prefix_chars !== undefined) {\n arg_strings = this._read_args_from_files(arg_strings)\n }\n\n // map all mutually exclusive arguments to the other arguments\n // they can't occur with\n let action_conflicts = new Map()\n for (let mutex_group of this._mutually_exclusive_groups) {\n let group_actions = mutex_group._group_actions\n for (let [ i, mutex_action ] of Object.entries(mutex_group._group_actions)) {\n let conflicts = action_conflicts.get(mutex_action) || []\n conflicts = conflicts.concat(group_actions.slice(0, +i))\n conflicts = conflicts.concat(group_actions.slice(+i + 1))\n action_conflicts.set(mutex_action, conflicts)\n }\n }\n\n // find all option indices, and determine the arg_string_pattern\n // which has an 'O' if there is an option at an index,\n // an 'A' if there is an argument, or a '-' if there is a '--'\n let option_string_indices = {}\n let arg_string_pattern_parts = []\n let arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]()\n for (let [ i, arg_string ] of arg_strings_iter) {\n\n // all args after -- are non-options\n if (arg_string === '--') {\n arg_string_pattern_parts.push('-')\n for ([ i, arg_string ] of arg_strings_iter) {\n arg_string_pattern_parts.push('A')\n }\n\n // otherwise, add the arg to the arg strings\n // and note the index if it was an option\n } else {\n let option_tuple = this._parse_optional(arg_string)\n let pattern\n if (option_tuple === undefined) {\n pattern = 'A'\n } else {\n option_string_indices[i] = option_tuple\n pattern = 'O'\n }\n arg_string_pattern_parts.push(pattern)\n }\n }\n\n // join the pieces together to form the pattern\n let arg_strings_pattern = arg_string_pattern_parts.join('')\n\n // converts arg strings to the appropriate and then takes the action\n let seen_actions = new Set()\n let seen_non_default_actions = new Set()\n let extras\n\n let take_action = (action, argument_strings, option_string = undefined) => {\n seen_actions.add(action)\n let argument_values = this._get_values(action, argument_strings)\n\n // error if this argument is not allowed with other previously\n // seen arguments, assuming that actions that use the default\n // value don't really count as \"present\"\n if (argument_values !== action.default) {\n seen_non_default_actions.add(action)\n for (let conflict_action of action_conflicts.get(action) || []) {\n if (seen_non_default_actions.has(conflict_action)) {\n let msg = 'not allowed with argument %s'\n let action_name = _get_action_name(conflict_action)\n throw new ArgumentError(action, sub(msg, action_name))\n }\n }\n }\n\n // take the action if we didn't receive a SUPPRESS value\n // (e.g. from a default)\n if (argument_values !== SUPPRESS) {\n action(this, namespace, argument_values, option_string)\n }\n }\n\n // function to convert arg_strings into an optional action\n let consume_optional = start_index => {\n\n // get the optional identified at this index\n let option_tuple = option_string_indices[start_index]\n let [ action, option_string, explicit_arg ] = option_tuple\n\n // identify additional optionals in the same arg string\n // (e.g. -xyz is the same as -x -y -z if no args are required)\n let action_tuples = []\n let stop\n for (;;) {\n\n // if we found no optional action, skip it\n if (action === undefined) {\n extras.push(arg_strings[start_index])\n return start_index + 1\n }\n\n // if there is an explicit argument, try to match the\n // optional's string arguments to only this\n if (explicit_arg !== undefined) {\n let arg_count = this._match_argument(action, 'A')\n\n // if the action is a single-dash option and takes no\n // arguments, try to parse more single-dash options out\n // of the tail of the option string\n let chars = this.prefix_chars\n if (arg_count === 0 && !chars.includes(option_string[1])) {\n action_tuples.push([ action, [], option_string ])\n let char = option_string[0]\n option_string = char + explicit_arg[0]\n let new_explicit_arg = explicit_arg.slice(1) || undefined\n let optionals_map = this._option_string_actions\n if (hasattr(optionals_map, option_string)) {\n action = optionals_map[option_string]\n explicit_arg = new_explicit_arg\n } else {\n let msg = 'ignored explicit argument %r'\n throw new ArgumentError(action, sub(msg, explicit_arg))\n }\n\n // if the action expect exactly one argument, we've\n // successfully matched the option; exit the loop\n } else if (arg_count === 1) {\n stop = start_index + 1\n let args = [ explicit_arg ]\n action_tuples.push([ action, args, option_string ])\n break\n\n // error if a double-dash option did not use the\n // explicit argument\n } else {\n let msg = 'ignored explicit argument %r'\n throw new ArgumentError(action, sub(msg, explicit_arg))\n }\n\n // if there is no explicit argument, try to match the\n // optional's string arguments with the following strings\n // if successful, exit the loop\n } else {\n let start = start_index + 1\n let selected_patterns = arg_strings_pattern.slice(start)\n let arg_count = this._match_argument(action, selected_patterns)\n stop = start + arg_count\n let args = arg_strings.slice(start, stop)\n action_tuples.push([ action, args, option_string ])\n break\n }\n }\n\n // add the Optional to the list and return the index at which\n // the Optional's string args stopped\n assert(action_tuples.length)\n for (let [ action, args, option_string ] of action_tuples) {\n take_action(action, args, option_string)\n }\n return stop\n }\n\n // the list of Positionals left to be parsed; this is modified\n // by consume_positionals()\n let positionals = this._get_positional_actions()\n\n // function to convert arg_strings into positional actions\n let consume_positionals = start_index => {\n // match as many Positionals as possible\n let selected_pattern = arg_strings_pattern.slice(start_index)\n let arg_counts = this._match_arguments_partial(positionals, selected_pattern)\n\n // slice off the appropriate arg strings for each Positional\n // and add the Positional and its args to the list\n for (let i = 0; i < positionals.length && i < arg_counts.length; i++) {\n let action = positionals[i]\n let arg_count = arg_counts[i]\n let args = arg_strings.slice(start_index, start_index + arg_count)\n start_index += arg_count\n take_action(action, args)\n }\n\n // slice off the Positionals that we just parsed and return the\n // index at which the Positionals' string args stopped\n positionals = positionals.slice(arg_counts.length)\n return start_index\n }\n\n // consume Positionals and Optionals alternately, until we have\n // passed the last option string\n extras = []\n let start_index = 0\n let max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number))\n while (start_index <= max_option_string_index) {\n\n // consume any Positionals preceding the next option\n let next_option_string_index = Math.min(\n // eslint-disable-next-line no-loop-func\n ...Object.keys(option_string_indices).map(Number).filter(index => index >= start_index)\n )\n if (start_index !== next_option_string_index) {\n let positionals_end_index = consume_positionals(start_index)\n\n // only try to parse the next optional if we didn't consume\n // the option string during the positionals parsing\n if (positionals_end_index > start_index) {\n start_index = positionals_end_index\n continue\n } else {\n start_index = positionals_end_index\n }\n }\n\n // if we consumed all the positionals we could and we're not\n // at the index of an option string, there were extra arguments\n if (!(start_index in option_string_indices)) {\n let strings = arg_strings.slice(start_index, next_option_string_index)\n extras = extras.concat(strings)\n start_index = next_option_string_index\n }\n\n // consume the next optional and any arguments for it\n start_index = consume_optional(start_index)\n }\n\n // consume any positionals following the last Optional\n let stop_index = consume_positionals(start_index)\n\n // if we didn't consume all the argument strings, there were extras\n extras = extras.concat(arg_strings.slice(stop_index))\n\n // make sure all required actions were present and also convert\n // action defaults which were not given as arguments\n let required_actions = []\n for (let action of this._actions) {\n if (!seen_actions.has(action)) {\n if (action.required) {\n required_actions.push(_get_action_name(action))\n } else {\n // Convert action default now instead of doing it before\n // parsing arguments to avoid calling convert functions\n // twice (which may fail) if the argument was given, but\n // only if it was defined already in the namespace\n if (action.default !== undefined &&\n typeof action.default === 'string' &&\n hasattr(namespace, action.dest) &&\n action.default === getattr(namespace, action.dest)) {\n setattr(namespace, action.dest,\n this._get_value(action, action.default))\n }\n }\n }\n }\n\n if (required_actions.length) {\n this.error(sub('the following arguments are required: %s',\n required_actions.join(', ')))\n }\n\n // make sure all required groups had one option present\n for (let group of this._mutually_exclusive_groups) {\n if (group.required) {\n let no_actions_used = true\n for (let action of group._group_actions) {\n if (seen_non_default_actions.has(action)) {\n no_actions_used = false\n break\n }\n }\n\n // if no actions were used, report the error\n if (no_actions_used) {\n let names = group._group_actions\n .filter(action => action.help !== SUPPRESS)\n .map(action => _get_action_name(action))\n let msg = 'one of the arguments %s is required'\n this.error(sub(msg, names.join(' ')))\n }\n }\n }\n\n // return the updated namespace and the extra arguments\n return [ namespace, extras ]\n }\n\n _read_args_from_files(arg_strings) {\n // expand arguments referencing files\n let new_arg_strings = []\n for (let arg_string of arg_strings) {\n\n // for regular arguments, just add them back into the list\n if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) {\n new_arg_strings.push(arg_string)\n\n // replace arguments referencing files with the file content\n } else {\n try {\n let args_file = fs.readFileSync(arg_string.slice(1), 'utf8')\n let arg_strings = []\n for (let arg_line of splitlines(args_file)) {\n for (let arg of this.convert_arg_line_to_args(arg_line)) {\n arg_strings.push(arg)\n }\n }\n arg_strings = this._read_args_from_files(arg_strings)\n new_arg_strings = new_arg_strings.concat(arg_strings)\n } catch (err) {\n this.error(err.message)\n }\n }\n }\n\n // return the modified argument list\n return new_arg_strings\n }\n\n convert_arg_line_to_args(arg_line) {\n return [arg_line]\n }\n\n _match_argument(action, arg_strings_pattern) {\n // match the pattern for this action to the arg strings\n let nargs_pattern = this._get_nargs_pattern(action)\n let match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern))\n\n // raise an exception if we weren't able to find a match\n if (match === null) {\n let nargs_errors = {\n undefined: 'expected one argument',\n [OPTIONAL]: 'expected at most one argument',\n [ONE_OR_MORE]: 'expected at least one argument'\n }\n let msg = nargs_errors[action.nargs]\n if (msg === undefined) {\n msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs)\n }\n throw new ArgumentError(action, msg)\n }\n\n // return the number of arguments matched\n return match[1].length\n }\n\n _match_arguments_partial(actions, arg_strings_pattern) {\n // progressively shorten the actions list by slicing off the\n // final actions until we find a match\n let result = []\n for (let i of range(actions.length, 0, -1)) {\n let actions_slice = actions.slice(0, i)\n let pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('')\n let match = arg_strings_pattern.match(new RegExp('^' + pattern))\n if (match !== null) {\n result = result.concat(match.slice(1).map(string => string.length))\n break\n }\n }\n\n // return the list of arg string counts\n return result\n }\n\n _parse_optional(arg_string) {\n // if it's an empty string, it was meant to be a positional\n if (!arg_string) {\n return undefined\n }\n\n // if it doesn't start with a prefix, it was meant to be positional\n if (!this.prefix_chars.includes(arg_string[0])) {\n return undefined\n }\n\n // if the option string is present in the parser, return the action\n if (arg_string in this._option_string_actions) {\n let action = this._option_string_actions[arg_string]\n return [ action, arg_string, undefined ]\n }\n\n // if it's just a single character, it was meant to be positional\n if (arg_string.length === 1) {\n return undefined\n }\n\n // if the option string before the \"=\" is present, return the action\n if (arg_string.includes('=')) {\n let [ option_string, explicit_arg ] = _string_split(arg_string, '=', 1)\n if (option_string in this._option_string_actions) {\n let action = this._option_string_actions[option_string]\n return [ action, option_string, explicit_arg ]\n }\n }\n\n // search through all possible prefixes of the option string\n // and all actions in the parser for possible interpretations\n let option_tuples = this._get_option_tuples(arg_string)\n\n // if multiple actions match, the option string was ambiguous\n if (option_tuples.length > 1) {\n let options = option_tuples.map(([ /*action*/, option_string/*, explicit_arg*/ ]) => option_string).join(', ')\n let args = {option: arg_string, matches: options}\n let msg = 'ambiguous option: %(option)s could match %(matches)s'\n this.error(sub(msg, args))\n\n // if exactly one action matched, this segmentation is good,\n // so return the parsed action\n } else if (option_tuples.length === 1) {\n let [ option_tuple ] = option_tuples\n return option_tuple\n }\n\n // if it was not found as an option, but it looks like a negative\n // number, it was meant to be positional\n // unless there are negative-number-like options\n if (this._negative_number_matcher.test(arg_string)) {\n if (!this._has_negative_number_optionals.length) {\n return undefined\n }\n }\n\n // if it contains a space, it was meant to be a positional\n if (arg_string.includes(' ')) {\n return undefined\n }\n\n // it was meant to be an optional but there is no such option\n // in this parser (though it might be a valid option in a subparser)\n return [ undefined, arg_string, undefined ]\n }\n\n _get_option_tuples(option_string) {\n let result = []\n\n // option strings starting with two prefix characters are only\n // split at the '='\n let chars = this.prefix_chars\n if (chars.includes(option_string[0]) && chars.includes(option_string[1])) {\n if (this.allow_abbrev) {\n let option_prefix, explicit_arg\n if (option_string.includes('=')) {\n [ option_prefix, explicit_arg ] = _string_split(option_string, '=', 1)\n } else {\n option_prefix = option_string\n explicit_arg = undefined\n }\n for (let option_string of Object.keys(this._option_string_actions)) {\n if (option_string.startsWith(option_prefix)) {\n let action = this._option_string_actions[option_string]\n let tup = [ action, option_string, explicit_arg ]\n result.push(tup)\n }\n }\n }\n\n // single character options can be concatenated with their arguments\n // but multiple character options always have to have their argument\n // separate\n } else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) {\n let option_prefix = option_string\n let explicit_arg = undefined\n let short_option_prefix = option_string.slice(0, 2)\n let short_explicit_arg = option_string.slice(2)\n\n for (let option_string of Object.keys(this._option_string_actions)) {\n if (option_string === short_option_prefix) {\n let action = this._option_string_actions[option_string]\n let tup = [ action, option_string, short_explicit_arg ]\n result.push(tup)\n } else if (option_string.startsWith(option_prefix)) {\n let action = this._option_string_actions[option_string]\n let tup = [ action, option_string, explicit_arg ]\n result.push(tup)\n }\n }\n\n // shouldn't ever get here\n } else {\n this.error(sub('unexpected option string: %s', option_string))\n }\n\n // return the collected option tuples\n return result\n }\n\n _get_nargs_pattern(action) {\n // in all examples below, we have to allow for '--' args\n // which are represented as '-' in the pattern\n let nargs = action.nargs\n let nargs_pattern\n\n // the default (None) is assumed to be a single argument\n if (nargs === undefined) {\n nargs_pattern = '(-*A-*)'\n\n // allow zero or one arguments\n } else if (nargs === OPTIONAL) {\n nargs_pattern = '(-*A?-*)'\n\n // allow zero or more arguments\n } else if (nargs === ZERO_OR_MORE) {\n nargs_pattern = '(-*[A-]*)'\n\n // allow one or more arguments\n } else if (nargs === ONE_OR_MORE) {\n nargs_pattern = '(-*A[A-]*)'\n\n // allow any number of options or arguments\n } else if (nargs === REMAINDER) {\n nargs_pattern = '([-AO]*)'\n\n // allow one argument followed by any number of options or arguments\n } else if (nargs === PARSER) {\n nargs_pattern = '(-*A[-AO]*)'\n\n // suppress action, like nargs=0\n } else if (nargs === SUPPRESS) {\n nargs_pattern = '(-*-*)'\n\n // all others should be integers\n } else {\n nargs_pattern = sub('(-*%s-*)', 'A'.repeat(nargs).split('').join('-*'))\n }\n\n // if this is an optional action, -- is not allowed\n if (action.option_strings.length) {\n nargs_pattern = nargs_pattern.replace(/-\\*/g, '')\n nargs_pattern = nargs_pattern.replace(/-/g, '')\n }\n\n // return the pattern\n return nargs_pattern\n }\n\n // ========================\n // Alt command line argument parsing, allowing free intermix\n // ========================\n\n parse_intermixed_args(args = undefined, namespace = undefined) {\n let argv\n [ args, argv ] = this.parse_known_intermixed_args(args, namespace)\n if (argv.length) {\n let msg = 'unrecognized arguments: %s'\n this.error(sub(msg, argv.join(' ')))\n }\n return args\n }\n\n parse_known_intermixed_args(args = undefined, namespace = undefined) {\n // returns a namespace and list of extras\n //\n // positional can be freely intermixed with optionals. optionals are\n // first parsed with all positional arguments deactivated. The 'extras'\n // are then parsed. If the parser definition is incompatible with the\n // intermixed assumptions (e.g. use of REMAINDER, subparsers) a\n // TypeError is raised.\n //\n // positionals are 'deactivated' by setting nargs and default to\n // SUPPRESS. This blocks the addition of that positional to the\n // namespace\n\n let extras\n let positionals = this._get_positional_actions()\n let a = positionals.filter(action => [ PARSER, REMAINDER ].includes(action.nargs))\n if (a.length) {\n throw new TypeError(sub('parse_intermixed_args: positional arg' +\n ' with nargs=%s', a[0].nargs))\n }\n\n for (let group of this._mutually_exclusive_groups) {\n for (let action of group._group_actions) {\n if (positionals.includes(action)) {\n throw new TypeError('parse_intermixed_args: positional in' +\n ' mutuallyExclusiveGroup')\n }\n }\n }\n\n let save_usage\n try {\n save_usage = this.usage\n let remaining_args\n try {\n if (this.usage === undefined) {\n // capture the full usage for use in error messages\n this.usage = this.format_usage().slice(7)\n }\n for (let action of positionals) {\n // deactivate positionals\n action.save_nargs = action.nargs\n // action.nargs = 0\n action.nargs = SUPPRESS\n action.save_default = action.default\n action.default = SUPPRESS\n }\n [ namespace, remaining_args ] = this.parse_known_args(args,\n namespace)\n for (let action of positionals) {\n // remove the empty positional values from namespace\n let attr = getattr(namespace, action.dest)\n if (Array.isArray(attr) && attr.length === 0) {\n // eslint-disable-next-line no-console\n console.warn(sub('Do not expect %s in %s', action.dest, namespace))\n delattr(namespace, action.dest)\n }\n }\n } finally {\n // restore nargs and usage before exiting\n for (let action of positionals) {\n action.nargs = action.save_nargs\n action.default = action.save_default\n }\n }\n let optionals = this._get_optional_actions()\n try {\n // parse positionals. optionals aren't normally required, but\n // they could be, so make sure they aren't.\n for (let action of optionals) {\n action.save_required = action.required\n action.required = false\n }\n for (let group of this._mutually_exclusive_groups) {\n group.save_required = group.required\n group.required = false\n }\n [ namespace, extras ] = this.parse_known_args(remaining_args,\n namespace)\n } finally {\n // restore parser values before exiting\n for (let action of optionals) {\n action.required = action.save_required\n }\n for (let group of this._mutually_exclusive_groups) {\n group.required = group.save_required\n }\n }\n } finally {\n this.usage = save_usage\n }\n return [ namespace, extras ]\n }\n\n // ========================\n // Value conversion methods\n // ========================\n _get_values(action, arg_strings) {\n // for everything but PARSER, REMAINDER args, strip out first '--'\n if (![PARSER, REMAINDER].includes(action.nargs)) {\n try {\n _array_remove(arg_strings, '--')\n } catch (err) {}\n }\n\n let value\n // optional argument produces a default when not present\n if (!arg_strings.length && action.nargs === OPTIONAL) {\n if (action.option_strings.length) {\n value = action.const\n } else {\n value = action.default\n }\n if (typeof value === 'string') {\n value = this._get_value(action, value)\n this._check_value(action, value)\n }\n\n // when nargs='*' on a positional, if there were no command-line\n // args, use the default if it is anything other than None\n } else if (!arg_strings.length && action.nargs === ZERO_OR_MORE &&\n !action.option_strings.length) {\n if (action.default !== undefined) {\n value = action.default\n } else {\n value = arg_strings\n }\n this._check_value(action, value)\n\n // single argument or optional argument produces a single value\n } else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) {\n let arg_string = arg_strings[0]\n value = this._get_value(action, arg_string)\n this._check_value(action, value)\n\n // REMAINDER arguments convert all values, checking none\n } else if (action.nargs === REMAINDER) {\n value = arg_strings.map(v => this._get_value(action, v))\n\n // PARSER arguments convert all values, but check only the first\n } else if (action.nargs === PARSER) {\n value = arg_strings.map(v => this._get_value(action, v))\n this._check_value(action, value[0])\n\n // SUPPRESS argument does not put anything in the namespace\n } else if (action.nargs === SUPPRESS) {\n value = SUPPRESS\n\n // all other types of nargs produce a list\n } else {\n value = arg_strings.map(v => this._get_value(action, v))\n for (let v of value) {\n this._check_value(action, v)\n }\n }\n\n // return the converted value\n return value\n }\n\n _get_value(action, arg_string) {\n let type_func = this._registry_get('type', action.type, action.type)\n if (typeof type_func !== 'function') {\n let msg = '%r is not callable'\n throw new ArgumentError(action, sub(msg, type_func))\n }\n\n // convert the value to the appropriate type\n let result\n try {\n try {\n result = type_func(arg_string)\n } catch (err) {\n // Dear TC39, why would you ever consider making es6 classes not callable?\n // We had one universal interface, [[Call]], which worked for anything\n // (with familiar this-instanceof guard for classes). Now we have two.\n if (err instanceof TypeError &&\n /Class constructor .* cannot be invoked without 'new'/.test(err.message)) {\n // eslint-disable-next-line new-cap\n result = new type_func(arg_string)\n } else {\n throw err\n }\n }\n\n } catch (err) {\n // ArgumentTypeErrors indicate errors\n if (err instanceof ArgumentTypeError) {\n //let name = getattr(action.type, 'name', repr(action.type))\n let msg = err.message\n throw new ArgumentError(action, msg)\n\n // TypeErrors or ValueErrors also indicate errors\n } else if (err instanceof TypeError) {\n let name = getattr(action.type, 'name', repr(action.type))\n let args = {type: name, value: arg_string}\n let msg = 'invalid %(type)s value: %(value)r'\n throw new ArgumentError(action, sub(msg, args))\n } else {\n throw err\n }\n }\n\n // return the converted value\n return result\n }\n\n _check_value(action, value) {\n // converted value must be one of the choices (if specified)\n if (action.choices !== undefined && !_choices_to_array(action.choices).includes(value)) {\n let args = {value,\n choices: _choices_to_array(action.choices).map(repr).join(', ')}\n let msg = 'invalid choice: %(value)r (choose from %(choices)s)'\n throw new ArgumentError(action, sub(msg, args))\n }\n }\n\n // =======================\n // Help-formatting methods\n // =======================\n format_usage() {\n let formatter = this._get_formatter()\n formatter.add_usage(this.usage, this._actions,\n this._mutually_exclusive_groups)\n return formatter.format_help()\n }\n\n format_help() {\n let formatter = this._get_formatter()\n\n // usage\n formatter.add_usage(this.usage, this._actions,\n this._mutually_exclusive_groups)\n\n // description\n formatter.add_text(this.description)\n\n // positionals, optionals and user-defined groups\n for (let action_group of this._action_groups) {\n formatter.start_section(action_group.title)\n formatter.add_text(action_group.description)\n formatter.add_arguments(action_group._group_actions)\n formatter.end_section()\n }\n\n // epilog\n formatter.add_text(this.epilog)\n\n // determine help from format above\n return formatter.format_help()\n }\n\n _get_formatter() {\n // eslint-disable-next-line new-cap\n return new this.formatter_class({ prog: this.prog })\n }\n\n // =====================\n // Help-printing methods\n // =====================\n print_usage(file = undefined) {\n if (file === undefined) file = process.stdout\n this._print_message(this.format_usage(), file)\n }\n\n print_help(file = undefined) {\n if (file === undefined) file = process.stdout\n this._print_message(this.format_help(), file)\n }\n\n _print_message(message, file = undefined) {\n if (message) {\n if (file === undefined) file = process.stderr\n file.write(message)\n }\n }\n\n // ===============\n // Exiting methods\n // ===============\n exit(status = 0, message = undefined) {\n if (message) {\n this._print_message(message, process.stderr)\n }\n process.exit(status)\n }\n\n error(message) {\n /*\n * error(message: string)\n *\n * Prints a usage message incorporating the message to stderr and\n * exits.\n *\n * If you override this in a subclass, it should not return -- it\n * should either exit or raise an exception.\n */\n\n // LEGACY (v1 compatibility), debug mode\n if (this.debug === true) throw new Error(message)\n // end\n this.print_usage(process.stderr)\n let args = {prog: this.prog, message: message}\n this.exit(2, sub('%(prog)s: error: %(message)s\\n', args))\n }\n}))\n\n\nmodule.exports = {\n ArgumentParser,\n ArgumentError,\n ArgumentTypeError,\n BooleanOptionalAction,\n FileType,\n HelpFormatter,\n ArgumentDefaultsHelpFormatter,\n RawDescriptionHelpFormatter,\n RawTextHelpFormatter,\n MetavarTypeHelpFormatter,\n Namespace,\n Action,\n ONE_OR_MORE,\n OPTIONAL,\n PARSER,\n REMAINDER,\n SUPPRESS,\n ZERO_OR_MORE\n}\n\n// LEGACY (v1 compatibility), Const alias\nObject.defineProperty(module.exports, 'Const', {\n get() {\n let result = {}\n Object.entries({ ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE }).forEach(([ n, v ]) => {\n Object.defineProperty(result, n, {\n get() {\n deprecate(n, sub('use argparse.%s instead of argparse.Const.%s', n, n))\n return v\n }\n })\n })\n Object.entries({ _UNRECOGNIZED_ARGS_ATTR }).forEach(([ n, v ]) => {\n Object.defineProperty(result, n, {\n get() {\n deprecate(n, sub('argparse.Const.%s is an internal symbol and will no longer be available', n))\n return v\n }\n })\n })\n return result\n },\n enumerable: false\n})\n// end\n", "/*!\n * Tmp\n *\n * Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>\n *\n * MIT Licensed\n */\n\n/*\n * Module dependencies.\n */\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\nconst crypto = require('crypto');\nconst _c = { fs: fs.constants, os: os.constants };\n\n/*\n * The working inner variables.\n */\nconst // the random characters to choose from\n RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n TEMPLATE_PATTERN = /XXXXXX/,\n DEFAULT_TRIES = 3,\n CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR),\n // constants are off on the windows platform and will not match the actual errno codes\n IS_WIN32 = os.platform() === 'win32',\n EBADF = _c.EBADF || _c.os.errno.EBADF,\n ENOENT = _c.ENOENT || _c.os.errno.ENOENT,\n DIR_MODE = 0o700 /* 448 */,\n FILE_MODE = 0o600 /* 384 */,\n EXIT = 'exit',\n // this will hold the objects need to be removed on exit\n _removeObjects = [],\n // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback\n FN_RMDIR_SYNC = fs.rmdirSync.bind(fs);\n\nlet _gracefulCleanup = false;\n\n/**\n * Recursively remove a directory and its contents.\n *\n * @param {string} dirPath path of directory to remove\n * @param {Function} callback\n * @private\n */\nfunction rimraf(dirPath, callback) {\n return fs.rm(dirPath, { recursive: true }, callback);\n}\n\n/**\n * Recursively remove a directory and its contents, synchronously.\n *\n * @param {string} dirPath path of directory to remove\n * @private\n */\nfunction FN_RIMRAF_SYNC(dirPath) {\n return fs.rmSync(dirPath, { recursive: true });\n}\n\n/**\n * Gets a temporary file name.\n *\n * @param {(Options|tmpNameCallback)} options options or callback\n * @param {?tmpNameCallback} callback the callback function\n */\nfunction tmpName(options, callback) {\n const args = _parseArguments(options, callback),\n opts = args[0],\n cb = args[1];\n\n _assertAndSanitizeOptions(opts, function (err, sanitizedOptions) {\n if (err) return cb(err);\n\n let tries = sanitizedOptions.tries;\n (function _getUniqueName() {\n try {\n const name = _generateTmpName(sanitizedOptions);\n\n // check whether the path exists then retry if needed\n fs.stat(name, function (err) {\n /* istanbul ignore else */\n if (!err) {\n /* istanbul ignore else */\n if (tries-- > 0) return _getUniqueName();\n\n return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));\n }\n\n cb(null, name);\n });\n } catch (err) {\n cb(err);\n }\n })();\n });\n}\n\n/**\n * Synchronous version of tmpName.\n *\n * @param {Object} options\n * @returns {string} the generated random name\n * @throws {Error} if the options are invalid or could not generate a filename\n */\nfunction tmpNameSync(options) {\n const args = _parseArguments(options),\n opts = args[0];\n\n const sanitizedOptions = _assertAndSanitizeOptionsSync(opts);\n\n let tries = sanitizedOptions.tries;\n do {\n const name = _generateTmpName(sanitizedOptions);\n try {\n fs.statSync(name);\n } catch (e) {\n return name;\n }\n } while (tries-- > 0);\n\n throw new Error('Could not get a unique tmp filename, max tries reached');\n}\n\n/**\n * Creates and opens a temporary file.\n *\n * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined\n * @param {?fileCallback} callback\n */\nfunction file(options, callback) {\n const args = _parseArguments(options, callback),\n opts = args[0],\n cb = args[1];\n\n // gets a temporary filename\n tmpName(opts, function _tmpNameCreated(err, name) {\n /* istanbul ignore else */\n if (err) return cb(err);\n\n // create and open the file\n fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) {\n /* istanbu ignore else */\n if (err) return cb(err);\n\n if (opts.discardDescriptor) {\n return fs.close(fd, function _discardCallback(possibleErr) {\n // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only\n return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false));\n });\n } else {\n // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care\n // about the descriptor\n const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;\n cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false));\n }\n });\n });\n}\n\n/**\n * Synchronous version of file.\n *\n * @param {Options} options\n * @returns {FileSyncObject} object consists of name, fd and removeCallback\n * @throws {Error} if cannot create a file\n */\nfunction fileSync(options) {\n const args = _parseArguments(options),\n opts = args[0];\n\n const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;\n const name = tmpNameSync(opts);\n let fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);\n /* istanbul ignore else */\n if (opts.discardDescriptor) {\n fs.closeSync(fd);\n fd = undefined;\n }\n\n return {\n name: name,\n fd: fd,\n removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true)\n };\n}\n\n/**\n * Creates a temporary directory.\n *\n * @param {(Options|dirCallback)} options the options or the callback function\n * @param {?dirCallback} callback\n */\nfunction dir(options, callback) {\n const args = _parseArguments(options, callback),\n opts = args[0],\n cb = args[1];\n\n // gets a temporary filename\n tmpName(opts, function _tmpNameCreated(err, name) {\n /* istanbul ignore else */\n if (err) return cb(err);\n\n // create the directory\n fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {\n /* istanbul ignore else */\n if (err) return cb(err);\n\n cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false));\n });\n });\n}\n\n/**\n * Synchronous version of dir.\n *\n * @param {Options} options\n * @returns {DirSyncObject} object consists of name and removeCallback\n * @throws {Error} if it cannot create a directory\n */\nfunction dirSync(options) {\n const args = _parseArguments(options),\n opts = args[0];\n\n const name = tmpNameSync(opts);\n fs.mkdirSync(name, opts.mode || DIR_MODE);\n\n return {\n name: name,\n removeCallback: _prepareTmpDirRemoveCallback(name, opts, true)\n };\n}\n\n/**\n * Removes files asynchronously.\n *\n * @param {Object} fdPath\n * @param {Function} next\n * @private\n */\nfunction _removeFileAsync(fdPath, next) {\n const _handler = function (err) {\n if (err && !_isENOENT(err)) {\n // reraise any unanticipated error\n return next(err);\n }\n next();\n };\n\n if (0 <= fdPath[0])\n fs.close(fdPath[0], function () {\n fs.unlink(fdPath[1], _handler);\n });\n else fs.unlink(fdPath[1], _handler);\n}\n\n/**\n * Removes files synchronously.\n *\n * @param {Object} fdPath\n * @private\n */\nfunction _removeFileSync(fdPath) {\n let rethrownException = null;\n try {\n if (0 <= fdPath[0]) fs.closeSync(fdPath[0]);\n } catch (e) {\n // reraise any unanticipated error\n if (!_isEBADF(e) && !_isENOENT(e)) throw e;\n } finally {\n try {\n fs.unlinkSync(fdPath[1]);\n } catch (e) {\n // reraise any unanticipated error\n if (!_isENOENT(e)) rethrownException = e;\n }\n }\n if (rethrownException !== null) {\n throw rethrownException;\n }\n}\n\n/**\n * Prepares the callback for removal of the temporary file.\n *\n * Returns either a sync callback or a async callback depending on whether\n * fileSync or file was called, which is expressed by the sync parameter.\n *\n * @param {string} name the path of the file\n * @param {number} fd file descriptor\n * @param {Object} opts\n * @param {boolean} sync\n * @returns {fileCallback | fileCallbackSync}\n * @private\n */\nfunction _prepareTmpFileRemoveCallback(name, fd, opts, sync) {\n const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync);\n const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync);\n\n if (!opts.keep) _removeObjects.unshift(removeCallbackSync);\n\n return sync ? removeCallbackSync : removeCallback;\n}\n\n/**\n * Prepares the callback for removal of the temporary directory.\n *\n * Returns either a sync callback or a async callback depending on whether\n * tmpFileSync or tmpFile was called, which is expressed by the sync parameter.\n *\n * @param {string} name\n * @param {Object} opts\n * @param {boolean} sync\n * @returns {Function} the callback\n * @private\n */\nfunction _prepareTmpDirRemoveCallback(name, opts, sync) {\n const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs);\n const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC;\n const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync);\n const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync);\n if (!opts.keep) _removeObjects.unshift(removeCallbackSync);\n\n return sync ? removeCallbackSync : removeCallback;\n}\n\n/**\n * Creates a guarded function wrapping the removeFunction call.\n *\n * The cleanup callback is save to be called multiple times.\n * Subsequent invocations will be ignored.\n *\n * @param {Function} removeFunction\n * @param {string} fileOrDirName\n * @param {boolean} sync\n * @param {cleanupCallbackSync?} cleanupCallbackSync\n * @returns {cleanupCallback | cleanupCallbackSync}\n * @private\n */\nfunction _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) {\n let called = false;\n\n // if sync is true, the next parameter will be ignored\n return function _cleanupCallback(next) {\n /* istanbul ignore else */\n if (!called) {\n // remove cleanupCallback from cache\n const toRemove = cleanupCallbackSync || _cleanupCallback;\n const index = _removeObjects.indexOf(toRemove);\n /* istanbul ignore else */\n if (index >= 0) _removeObjects.splice(index, 1);\n\n called = true;\n if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) {\n return removeFunction(fileOrDirName);\n } else {\n return removeFunction(fileOrDirName, next || function () {});\n }\n }\n };\n}\n\n/**\n * The garbage collector.\n *\n * @private\n */\nfunction _garbageCollector() {\n /* istanbul ignore else */\n if (!_gracefulCleanup) return;\n\n // the function being called removes itself from _removeObjects,\n // loop until _removeObjects is empty\n while (_removeObjects.length) {\n try {\n _removeObjects[0]();\n } catch (e) {\n // already removed?\n }\n }\n}\n\n/**\n * Random name generator based on crypto.\n * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript\n *\n * @param {number} howMany\n * @returns {string} the generated random name\n * @private\n */\nfunction _randomChars(howMany) {\n let value = [],\n rnd = null;\n\n // make sure that we do not fail because we ran out of entropy\n try {\n rnd = crypto.randomBytes(howMany);\n } catch (e) {\n rnd = crypto.pseudoRandomBytes(howMany);\n }\n\n for (let i = 0; i < howMany; i++) {\n value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);\n }\n\n return value.join('');\n}\n\n/**\n * Checks whether the `obj` parameter is defined or not.\n *\n * @param {Object} obj\n * @returns {boolean} true if the object is undefined\n * @private\n */\nfunction _isUndefined(obj) {\n return typeof obj === 'undefined';\n}\n\n/**\n * Parses the function arguments.\n *\n * This function helps to have optional arguments.\n *\n * @param {(Options|null|undefined|Function)} options\n * @param {?Function} callback\n * @returns {Array} parsed arguments\n * @private\n */\nfunction _parseArguments(options, callback) {\n /* istanbul ignore else */\n if (typeof options === 'function') {\n return [{}, options];\n }\n\n /* istanbul ignore else */\n if (_isUndefined(options)) {\n return [{}, callback];\n }\n\n // copy options so we do not leak the changes we make internally\n const actualOptions = {};\n for (const key of Object.getOwnPropertyNames(options)) {\n actualOptions[key] = options[key];\n }\n\n return [actualOptions, callback];\n}\n\n/**\n * Resolve the specified path name in respect to tmpDir.\n *\n * The specified name might include relative path components, e.g. ../\n * so we need to resolve in order to be sure that is is located inside tmpDir\n *\n * @private\n */\nfunction _resolvePath(name, tmpDir, cb) {\n const pathToResolve = path.isAbsolute(name) ? name : path.join(tmpDir, name);\n\n fs.stat(pathToResolve, function (err) {\n if (err) {\n fs.realpath(path.dirname(pathToResolve), function (err, parentDir) {\n if (err) return cb(err);\n\n cb(null, path.join(parentDir, path.basename(pathToResolve)));\n });\n } else {\n fs.realpath(pathToResolve, cb);\n }\n });\n}\n\n/**\n * Resolve the specified path name in respect to tmpDir.\n *\n * The specified name might include relative path components, e.g. ../\n * so we need to resolve in order to be sure that is is located inside tmpDir\n *\n * @private\n */\nfunction _resolvePathSync(name, tmpDir) {\n const pathToResolve = path.isAbsolute(name) ? name : path.join(tmpDir, name);\n\n try {\n fs.statSync(pathToResolve);\n return fs.realpathSync(pathToResolve);\n } catch (_err) {\n const parentDir = fs.realpathSync(path.dirname(pathToResolve));\n\n return path.join(parentDir, path.basename(pathToResolve));\n }\n}\n\n/**\n * Generates a new temporary name.\n *\n * @param {Object} opts\n * @returns {string} the new random name according to opts\n * @private\n */\nfunction _generateTmpName(opts) {\n const tmpDir = opts.tmpdir;\n\n /* istanbul ignore else */\n if (!_isUndefined(opts.name)) {\n return path.join(tmpDir, opts.dir, opts.name);\n }\n\n /* istanbul ignore else */\n if (!_isUndefined(opts.template)) {\n return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6));\n }\n\n // prefix and postfix\n const name = [\n opts.prefix ? opts.prefix : 'tmp',\n '-',\n process.pid,\n '-',\n _randomChars(12),\n opts.postfix ? '-' + opts.postfix : ''\n ].join('');\n\n return path.join(tmpDir, opts.dir, name);\n}\n\n/**\n * Asserts and sanitizes the basic options.\n *\n * @private\n */\nfunction _assertOptionsBase(options) {\n if (!_isUndefined(options.name)) {\n const name = options.name;\n\n // assert that name is not absolute and does not contain a path\n if (path.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found \"${name}\".`);\n\n // must not fail on valid .<name> or ..<name> or similar such constructs\n const basename = path.basename(name);\n if (basename === '..' || basename === '.' || basename !== name)\n throw new Error(`name option must not contain a path, found \"${name}\".`);\n }\n\n /* istanbul ignore else */\n if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) {\n throw new Error(`Invalid template, found \"${options.template}\".`);\n }\n\n /* istanbul ignore else */\n if ((!_isUndefined(options.tries) && isNaN(options.tries)) || options.tries < 0) {\n throw new Error(`Invalid tries, found \"${options.tries}\".`);\n }\n\n // if a name was specified we will try once\n options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1;\n options.keep = !!options.keep;\n options.detachDescriptor = !!options.detachDescriptor;\n options.discardDescriptor = !!options.discardDescriptor;\n options.unsafeCleanup = !!options.unsafeCleanup;\n\n // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to\n options.prefix = _isUndefined(options.prefix) ? '' : options.prefix;\n options.postfix = _isUndefined(options.postfix) ? '' : options.postfix;\n}\n\n/**\n * Gets the relative directory to tmpDir.\n *\n * @private\n */\nfunction _getRelativePath(option, name, tmpDir, cb) {\n if (_isUndefined(name)) return cb(null);\n\n _resolvePath(name, tmpDir, function (err, resolvedPath) {\n if (err) return cb(err);\n\n const relativePath = path.relative(tmpDir, resolvedPath);\n\n if (!resolvedPath.startsWith(tmpDir)) {\n return cb(new Error(`${option} option must be relative to \"${tmpDir}\", found \"${relativePath}\".`));\n }\n\n cb(null, relativePath);\n });\n}\n\n/**\n * Gets the relative path to tmpDir.\n *\n * @private\n */\nfunction _getRelativePathSync(option, name, tmpDir) {\n if (_isUndefined(name)) return;\n\n const resolvedPath = _resolvePathSync(name, tmpDir);\n const relativePath = path.relative(tmpDir, resolvedPath);\n\n if (!resolvedPath.startsWith(tmpDir)) {\n throw new Error(`${option} option must be relative to \"${tmpDir}\", found \"${relativePath}\".`);\n }\n\n return relativePath;\n}\n\n/**\n * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing\n * options.\n *\n * @private\n */\nfunction _assertAndSanitizeOptions(options, cb) {\n _getTmpDir(options, function (err, tmpDir) {\n if (err) return cb(err);\n\n options.tmpdir = tmpDir;\n\n try {\n _assertOptionsBase(options, tmpDir);\n } catch (err) {\n return cb(err);\n }\n\n // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to\n _getRelativePath('dir', options.dir, tmpDir, function (err, dir) {\n if (err) return cb(err);\n\n options.dir = _isUndefined(dir) ? '' : dir;\n\n // sanitize further if template is relative to options.dir\n _getRelativePath('template', options.template, tmpDir, function (err, template) {\n if (err) return cb(err);\n\n options.template = template;\n\n cb(null, options);\n });\n });\n });\n}\n\n/**\n * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing\n * options.\n *\n * @private\n */\nfunction _assertAndSanitizeOptionsSync(options) {\n const tmpDir = (options.tmpdir = _getTmpDirSync(options));\n\n _assertOptionsBase(options, tmpDir);\n\n const dir = _getRelativePathSync('dir', options.dir, tmpDir);\n options.dir = _isUndefined(dir) ? '' : dir;\n\n options.template = _getRelativePathSync('template', options.template, tmpDir);\n\n return options;\n}\n\n/**\n * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows.\n *\n * @private\n */\nfunction _isEBADF(error) {\n return _isExpectedError(error, -EBADF, 'EBADF');\n}\n\n/**\n * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows.\n *\n * @private\n */\nfunction _isENOENT(error) {\n return _isExpectedError(error, -ENOENT, 'ENOENT');\n}\n\n/**\n * Helper to determine whether the expected error code matches the actual code and errno,\n * which will differ between the supported node versions.\n *\n * - Node >= 7.0:\n * error.code {string}\n * error.errno {number} any numerical value will be negated\n *\n * CAVEAT\n *\n * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT\n * is no different here.\n *\n * @param {SystemError} error\n * @param {number} errno\n * @param {string} code\n * @private\n */\nfunction _isExpectedError(error, errno, code) {\n return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno;\n}\n\n/**\n * Sets the graceful cleanup.\n *\n * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the\n * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary\n * object removals.\n */\nfunction setGracefulCleanup() {\n _gracefulCleanup = true;\n}\n\n/**\n * Returns the currently configured tmp dir from os.tmpdir().\n *\n * @private\n */\nfunction _getTmpDir(options, cb) {\n return fs.realpath((options && options.tmpdir) || os.tmpdir(), cb);\n}\n\n/**\n * Returns the currently configured tmp dir from os.tmpdir().\n *\n * @private\n */\nfunction _getTmpDirSync(options) {\n return fs.realpathSync((options && options.tmpdir) || os.tmpdir());\n}\n\n// Install process exit listener\nprocess.addListener(EXIT, _garbageCollector);\n\n/**\n * Configuration options.\n *\n * @typedef {Object} Options\n * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected\n * @property {?number} tries the number of tries before give up the name generation\n * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files\n * @property {?string} template the \"mkstemp\" like filename template\n * @property {?string} name fixed name relative to tmpdir or the specified dir option\n * @property {?string} dir tmp directory relative to the root tmp directory in use\n * @property {?string} prefix prefix for the generated name\n * @property {?string} postfix postfix for the generated name\n * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir\n * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty\n * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection\n * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection\n */\n\n/**\n * @typedef {Object} FileSyncObject\n * @property {string} name the name of the file\n * @property {string} fd the file descriptor or -1 if the fd has been discarded\n * @property {fileCallback} removeCallback the callback function to remove the file\n */\n\n/**\n * @typedef {Object} DirSyncObject\n * @property {string} name the name of the directory\n * @property {fileCallback} removeCallback the callback function to remove the directory\n */\n\n/**\n * @callback tmpNameCallback\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n */\n\n/**\n * @callback fileCallback\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {number} fd the file descriptor or -1 if the fd had been discarded\n * @param {cleanupCallback} fn the cleanup callback function\n */\n\n/**\n * @callback fileCallbackSync\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {number} fd the file descriptor or -1 if the fd had been discarded\n * @param {cleanupCallbackSync} fn the cleanup callback function\n */\n\n/**\n * @callback dirCallback\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {cleanupCallback} fn the cleanup callback function\n */\n\n/**\n * @callback dirCallbackSync\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {cleanupCallbackSync} fn the cleanup callback function\n */\n\n/**\n * Removes the temporary created file or directory.\n *\n * @callback cleanupCallback\n * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed\n */\n\n/**\n * Removes the temporary created file or directory.\n *\n * @callback cleanupCallbackSync\n */\n\n/**\n * Callback function for function composition.\n * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57}\n *\n * @callback simpleCallback\n */\n\n// exporting all the needed methods\n\n// evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will\n// allow users to reconfigure the temporary directory\nObject.defineProperty(module.exports, 'tmpdir', {\n enumerable: true,\n configurable: false,\n get: function () {\n return _getTmpDirSync();\n }\n});\n\nmodule.exports.dir = dir;\nmodule.exports.dirSync = dirSync;\n\nmodule.exports.file = file;\nmodule.exports.fileSync = fileSync;\n\nmodule.exports.tmpName = tmpName;\nmodule.exports.tmpNameSync = tmpNameSync;\n\nmodule.exports.setGracefulCleanup = setGracefulCleanup;\n", "'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numberic identifiers include numberic identifiers but can be longer.\n// Therefore non-numberic identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // If the main part has no difference\n if (lowVersion.compareMain(highVersion) === 0) {\n if (lowVersion.minor && !lowVersion.patch) {\n return 'minor'\n }\n return 'patch'\n }\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are preleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n", "'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n", "'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n", "/* eslint-disable no-console -- this is a cli tool */\n\nimport { createWriteStream, existsSync, promises as fs, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { stylish } from \"@html-validate/stylish\";\nimport { type DocumentNode, parse } from \"@humanwhocodes/momoa\";\nimport { ArgumentParser } from \"argparse\";\nimport { findUp } from \"find-up\";\nimport tmp from \"tmp\";\nimport { setupBlacklist } from \"./blacklist\";\nimport { type TarballMeta, getFileContent } from \"./tarball\";\nimport { tarballLocation } from \"./tarball-location\";\nimport { type PackageJson } from \"./types\";\nimport { setCacheDirecory } from \"./utils/persistent-cache\";\nimport { type VerifyOptions, verify } from \"./verify\";\n\nconst pkgFilepath = fileURLToPath(new URL(\"../package.json\", import.meta.url));\nconst { version } = JSON.parse(readFileSync(pkgFilepath, \"utf-8\")) as { version: string };\n\nconst PACKAGE_JSON = \"package.json\";\n\ninterface ParsedArgs {\n\tcache?: string;\n\tpkgfile: string;\n\ttarball?: string;\n\tignore_missing_fields?: boolean;\n\tignore_node_version: boolean | number;\n\tallow_dependency: string[];\n\tallow_types_dependencies?: boolean;\n}\n\ninterface GetPackageJsonResults {\n\tpkg: PackageJson;\n\tpkgAst: DocumentNode;\n\tpkgPath: string;\n}\n\nasync function preloadStdin(): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\ttmp.file((err, path, fd) => {\n\t\t\tif (err) {\n\t\t\t\treject(err);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst st = createWriteStream(\"\", { fd, autoClose: true });\n\t\t\tprocess.stdin.pipe(st);\n\t\t\tst.on(\"finish\", () => {\n\t\t\t\tresolve(path);\n\t\t\t});\n\t\t\tst.on(\"error\", (err) => {\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t});\n}\n\nasync function getPackageJson(\n\targs: ParsedArgs,\n\tregenerateReportName: boolean,\n): Promise<GetPackageJsonResults | { pkg: undefined; pkgAst: undefined; pkgPath: undefined }> {\n\t/* get from explicit path passed as argument */\n\tif (args.pkgfile) {\n\t\tconst content = await fs.readFile(args.pkgfile, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as PackageJson;\n\t\tconst pkgAst = parse(content);\n\t\treturn {\n\t\t\tpkg,\n\t\t\tpkgAst,\n\t\t\tpkgPath: args.pkgfile,\n\t\t};\n\t}\n\n\t/* extract package.json from explicit tarball location */\n\tif (args.tarball) {\n\t\tconst contents = await getFileContent({ filePath: args.tarball }, [PACKAGE_JSON]);\n\t\tconst content = contents[PACKAGE_JSON].toString(\"utf-8\");\n\t\tconst pkg = JSON.parse(content) as PackageJson;\n\t\tconst pkgAst = parse(content);\n\t\treturn {\n\t\t\tpkg,\n\t\t\tpkgAst,\n\t\t\tpkgPath: path.join(\n\t\t\t\tregenerateReportName ? `${pkg.name}-${pkg.version}.tgz` : args.tarball,\n\t\t\t\tPACKAGE_JSON,\n\t\t\t),\n\t\t};\n\t}\n\n\t/* try to locate package.json from file structure */\n\tconst pkgPath = await findUp(PACKAGE_JSON);\n\tif (pkgPath) {\n\t\tconst content = await fs.readFile(pkgPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as PackageJson;\n\t\tconst pkgAst = parse(content);\n\t\treturn {\n\t\t\tpkg,\n\t\t\tpkgAst,\n\t\t\tpkgPath,\n\t\t};\n\t}\n\n\treturn { pkg: undefined, pkgAst: undefined, pkgPath: undefined };\n}\n\nasync function run(): Promise<void> {\n\tconst parser = new ArgumentParser({\n\t\tdescription: \"Opiniated linter for NPM package tarball and package.json metadata\",\n\t});\n\n\tparser.add_argument(\"-v\", \"--version\", { action: \"version\", version });\n\tparser.add_argument(\"-t\", \"--tarball\", { help: \"specify tarball location\" });\n\tparser.add_argument(\"-p\", \"--pkgfile\", { help: \"specify package.json location\" });\n\tparser.add_argument(\"--cache\", { help: \"specify cache directory\" });\n\tparser.add_argument(\"--allow-dependency\", {\n\t\taction: \"append\",\n\t\tdefault: [],\n\t\tmetavar: \"DEPENDENCY\",\n\t\thelp: \"explicitly allow given dependency (can be given multiple times or as a comma-separated list)\",\n\t});\n\tparser.add_argument(\"--allow-types-dependencies\", {\n\t\taction: \"store_true\",\n\t\thelp: \"allow production dependencies to `@types/*`\",\n\t});\n\tparser.add_argument(\"--ignore-missing-fields\", {\n\t\taction: \"store_true\",\n\t\thelp: \"ignore errors for missing fields (but still checks for empty and valid)\",\n\t});\n\tparser.add_argument(\"--ignore-node-version\", {\n\t\tnargs: \"?\",\n\t\tmetavar: \"MAJOR\",\n\t\ttype: \"int\",\n\t\tdefault: false,\n\t\tconst: true,\n\t\thelp: \"ignore error for outdated node version (restricted to MAJOR version if given)\",\n\t});\n\n\tconst args = parser.parse_args() as ParsedArgs;\n\tconst allowedDependencies = new Set(args.allow_dependency.map((it) => it.split(\",\")).flat());\n\n\tif (args.cache) {\n\t\tawait setCacheDirecory(args.cache);\n\t}\n\n\t/* this library assumes the file source can be randomly accessed but with\n\t * stdin this is not possible so stdin is read into a temporary file which is\n\t * used instead */\n\tlet regenerateReportName = false;\n\tif (args.tarball === \"-\") {\n\t\targs.tarball = await preloadStdin();\n\t\tregenerateReportName = true;\n\t}\n\n\tconst { pkg, pkgAst, pkgPath } = await getPackageJson(args, regenerateReportName);\n\n\tif (!pkg) {\n\t\tconsole.error(\"Failed to locate package.json and no location was specificed with `--pkgfile'\");\n\t\tprocess.exitCode = 1;\n\t\treturn;\n\t}\n\n\tconst tarball: TarballMeta = {\n\t\tfilePath: args.tarball ?? tarballLocation(pkg, pkgPath),\n\t\treportPath: regenerateReportName ? `${pkg.name}-${pkg.version}.tgz` : undefined,\n\t};\n\tif (!existsSync(tarball.filePath)) {\n\t\tconsole.error(`\"${tarball.filePath}\" does not exist, did you forget to run \\`npm pack'?`);\n\t\tprocess.exitCode = 1;\n\t\treturn;\n\t}\n\n\tsetupBlacklist(pkg.name);\n\n\tconst options: VerifyOptions = {\n\t\tallowedDependencies,\n\t\tallowTypesDependencies: args.allow_types_dependencies,\n\t\tignoreMissingFields: args.ignore_missing_fields,\n\t\tignoreNodeVersion: args.ignore_node_version,\n\t};\n\n\tconst results = await verify(pkg, pkgAst, pkgPath, tarball, options);\n\n\tfor (const result of results) {\n\t\tresult.messages.sort((a, b) => {\n\t\t\tif (a.line !== b.line) {\n\t\t\t\treturn a.line - b.line;\n\t\t\t} else {\n\t\t\t\treturn a.column - b.column;\n\t\t\t}\n\t\t});\n\t}\n\n\tconst output = stylish(results);\n\tprocess.stdout.write(output);\n\n\tconst totalErrors = results.reduce((sum, result) => {\n\t\treturn sum + result.errorCount;\n\t}, 0);\n\n\tprocess.exitCode = totalErrors > 0 ? 1 : 0;\n}\n\nrun().catch((err: unknown) => {\n\tconsole.error(err);\n\tprocess.exitCode = 1;\n});\n", "let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;\nif (typeof process !== 'undefined') {\n\t({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});\n\tisTTY = process.stdout && process.stdout.isTTY;\n}\n\nexport const $ = {\n\tenabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (\n\t\tFORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY\n\t)\n}\n\nfunction init(x, y) {\n\tlet rgx = new RegExp(`\\\\x1b\\\\[${y}m`, 'g');\n\tlet open = `\\x1b[${x}m`, close = `\\x1b[${y}m`;\n\n\treturn function (txt) {\n\t\tif (!$.enabled || txt == null) return txt;\n\t\treturn open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;\n\t};\n}\n\n// modifiers\nexport const reset = init(0, 0);\nexport const bold = init(1, 22);\nexport const dim = init(2, 22);\nexport const italic = init(3, 23);\nexport const underline = init(4, 24);\nexport const inverse = init(7, 27);\nexport const hidden = init(8, 28);\nexport const strikethrough = init(9, 29);\n\n// colors\nexport const black = init(30, 39);\nexport const red = init(31, 39);\nexport const green = init(32, 39);\nexport const yellow = init(33, 39);\nexport const blue = init(34, 39);\nexport const magenta = init(35, 39);\nexport const cyan = init(36, 39);\nexport const white = init(37, 39);\nexport const gray = init(90, 39);\nexport const grey = init(90, 39);\n\n// background colors\nexport const bgBlack = init(40, 49);\nexport const bgRed = init(41, 49);\nexport const bgGreen = init(42, 49);\nexport const bgYellow = init(43, 49);\nexport const bgBlue = init(44, 49);\nexport const bgMagenta = init(45, 49);\nexport const bgCyan = init(46, 49);\nexport const bgWhite = init(47, 49);\n", "module.exports = function (rows_, opts) {\n if (!opts) opts = {};\n var hsep = opts.hsep === undefined ? ' ' : opts.hsep;\n var align = opts.align || [];\n var stringLength = opts.stringLength\n || function (s) { return String(s).length; }\n ;\n \n var dotsizes = reduce(rows_, function (acc, row) {\n forEach(row, function (c, ix) {\n var n = dotindex(c);\n if (!acc[ix] || n > acc[ix]) acc[ix] = n;\n });\n return acc;\n }, []);\n \n var rows = map(rows_, function (row) {\n return map(row, function (c_, ix) {\n var c = String(c_);\n if (align[ix] === '.') {\n var index = dotindex(c);\n var size = dotsizes[ix] + (/\\./.test(c) ? 1 : 2)\n - (stringLength(c) - index)\n ;\n return c + Array(size).join(' ');\n }\n else return c;\n });\n });\n \n var sizes = reduce(rows, function (acc, row) {\n forEach(row, function (c, ix) {\n var n = stringLength(c);\n if (!acc[ix] || n > acc[ix]) acc[ix] = n;\n });\n return acc;\n }, []);\n \n return map(rows, function (row) {\n return map(row, function (c, ix) {\n var n = (sizes[ix] - stringLength(c)) || 0;\n var s = Array(Math.max(n + 1, 1)).join(' ');\n if (align[ix] === 'r' || align[ix] === '.') {\n return s + c;\n }\n if (align[ix] === 'c') {\n return Array(Math.ceil(n / 2 + 1)).join(' ')\n + c + Array(Math.floor(n / 2 + 1)).join(' ')\n ;\n }\n \n return c + s;\n }).join(hsep).replace(/\\s+$/, '');\n }).join('\\n');\n};\n\nfunction dotindex (c) {\n var m = /\\.[^.]*$/.exec(c);\n return m ? m.index + 1 : c.length;\n}\n\nfunction reduce (xs, f, init) {\n if (xs.reduce) return xs.reduce(f, init);\n var i = 0;\n var acc = arguments.length >= 3 ? init : xs[i++];\n for (; i < xs.length; i++) {\n f(acc, xs[i], i);\n }\n return acc;\n}\n\nfunction forEach (xs, f) {\n if (xs.forEach) return xs.forEach(f);\n for (var i = 0; i < xs.length; i++) {\n f.call(xs, xs[i], i);\n }\n}\n\nfunction map (xs, f) {\n if (xs.map) return xs.map(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n res.push(f.call(xs, xs[i], i));\n }\n return res;\n}\n", "import table, { type Options } from \"text-table\";\nimport * as colors from \"./colors-node\";\nimport { type Result } from \"./result\";\nimport { Severity } from \"./severity\";\n\n/**\n * Given a word and a count, append an s if count is not one.\n * @param word - A word in its singular form.\n * @param count - A number controlling whether word should be pluralized.\n * @returns - The original word with an s on the end if count is not one.\n */\nfunction pluralize(word: string, count: number): string {\n\treturn count === 1 ? word : `${word}s`;\n}\n\n/**\n * Given a line with \" $\\{line\\} $\\{column\\} \" where line is right-aligned and\n * column is left-aligned it replaces the delimiter with a colon.\n */\nfunction centerLineColumn(el: string): string {\n\t/* eslint-disable-next-line sonarjs/slow-regex -- false positive? unless I'm missing something here */\n\treturn el.replace(/(\\d+)\\s+(\\d+)/u, (_m, p1: string, p2: string) => colors.dim(`${p1}:${p2}`));\n}\n\n/**\n * Strip ANSI color escape sequences from text.\n */\nfunction stripAnsi(text: string): string {\n\t/* eslint-disable-next-line no-control-regex -- expected to match control characters */\n\treturn text.replace(/\\u001B\\[[0-9;]*m/g, \"\");\n}\n\nexport function stylish(results: Result[]): string {\n\tlet output = \"\\n\";\n\tlet errorCount = 0;\n\tlet warningCount = 0;\n\tlet fixableErrorCount = 0;\n\tlet fixableWarningCount = 0;\n\tlet summaryColor: colors.Colorize = colors.yellow;\n\n\tresults.forEach((result) => {\n\t\tconst messages = result.messages;\n\n\t\tif (messages.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\terrorCount += result.errorCount;\n\t\twarningCount += result.warningCount;\n\t\tfixableErrorCount += result.fixableErrorCount;\n\t\tfixableWarningCount += result.fixableWarningCount;\n\n\t\tconst rows = messages.map((message) => {\n\t\t\tlet messageType;\n\n\t\t\tif (Boolean(message.fatal) || message.severity === Severity.ERROR) {\n\t\t\t\tmessageType = colors.red(\"error\");\n\t\t\t\tsummaryColor = colors.red;\n\t\t\t} else {\n\t\t\t\tmessageType = colors.yellow(\"warning\");\n\t\t\t}\n\n\t\t\treturn [\n\t\t\t\t\"\",\n\t\t\t\tmessage.line ?? 0,\n\t\t\t\tmessage.column ?? 0,\n\t\t\t\tmessageType,\n\t\t\t\tmessage.message.replace(/([^ ])\\.$/u, \"$1\"),\n\t\t\t\tmessage.ruleId ? colors.dim(message.ruleId) : \"\",\n\t\t\t];\n\t\t});\n\n\t\tconst options: Options = {\n\t\t\talign: [\"l\", \"r\", \"l\"],\n\t\t\tstringLength(str: string): number {\n\t\t\t\treturn stripAnsi(str).length;\n\t\t\t},\n\t\t};\n\t\tconst formattedTable = table(rows, options).split(\"\\n\").map(centerLineColumn).join(\"\\n\");\n\n\t\toutput += `${colors.underline(result.filePath)}\\n`;\n\t\toutput += `${formattedTable}\\n\\n`;\n\t});\n\n\tconst total = errorCount + warningCount;\n\n\tif (total > 0) {\n\t\toutput += summaryColor(\n\t\t\tcolors.bold(\n\t\t\t\t[\n\t\t\t\t\t\"\\u2716 \",\n\t\t\t\t\ttotal,\n\t\t\t\t\tpluralize(\" problem\", total),\n\t\t\t\t\t\" (\",\n\t\t\t\t\terrorCount,\n\t\t\t\t\tpluralize(\" error\", errorCount),\n\t\t\t\t\t\", \",\n\t\t\t\t\twarningCount,\n\t\t\t\t\tpluralize(\" warning\", warningCount),\n\t\t\t\t\t\")\\n\",\n\t\t\t\t].join(\"\"),\n\t\t\t),\n\t\t);\n\n\t\tif (fixableErrorCount > 0 || fixableWarningCount > 0) {\n\t\t\toutput += summaryColor(\n\t\t\t\tcolors.bold(\n\t\t\t\t\t[\n\t\t\t\t\t\t\" \",\n\t\t\t\t\t\tfixableErrorCount,\n\t\t\t\t\t\tpluralize(\" error\", fixableErrorCount),\n\t\t\t\t\t\t\" and \",\n\t\t\t\t\t\tfixableWarningCount,\n\t\t\t\t\t\tpluralize(\" warning\", fixableWarningCount),\n\t\t\t\t\t\t\" potentially fixable with the `--fix` option.\\n\",\n\t\t\t\t\t].join(\"\"),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Resets output color, for prevent change on top level\n\treturn total > 0 ? colors.reset(output) : \"\";\n}\n", "import * as kleur from \"kleur/colors\";\n\nexport type Colorize = kleur.Colorize;\n\nexport const reset = kleur.reset;\nexport const bold = kleur.bold;\nexport const dim = kleur.dim;\nexport const underline = kleur.underline;\n\nexport const yellow = kleur.yellow;\nexport const red = kleur.red;\n", "export enum Severity {\n\tOFF = 0,\n\tWARN = 1,\n\tERROR = 2,\n}\n", "/**\n * @fileoverview Character codes.\n * @author Nicholas C. Zakas\n */\n\nconst CHAR_0 = 48; // 0\nconst CHAR_1 = 49; // 1\nconst CHAR_9 = 57; // 9\nconst CHAR_BACKSLASH = 92; // \\\nconst CHAR_DOLLAR = 36; // $\nconst CHAR_DOT = 46; // .\nconst CHAR_DOUBLE_QUOTE = 34; // \"\nconst CHAR_LOWER_A = 97; // a\nconst CHAR_LOWER_E = 101; // e\nconst CHAR_LOWER_F = 102; // f\nconst CHAR_LOWER_N = 110; // n\nconst CHAR_LOWER_T = 116; // t\nconst CHAR_LOWER_U = 117; // u\nconst CHAR_LOWER_X = 120; // x\nconst CHAR_LOWER_Z = 122; // z\nconst CHAR_MINUS = 45; // -\nconst CHAR_NEWLINE = 10; // newline\nconst CHAR_PLUS = 43; // +\nconst CHAR_RETURN = 13; // return\nconst CHAR_SINGLE_QUOTE = 39; // '\nconst CHAR_SLASH = 47; // /\nconst CHAR_SPACE = 32; // space\nconst CHAR_TAB = 9; // tab\nconst CHAR_UNDERSCORE = 95; // _\nconst CHAR_UPPER_A = 65; // A\nconst CHAR_UPPER_E = 69; // E\nconst CHAR_UPPER_F = 70; // F\nconst CHAR_UPPER_N = 78; // N\nconst CHAR_UPPER_X = 88; // X\nconst CHAR_UPPER_Z = 90; // Z\nconst CHAR_LOWER_B = 98; // b\nconst CHAR_LOWER_R = 114; // r\nconst CHAR_LOWER_V = 118; // v\nconst CHAR_LINE_SEPARATOR = 0x2028;\nconst CHAR_PARAGRAPH_SEPARATOR = 0x2029;\nconst CHAR_UPPER_I = 73; // I\nconst CHAR_STAR = 42; // *\nconst CHAR_VTAB = 11; // U+000B Vertical tab\nconst CHAR_FORM_FEED = 12; // U+000C Form feed\nconst CHAR_NBSP = 160; // U+00A0 Non-breaking space\nconst CHAR_BOM = 65279; // U+FEFF\nconst CHAR_NON_BREAKING_SPACE = 160;\nconst CHAR_EN_QUAD = 8192;\nconst CHAR_EM_QUAD = 8193;\nconst CHAR_EN_SPACE = 8194;\nconst CHAR_EM_SPACE = 8195;\nconst CHAR_THREE_PER_EM_SPACE = 8196;\nconst CHAR_FOUR_PER_EM_SPACE = 8197;\nconst CHAR_SIX_PER_EM_SPACE = 8198;\nconst CHAR_FIGURE_SPACE = 8199;\nconst CHAR_PUNCTUATION_SPACE = 8200;\nconst CHAR_THIN_SPACE = 8201;\nconst CHAR_HAIR_SPACE = 8202;\nconst CHAR_NARROW_NO_BREAK_SPACE = 8239;\nconst CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287;\nconst CHAR_IDEOGRAPHIC_SPACE = 12288;\n\n/**\n * @fileoverview JSON syntax helpers\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Types\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").TokenType} TokenType */\n\n//-----------------------------------------------------------------------------\n// Predefined Tokens\n//-----------------------------------------------------------------------------\n\nconst LBRACKET = \"[\";\nconst RBRACKET = \"]\";\nconst LBRACE = \"{\";\nconst RBRACE = \"}\";\nconst COLON = \":\";\nconst COMMA = \",\";\n\nconst TRUE = \"true\";\nconst FALSE = \"false\";\nconst NULL = \"null\";\nconst NAN$1 = \"NaN\";\nconst INFINITY$1 = \"Infinity\";\nconst QUOTE = \"\\\"\";\n\nconst escapeToChar = new Map([\n [CHAR_DOUBLE_QUOTE, QUOTE],\n [CHAR_BACKSLASH, \"\\\\\"],\n [CHAR_SLASH, \"/\"],\n [CHAR_LOWER_B, \"\\b\"],\n [CHAR_LOWER_N, \"\\n\"],\n [CHAR_LOWER_F, \"\\f\"],\n [CHAR_LOWER_R, \"\\r\"],\n [CHAR_LOWER_T, \"\\t\"]\n]);\n\nconst json5EscapeToChar = new Map([\n ...escapeToChar,\n [CHAR_LOWER_V, \"\\v\"],\n [CHAR_0, \"\\0\"]\n]);\n\nconst charToEscape = new Map([\n [QUOTE, QUOTE],\n [\"\\\\\", \"\\\\\"],\n [\"/\", \"/\"],\n [\"\\b\", \"b\"],\n [\"\\n\", \"n\"],\n [\"\\f\", \"f\"],\n [\"\\r\", \"r\"],\n [\"\\t\", \"t\"]\n]);\n\nconst json5CharToEscape = new Map([\n ...charToEscape,\n [\"\\v\", \"v\"],\n [\"\\0\", \"0\"],\n [\"\\u2028\", \"u2028\"],\n [\"\\u2029\", \"u2029\"]\n]);\n\n/** @type {Map<string,TokenType>} */\nconst knownTokenTypes = new Map([\n [LBRACKET, \"LBracket\"],\n [RBRACKET, \"RBracket\"],\n [LBRACE, \"LBrace\"],\n [RBRACE, \"RBrace\"],\n [COLON, \"Colon\"],\n [COMMA, \"Comma\"],\n [TRUE, \"Boolean\"],\n [FALSE, \"Boolean\"],\n [NULL, \"Null\"]\n]);\n\n/** @type {Map<string,TokenType>} */\nconst knownJSON5TokenTypes = new Map([\n ...knownTokenTypes,\n [NAN$1, \"Number\"],\n [INFINITY$1, \"Number\"]\n]);\n\n// JSON5\nconst json5LineTerminators = new Set([\n CHAR_NEWLINE,\n CHAR_RETURN,\n CHAR_LINE_SEPARATOR,\n CHAR_PARAGRAPH_SEPARATOR\n]);\n\n/**\n * @fileoverview JSON tokenization/parsing errors\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Location} Location */\n/** @typedef {import(\"./typedefs.js\").Token} Token */\n\n//-----------------------------------------------------------------------------\n// Errors\n//-----------------------------------------------------------------------------\n\n/**\n * Base class that attaches location to an error.\n */\nclass ErrorWithLocation extends Error {\n\n /**\n * Creates a new instance.\n * @param {string} message The error message to report. \n * @param {Location} loc The location information for the error.\n */\n constructor(message, { line, column, offset }) {\n super(`${ message } (${ line }:${ column})`);\n\n /**\n * The line on which the error occurred.\n * @type {number}\n */\n this.line = line;\n\n /**\n * The column on which the error occurred.\n * @type {number}\n */\n this.column = column;\n \n /**\n * The index into the string where the error occurred.\n * @type {number}\n */\n this.offset = offset;\n }\n\n}\n\n/**\n * Error thrown when an unexpected character is found during tokenizing.\n */\nclass UnexpectedChar extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {number} unexpected The character that was found.\n * @param {Location} loc The location information for the found character.\n */\n constructor(unexpected, loc) {\n super(`Unexpected character '${ String.fromCharCode(unexpected) }' found.`, loc);\n }\n}\n\n/**\n * Error thrown when an unexpected identifier is found during tokenizing.\n */\nclass UnexpectedIdentifier extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {string} unexpected The character that was found.\n * @param {Location} loc The location information for the found character.\n */\n constructor(unexpected, loc) {\n super(`Unexpected identifier '${ unexpected }' found.`, loc);\n }\n}\n\n/**\n * Error thrown when an unexpected token is found during parsing.\n */\nclass UnexpectedToken extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {Token} token The token that was found. \n */\n constructor(token) {\n super(`Unexpected token ${ token.type } found.`, token.loc.start);\n }\n}\n\n/**\n * Error thrown when the end of input is found where it isn't expected.\n */\nclass UnexpectedEOF extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {Location} loc The location information for the found character.\n */\n constructor(loc) {\n super(\"Unexpected end of input found.\", loc);\n }\n}\n\n/*\n * The following is extracted from https://github.com/json5/json5/\n *\n * MIT License\n * \n * Copyright (c) 2012-2018 Aseem Kishore, and others.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\nconst ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\u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DEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE83\\uDE86-\\uDE89\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]/;\n// eslint-disable-next-line no-misleading-character-class\nconst ID_Continue = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09FC\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0AF9-\\u0AFF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0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E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]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uDE37\\uDE3E\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEEA\\uDEF0-\\uDEF9\\uDF00-\\uDF03\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3C-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF50\\uDF57\\uDF5D-\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC00-\\uDC4A\\uDC50-\\uDC59\\uDC80-\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDB5\\uDDB8-\\uDDC0\\uDDD8-\\uDDDD\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB7\\uDEC0-\\uDEC9\\uDF00-\\uDF19\\uDF1D-\\uDF2B\\uDF30-\\uDF39]|\\uD806[\\uDCA0-\\uDCE9\\uDCFF\\uDE00-\\uDE3E\\uDE47\\uDE50-\\uDE83\\uDE86-\\uDE99\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36\\uDC38-\\uDC40\\uDC50-\\uDC59\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD47\\uDD50-\\uDD59]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\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\\uDD00-\\uDD4A\\uDD50-\\uDD59]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/;\n\n/**\n * @fileoverview A charactor code reader.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Type Definitions\n//-----------------------------------------------------------------------------\n\n\n//-----------------------------------------------------------------------------\n// Data\n//-----------------------------------------------------------------------------\n\nconst CHAR_CR = 13; // \\r\nconst CHAR_LF = 10; // \\n\n\n//-----------------------------------------------------------------------------\n// CharCodeReader\n//-----------------------------------------------------------------------------\n\n/**\n * A reader that reads character codes from a string.\n */\nclass CharCodeReader {\n\n /**\n * The text to read from.\n * @type {string}\n */\n #text = \"\";\n\n /**\n * The current line number.\n * @type {number}\n */\n #line = 1;\n\n /**\n * The current column number.\n * @type {number}\n */\n #column = 0;\n\n /**\n * The current offset in the text.\n * @type {number}\n */\n #offset = -1;\n\n /**\n * Whether the last character read was a new line.\n * @type {boolean}\n */\n #newLine = false;\n\n /**\n * The last character code read.\n * @type {number}\n */\n #last = -1;\n\n /**\n * Whether the reader has ended.\n * @type {boolean}\n */\n #ended = false;\n\n /**\n * Creates a new instance.\n * @param {string} text The text to read from\n */\n constructor(text) {\n this.#text = text;\n }\n\n /**\n * Ends the reader.\n * @returns {void}\n */\n #end() {\n if (this.#ended) {\n return;\n }\n\n this.#column++;\n this.#offset++;\n this.#last = -1;\n this.#ended = true;\n }\n\n /**\n * Returns the current position of the reader.\n * @returns {Location} An object with line, column, and offset properties.\n */\n locate() {\n return {\n line: this.#line,\n column: this.#column,\n offset: this.#offset\n };\n }\n\n /**\n * Reads the next character code in the text.\n * @returns {number} The next character code, or -1 if there are no more characters.\n */\n next() {\n if (this.#offset >= this.#text.length - 1) {\n this.#end();\n return -1;\n }\n\n this.#offset++;\n const charCode = this.#text.charCodeAt(this.#offset);\n\n if (this.#newLine) {\n this.#line++;\n this.#column = 1;\n this.#newLine = false;\n } else {\n this.#column++;\n }\n\n if (charCode === CHAR_CR) {\n this.#newLine = true;\n\n // if we already see a \\r, just ignore upcoming \\n\n if (this.peek() === CHAR_LF) {\n this.#offset++;\n }\n } else if (charCode === CHAR_LF) {\n this.#newLine = true;\n }\n\n this.#last = charCode;\n\n return charCode;\n }\n\n /**\n * Peeks at the next character code in the text.\n * @returns {number} The next character code, or -1 if there are no more characters.\n */\n peek() {\n if (this.#offset === this.#text.length - 1) {\n return -1;\n }\n\n return this.#text.charCodeAt(this.#offset + 1);\n }\n\n /**\n * Determines if the next character code in the text matches a specific character code.\n * @param {(number) => boolean} fn A function to call on the next character.\n * @returns {boolean} True if the next character code matches, false if not.\n */ \n match(fn) {\n if (fn(this.peek())) {\n this.next();\n return true;\n }\n\n return false;\n }\n\n /**\n * Returns the last character code read.\n * @returns {number} The last character code read.\n */\n current() {\n return this.#last;\n }\n\n\n}\n\n/**\n * @fileoverview JSON tokenizer\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Range} Range */\n/** @typedef {import(\"./typedefs.js\").TokenizeOptions} TokenizeOptions */\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\nconst INFINITY = \"Infinity\";\nconst NAN = \"NaN\";\n\nconst keywordStarts = new Set([CHAR_LOWER_T, CHAR_LOWER_F, CHAR_LOWER_N]);\nconst whitespace = new Set([CHAR_SPACE, CHAR_TAB, CHAR_NEWLINE, CHAR_RETURN]);\nconst json5Whitespace = new Set([\n ...whitespace,\n CHAR_VTAB,\n CHAR_FORM_FEED,\n CHAR_NBSP,\n CHAR_LINE_SEPARATOR,\n CHAR_PARAGRAPH_SEPARATOR,\n CHAR_BOM,\n CHAR_NON_BREAKING_SPACE,\n CHAR_EN_QUAD,\n CHAR_EM_QUAD,\n CHAR_EN_SPACE,\n CHAR_EM_SPACE,\n CHAR_THREE_PER_EM_SPACE,\n CHAR_FOUR_PER_EM_SPACE,\n CHAR_SIX_PER_EM_SPACE,\n CHAR_FIGURE_SPACE,\n CHAR_PUNCTUATION_SPACE,\n CHAR_THIN_SPACE,\n CHAR_HAIR_SPACE,\n CHAR_NARROW_NO_BREAK_SPACE,\n CHAR_MEDIUM_MATHEMATICAL_SPACE,\n CHAR_IDEOGRAPHIC_SPACE,\n]);\n\n\n/** @type {TokenizeOptions} */\nconst DEFAULT_OPTIONS$1 = {\n mode: \"json\",\n ranges: false\n};\n\nconst jsonKeywords = new Set([\"true\", \"false\", \"null\"]);\n\nconst tt = {\n EOF: 0,\n Number: 1,\n String: 2,\n Boolean: 3,\n Null: 4,\n NaN: 5,\n Infinity: 6,\n Identifier: 7,\n Colon: 20,\n LBrace: 21,\n RBrace: 22,\n LBracket: 23,\n RBracket: 24,\n Comma: 25,\n LineComment: 40,\n BlockComment: 41\n};\n\n\n// #region Helpers\n\n\n/**\n * Determines if a given character is a decimal digit.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a digit.\n */\nfunction isDigit(c) {\n return c >= CHAR_0 && c <= CHAR_9;\n}\n\n/**\n * Determines if a given character is a hexadecimal digit.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a hexadecimal digit.\n */\nfunction isHexDigit(c) {\n return isDigit(c) ||\n c >= CHAR_UPPER_A && c <= CHAR_UPPER_F ||\n c >= CHAR_LOWER_A && c <= CHAR_LOWER_F;\n}\n\n/**\n * Determines if a given character is a positive digit (1-9).\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a positive digit.\n */\nfunction isPositiveDigit(c) {\n return c >= CHAR_1 && c <= CHAR_9;\n}\n\n/**\n * Determines if a given character is the start of a keyword.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a keyword.\n */\nfunction isKeywordStart(c) {\n return keywordStarts.has(c);\n}\n\n/**\n * Determines if a given character is the start of a number.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a number.\n */\nfunction isNumberStart(c) {\n return isDigit(c) || c === CHAR_DOT || c === CHAR_MINUS;\n}\n\n/**\n * Determines if a given character is the start of a JSON5 number.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a JSON5 number.\n */\nfunction isJSON5NumberStart(c) {\n return isNumberStart(c) || c === CHAR_PLUS;\n}\n\n/**\n * Determines if a given character is the start of a string.\n * @param {number} c The character to check.\n * @param {boolean} json5 `true` if JSON5 mode is enabled.\n * @returns {boolean} `true` if the character is the start of a string.\n */\nfunction isStringStart(c, json5) {\n return c === CHAR_DOUBLE_QUOTE || (json5 && c === CHAR_SINGLE_QUOTE);\n}\n\n/**\n * Tests that a given character is a valid first character of a\n * JSON5 identifier\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a valid first character. \n */\nfunction isJSON5IdentifierStart(c) {\n\n // test simple cases first\n\n if (c === CHAR_DOLLAR || c === CHAR_UNDERSCORE || c === CHAR_BACKSLASH) {\n return true;\n }\n\n if (c >= CHAR_LOWER_A && c <= CHAR_LOWER_Z || c >= CHAR_UPPER_A && c <= CHAR_UPPER_Z) {\n return true;\n }\n\n if (c === 0x200C || c === 0x200D) {\n return true;\n }\n \n const ct = String.fromCharCode(c);\n return ID_Start.test(ct);\n}\n\n/**\n * Tests that a given character is a valid part of a JSON5 identifier.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a valid part of an identifier.\n */\nfunction isJSON5IdentifierPart(c) {\n\n // fast path for simple cases\n if (isJSON5IdentifierStart(c) || isDigit(c)) {\n return true;\n }\n\n const ct = String.fromCharCode(c);\n return ID_Continue.test(ct);\n}\n\n\n// #endregion\n\nclass Tokenizer {\n\n /**\n * Options for the tokenizer.\n * @type {TokenizeOptions}\n */\n #options;\n\n /**\n * The source text to tokenize.\n * @type {string}\n */\n #text;\n\n /**\n * The reader for the source text.\n * @type {CharCodeReader}\n */\n #reader;\n\n /**\n * Indicates if the tokenizer is in JSON5 mode.\n * @type {boolean}\n */\n #json5;\n\n /**\n * Indicates if comments are allowed.\n * @type {boolean}\n */\n #allowComments;\n\n /**\n * Indicates if ranges should be included in the tokens.\n * @type {boolean}\n */\n #ranges;\n\n /**\n * The last token type read.\n * @type {Token}\n */\n #token;\n\n /**\n * Determines if a character is an escaped character.\n * @type {(c:number) => boolean}\n */\n #isEscapedCharacter;\n\n /**\n * Determines if a character is a JSON5 line terminator.\n * @type {(c:number) => boolean}\n */\n #isJSON5LineTerminator;\n\n\n /**\n * Determines if a character is a JSON5 hex escape.\n * @type {(c:number) => boolean}\n */\n #isJSON5HexEscape;\n\n /**\n * Determines if a character is whitespace.\n * @type {(c:number) => boolean}\n */\n #isWhitespace;\n\n /**\n * Creates a new instance of the tokenizer.\n * @param {string} text The source text\n * @param {TokenizeOptions} [options] Options for the tokenizer.\n */ \n constructor(text, options) {\n this.#text = text;\n this.#options = {\n ...DEFAULT_OPTIONS$1,\n ...options\n };\n\n this.#reader = new CharCodeReader(text);\n this.#json5 = this.#options.mode === \"json5\";\n this.#allowComments = this.#options.mode !== \"json\";\n this.#ranges = this.#options.ranges;\n\n // TODO: Clean this up\n this.#isEscapedCharacter = this.#json5 ? json5EscapeToChar.has.bind(json5EscapeToChar) : escapeToChar.has.bind(escapeToChar);\n this.#isJSON5LineTerminator = this.#json5 ? json5LineTerminators.has.bind(json5LineTerminators) : () => false;\n this.#isJSON5HexEscape = this.#json5 ? c => c === CHAR_LOWER_X : () => false;\n this.#isWhitespace = this.#json5 ? json5Whitespace.has.bind(json5Whitespace) : whitespace.has.bind(whitespace);\n }\n\n // #region Errors\n\n /**\n * Convenience function for throwing unexpected character errors.\n * @param {number} c The unexpected character.\n * @param {Location} [loc] The location of the unexpected character.\n * @returns {never}\n * @throws {UnexpectedChar} always.\n */\n #unexpected(c, loc = this.#reader.locate()) {\n throw new UnexpectedChar(c, loc);\n }\n\n /**\n * Convenience function for throwing unexpected identifier errors.\n * @param {string} identifier The unexpected identifier.\n * @param {Location} [loc] The location of the unexpected identifier.\n * @returns {never}\n * @throws {UnexpectedIdentifier} always.\n */\n #unexpectedIdentifier(identifier, loc = this.#reader.locate()) {\n throw new UnexpectedIdentifier(identifier, loc);\n }\n\n /**\n * Convenience function for throwing unexpected EOF errors.\n * @returns {never}\n * @throws {UnexpectedEOF} always.\n */\n #unexpectedEOF() {\n throw new UnexpectedEOF(this.#reader.locate());\n }\n\n // #endregion\n\n // #region Helpers\n\n /**\n * Creates a new token.\n * @param {TokenType} tokenType The type of token to create.\n * @param {number} length The length of the token.\n * @param {Location} startLoc The start location for the token.\n * @param {Location} [endLoc] The end location for the token.\n * @returns {Token} The token.\n */\n #createToken(tokenType, length, startLoc, endLoc) {\n\n const endOffset = startLoc.offset + length;\n\n let range = this.#options.ranges ? {\n range: /** @type {Range} */ ([startLoc.offset, endOffset])\n } : undefined;\n\n return {\n type: tokenType,\n loc: {\n start: startLoc,\n end: endLoc || {\n line: startLoc.line,\n column: startLoc.column + length,\n offset: endOffset\n }\n },\n ...range\n }; \n }\n\n /**\n * Reads in a specific number of hex digits.\n * @param {number} count The number of hex digits to read.\n * @returns {string} The hex digits read.\n */\n #readHexDigits(count) {\n let value = \"\";\n let c;\n\n for (let i = 0; i < count; i++) {\n c = this.#reader.peek();\n if (isHexDigit(c)) {\n this.#reader.next();\n value += String.fromCharCode(c);\n continue;\n }\n\n this.#unexpected(c);\n }\n\n return value;\n }\n\n /**\n * Reads in a JSON5 identifier. Also used for JSON but we validate\n * the identifier later.\n * @param {number} c The first character of the identifier.\n * @returns {string} The identifier read.\n * @throws {UnexpectedChar} when the identifier cannot be read.\n */\n #readIdentifier(c) {\n let value = \"\";\n\n do {\n\n value += String.fromCharCode(c);\n\n if (c === CHAR_BACKSLASH) {\n\n c = this.#reader.next();\n\n if (c !== CHAR_LOWER_U) {\n this.#unexpected(c);\n }\n\n value += String.fromCharCode(c);\n\n const hexDigits = this.#readHexDigits(4);\n\n // check for a valid character code\n const charCode = parseInt(hexDigits, 16);\n\n if (value.length === 2 && !isJSON5IdentifierStart(charCode)) {\n const loc = this.#reader.locate();\n this.#unexpected(CHAR_BACKSLASH, { line: loc.line, column: loc.column - 5, offset: loc.offset - 5 });\n } else if (!isJSON5IdentifierPart(charCode)) {\n const loc = this.#reader.locate();\n this.#unexpected(charCode, { line: loc.line, column: loc.column - 5, offset: loc.offset - 5 });\n }\n\n value += hexDigits;\n }\n\n c = this.#reader.peek();\n\n if (!isJSON5IdentifierPart(c)) {\n break;\n }\n\n this.#reader.next();\n\n } while (true); // eslint-disable-line no-constant-condition\n\n return value;\n }\n\n /**\n * Reads in a string. Works for both JSON and JSON5.\n * @param {number} c The first character of the string (either \" or ').\n * @returns {number} The length of the string.\n * @throws {UnexpectedChar} when the string cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the string is finalized.\n */\n #readString(c) {\n \n const delimiter = c;\n let length = 1;\n c = this.#reader.peek();\n\n while (c !== -1 && c !== delimiter) {\n\n this.#reader.next();\n length++;\n\n // escapes\n if (c === CHAR_BACKSLASH) {\n c = this.#reader.peek();\n\n if (this.#isEscapedCharacter(c) || this.#isJSON5LineTerminator(c)) {\n this.#reader.next();\n length++;\n } else if (c === CHAR_LOWER_U) {\n this.#reader.next();\n length++;\n\n const result = this.#readHexDigits(4);\n length += result.length;\n } else if (this.#isJSON5HexEscape(c)) {\n this.#reader.next();\n length++;\n\n // hex escapes: \\xHH\n const result = this.#readHexDigits(2);\n length += result.length;\n } else if (this.#json5) { // JSON doesn't allow anything else\n this.#reader.next();\n length++;\n } else {\n this.#unexpected(c);\n }\n }\n\n c = this.#reader.peek();\n }\n\n if (c === -1) {\n this.#reader.next();\n this.#unexpectedEOF();\n }\n\n // c is the delimiter\n this.#reader.next();\n length++;\n\n return length;\n \n \n }\n\n /**\n * Reads a number. Works for both JSON and JSON5.\n * @param {number} c The first character of the number.\n * @returns {number} The length of the number.\n * @throws {UnexpectedChar} when the number cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the number is finalized.\n */\n #readNumber(c) {\n \n // we've already read the first character\n let length = 1;\n\n // JSON number may start with a minus but not a plus\n // JSON5 allows a plus.\n if (c === CHAR_MINUS || this.#json5 && c === CHAR_PLUS) {\n \n c = this.#reader.peek();\n \n /*\n * JSON5 allows Infinity or NaN preceded by a sign.\n * This blocks handles +Infinity, -Infinity, +NaN, and -NaN.\n * Standalone Infinity and NaN are handled in `readJSON5Identifier()`\n */\n if (this.#json5) {\n\n if (c === CHAR_UPPER_I || c === CHAR_UPPER_N) {\n this.#reader.next();\n const identifier = this.#readIdentifier(c);\n\n if (identifier !== INFINITY && identifier !== NAN) {\n this.#unexpected(c);\n }\n\n return length + identifier.length;\n }\n }\n\n // Next digit cannot be zero\n if (!isDigit(c)) {\n this.#unexpected(c);\n }\n\n // if we made it here, we need to continue on, so register the character\n this.#reader.next();\n length++;\n }\n\n /*\n * In JSON, a zero must be followed by a decimal point or nothing.\n * In JSON5, a zero can additionally be followed by an `x` indicating\n * that it's a hexadecimal number.\n */\n if (c === CHAR_0) {\n\n // c = this.#reader.next();\n // length++;\n c = this.#reader.peek();\n\n // check for a hex number\n if (this.#json5 && (c === CHAR_LOWER_X || c === CHAR_UPPER_X)) {\n\n this.#reader.next();\n length++;\n\n c = this.#reader.peek();\n\n if (!isHexDigit(c)) {\n this.#reader.next();\n this.#unexpected(c);\n }\n\n do {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n } while (isHexDigit(c));\n\n } else if (isDigit(c)) {\n this.#unexpected(c);\n }\n\n } else {\n\n // JSON5 allows leading decimal points\n if (!this.#json5 || c !== CHAR_DOT) {\n if (!isPositiveDigit(c)) {\n this.#unexpected(c);\n }\n\n c = this.#reader.peek();\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n }\n }\n\n /*\n * In JSON, a decimal point must be followed by at least one digit.\n * In JSON5, a decimal point need not be followed by any digits.\n */\n if (c === CHAR_DOT) {\n \n let digitCount = -1;\n this.#reader.next();\n length++;\n digitCount++;\n\n c = this.#reader.peek();\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n digitCount++;\n c = this.#reader.peek();\n }\n\n if (!this.#json5 && digitCount === 0) {\n this.#reader.next();\n if (c) {\n this.#unexpected(c);\n } else {\n this.#unexpectedEOF();\n }\n }\n }\n\n // Exponent is always last\n if (c === CHAR_LOWER_E || c === CHAR_UPPER_E) {\n\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n\n if (c === CHAR_PLUS || c === CHAR_MINUS) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n\n /*\n * Must always have a digit in this position to avoid:\n * 5e\n * 12E+\n * 42e-\n */\n if (c === -1) {\n this.#reader.next();\n this.#unexpectedEOF();\n }\n\n if (!isDigit(c)) {\n this.#reader.next();\n this.#unexpected(c);\n }\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n }\n\n return length;\n }\n\n /**\n * Reads a comment. Works for both JSON and JSON5.\n * @param {number} c The first character of the comment.\n * @returns {{length: number, multiline: boolean}} The length of the comment, and whether the comment is multi-line.\n * @throws {UnexpectedChar} when the comment cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the comment is finalized.\n */ \n #readComment(c) {\n \n let length = 1;\n\n // next character determines single- or multi-line\n c = this.#reader.peek();\n\n // single-line comments\n if (c === CHAR_SLASH) {\n \n do {\n this.#reader.next();\n length += 1;\n c = this.#reader.peek();\n } while (c > -1 && c !== CHAR_RETURN && c !== CHAR_NEWLINE);\n\n return { length, multiline: false };\n }\n\n // multi-line comments\n if (c === CHAR_STAR) {\n\n this.#reader.next();\n length += 1;\n\n while (c > -1) {\n c = this.#reader.peek();\n\n // check for end of comment\n if (c === CHAR_STAR) {\n this.#reader.next();\n length += 1;\n c = this.#reader.peek();\n \n //end of comment\n if (c === CHAR_SLASH) {\n this.#reader.next();\n length += 1;\n\n return { length, multiline: true };\n }\n } else {\n this.#reader.next();\n length += 1;\n }\n }\n\n this.#reader.next();\n this.#unexpectedEOF();\n \n }\n\n // if we've made it here, there's an invalid character\n this.#reader.next();\n this.#unexpected(c); \n }\n // #endregion\n\n /**\n * Returns the next token in the source text.\n * @returns {number} The code for the next token.\n */\n next() {\n\n let c = this.#reader.next();\n\n while (this.#isWhitespace(c)) {\n c = this.#reader.next();\n }\n\n if (c === -1) {\n return tt.EOF;\n }\n\n const start = this.#reader.locate();\n const ct = String.fromCharCode(c);\n\n // check for JSON5 syntax only\n if (this.#json5) {\n \n if (knownJSON5TokenTypes.has(ct)) {\n this.#token = this.#createToken(knownJSON5TokenTypes.get(ct), 1, start);\n } else if (isJSON5IdentifierStart(c)) {\n const value = this.#readIdentifier(c);\n\n if (knownJSON5TokenTypes.has(value)) {\n this.#token = this.#createToken(knownJSON5TokenTypes.get(value), value.length, start);\n } else {\n this.#token = this.#createToken(\"Identifier\", value.length, start);\n }\n } else if (isJSON5NumberStart(c)) {\n const result = this.#readNumber(c);\n this.#token = this.#createToken(\"Number\", result, start);\n } else if (isStringStart(c, this.#json5)) {\n const result = this.#readString(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(\"String\", result, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else if (c === CHAR_SLASH && this.#allowComments) {\n const result = this.#readComment(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(!result.multiline ? \"LineComment\" : \"BlockComment\", result.length, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else {\n this.#unexpected(c);\n }\n\n } else {\n\n // check for JSON/JSONC syntax only\n if (knownTokenTypes.has(ct)) {\n this.#token = this.#createToken(knownTokenTypes.get(ct), 1, start);\n } else if (isKeywordStart(c)) {\n const value = this.#readIdentifier(c);\n\n if (!jsonKeywords.has(value)) {\n this.#unexpectedIdentifier(value, start);\n }\n\n this.#token = this.#createToken(knownTokenTypes.get(value), value.length, start);\n } else if (isNumberStart(c)) {\n const result = this.#readNumber(c);\n this.#token = this.#createToken(\"Number\", result, start);\n } else if (isStringStart(c, this.#json5)) {\n const result = this.#readString(c);\n this.#token = this.#createToken(\"String\", result, start);\n } else if (c === CHAR_SLASH && this.#allowComments) {\n const result = this.#readComment(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(!result.multiline ? \"LineComment\" : \"BlockComment\", result.length, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else {\n this.#unexpected(c);\n }\n }\n return tt[this.#token.type];\n }\n\n /**\n * Returns the current token in the source text.\n * @returns {Token} The current token.\n */\n get token() {\n return this.#token;\n }\n}\n\n//-----------------------------------------------------------------------------\n// Main\n//-----------------------------------------------------------------------------\n\n/**\n * Creates an iterator over the tokens representing the source text.\n * @param {string} text The source text to tokenize.\n * @param {TokenizeOptions} [options] Options for doing the tokenization.\n * @returns {Array<Token>} An iterator over the tokens. \n */\nfunction tokenize(text, options) {\n\n const tokenizer = new Tokenizer(text, options);\n const tokens = [];\n\n while (tokenizer.next() !== tt.EOF) {\n tokens.push(tokenizer.token);\n }\n\n return tokens;\n\n}\n\n/**\n * @fileoverview JSON AST types\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").LocationRange} LocationRange */\n/** @typedef {import(\"./typedefs.js\").NodeParts} NodeParts */\n/** @typedef {import(\"./typedefs.js\").DocumentNode} DocumentNode */\n/** @typedef {import(\"./typedefs.js\").StringNode} StringNode */\n/** @typedef {import(\"./typedefs.js\").NumberNode} NumberNode */\n/** @typedef {import(\"./typedefs.js\").BooleanNode} BooleanNode */\n/** @typedef {import(\"./typedefs.js\").MemberNode} MemberNode */\n/** @typedef {import(\"./typedefs.js\").ObjectNode} ObjectNode */\n/** @typedef {import(\"./typedefs.js\").ElementNode} ElementNode */\n/** @typedef {import(\"./typedefs.js\").ArrayNode} ArrayNode */\n/** @typedef {import(\"./typedefs.js\").NullNode} NullNode */\n/** @typedef {import(\"./typedefs.js\").ValueNode} ValueNode */\n/** @typedef {import(\"./typedefs.js\").IdentifierNode} IdentifierNode */\n/** @typedef {import(\"./typedefs.js\").NaNNode} NaNNode */\n/** @typedef {import(\"./typedefs.js\").InfinityNode} InfinityNode */\n/** @typedef {import(\"./typedefs.js\").Sign} Sign */\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nconst types = {\n\n /**\n * Creates a document node.\n * @param {ValueNode} body The body of the document.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {DocumentNode} The document node.\n */\n document(body, parts = {}) {\n return {\n type: \"Document\",\n body,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a string node.\n * @param {string} value The value for the string.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {StringNode} The string node.\n */\n string(value, parts = {}) {\n return {\n type: \"String\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a number node.\n * @param {number} value The value for the number.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {NumberNode} The number node.\n */\n number(value, parts = {}) {\n return {\n type: \"Number\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a boolean node.\n * @param {boolean} value The value for the boolean.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {BooleanNode} The boolean node.\n */\n boolean(value, parts = {}) {\n return {\n type: \"Boolean\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a null node.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {NullNode} The null node.\n */\n null(parts = {}) {\n return {\n type: \"Null\",\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an array node.\n * @param {Array<ElementNode>} elements The elements to add.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ArrayNode} The array node.\n */\n array(elements, parts = {}) {\n return {\n type: \"Array\",\n elements,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an element node.\n * @param {ValueNode} value The value for the element.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ElementNode} The element node.\n */\n element(value, parts = {}) {\n return {\n type: \"Element\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an object node.\n * @param {Array<MemberNode>} members The members to add.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ObjectNode} The object node.\n */\n object(members, parts = {}) {\n return {\n type: \"Object\",\n members,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a member node.\n * @param {StringNode|IdentifierNode} name The name for the member.\n * @param {ValueNode} value The value for the member.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {MemberNode} The member node.\n */\n member(name, value, parts = {}) {\n return {\n type: \"Member\",\n name,\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an identifier node.\n * @param {string} name The name for the identifier.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {IdentifierNode} The identifier node.\n */\n identifier(name, parts = {}) {\n return {\n type: \"Identifier\",\n name,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a NaN node.\n * @param {Sign} sign The sign for the Infinity.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {NaNNode} The NaN node.\n */ \n nan(sign = \"\", parts = {}) {\n return {\n type: \"NaN\",\n sign,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an Infinity node.\n * @param {Sign} sign The sign for the Infinity.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {InfinityNode} The Infinity node.\n */\n infinity(sign = \"\", parts = {}) {\n return {\n type: \"Infinity\",\n sign,\n loc: parts.loc,\n ...parts\n };\n },\n\n};\n\n/**\n * @fileoverview JSON parser\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Node} Node */\n/** @typedef {import(\"./typedefs.js\").Mode} Mode */\n/** @typedef {import(\"./typedefs.js\").ParseOptions} ParseOptions */\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/** @type {ParseOptions} */\nconst DEFAULT_OPTIONS = {\n mode: \"json\",\n ranges: false,\n tokens: false,\n allowTrailingCommas: false\n};\n\nconst UNICODE_SEQUENCE = /\\\\u[\\da-fA-F]{4}/gu;\n\n/**\n * Normalizes a JSON5 identifier by converting Unicode escape sequences into\n * their corresponding characters.\n * @param {string} identifier The identifier to normalize.\n * @returns {string} The normalized identifier.\n */\nfunction normalizeIdentifier(identifier) {\n return identifier.replace(UNICODE_SEQUENCE, unicodeEscape => {\n return String.fromCharCode(parseInt(unicodeEscape.slice(2), 16));\n });\n}\n\n/**\n * Calculates the location at the end of the given text.\n * @param {string} text The text to calculate the end location for.\n * @returns {Location} The location at the end of the text.\n */\nfunction getEndLocation(text) {\n let line = 1;\n let column = 1;\n \n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"\\n\") {\n line++;\n column = 1;\n } else if (char === \"\\r\") {\n // Handle \\r\\n as a single line ending\n if (text[i + 1] === \"\\n\") {\n i++; // Skip the \\n\n }\n line++;\n column = 1;\n } else {\n column++;\n }\n }\n \n return {\n line,\n column,\n offset: text.length\n };\n}\n\n/**\n * Converts a JSON-encoded string into a JavaScript string, interpreting each\n * escape sequence.\n * @param {string} value The text for the token.\n * @param {Token} token The string token to convert into a JavaScript string.\n * @param {boolean} json5 `true` if parsing JSON5, `false` otherwise.\n * @returns {string} A JavaScript string.\n */\nfunction getStringValue(value, token, json5 = false) {\n \n let result = \"\";\n let escapeIndex = value.indexOf(\"\\\\\");\n let lastIndex = 0;\n\n // While there are escapes, interpret them to build up the result\n while (escapeIndex >= 0) {\n\n // append the text that happened before the escape\n result += value.slice(lastIndex, escapeIndex);\n\n // get the character immediately after the \\\n const escapeChar = value.charAt(escapeIndex + 1);\n const escapeCharCode = escapeChar.charCodeAt(0);\n \n // check for the non-Unicode escape sequences first\n if (json5 && json5EscapeToChar.has(escapeCharCode)) {\n result += json5EscapeToChar.get(escapeCharCode);\n lastIndex = escapeIndex + 2;\n } else if (escapeToChar.has(escapeCharCode)) {\n result += escapeToChar.get(escapeCharCode);\n lastIndex = escapeIndex + 2;\n } else if (escapeChar === \"u\") {\n const hexCode = value.slice(escapeIndex + 2, escapeIndex + 6);\n if (hexCode.length < 4 || /[^0-9a-f]/i.test(hexCode)) {\n throw new ErrorWithLocation(\n `Invalid unicode escape \\\\u${ hexCode}.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n\n result += String.fromCharCode(parseInt(hexCode, 16));\n lastIndex = escapeIndex + 6;\n } else if (json5 && escapeChar === \"x\") {\n const hexCode = value.slice(escapeIndex + 2, escapeIndex + 4);\n if (hexCode.length < 2 || /[^0-9a-f]/i.test(hexCode)) {\n throw new ErrorWithLocation(\n `Invalid hex escape \\\\x${ hexCode}.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n\n result += String.fromCharCode(parseInt(hexCode, 16));\n lastIndex = escapeIndex + 4;\n } else if (json5 && json5LineTerminators.has(escapeCharCode)) {\n lastIndex = escapeIndex + 2;\n\n // we also need to skip \\n after a \\r\n if (escapeChar === \"\\r\" && value.charAt(lastIndex) === \"\\n\") {\n lastIndex++;\n }\n \n } else {\n // all characters can be escaped in JSON5\n if (json5) {\n result += escapeChar;\n lastIndex = escapeIndex + 2;\n } else {\n throw new ErrorWithLocation(\n `Invalid escape \\\\${ escapeChar }.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n }\n\n // find the next escape sequence\n escapeIndex = value.indexOf(\"\\\\\", lastIndex);\n }\n\n // get the last segment of the string value\n result += value.slice(lastIndex);\n\n return result;\n}\n\n/**\n * Gets the JavaScript value represented by a JSON token.\n * @param {string} value The text value of the token.\n * @param {Token} token The JSON token to get a value for.\n * @param {boolean} json5 `true` if parsing JSON5, `false` otherwise.\n * @returns {string|boolean|number} A number, string, or boolean.\n * @throws {TypeError} If an unknown token type is found. \n */\nfunction getLiteralValue(value, token, json5 = false) {\n switch (token.type) {\n case \"Boolean\":\n return value === \"true\";\n \n case \"Number\":\n if (json5) {\n\n /*\n * Numbers like -0x1 are converted to NaN by Number(), so we need\n * to handle them separately. Rather than checking for -0x, we can\n * just check if the first character is a minus sign. The same for\n * checking for +0x.\n */\n\n if (value.charCodeAt(0) === 45) { // 45 is the char code for '-'\n return -Number(value.slice(1));\n }\n\n if (value.charCodeAt(0) === 43) { // 43 is the char code for '+'\n return Number(value.slice(1));\n }\n }\n return Number(value);\n\n case \"String\":\n return getStringValue(value.slice(1, -1), token, json5);\n\n default:\n throw new TypeError(`Unknown token type \"${token.type}.`);\n }\n}\n\n//-----------------------------------------------------------------------------\n// Main Function\n//-----------------------------------------------------------------------------\n\n/**\n * \n * @param {string} text The text to parse.\n * @param {ParseOptions} [options] The options object.\n * @returns {DocumentNode} The AST representing the parsed JSON.\n * @throws {Error} When there is a parsing error. \n */\nfunction parse(text, options) {\n\n options = Object.freeze({\n ...DEFAULT_OPTIONS,\n ...options\n });\n\n const tokens = [];\n const tokenizer = new Tokenizer(text, {\n mode: options.mode,\n ranges: options.ranges\n });\n\n const json5 = options.mode === \"json5\";\n const allowTrailingCommas = options.allowTrailingCommas || json5;\n\n /**\n * Returns the next token knowing there are no comments.\n * @returns {number} The next token type or 0 if no next token.\n */\n function nextNoComments() {\n const nextType = tokenizer.next();\n\n if (nextType && options.tokens) {\n tokens.push(tokenizer.token);\n }\n return nextType;\n }\n \n /**\n * Returns the next token knowing there are comments to skip.\n * @returns {number} The next token type or 0 if no next token.\n */\n function nextSkipComments() {\n const nextType = tokenizer.next();\n if (nextType && options.tokens) {\n tokens.push(tokenizer.token);\n }\n\n if (nextType >= tt.LineComment) {\n return nextSkipComments();\n }\n\n return nextType;\n\n }\n\n // determine correct way to evaluate tokens based on presence of comments\n const next = options.mode === \"json\" ? nextNoComments : nextSkipComments;\n\n /**\n * Asserts a token has the given type.\n * @param {number} token The token to check.\n * @param {number} type The token type.\n * @throws {UnexpectedToken} If the token type isn't expected.\n * @returns {void}\n */\n function assertTokenType(token, type) {\n if (token !== type) {\n throw new UnexpectedToken(tokenizer.token);\n }\n }\n\n /**\n * Asserts a token has one of the given types.\n * @param {number} token The token to check.\n * @param {number[]} types The token types.\n * @returns {void}\n * @throws {UnexpectedToken} If the token type isn't expected.\n */ \n function assertTokenTypes(token, types) {\n if (!types.includes(token)) {\n throw new UnexpectedToken(tokenizer.token);\n }\n }\n\n /**\n * Creates a range only if ranges are specified.\n * @param {Location} start The start offset for the range.\n * @param {Location} end The end offset for the range.\n * @returns {{range:[number,number]}|undefined} An object with a \n */\n function createRange(start, end) {\n // @ts-ignore tsc incorrect - options might be undefined\n return options.ranges ? {\n range: [start.offset, end.offset]\n } : undefined;\n }\n\n /**\n * Creates a node for a string, boolean, or number.\n * @param {number} tokenType The token representing the literal. \n * @returns {StringNode|NumberNode|BooleanNode} The node representing\n * the value.\n */\n function createLiteralNode(tokenType) {\n const token = tokenizer.token;\n const range = createRange(token.loc.start, token.loc.end);\n const value = getLiteralValue(\n text.slice(token.loc.start.offset, token.loc.end.offset),\n token,\n json5\n );\n const loc = {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n };\n const parts = { loc, ...range };\n\n switch (tokenType) {\n case tt.String:\n return types.string(/** @type {string} */ (value), parts);\n\n case tt.Number:\n return types.number(/** @type {number} */ (value), parts);\n \n case tt.Boolean:\n return types.boolean(/** @type {boolean} */ (value), parts);\n\n default:\n throw new TypeError(`Unknown token type ${token.type}.`);\n }\n }\n\n /**\n * Creates a node for a JSON5 identifier.\n * @param {Token} token The token representing the identifer. \n * @returns {NaNNode|InfinityNode|IdentifierNode} The node representing\n * the value.\n */\n function createJSON5IdentifierNode(token) {\n const range = createRange(token.loc.start, token.loc.end);\n const identifier = text.slice(token.loc.start.offset, token.loc.end.offset);\n const loc = {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n };\n const parts = { loc, ...range };\n\n // Check for NaN or Infinity\n if (token.type !== \"Identifier\") {\n\n let sign = \"\";\n\n // check if the first character in the token is a plus or minus\n if (identifier[0] === \"+\" || identifier[0] === \"-\") {\n sign = identifier[0];\n }\n\n // check if the token is NaN or Infinity\n return types[identifier.includes(\"NaN\") ? \"nan\" : \"infinity\"](/** @type {Sign} */ (sign), parts);\n }\n return types.identifier(normalizeIdentifier(identifier), parts);\n }\n\n /**\n * Creates a node for a null.\n * @param {Token} token The token representing null. \n * @returns {NullNode} The node representing null.\n */\n function createNullNode(token) {\n const range = createRange(token.loc.start, token.loc.end);\n\n return types.null({\n loc: {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n },\n ...range\n });\n }\n\n\n /**\n * Parses a property in an object.\n * @param {number} tokenType The token representing the property.\n * @returns {MemberNode} The node representing the property.\n * @throws {UnexpectedToken} When an unexpected token is found.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n */\n function parseProperty(tokenType) {\n\n if (json5) {\n assertTokenTypes(tokenType, [tt.String, tt.Identifier, tt.Number]);\n } else {\n assertTokenType(tokenType, tt.String);\n }\n\n const token = tokenizer.token;\n\n // check for -NaN, +NaN, -Infinity, +Infinity, and any number\n if (json5 && tokenType === tt.Number && /[+\\-0-9]/.test(text[token.loc.start.offset])) {\n throw new UnexpectedToken(token);\n }\n\n // TODO: Clean this up a bit\n let key = tokenType === tt.String\n ? /** @type {StringNode} */ (createLiteralNode(tokenType))\n : /** @type {IdentifierNode|NaNNode|InfinityNode} */ (createJSON5IdentifierNode(token));\n\n // in JSON5, need to check for NaN and Infinity and create identifier nodes\n if (json5 && (key.type === \"NaN\" || key.type === \"Infinity\")) {\n\n // NaN and Infinity cannot be signed and be a property key\n if (key.sign !== \"\") {\n throw new UnexpectedToken(tokenizer.token);\n }\n\n key = types.identifier(key.type, { loc: key.loc, ...createRange(key.loc.start, key.loc.end) });\n }\n\n tokenType = next();\n assertTokenType(tokenType, tt.Colon);\n const value = parseValue();\n const range = createRange(key.loc.start, value.loc.end);\n\n return types.member(\n /** @type {StringNode|IdentifierNode} */ (key),\n /** @type {ValueNode} */ (value),\n {\n loc: {\n start: {\n ...key.loc.start\n },\n end: {\n ...value.loc.end\n }\n },\n ...range\n }\n );\n }\n\n /**\n * Parses an object literal.\n * @param {number} firstTokenType The first token type in the object.\n * @returns {ObjectNode} The object node.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n * @throws {UnexpectedToken} When an unexpected token is found.\n */\n function parseObject(firstTokenType) {\n\n // The first token must be a { or else it's an error\n assertTokenType(firstTokenType, tt.LBrace);\n\n const firstToken = tokenizer.token;\n const members = [];\n let tokenType = next();\n\n if (tokenType !== tt.RBrace) {\n do {\n \n // add the value into the array\n members.push(parseProperty(tokenType));\n \n tokenType = next();\n\n if (!tokenType) {\n throw new UnexpectedEOF(members[members.length-1].loc.end);\n }\n \n if (tokenType === tt.Comma) {\n tokenType = next();\n\n /*\n * Trailing commas.\n * So we need to check if the token is a comma,\n * and if so, then we need to check if the next\n * token is a RBrace. If it is, then we need to\n * break out of the loop.\n */\n if (allowTrailingCommas && tokenType === tt.RBrace) {\n break;\n } \n } else {\n break;\n }\n } while (tokenType);\n }\n\n assertTokenType(tokenType, tt.RBrace);\n const lastToken = tokenizer.token;\n const range = createRange(firstToken.loc.start, lastToken.loc.end);\n\n return types.object(members, {\n loc: {\n start: {\n ...firstToken.loc.start\n },\n end: {\n ...lastToken.loc.end\n }\n },\n ...range\n });\n\n }\n\n /**\n * Parses an array literal.\n * @param {number} firstTokenType The first token in the array.\n * @returns {ArrayNode} The array node.\n * @throws {UnexpectedToken} When an unexpected token is found.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n */\n function parseArray(firstTokenType) {\n\n // The first token must be a [ or else it's an error\n assertTokenType(firstTokenType, tt.LBracket);\n\n const firstToken = tokenizer.token;\n const elements = [];\n let tokenType = next();\n \n if (tokenType !== tt.RBracket) {\n\n do {\n\n // add the value into the array\n const value = parseValue(tokenType);\n\n elements.push(types.element(\n /** @type {ValueNode} */ (value),\n { loc: value.loc }\n ));\n\n tokenType = next();\n \n if (tokenType === tt.Comma) {\n tokenType = next();\n\n /*\n * Trailing commas.\n * So we need to check if the token is a comma,\n * and if so, then we need to check if the next\n * token is a RBracket. If it is, then we need to\n * break out of the loop.\n */\n if (allowTrailingCommas && tokenType === tt.RBracket) {\n break;\n } \n } else {\n break;\n }\n } while (tokenType);\n }\n\n assertTokenType(tokenType, tt.RBracket);\n\n const lastToken = tokenizer.token;\n const range = createRange(firstToken.loc.start, lastToken.loc.end);\n\n return types.array(elements, {\n loc: {\n start: {\n ...firstToken.loc.start\n },\n end: {\n ...lastToken.loc.end\n }\n },\n ...range\n });\n\n }\n\n /**\n * Parses a JSON value.\n * @param {number} [tokenType] The token type to parse.\n * @returns {ValueNode|IdentifierNode} The node representing the value.\n */\n function parseValue(tokenType) {\n\n tokenType = tokenType ?? next();\n const token = tokenizer.token;\n \n switch (tokenType) {\n case tt.String:\n case tt.Boolean:\n return createLiteralNode(tokenType);\n\n case tt.Number:\n if (json5) {\n let tokenText = text.slice(token.loc.start.offset, token.loc.end.offset);\n if (tokenText[0] === \"+\" || tokenText[0] === \"-\") {\n tokenText = tokenText.slice(1);\n }\n\n if (tokenText === \"NaN\" || tokenText === \"Infinity\") {\n return createJSON5IdentifierNode(token);\n }\n }\n return createLiteralNode(tokenType);\n\n case tt.Null:\n return createNullNode(token);\n\n case tt.LBrace:\n return parseObject(tokenType);\n\n case tt.LBracket:\n return parseArray(tokenType);\n\n default:\n throw new UnexpectedToken(token);\n }\n\n }\n\n \n const docBody = parseValue();\n \n const unexpectedToken = next();\n if (unexpectedToken) {\n throw new UnexpectedToken(tokenizer.token);\n }\n \n \n const textEndLocation = getEndLocation(text);\n const docParts = {\n loc: {\n start: {\n line: 1,\n column: 1,\n offset: 0\n },\n end: {\n ...textEndLocation\n }\n }\n };\n \n if (options.tokens) {\n docParts.tokens = tokens;\n }\n\n if (options.ranges) {\n docParts.range = [\n docParts.loc.start.offset,\n docParts.loc.end.offset\n ];\n }\n\n return types.document(/** @type {ValueNode} */ (docBody), docParts);\n}\n\n/**\n * @fileoverview Traversal approaches for Momoa JSON AST.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").TraversalPhase} TraversalPhase */\n/**\n * @typedef {Object} TraversalVisitor\n * @property {(node: Node, parent?: Node) => void} [enter]\n * @property {(node: Node, parent?: Node) => void} [exit]\n */\n\n//-----------------------------------------------------------------------------\n// Data\n//-----------------------------------------------------------------------------\n\nconst childKeys = new Map([\n [\"Document\", [\"body\"]],\n [\"Object\", [\"members\"]],\n [\"Member\", [\"name\", \"value\"]],\n [\"Element\", [\"value\"]],\n [\"Array\", [\"elements\"]],\n [\"String\", []],\n [\"Number\", []],\n [\"Boolean\", []],\n [\"Null\", []],\n [\"NaN\", []],\n [\"Infinity\", []],\n [\"Identifier\", []],\n]);\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Determines if a given value is an object.\n * @param {*} value The value to check.\n * @returns {boolean} True if the value is an object, false if not. \n */\nfunction isObject(value) {\n return value && (typeof value === \"object\");\n}\n\n/**\n * Determines if a given value is an AST node.\n * @param {*} value The value to check.\n * @returns {boolean} True if the value is a node, false if not. \n */\nfunction isNode(value) {\n return isObject(value) && (typeof value.type === \"string\");\n}\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Traverses an AST from the given node.\n * @param {Node} root The node to traverse from \n * @param {TraversalVisitor} visitor An object with an `enter` and `exit` method. \n */\nfunction traverse(root, visitor) {\n\n /**\n * Recursively visits a node.\n * @param {Node} node The node to visit.\n * @param {Node} [parent] The parent of the node to visit.\n * @returns {void}\n */\n function visitNode(node, parent) {\n\n if (typeof visitor.enter === \"function\") {\n visitor.enter(node, parent);\n }\n\n for (const key of childKeys.get(node.type)) {\n const value = node[key];\n\n if (isObject(value)) {\n if (Array.isArray(value)) {\n value.forEach(child => visitNode(child, node));\n } else if (isNode(value)) {\n visitNode(value, node);\n }\n }\n }\n\n if (typeof visitor.exit === \"function\") {\n visitor.exit(node, parent);\n }\n }\n\n visitNode(root);\n}\n\n/**\n * @callback FilterPredicate\n * @param {{node: Node, parent?: Node, phase: TraversalPhase}} item\n * @param {number} index\n * @param {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} array\n * @returns {boolean}\n */\n\n/**\n * Creates an iterator over the given AST.\n * @param {Node} root The root AST node to traverse. \n * @param {FilterPredicate} [filter] A filter function to determine which steps to\n * return;\n * @returns {IterableIterator<{node: Node, parent?: Node, phase: TraversalPhase}>} An iterator over the AST. \n */\nfunction iterator(root, filter = () => true) {\n\n /** @type {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} */\n const traversal = [];\n\n traverse(root, {\n enter(node, parent) {\n traversal.push({ node, parent, phase: \"enter\" });\n },\n exit(node, parent) {\n traversal.push({ node, parent, phase: \"exit\" });\n }\n });\n\n return traversal.filter(filter).values();\n}\n\n/**\n * @fileoverview Evaluator for Momoa AST.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").AnyNode} AnyNode */\n/** @typedef {import(\"./typedefs.js\").JSONValue} JSONValue */\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Evaluates a Momoa AST node into a JavaScript value.\n * @param {AnyNode} node The node to interpet.\n * @returns {JSONValue} The JavaScript value for the node. \n */\nfunction evaluate(node) {\n switch (node.type) {\n case \"String\":\n return node.value;\n\n case \"Number\":\n return node.value;\n\n case \"Boolean\":\n return node.value;\n\n case \"Null\":\n return null;\n\n case \"NaN\":\n return NaN;\n \n case \"Infinity\":\n return node.sign === \"-\" ? -Infinity : Infinity;\n\n case \"Identifier\":\n return node.name;\n\n case \"Array\": {\n // const arrayNode = /** @type {ArrayNode} */ (node);\n return node.elements.map(element => evaluate(element.value));\n }\n\n case \"Object\": {\n\n /** @type {{[property: string]: JSONValue}} */\n const object = {};\n\n node.members.forEach(member => {\n object[/** @type {string} */ (evaluate(member.name))] = evaluate(member.value);\n }); \n\n return object;\n } \n\n case \"Document\": {\n return evaluate(node.body);\n }\n\n case \"Element\":\n throw new Error(\"Cannot evaluate array element outside of an array.\");\n\n case \"Member\":\n throw new Error(\"Cannot evaluate object member outside of an object.\");\n\n default:\n // @ts-ignore tsc doesn't know about the type property here?\n throw new Error(`Unknown node type ${ node.type }.`);\n }\n}\n\n/**\n * @fileoverview Printer for Momoa AST.\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Prints the string representation of a Boolean node.\n * @param {BooleanNode} node The node to print.\n * @returns {string} The boolean value.\n */\nfunction printBoolean(node) {\n return node.value ? \"true\" : \"false\";\n}\n\n/**\n * Prints the string representation of a null node.\n * @returns {string} The string \"null\".\n */\nfunction printNull() {\n return \"null\";\n}\n\n/**\n * Prints the string representation of a number node.\n * @param {NumberNode} node The node to print.\n * @returns {string} The number value.\n */\nfunction printNumber(node) {\n return node.value.toString();\n}\n\n/**\n * Prints the string representation of a NaN node.\n * @returns {string} The string \"NaN\".\n */\nfunction printNaN() {\n return \"NaN\";\n}\n\n/**\n * Prints the string representation of an Infinity node.\n * @param {InfinityNode} node The node to print.\n * @returns {string} The string \"Infinity\" or \"-Infinity\".\n */\nfunction printInfinity(node) {\n return node.sign + \"Infinity\";\n}\n\n/**\n * Prints the string representation of a string node.\n * @param {StringNode} node The node to print.\n * @returns {string} The string value.\n */\nfunction printString(node) {\n\n let result = \"\\\"\";\n\n // escape all characters that need escaping\n for (const c of node.value) {\n\n const newChar = json5CharToEscape.get(c);\n\n if (newChar) {\n result += \"\\\\\" + newChar;\n continue;\n }\n\n // if it's a double quote, escape it\n if (c === \"\\\"\") {\n result += \"\\\\\\\"\";\n continue;\n }\n\n // if it's a control character, escape it\n if (c < \" \" || c === \"\\u007F\") {\n const hex = c.codePointAt(0).toString(16).toUpperCase();\n result += `\\\\u${\"0000\".substring(hex.length)}${hex}`;\n continue;\n }\n\n // otherwise, just add the character\n result += c;\n\n }\n \n return result + \"\\\"\";\n}\n\n/**\n * Prints the string representation of an identifier node.\n * @param {IdentifierNode} node The node to print.\n * @returns {string} The identifier name.\n */\nfunction printIdentifier(node) {\n return node.name;\n}\n\n/**\n * Prints the string representation of an array node.\n * @param {ArrayNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The array value.\n */\nfunction printArray(node, indent, indentLevel) {\n const newLine = indent ? \"\\n\" : \"\";\n const indentString = indent.repeat(indentLevel);\n const elementIndentString = indent.repeat(indentLevel + 1);\n\n return `[${newLine}${\n node.elements.map(element =>\n `${elementIndentString}${printValue(element.value, indent, indentLevel + 1)}`\n ).join(`,${newLine}`)\n }${newLine}${indentString}]`;\n}\n\n/**\n * Prints the string representation of a member node.\n * @param {MemberNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The member value.\n */\nfunction printMember(node, indent, indentLevel) {\n const space = indent ? \" \" : \"\";\n return `${printValue(node.name, indent, indentLevel)}:${space}${printValue(node.value, indent, indentLevel + 1)}`;\n}\n\n/**\n * Prints the string representation of an object node.\n * @param {ObjectNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The object value.\n */\nfunction printObject(node, indent, indentLevel) {\n const newLine = indent ? \"\\n\" : \"\";\n const indentString = indent.repeat(indentLevel);\n const memberIndentString = indent.repeat(indentLevel + 1);\n\n return `{${newLine}${\n node.members.map(member => \n `${memberIndentString}${printMember(member, indent, indentLevel)}`\n ).join(`,${newLine}`)\n }${newLine}${indentString}}`;\n}\n\n/**\n * Prints the string representation of a node.\n * @param {AnyNode} node The node to print.\n * @param {string} indentString The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The string representation of the node.\n * @throws {TypeError} If the node type is unknown.\n\n */\nfunction printValue(node, indentString, indentLevel) {\n switch (node.type) {\n case \"String\":\n return printString(node);\n case \"Number\":\n return printNumber(node);\n case \"Boolean\":\n return printBoolean(node);\n case \"Null\":\n return printNull();\n case \"NaN\":\n return printNaN();\n case \"Infinity\":\n return printInfinity(node);\n case \"Identifier\":\n return printIdentifier(node);\n case \"Array\":\n return printArray(node, indentString, indentLevel);\n case \"Object\":\n return printObject(node, indentString, indentLevel);\n case \"Document\":\n return printValue(node.body, indentString, indentLevel);\n default:\n throw new TypeError(`Unknown node type: ${node.type}`);\n }\n}\n\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Converts a Momoa AST back into a JSON string.\n * @param {AnyNode} node The node to print.\n * @param {Object} options Options for the print.\n * @param {number} [options.indent=0] The number of spaces to indent each line. If\n * greater than 0, then newlines and indents will be added to output. \n * @returns {string} The JSON representation of the AST.\n */\nfunction print(node, { indent = 0 } = {}) {\n\n const indentLevel = 0;\n const indentString = \" \".repeat(indent);\n\n return printValue(node, indentString, indentLevel);\n}\n\nexport { evaluate, iterator, parse, print, tokenize, traverse, types, childKeys as visitorKeys };\n", "import path from 'node:path';\nimport fs from 'node:fs';\nimport {locatePath, locatePathSync} from 'locate-path';\nimport {toPath} from 'unicorn-magic';\n\nexport const findUpStop = Symbol('findUpStop');\n\nexport async function findUpMultiple(name, options = {}) {\n\tlet directory = path.resolve(toPath(options.cwd) ?? '');\n\tconst {root} = path.parse(directory);\n\tconst stopAt = path.resolve(directory, toPath(options.stopAt) ?? root);\n\tconst limit = options.limit ?? Number.POSITIVE_INFINITY;\n\tconst paths = [name].flat();\n\n\tconst runMatcher = async locateOptions => {\n\t\tif (typeof name !== 'function') {\n\t\t\treturn locatePath(paths, locateOptions);\n\t\t}\n\n\t\tconst foundPath = await name(locateOptions.cwd);\n\t\tif (typeof foundPath === 'string') {\n\t\t\treturn locatePath([foundPath], locateOptions);\n\t\t}\n\n\t\treturn foundPath;\n\t};\n\n\tconst matches = [];\n\twhile (true) {\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tconst foundPath = await runMatcher({...options, cwd: directory});\n\n\t\tif (foundPath === findUpStop) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (foundPath) {\n\t\t\tmatches.push(path.resolve(directory, foundPath));\n\t\t}\n\n\t\tif (directory === stopAt || matches.length >= limit) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n\n\treturn matches;\n}\n\nexport function findUpMultipleSync(name, options = {}) {\n\tlet directory = path.resolve(toPath(options.cwd) ?? '');\n\tconst {root} = path.parse(directory);\n\tconst stopAt = path.resolve(directory, toPath(options.stopAt) ?? root);\n\tconst limit = options.limit ?? Number.POSITIVE_INFINITY;\n\tconst paths = [name].flat();\n\n\tconst runMatcher = locateOptions => {\n\t\tif (typeof name !== 'function') {\n\t\t\treturn locatePathSync(paths, locateOptions);\n\t\t}\n\n\t\tconst foundPath = name(locateOptions.cwd);\n\t\tif (typeof foundPath === 'string') {\n\t\t\treturn locatePathSync([foundPath], locateOptions);\n\t\t}\n\n\t\treturn foundPath;\n\t};\n\n\tconst matches = [];\n\twhile (true) {\n\t\tconst foundPath = runMatcher({...options, cwd: directory});\n\n\t\tif (foundPath === findUpStop) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (foundPath) {\n\t\t\tmatches.push(path.resolve(directory, foundPath));\n\t\t}\n\n\t\tif (directory === stopAt || matches.length >= limit) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n\n\treturn matches;\n}\n\nexport async function findUp(name, options = {}) {\n\tconst matches = await findUpMultiple(name, {...options, limit: 1});\n\treturn matches[0];\n}\n\nexport function findUpSync(name, options = {}) {\n\tconst matches = findUpMultipleSync(name, {...options, limit: 1});\n\treturn matches[0];\n}\n\nasync function findDownDepthFirst(directory, paths, maxDepth, locateOptions, currentDepth = 0) {\n\tconst found = await locatePath(paths, {cwd: directory, ...locateOptions});\n\tif (found) {\n\t\treturn path.resolve(directory, found);\n\t}\n\n\tif (currentDepth >= maxDepth) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst entries = await fs.promises.readdir(directory, {withFileTypes: true});\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\t\tconst result = await findDownDepthFirst(\n\t\t\t\t\tpath.join(directory, entry.name),\n\t\t\t\t\tpaths,\n\t\t\t\t\tmaxDepth,\n\t\t\t\t\tlocateOptions,\n\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {}\n\n\treturn undefined;\n}\n\nfunction findDownDepthFirstSync(directory, paths, maxDepth, locateOptions, currentDepth = 0) {\n\tconst found = locatePathSync(paths, {cwd: directory, ...locateOptions});\n\tif (found) {\n\t\treturn path.resolve(directory, found);\n\t}\n\n\tif (currentDepth >= maxDepth) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst entries = fs.readdirSync(directory, {withFileTypes: true});\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tconst result = findDownDepthFirstSync(\n\t\t\t\t\tpath.join(directory, entry.name),\n\t\t\t\t\tpaths,\n\t\t\t\t\tmaxDepth,\n\t\t\t\t\tlocateOptions,\n\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {}\n\n\treturn undefined;\n}\n\nfunction prepareFindDownOptions(name, options) {\n\tconst startDirectory = path.resolve(toPath(options.cwd) ?? '');\n\tconst maxDepth = Math.max(0, options.depth ?? 1);\n\tconst paths = [name].flat();\n\tconst {type = 'file', allowSymlinks = true, strategy = 'breadth'} = options;\n\tconst locateOptions = {type, allowSymlinks};\n\treturn {\n\t\tstartDirectory,\n\t\tmaxDepth,\n\t\tpaths,\n\t\tlocateOptions,\n\t\tstrategy,\n\t};\n}\n\nasync function findDownBreadthFirst(startDirectory, paths, maxDepth, locateOptions) {\n\tconst queue = [{directory: startDirectory, depth: 0}];\n\n\twhile (queue.length > 0) {\n\t\tconst {directory, depth} = queue.shift();\n\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tconst found = await locatePath(paths, {cwd: directory, ...locateOptions});\n\t\tif (found) {\n\t\t\treturn path.resolve(directory, found);\n\t\t}\n\n\t\tif (depth >= maxDepth) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst entries = await fs.promises.readdir(directory, {withFileTypes: true});\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\tqueue.push({directory: path.join(directory, entry.name), depth: depth + 1});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\t}\n\n\treturn undefined;\n}\n\nfunction findDownBreadthFirstSync(startDirectory, paths, maxDepth, locateOptions) {\n\tconst queue = [{directory: startDirectory, depth: 0}];\n\n\twhile (queue.length > 0) {\n\t\tconst {directory, depth} = queue.shift();\n\n\t\tconst found = locatePathSync(paths, {cwd: directory, ...locateOptions});\n\t\tif (found) {\n\t\t\treturn path.resolve(directory, found);\n\t\t}\n\n\t\tif (depth >= maxDepth) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst entries = fs.readdirSync(directory, {withFileTypes: true});\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\tqueue.push({directory: path.join(directory, entry.name), depth: depth + 1});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\t}\n\n\treturn undefined;\n}\n\nexport async function findDown(name, options = {}) {\n\tconst {startDirectory, maxDepth, paths, locateOptions, strategy} = prepareFindDownOptions(name, options);\n\n\treturn strategy === 'depth'\n\t\t? findDownDepthFirst(startDirectory, paths, maxDepth, locateOptions)\n\t\t: findDownBreadthFirst(startDirectory, paths, maxDepth, locateOptions);\n}\n\nexport function findDownSync(name, options = {}) {\n\tconst {startDirectory, maxDepth, paths, locateOptions, strategy} = prepareFindDownOptions(name, options);\n\n\treturn strategy === 'depth'\n\t\t? findDownDepthFirstSync(startDirectory, paths, maxDepth, locateOptions)\n\t\t: findDownBreadthFirstSync(startDirectory, paths, maxDepth, locateOptions);\n}\n\n", "import process from 'node:process';\nimport path from 'node:path';\nimport fs, {promises as fsPromises} from 'node:fs';\nimport {fileURLToPath} from 'node:url';\nimport pLocate from 'p-locate';\n\nconst typeMappings = {\n\tdirectory: 'isDirectory',\n\tfile: 'isFile',\n};\n\nfunction checkType(type) {\n\tif (type === 'both' || Object.hasOwn(typeMappings, type)) {\n\t\treturn;\n\t}\n\n\tthrow new Error(`Invalid type specified: ${type}`);\n}\n\nconst matchType = (type, stat) => type === 'both' ? (stat.isFile() || stat.isDirectory()) : stat[typeMappings[type]]();\n\nconst toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;\n\nexport async function locatePath(\n\tpaths,\n\t{\n\t\tcwd = process.cwd(),\n\t\ttype = 'file',\n\t\tallowSymlinks = true,\n\t\tconcurrency,\n\t\tpreserveOrder,\n\t} = {},\n) {\n\tcheckType(type);\n\tcwd = toPath(cwd);\n\n\tconst statFunction = allowSymlinks ? fsPromises.stat : fsPromises.lstat;\n\n\treturn pLocate(paths, async path_ => {\n\t\ttry {\n\t\t\tconst stat = await statFunction(path.resolve(cwd, path_));\n\t\t\treturn matchType(type, stat);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}, {concurrency, preserveOrder});\n}\n\nexport function locatePathSync(\n\tpaths,\n\t{\n\t\tcwd = process.cwd(),\n\t\ttype = 'file',\n\t\tallowSymlinks = true,\n\t} = {},\n) {\n\tcheckType(type);\n\tcwd = toPath(cwd);\n\n\tconst statFunction = allowSymlinks ? fs.statSync : fs.lstatSync;\n\n\tfor (const path_ of paths) {\n\t\ttry {\n\t\t\tconst stat = statFunction(path.resolve(cwd, path_), {\n\t\t\t\tthrowIfNoEntry: false,\n\t\t\t});\n\n\t\t\tif (!stat) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (matchType(type, stat)) {\n\t\t\t\treturn path_;\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n", "/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\n\t\t// Clean up tail reference when queue becomes empty\n\t\tif (!this.#head) {\n\t\t\tthis.#tail = undefined;\n\t\t}\n\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n\n\t* drain() {\n\t\twhile (this.#head) {\n\t\t\tyield this.dequeue();\n\t\t}\n\t}\n}\n", "import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t}\n\t};\n\n\tconst run = async (fn, resolve, args) => {\n\t\tactiveCount++;\n\n\t\tconst result = (async () => fn(...args))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (fn, resolve, args) => {\n\t\tqueue.enqueue(run.bind(undefined, fn, resolve, args));\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// when the run function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\t\tqueue.dequeue()();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => {\n\t\tenqueue(fn, resolve, args);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n", "import pLimit from 'p-limit';\n\nclass EndError extends Error {\n\tconstructor(value) {\n\t\tsuper();\n\t\tthis.value = value;\n\t}\n}\n\n// The input can also be a promise, so we await it.\nconst testElement = async (element, tester) => tester(await element);\n\n// The input can also be a promise, so we `Promise.all()` them both.\nconst finder = async element => {\n\tconst values = await Promise.all(element);\n\tif (values[1] === true) {\n\t\tthrow new EndError(values[0]);\n\t}\n\n\treturn false;\n};\n\nexport default async function pLocate(\n\titerable,\n\ttester,\n\t{\n\t\tconcurrency = Number.POSITIVE_INFINITY,\n\t\tpreserveOrder = true,\n\t} = {},\n) {\n\tconst limit = pLimit(concurrency);\n\n\t// Start all the promises concurrently with optional limit.\n\tconst items = [...iterable].map(element => [element, limit(testElement, element, tester)]);\n\n\t// Check the promises either serially or concurrently.\n\tconst checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY);\n\n\ttry {\n\t\tawait Promise.all(items.map(element => checkLimit(finder, element)));\n\t} catch (error) {\n\t\tif (error instanceof EndError) {\n\t\t\treturn error.value;\n\t\t}\n\n\t\tthrow error;\n\t}\n}\n", "import {promisify} from 'node:util';\nimport {execFile as execFileCallback, execFileSync as execFileSyncOriginal} from 'node:child_process';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\n\nconst execFileOriginal = promisify(execFileCallback);\n\nexport function toPath(urlOrPath) {\n\treturn urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;\n}\n\nexport function rootDirectory(pathInput) {\n\treturn path.parse(toPath(pathInput)).root;\n}\n\nexport function traversePathUp(startPath) {\n\treturn {\n\t\t* [Symbol.iterator]() {\n\t\t\tlet currentPath = path.resolve(toPath(startPath));\n\t\t\tlet previousPath;\n\n\t\t\twhile (previousPath !== currentPath) {\n\t\t\t\tyield currentPath;\n\t\t\t\tpreviousPath = currentPath;\n\t\t\t\tcurrentPath = path.resolve(currentPath, '..');\n\t\t\t}\n\t\t},\n\t};\n}\n\nconst TEN_MEGABYTES_IN_BYTES = 10 * 1024 * 1024;\n\nexport async function execFile(file, arguments_, options = {}) {\n\treturn execFileOriginal(file, arguments_, {\n\t\tmaxBuffer: TEN_MEGABYTES_IN_BYTES,\n\t\t...options,\n\t});\n}\n\nexport function execFileSync(file, arguments_ = [], options = {}) {\n\treturn execFileSyncOriginal(file, arguments_, {\n\t\tmaxBuffer: TEN_MEGABYTES_IN_BYTES,\n\t\tencoding: 'utf8',\n\t\tstdio: 'pipe',\n\t\t...options,\n\t});\n}\n\nexport * from './default.js';\n", "/* eslint-disable security/detect-non-literal-regexp -- expected to be non-literal */\n\nexport function escape(text: string): string {\n\treturn text.replace(/\\./, \"\\\\.\");\n}\n\nexport function directory(path: string): RegExp {\n\treturn new RegExp(`(^|/)${path}/`);\n}\n\nexport function extension(ext: string): RegExp {\n\treturn new RegExp(`${escape(ext)}$`);\n}\n\nexport function filename(path: string): RegExp {\n\treturn new RegExp(`(^|/)${escape(path)}$`);\n}\n\nexport function rcfile(base: string): RegExp {\n\treturn new RegExp(`${escape(base)}(\\\\.(js|cjs|mjs|ts|yaml|yml|json))?$`);\n}\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tfilename(\"ava.config.js\"),\n\tfilename(\"ava.config.cjs\"),\n\tfilename(\"ava.config.mjs\"),\n];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [/#[^#]*#$/, /~$/, filename(\".dir-locals.el\")];\n\nexport default regexp;\n", "import { directory, filename, rcfile } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tdirectory(\".eslintcache\"),\n\tfilename(\".eslintignore\"),\n\trcfile(`.eslintrc`),\n\tfilename(\"eslint.config.js\"),\n\tfilename(\"eslint.config.cjs\"),\n\tfilename(\"eslint.config.mjs\"),\n\tfilename(\"eslint.config.ts\"),\n];\n\nexport default regexp;\n", "import { filename, rcfile } from \"./helpers\";\n\nconst regexp: RegExp[] = [filename(\".fimbullinter.yaml\"), rcfile(\".wotanrc\")];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tfilename(\".gitattributes\"),\n\tfilename(\".keep\"),\n\tfilename(\".gitkeep\"),\n\tfilename(\".gitmodules\"),\n];\n\nexport default regexp;\n", "import { directory, extension } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tdirectory(\"__fixtures__\"),\n\tdirectory(\"__snapshots__\"),\n\tdirectory(\"__tests__\"),\n\textension(\".snap\"),\n\textension(\".spec.[jt]sx?\"),\n\textension(\".spec.js.map\"),\n\textension(\".spec.d.ts\"),\n\textension(\".spec.d.ts.map\"),\n\textension(\".test.[jt]sx?\"),\n\textension(\".test.js.map\"),\n\textension(\".test.d.ts\"),\n\textension(\".test.d.ts.map\"),\n];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\t/(^|\\/)(npm|yarn|lerna)-(debug|error)\\.log.*$/,\n\tfilename(\"report.\\\\d+.\\\\d+.\\\\d+.\\\\d+.\\\\d+.json\"),\n\tfilename(\".npmignore\"),\n\tfilename(\".npmrc\"),\n\tfilename(\".nvmrc\"),\n\tfilename(\"lerna.json\"),\n\tfilename(\"yarn.lock\"),\n];\n\nexport default regexp;\n", "import { filename, rcfile } from \"./helpers\";\n\nconst regexp: RegExp[] = [filename(\".prettierignore\"), rcfile(`.prettierrc`)];\n\nexport default regexp;\n", "import { directory, filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [directory(\".tsbuildinfo\"), filename(\"tsconfig.json\")];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\n/* reserved filenames on windows */\nconst regexp: RegExp[] = [\n\tfilename(\"CON\"),\n\tfilename(\"PRN\"),\n\tfilename(\"AUX\"),\n\tfilename(\"NUL\"),\n\t/(^|\\/)COM\\d/,\n\t/(^|\\/)LPT\\d/,\n];\n\nexport default regexp;\n", "import ava from \"./ava\";\nimport emacs from \"./emacs\";\nimport eslint from \"./eslint\";\nimport fimbullinter from \"./fimbullinter\";\nimport git from \"./git\";\nimport { directory, extension, filename, rcfile } from \"./helpers\";\nimport jest from \"./jest\";\nimport node from \"./node\";\nimport prettier from \"./prettier\";\nimport typescript from \"./typescript\";\nimport windows from \"./windows\";\n\nconst blacklist: RegExp[] = [\n\t/* tests in general */\n\tdirectory(\".nyc_output\"),\n\tdirectory(\"coverage\"),\n\textension(\".lcov\"),\n\textension(\"[.-]junit.xml\"),\n\tfilename(\".istanbul.yml\"),\n\tfilename(\"junit.xml\"),\n\tfilename(\"lcov.info\"),\n\tfilename(\".airtap.yml\"),\n\trcfile(\".c8rc\"),\n\trcfile(\".nycrc\"),\n\n\t/* tests */\n\tdirectory(\"examples?\"),\n\tdirectory(\"perf\"),\n\tdirectory(\"tests?\"),\n\tfilename(\"cypress.json\"),\n\tfilename(\"cypress.config.js\"),\n\tfilename(\"cypress.config.cjs\"),\n\tfilename(\"cypress.config.mjs\"),\n\tfilename(\"cypress.config.ts\"),\n\tfilename(\"karma.config.js\"),\n\tfilename(\"mocha.opts\"),\n\tfilename(\"playwright.config.js\"),\n\tfilename(\"playwright.config.cjs\"),\n\tfilename(\"playwright.config.mjs\"),\n\tfilename(\"playwright.config.ts\"),\n\tfilename(\"test.js\"),\n\tfilename(\"testem.json\"),\n\tfilename(\"testem.yml\"),\n\tfilename(\"wallaby.config.js\"),\n\tfilename(\"wallaby.js\"),\n\n\t/* linting */\n\tfilename(\".htmlvalidate.json\"),\n\tfilename(\".jshintignore\"),\n\tfilename(`tslint.json`),\n\tfilename(`tslint.yaml`),\n\tfilename(\".jscs.json\"),\n\trcfile(`.jscsrc`),\n\trcfile(`.jshintrc`),\n\n\t/* toolchains */\n\tfilename(\"rollup.config.js\"),\n\tfilename(\"webpack.config.js\"),\n\n\t/* task runners */\n\tfilename(\"[gG]runtfile.js\"),\n\tfilename(\"[gG]ulpfile.[jt]s\"),\n\tfilename(\"dangerfile.[jt]s\"),\n\tfilename(\"gulpfile.babel.js\"),\n\tfilename(\"gulpfile.esm.js\"),\n\tfilename(\"Herebyfile.js\"),\n\tfilename(\"Herebyfile.mjs\"),\n\n\t/* ci */\n\t/^\\.azure-.*$/,\n\tdirectory(\".circleci\"),\n\tdirectory(\".github\"),\n\tdirectory(\".gitlab\"),\n\tdirectory(\".?zuul.d\"),\n\tfilename(\".coveralls.yml\"),\n\tfilename(\".gitlab-ci.yml\"),\n\tfilename(\".travis.yml\"),\n\tfilename(\".?zuul.ya?ml\"),\n\tfilename(\"ISSUE_TEMPLATE.md\"),\n\tfilename(\"Jenkinsfile\"),\n\tfilename(\"PULL_REQUEST_TEMPLATE.md\"),\n\tfilename(\"appveyor.yml\"),\n\n\t/* editor specific files */\n\t/(^|\\/)\\.sw[a-p]/ /* vim */,\n\tdirectory(\".vscode\"),\n\textension(\".sublime-project\"),\n\textension(\".sublime-workspace\"),\n\tfilename(\".vscodeignore\"),\n\tfilename(\"Session.vim\"),\n\tfilename(\"Sessionx.vim\"),\n\tdirectory(\".idea\"),\n\tfilename(\".tm_properties\") /* textmate */,\n\n\t/* OS */\n\tdirectory(\".AppleDouble\"),\n\tdirectory(\".DS_Store\"),\n\tdirectory(\".LSOverride\"),\n\n\t/* logs */\n\tdirectory(\"logs\"),\n\textension(\".log\"),\n\n\t/* runtime */\n\tdirectory(\"pids\"),\n\textension(\".pid\"),\n\textension(\".pid.lock\"),\n\textension(\".seed\"),\n\n\t/* misc */\n\t/^[Jj]akefile(\\.js)?$/,\n\textension(\".bak\"),\n\textension(\".swp\"),\n\textension(\".tgz\"),\n\textension(\".tmp\"),\n\tfilename(\".env\"),\n\tfilename(\".svgo.yml\"),\n\tfilename(\".editorconfig\"),\n\tfilename(\".ext-prepush\"),\n\tfilename(\".tonic_example.js\"),\n\tfilename(\".flowconfig\"),\n\tfilename(\".cardinalrc\"),\n\tfilename(\"bower.json\"),\n\tfilename(\"commitlint.config.js\") /* commitlint */,\n\tfilename(\"composer.json\"),\n\tfilename(\"netlify.toml\"),\n\tfilename(\"release.config.js\") /* semantic release */,\n\n\t...ava,\n\t...emacs,\n\t...eslint,\n\t...fimbullinter,\n\t...git,\n\t...jest,\n\t...node,\n\t...prettier,\n\t...typescript,\n\t...windows,\n];\n\nexport default blacklist;\n", "import blacklist from \"./blacklist/index\";\n\nexport function setupBlacklist(name: string): void {\n\t/* eslint-disable-next-line security/detect-non-literal-regexp -- expected to be non-literal */\n\tblacklist.push(new RegExp(`^${name}-\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.tgz$`));\n}\n\nexport function isBlacklisted(filename: string): boolean {\n\treturn blacklist.some((entry) => filename.match(entry));\n}\n", "import fs from \"node:fs\";\nimport * as tar from \"tar\";\nimport { type ReadEntry, Parser } from \"tar\";\nimport { isBlacklisted } from \"./blacklist\";\nimport { type Message } from \"./message\";\nimport { type Result } from \"./result\";\nimport { type PackageJson, type PackageJsonExports } from \"./types\";\n\nexport interface TarballMeta {\n\t/** Path to tarball on disk */\n\tfilePath: string;\n\n\t/** Path to use in report (default filePath) */\n\treportPath?: string | undefined;\n}\n\ninterface RequiredFile {\n\tfield: string;\n\truleId: string;\n\tfilename: string;\n}\n\nconst ruleId = \"no-missing-main\";\n\nfunction normalize(filename: string): string {\n\treturn filename.replace(/^[^/]+\\//, \"\");\n}\n\nexport async function getFileList(filename: string): Promise<string[]> {\n\tconst entries: ReadEntry[] = [];\n\tawait tar.list({\n\t\tfile: filename,\n\t\tstrict: true,\n\t\tonentry: (entry: ReadEntry) => entries.push(entry),\n\t});\n\treturn entries.map((entry) => {\n\t\tconst filename = entry.path as unknown as string;\n\t\treturn normalize(filename);\n\t});\n}\n\nexport async function getFileContent(\n\ttarball: TarballMeta,\n\tfilenames: string[],\n): Promise<Record<string, Buffer>> {\n\tconst contents: Record<string, Buffer> = {};\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst t = new Parser({\n\t\t\tfilter(path): boolean {\n\t\t\t\treturn filenames.includes(normalize(path));\n\t\t\t},\n\t\t});\n\t\tt.on(\"entry\", (entry: tar.ReadEntry) => {\n\t\t\tconst p = normalize(entry.path);\n\t\t\tcontents[p] = Buffer.alloc(0);\n\t\t\tentry.on(\"data\", (data: Buffer) => {\n\t\t\t\tcontents[p] = Buffer.concat([contents[p], data]);\n\t\t\t});\n\t\t\tentry.on(\"error\", (error) => {\n\t\t\t\t/* eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- technical debt */\n\t\t\t\treject(error);\n\t\t\t});\n\t\t});\n\t\tt.on(\"end\", () => {\n\t\t\tresolve(contents);\n\t\t});\n\t\tconst rs = fs.createReadStream(tarball.filePath);\n\t\trs.pipe(t as unknown as NodeJS.WritableStream);\n\t});\n}\n\nexport function blacklistedFiles(filelist: string[]): string[] {\n\treturn filelist.filter(isBlacklisted);\n}\n\nfunction normalizeRequiredFiles(\n\tsrc: string | string[] | Record<string, string | boolean>,\n): string[] {\n\tif (typeof src === \"string\") {\n\t\treturn [src];\n\t} else if (Array.isArray(src)) {\n\t\treturn src;\n\t} else {\n\t\treturn Object.values(src).filter((it) => it !== false) as string[];\n\t}\n}\n\nfunction* yieldRequiredFiles(\n\tsrc: string | string[] | Record<string, string | boolean>,\n\ttemplate: Pick<RequiredFile, \"field\" | \"ruleId\">,\n): Generator<RequiredFile> {\n\tconst files = normalizeRequiredFiles(src);\n\tfor (const filename of files) {\n\t\tyield { ...template, filename };\n\t}\n}\n\nfunction* yieldExportedFiles(\n\texports: undefined | null | string | PackageJsonExports,\n): Generator<RequiredFile> {\n\tif (!exports) {\n\t\treturn;\n\t}\n\n\tif (typeof exports === \"string\") {\n\t\tyield {\n\t\t\tfield: \"exports\",\n\t\t\truleId: \"no-missing-exports\",\n\t\t\tfilename: exports,\n\t\t};\n\t\treturn;\n\t}\n\n\tfor (const [key, value] of Object.entries(exports)) {\n\t\t/* ignore wildcards for now */\n\t\tif (key.includes(\"*\")) {\n\t\t\tcontinue;\n\t\t}\n\t\tyield* yieldExportedFiles(value);\n\t}\n}\n\nfunction* requiredFiles(pkg: PackageJson): Generator<RequiredFile> {\n\tyield* yieldExportedFiles(pkg.exports);\n\tif (pkg.main) {\n\t\tyield* yieldRequiredFiles(pkg.main, { field: \"main\", ruleId });\n\t}\n\tif (pkg.browser) {\n\t\tyield* yieldRequiredFiles(pkg.browser, { field: \"browser\", ruleId });\n\t}\n\tif (pkg.module) {\n\t\tyield* yieldRequiredFiles(pkg.module, { field: \"module\", ruleId });\n\t}\n\tif (pkg[\"jsnext:main\"]) {\n\t\tyield* yieldRequiredFiles(pkg[\"jsnext:main\"], {\n\t\t\tfield: \"jsnext:main\",\n\t\t\truleId,\n\t\t});\n\t}\n\tif (pkg.types) {\n\t\tyield* yieldRequiredFiles(pkg.types, { field: \"types\", ruleId: \"no-missing-types\" });\n\t}\n\tif (pkg.typings) {\n\t\tyield* yieldRequiredFiles(pkg.typings, { field: \"typings\", ruleId: \"no-missing-typings\" });\n\t}\n\tif (pkg.bin) {\n\t\tyield* yieldRequiredFiles(pkg.bin, { field: \"bin\", ruleId: \"no-missing-binary\" });\n\t}\n\tif (pkg.man) {\n\t\tyield* yieldRequiredFiles(pkg.man, { field: \"man\", ruleId: \"no-missing-man\" });\n\t}\n}\n\nfunction fileExists(filelist: string[], filename: string): boolean {\n\t/* strip leading ./ */\n\tfilename = filename.replace(/^\\.\\//, \"\");\n\n\t/* exact match for filename */\n\tif (filelist.includes(filename)) {\n\t\treturn true;\n\t}\n\n\t/* try to append \".js\" */\n\tif (filelist.includes(`${filename}.js`)) {\n\t\treturn true;\n\t}\n\n\t/* test if it is actually a directory with index.js */\n\tif (filelist.includes(`${filename.replace(/\\/$/, \"\")}/index.js`)) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n/**\n * @param pkg - Parsed `package.json` data\n * @param tarball - Tarball paths\n */\nexport async function verifyTarball(pkg: PackageJson, tarball: TarballMeta): Promise<Result[]> {\n\tconst messages: Message[] = [];\n\tconst filelist = await getFileList(tarball.filePath);\n\n\tfor (const filename of blacklistedFiles(filelist)) {\n\t\tmessages.push({\n\t\t\truleId: \"no-disallowed-files\",\n\t\t\tseverity: 2,\n\t\t\tmessage: `${filename} is not allowed in tarball`,\n\t\t\tline: 1,\n\t\t\tcolumn: 1,\n\t\t});\n\t}\n\n\tfor (const requiredFile of requiredFiles(pkg)) {\n\t\tif (!fileExists(filelist, requiredFile.filename)) {\n\t\t\tmessages.push({\n\t\t\t\truleId: requiredFile.ruleId,\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `${requiredFile.filename} (pkg.${requiredFile.field}) is not present in tarball`,\n\t\t\t\tline: 1,\n\t\t\t\tcolumn: 1,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (messages.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [\n\t\t{\n\t\t\tmessages,\n\t\t\tfilePath: tarball.reportPath ?? tarball.filePath,\n\t\t\terrorCount: messages.filter((it) => it.severity === 2).length,\n\t\t\twarningCount: messages.filter((it) => it.severity === 1).length,\n\t\t\tfixableErrorCount: 0,\n\t\t\tfixableWarningCount: 0,\n\t\t},\n\t];\n}\n", "import EE from 'events'\nimport fs from 'fs'\nimport { Minipass } from 'minipass'\n\nconst writev = fs.writev\n\nconst _autoClose = Symbol('_autoClose')\nconst _close = Symbol('_close')\nconst _ended = Symbol('_ended')\nconst _fd = Symbol('_fd')\nconst _finished = Symbol('_finished')\nconst _flags = Symbol('_flags')\nconst _flush = Symbol('_flush')\nconst _handleChunk = Symbol('_handleChunk')\nconst _makeBuf = Symbol('_makeBuf')\nconst _mode = Symbol('_mode')\nconst _needDrain = Symbol('_needDrain')\nconst _onerror = Symbol('_onerror')\nconst _onopen = Symbol('_onopen')\nconst _onread = Symbol('_onread')\nconst _onwrite = Symbol('_onwrite')\nconst _open = Symbol('_open')\nconst _path = Symbol('_path')\nconst _pos = Symbol('_pos')\nconst _queue = Symbol('_queue')\nconst _read = Symbol('_read')\nconst _readSize = Symbol('_readSize')\nconst _reading = Symbol('_reading')\nconst _remain = Symbol('_remain')\nconst _size = Symbol('_size')\nconst _write = Symbol('_write')\nconst _writing = Symbol('_writing')\nconst _defaultFlag = Symbol('_defaultFlag')\nconst _errored = Symbol('_errored')\n\nexport type ReadStreamOptions =\n Minipass.Options<Minipass.ContiguousData> & {\n fd?: number\n readSize?: number\n size?: number\n autoClose?: boolean\n }\n\nexport type ReadStreamEvents = Minipass.Events<Minipass.ContiguousData> & {\n open: [fd: number]\n}\n\nexport class ReadStream extends Minipass<\n Minipass.ContiguousData,\n Buffer,\n ReadStreamEvents\n> {\n [_errored]: boolean = false;\n [_fd]?: number;\n [_path]: string;\n [_readSize]: number;\n [_reading]: boolean = false;\n [_size]: number;\n [_remain]: number;\n [_autoClose]: boolean\n\n constructor(path: string, opt: ReadStreamOptions) {\n opt = opt || {}\n super(opt)\n\n this.readable = true\n this.writable = false\n\n if (typeof path !== 'string') {\n throw new TypeError('path must be a string')\n }\n\n this[_errored] = false\n this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined\n this[_path] = path\n this[_readSize] = opt.readSize || 16 * 1024 * 1024\n this[_reading] = false\n this[_size] = typeof opt.size === 'number' ? opt.size : Infinity\n this[_remain] = this[_size]\n this[_autoClose] =\n typeof opt.autoClose === 'boolean' ? opt.autoClose : true\n\n if (typeof this[_fd] === 'number') {\n this[_read]()\n } else {\n this[_open]()\n }\n }\n\n get fd() {\n return this[_fd]\n }\n\n get path() {\n return this[_path]\n }\n\n //@ts-ignore\n write() {\n throw new TypeError('this is a readable stream')\n }\n\n //@ts-ignore\n end() {\n throw new TypeError('this is a readable stream')\n }\n\n [_open]() {\n fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd))\n }\n\n [_onopen](er?: NodeJS.ErrnoException | null, fd?: number) {\n if (er) {\n this[_onerror](er)\n } else {\n this[_fd] = fd\n this.emit('open', fd as number)\n this[_read]()\n }\n }\n\n [_makeBuf]() {\n return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]))\n }\n\n [_read]() {\n if (!this[_reading]) {\n this[_reading] = true\n const buf = this[_makeBuf]()\n /* c8 ignore start */\n if (buf.length === 0) {\n return process.nextTick(() => this[_onread](null, 0, buf))\n }\n /* c8 ignore stop */\n fs.read(this[_fd] as number, buf, 0, buf.length, null, (er, br, b) =>\n this[_onread](er, br, b),\n )\n }\n }\n\n [_onread](er?: NodeJS.ErrnoException | null, br?: number, buf?: Buffer) {\n this[_reading] = false\n if (er) {\n this[_onerror](er)\n } else if (this[_handleChunk](br as number, buf as Buffer)) {\n this[_read]()\n }\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.close(fd, er =>\n er ? this.emit('error', er) : this.emit('close'),\n )\n }\n }\n\n [_onerror](er: NodeJS.ErrnoException) {\n this[_reading] = true\n this[_close]()\n this.emit('error', er)\n }\n\n [_handleChunk](br: number, buf: Buffer) {\n let ret = false\n // no effect if infinite\n this[_remain] -= br\n if (br > 0) {\n ret = super.write(br < buf.length ? buf.subarray(0, br) : buf)\n }\n\n if (br === 0 || this[_remain] <= 0) {\n ret = false\n this[_close]()\n super.end()\n }\n\n return ret\n }\n\n emit<Event extends keyof ReadStreamEvents>(\n ev: Event,\n ...args: ReadStreamEvents[Event]\n ): boolean {\n switch (ev) {\n case 'prefinish':\n case 'finish':\n return false\n\n case 'drain':\n if (typeof this[_fd] === 'number') {\n this[_read]()\n }\n return false\n\n case 'error':\n if (this[_errored]) {\n return false\n }\n this[_errored] = true\n return super.emit(ev, ...args)\n\n default:\n return super.emit(ev, ...args)\n }\n }\n}\n\nexport class ReadStreamSync extends ReadStream {\n [_open]() {\n let threw = true\n try {\n this[_onopen](null, fs.openSync(this[_path], 'r'))\n threw = false\n } finally {\n if (threw) {\n this[_close]()\n }\n }\n }\n\n [_read]() {\n let threw = true\n try {\n if (!this[_reading]) {\n this[_reading] = true\n do {\n const buf = this[_makeBuf]()\n /* c8 ignore start */\n const br =\n buf.length === 0\n ? 0\n : fs.readSync(this[_fd] as number, buf, 0, buf.length, null)\n /* c8 ignore stop */\n if (!this[_handleChunk](br, buf)) {\n break\n }\n } while (true)\n this[_reading] = false\n }\n threw = false\n } finally {\n if (threw) {\n this[_close]()\n }\n }\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.closeSync(fd)\n this.emit('close')\n }\n }\n}\n\nexport type WriteStreamOptions = {\n fd?: number\n autoClose?: boolean\n mode?: number\n captureRejections?: boolean\n start?: number\n flags?: string\n}\n\nexport class WriteStream extends EE {\n readable: false = false\n writable: boolean = true;\n [_errored]: boolean = false;\n [_writing]: boolean = false;\n [_ended]: boolean = false;\n [_queue]: Buffer[] = [];\n [_needDrain]: boolean = false;\n [_path]: string;\n [_mode]: number;\n [_autoClose]: boolean;\n [_fd]?: number;\n [_defaultFlag]: boolean;\n [_flags]: string;\n [_finished]: boolean = false;\n [_pos]?: number\n\n constructor(path: string, opt: WriteStreamOptions) {\n opt = opt || {}\n super(opt)\n this[_path] = path\n this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined\n this[_mode] = opt.mode === undefined ? 0o666 : opt.mode\n this[_pos] = typeof opt.start === 'number' ? opt.start : undefined\n this[_autoClose] =\n typeof opt.autoClose === 'boolean' ? opt.autoClose : true\n\n // truncating makes no sense when writing into the middle\n const defaultFlag = this[_pos] !== undefined ? 'r+' : 'w'\n this[_defaultFlag] = opt.flags === undefined\n this[_flags] = opt.flags === undefined ? defaultFlag : opt.flags\n\n if (this[_fd] === undefined) {\n this[_open]()\n }\n }\n\n emit(ev: string, ...args: any[]) {\n if (ev === 'error') {\n if (this[_errored]) {\n return false\n }\n this[_errored] = true\n }\n return super.emit(ev, ...args)\n }\n\n get fd() {\n return this[_fd]\n }\n\n get path() {\n return this[_path]\n }\n\n [_onerror](er: NodeJS.ErrnoException) {\n this[_close]()\n this[_writing] = true\n this.emit('error', er)\n }\n\n [_open]() {\n fs.open(this[_path], this[_flags], this[_mode], (er, fd) =>\n this[_onopen](er, fd),\n )\n }\n\n [_onopen](er?: null | NodeJS.ErrnoException, fd?: number) {\n if (\n this[_defaultFlag] &&\n this[_flags] === 'r+' &&\n er &&\n er.code === 'ENOENT'\n ) {\n this[_flags] = 'w'\n this[_open]()\n } else if (er) {\n this[_onerror](er)\n } else {\n this[_fd] = fd\n this.emit('open', fd)\n if (!this[_writing]) {\n this[_flush]()\n }\n }\n }\n\n end(buf: string, enc?: BufferEncoding): this\n end(buf?: Buffer, enc?: undefined): this\n end(buf?: Buffer | string, enc?: BufferEncoding): this {\n if (buf) {\n //@ts-ignore\n this.write(buf, enc)\n }\n\n this[_ended] = true\n\n // synthetic after-write logic, where drain/finish live\n if (\n !this[_writing] &&\n !this[_queue].length &&\n typeof this[_fd] === 'number'\n ) {\n this[_onwrite](null, 0)\n }\n return this\n }\n\n write(buf: string, enc?: BufferEncoding): boolean\n write(buf: Buffer, enc?: undefined): boolean\n write(buf: Buffer | string, enc?: BufferEncoding): boolean {\n if (typeof buf === 'string') {\n buf = Buffer.from(buf, enc)\n }\n\n if (this[_ended]) {\n this.emit('error', new Error('write() after end()'))\n return false\n }\n\n if (this[_fd] === undefined || this[_writing] || this[_queue].length) {\n this[_queue].push(buf)\n this[_needDrain] = true\n return false\n }\n\n this[_writing] = true\n this[_write](buf)\n return true\n }\n\n [_write](buf: Buffer) {\n fs.write(\n this[_fd] as number,\n buf,\n 0,\n buf.length,\n this[_pos],\n (er, bw) => this[_onwrite](er, bw),\n )\n }\n\n [_onwrite](er?: null | NodeJS.ErrnoException, bw?: number) {\n if (er) {\n this[_onerror](er)\n } else {\n if (this[_pos] !== undefined && typeof bw === 'number') {\n this[_pos] += bw\n }\n if (this[_queue].length) {\n this[_flush]()\n } else {\n this[_writing] = false\n\n if (this[_ended] && !this[_finished]) {\n this[_finished] = true\n this[_close]()\n this.emit('finish')\n } else if (this[_needDrain]) {\n this[_needDrain] = false\n this.emit('drain')\n }\n }\n }\n }\n\n [_flush]() {\n if (this[_queue].length === 0) {\n if (this[_ended]) {\n this[_onwrite](null, 0)\n }\n } else if (this[_queue].length === 1) {\n this[_write](this[_queue].pop() as Buffer)\n } else {\n const iovec = this[_queue]\n this[_queue] = []\n writev(this[_fd] as number, iovec, this[_pos] as number, (er, bw) =>\n this[_onwrite](er, bw),\n )\n }\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.close(fd, er =>\n er ? this.emit('error', er) : this.emit('close'),\n )\n }\n }\n}\n\nexport class WriteStreamSync extends WriteStream {\n [_open](): void {\n let fd\n // only wrap in a try{} block if we know we'll retry, to avoid\n // the rethrow obscuring the error's source frame in most cases.\n if (this[_defaultFlag] && this[_flags] === 'r+') {\n try {\n fd = fs.openSync(this[_path], this[_flags], this[_mode])\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') {\n this[_flags] = 'w'\n return this[_open]()\n } else {\n throw er\n }\n }\n } else {\n fd = fs.openSync(this[_path], this[_flags], this[_mode])\n }\n\n this[_onopen](null, fd)\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.closeSync(fd)\n this.emit('close')\n }\n }\n\n [_write](buf: Buffer) {\n // throw the original, but try to close if it fails\n let threw = true\n try {\n this[_onwrite](\n null,\n fs.writeSync(this[_fd] as number, buf, 0, buf.length, this[_pos]),\n )\n threw = false\n } finally {\n if (threw) {\n try {\n this[_close]()\n } catch {\n // ok error\n }\n }\n }\n }\n}\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "import { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass'\nimport { Minipass } from 'minipass'\nimport path from 'node:path'\nimport { list } from './list.js'\nimport { makeCommand } from './make-command.js'\nimport {\n TarOptions,\n TarOptionsFile,\n TarOptionsSync,\n TarOptionsSyncFile,\n} from './options.js'\nimport { Pack, PackSync } from './pack.js'\n\nconst createFileSync = (opt: TarOptionsSyncFile, files: string[]) => {\n const p = new PackSync(opt)\n const stream = new WriteStreamSync(opt.file, {\n mode: opt.mode || 0o666,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n addFilesSync(p, files)\n}\n\nconst createFile = (opt: TarOptionsFile, files: string[]) => {\n const p = new Pack(opt)\n const stream = new WriteStream(opt.file, {\n mode: opt.mode || 0o666,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n\n const promise = new Promise<void>((res, rej) => {\n stream.on('error', rej)\n stream.on('close', res)\n p.on('error', rej)\n })\n\n addFilesAsync(p, files)\n\n return promise\n}\n\nconst addFilesSync = (p: PackSync, files: string[]) => {\n files.forEach(file => {\n if (file.charAt(0) === '@') {\n list({\n file: path.resolve(p.cwd, file.slice(1)),\n sync: true,\n noResume: true,\n onReadEntry: entry => p.add(entry),\n })\n } else {\n p.add(file)\n }\n })\n p.end()\n}\n\nconst addFilesAsync = async (\n p: Pack,\n files: string[],\n): Promise<void> => {\n for (let i = 0; i < files.length; i++) {\n const file = String(files[i])\n if (file.charAt(0) === '@') {\n await list({\n file: path.resolve(String(p.cwd), file.slice(1)),\n noResume: true,\n onReadEntry: entry => {\n p.add(entry)\n },\n })\n } else {\n p.add(file)\n }\n }\n p.end()\n}\n\nconst createSync = (opt: TarOptionsSync, files: string[]) => {\n const p = new PackSync(opt)\n addFilesSync(p, files)\n return p\n}\n\nconst createAsync = (opt: TarOptions, files: string[]) => {\n const p = new Pack(opt)\n addFilesAsync(p, files)\n return p\n}\n\nexport const create = makeCommand(\n createFileSync,\n createFile,\n createSync,\n createAsync,\n (_opt, files) => {\n if (!files?.length) {\n throw new TypeError('no paths specified to add to archive')\n }\n },\n)\n", "// tar -t\nimport * as fsm from '@isaacs/fs-minipass'\nimport fs from 'node:fs'\nimport { dirname, parse } from 'path'\nimport { makeCommand } from './make-command.js'\nimport {\n TarOptions,\n TarOptionsFile,\n TarOptionsSyncFile,\n} from './options.js'\nimport { Parser } from './parse.js'\nimport { stripTrailingSlashes } from './strip-trailing-slashes.js'\n\nconst onReadEntryFunction = (opt: TarOptions) => {\n const onReadEntry = opt.onReadEntry\n opt.onReadEntry =\n onReadEntry ?\n e => {\n onReadEntry(e)\n e.resume()\n }\n : e => e.resume()\n}\n\n// construct a filter that limits the file entries listed\n// include child entries if a dir is included\nexport const filesFilter = (opt: TarOptions, files: string[]) => {\n const map = new Map<string, boolean>(\n files.map(f => [stripTrailingSlashes(f), true]),\n )\n const filter = opt.filter\n\n const mapHas = (file: string, r: string = ''): boolean => {\n const root = r || parse(file).root || '.'\n let ret: boolean\n if (file === root) ret = false\n else {\n const m = map.get(file)\n if (m !== undefined) {\n ret = m\n } else {\n ret = mapHas(dirname(file), root)\n }\n }\n\n map.set(file, ret)\n return ret\n }\n\n opt.filter =\n filter ?\n (file, entry) =>\n filter(file, entry) && mapHas(stripTrailingSlashes(file))\n : file => mapHas(stripTrailingSlashes(file))\n}\n\nconst listFileSync = (opt: TarOptionsSyncFile) => {\n const p = new Parser(opt)\n const file = opt.file\n let fd: number | undefined\n try {\n fd = fs.openSync(file, 'r')\n const stat: fs.Stats = fs.fstatSync(fd)\n const readSize: number = opt.maxReadSize || 16 * 1024 * 1024\n if (stat.size < readSize) {\n const buf = Buffer.allocUnsafe(stat.size)\n const read = fs.readSync(fd, buf, 0, stat.size, 0)\n p.end(read === buf.byteLength ? buf : buf.subarray(0, read))\n } else {\n let pos = 0\n const buf = Buffer.allocUnsafe(readSize)\n while (pos < stat.size) {\n const bytesRead = fs.readSync(fd, buf, 0, readSize, pos)\n if (bytesRead === 0) break\n pos += bytesRead\n p.write(buf.subarray(0, bytesRead))\n }\n p.end()\n }\n } finally {\n if (typeof fd === 'number') {\n try {\n fs.closeSync(fd)\n /* c8 ignore next */\n } catch (er) {}\n }\n }\n}\n\nconst listFile = (\n opt: TarOptionsFile,\n _files: string[],\n): Promise<void> => {\n const parse = new Parser(opt)\n const readSize = opt.maxReadSize || 16 * 1024 * 1024\n\n const file = opt.file\n const p = new Promise<void>((resolve, reject) => {\n parse.on('error', reject)\n parse.on('end', resolve)\n\n fs.stat(file, (er, stat) => {\n if (er) {\n reject(er)\n } else {\n const stream = new fsm.ReadStream(file, {\n readSize: readSize,\n size: stat.size,\n })\n stream.on('error', reject)\n stream.pipe(parse)\n }\n })\n })\n return p\n}\n\nexport const list = makeCommand(\n listFileSync,\n listFile,\n opt => new Parser(opt) as Parser & { sync: true },\n opt => new Parser(opt),\n (opt, files) => {\n if (files?.length) filesFilter(opt, files)\n if (!opt.noResume) onReadEntryFunction(opt)\n },\n)\n", "// turn tar(1) style args like `C` into the more verbose things like `cwd`\n\nimport { type GzipOptions, type ZlibOptions } from 'minizlib'\nimport { type Stats } from 'node:fs'\nimport { type ReadEntry } from './read-entry.js'\nimport { type WarnData } from './warn-method.js'\nimport { WriteEntry } from './write-entry.js'\n\nconst argmap = new Map<keyof TarOptionsWithAliases, keyof TarOptions>(\n [\n ['C', 'cwd'],\n ['f', 'file'],\n ['z', 'gzip'],\n ['P', 'preservePaths'],\n ['U', 'unlink'],\n ['strip-components', 'strip'],\n ['stripComponents', 'strip'],\n ['keep-newer', 'newer'],\n ['keepNewer', 'newer'],\n ['keep-newer-files', 'newer'],\n ['keepNewerFiles', 'newer'],\n ['k', 'keep'],\n ['keep-existing', 'keep'],\n ['keepExisting', 'keep'],\n ['m', 'noMtime'],\n ['no-mtime', 'noMtime'],\n ['p', 'preserveOwner'],\n ['L', 'follow'],\n ['h', 'follow'],\n ['onentry', 'onReadEntry'],\n ],\n)\n\n/**\n * The options that can be provided to tar commands.\n *\n * Note that some of these are only relevant for certain commands, since\n * they are specific to reading or writing.\n *\n * Aliases are provided in the {@link TarOptionsWithAliases} type.\n */\nexport interface TarOptions {\n //////////////////////////\n // shared options\n\n /**\n * Perform all I/O operations synchronously. If the stream is ended\n * immediately, then it will be processed entirely synchronously.\n */\n sync?: boolean\n\n /**\n * The tar file to be read and/or written. When this is set, a stream\n * is not returned. Asynchronous commands will return a promise indicating\n * when the operation is completed, and synchronous commands will return\n * immediately.\n */\n file?: string\n\n /**\n * Treat warnings as crash-worthy errors. Defaults false.\n */\n strict?: boolean\n\n /**\n * The effective current working directory for this tar command\n */\n cwd?: string\n\n /**\n * When creating a tar archive, this can be used to compress it as well.\n * Set to `true` to use the default gzip options, or customize them as\n * needed.\n *\n * When reading, if this is unset, then the compression status will be\n * inferred from the archive data. This is generally best, unless you are\n * sure of the compression settings in use to create the archive, and want to\n * fail if the archive doesn't match expectations.\n */\n gzip?: boolean | GzipOptions\n\n /**\n * When creating archives, preserve absolute and `..` paths in the archive,\n * rather than sanitizing them under the cwd.\n *\n * When extracting, allow absolute paths, paths containing `..`, and\n * extracting through symbolic links. By default, the root `/` is stripped\n * from absolute paths (eg, turning `/x/y/z` into `x/y/z`), paths containing\n * `..` are not extracted, and any file whose location would be modified by a\n * symbolic link is not extracted.\n *\n * **WARNING** This is almost always unsafe, and must NEVER be used on\n * archives from untrusted sources, such as user input, and every entry must\n * be validated to ensure it is safe to write. Even if the input is not\n * malicious, mistakes can cause a lot of damage!\n */\n preservePaths?: boolean\n\n /**\n * When extracting, do not set the `mtime` value for extracted entries to\n * match the `mtime` in the archive.\n *\n * When creating archives, do not store the `mtime` value in the entry. Note\n * that this prevents properly using other mtime-based features (such as\n * `tar.update` or the `newer` option) with the resulting archive.\n */\n noMtime?: boolean\n\n /**\n * Set to `true` or an object with settings for `zlib.BrotliCompress()` to\n * create a brotli-compressed archive\n *\n * When extracting, this will cause the archive to be treated as a\n * brotli-compressed file if set to `true` or a ZlibOptions object.\n *\n * If set `false`, then brotli options will not be used.\n *\n * If this, the `gzip`, and `zstd` options are left `undefined`, then tar\n * will attempt to infer the brotli compression status, but can only do so\n * based on the filename. If the filename ends in `.tbr` or `.tar.br`, and\n * the first 512 bytes are not a valid tar header, then brotli decompression\n * will be attempted.\n */\n brotli?: boolean | ZlibOptions\n\n /**\n * Set to `true` or an object with settings for `zstd.compress()` to\n * create a zstd-compressed archive\n *\n * When extracting, this will cause the archive to be treated as a\n * zstd-compressed file if set to `true` or a ZlibOptions object.\n *\n * If set `false`, then zstd options will not be used.\n *\n * If this, the `gzip`, and `brotli` options are left `undefined`, then tar\n * will attempt to infer the zstd compression status, but can only do so\n * based on the filename. If the filename ends in `.tzst` or `.tar.zst`, and\n * the first 512 bytes are not a valid tar header, then zstd decompression\n * will be attempted.\n */\n zstd?: boolean | ZlibOptions\n\n /**\n * A function that is called with `(path, stat)` when creating an archive, or\n * `(path, entry)` when extracting. Return true to process the file/entry, or\n * false to exclude it.\n */\n filter?: (path: string, entry: Stats | ReadEntry) => boolean\n\n /**\n * A function that gets called for any warning encountered.\n *\n * Note: if `strict` is set, then the warning will throw, and this method\n * will not be called.\n */\n onwarn?: (code: string, message: string, data: WarnData) => any\n\n //////////////////////////\n // extraction options\n\n /**\n * When extracting, unlink files before creating them. Without this option,\n * tar overwrites existing files, which preserves existing hardlinks. With\n * this option, existing hardlinks will be broken, as will any symlink that\n * would affect the location of an extracted file.\n */\n unlink?: boolean\n\n /**\n * When extracting, strip the specified number of path portions from the\n * entry path. For example, with `{strip: 2}`, the entry `a/b/c/d` would be\n * extracted to `{cwd}/c/d`.\n *\n * Any entry whose entire path is stripped will be excluded.\n */\n strip?: number\n\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n newer?: boolean\n\n /**\n * When extracting, do not overwrite existing files at all.\n */\n keep?: boolean\n\n /**\n * When extracting, set the `uid` and `gid` of extracted entries to the `uid`\n * and `gid` fields in the archive. Defaults to true when run as root, and\n * false otherwise.\n *\n * If false, then files and directories will be set with the owner and group\n * of the user running the process. This is similar to `-p` in `tar(1)`, but\n * ACLs and other system-specific data is never unpacked in this\n * implementation, and modes are set by default already.\n */\n preserveOwner?: boolean\n\n /**\n * The maximum depth of subfolders to extract into. This defaults to 1024.\n * Anything deeper than the limit will raise a warning and skip the entry.\n * Set to `Infinity` to remove the limitation.\n */\n maxDepth?: number\n\n /**\n * When extracting, force all created files and directories, and all\n * implicitly created directories, to be owned by the specified user id,\n * regardless of the `uid` field in the archive.\n *\n * Cannot be used along with `preserveOwner`. Requires also setting the `gid`\n * option.\n */\n uid?: number\n\n /**\n * When extracting, force all created files and directories, and all\n * implicitly created directories, to be owned by the specified group id,\n * regardless of the `gid` field in the archive.\n *\n * Cannot be used along with `preserveOwner`. Requires also setting the `uid`\n * option.\n */\n gid?: number\n\n /**\n * When extracting, provide a function that takes an `entry` object, and\n * returns a stream, or any falsey value. If a stream is provided, then that\n * stream's data will be written instead of the contents of the archive\n * entry. If a falsey value is provided, then the entry is written to disk as\n * normal.\n *\n * To exclude items from extraction, use the `filter` option.\n *\n * Note that using an asynchronous stream type with the `transform` option\n * will cause undefined behavior in synchronous extractions.\n * [MiniPass](http://npm.im/minipass)-based streams are designed for this use\n * case.\n */\n transform?: (entry: ReadEntry) => any\n\n /**\n * Call `chmod()` to ensure that extracted files match the entry's mode\n * field. Without this field set, all mode fields in archive entries are a\n * best effort attempt only.\n *\n * Setting this necessitates a call to the deprecated `process.umask()`\n * method to determine the default umask value, unless a `processUmask`\n * config is provided as well.\n *\n * If not set, tar will attempt to create file system entries with whatever\n * mode is provided, and let the implicit process `umask` apply normally, but\n * if a file already exists to be written to, then its existing mode will not\n * be modified.\n *\n * When setting `chmod: true`, it is highly recommend to set the\n * {@link TarOptions#processUmask} option as well, to avoid the call to the\n * deprecated (and thread-unsafe) `process.umask()` method.\n */\n chmod?: boolean\n\n /**\n * When setting the {@link TarOptions#chmod} option to `true`, you may\n * provide a value here to avoid having to call the deprecated and\n * thread-unsafe `process.umask()` method.\n *\n * This has no effect with `chmod` is not set to true, as mode values are not\n * set explicitly anyway. If `chmod` is set to `true`, and a value is not\n * provided here, then `process.umask()` must be called, which will result in\n * deprecation warnings.\n *\n * The most common values for this are `0o22` (resulting in directories\n * created with mode `0o755` and files with `0o644` by default) and `0o2`\n * (resulting in directores created with mode `0o775` and files `0o664`, so\n * they are group-writable).\n */\n processUmask?: number\n\n //////////////////////////\n // archive creation options\n\n /**\n * When parsing/listing archives, `entry` streams are by default resumed\n * (set into \"flowing\" mode) immediately after the call to `onReadEntry()`.\n * Set `noResume: true` to suppress this behavior.\n *\n * Note that when this is set, the stream will never complete until the\n * data is consumed somehow.\n *\n * Set automatically in extract operations, since the entry is piped to\n * a file system entry right away. Only relevant when parsing.\n */\n noResume?: boolean\n\n /**\n * When creating, updating, or replacing within archives, this method will\n * be called with each WriteEntry that is created.\n */\n onWriteEntry?: (entry: WriteEntry) => any\n\n /**\n * When extracting or listing archives, this method will be called with\n * each entry that is not excluded by a `filter`.\n *\n * Important when listing archives synchronously from a file, because there\n * is otherwise no way to interact with the data!\n */\n onReadEntry?: (entry: ReadEntry) => any\n\n /**\n * Pack the targets of symbolic links rather than the link itself.\n */\n follow?: boolean\n\n /**\n * When creating archives, omit any metadata that is system-specific:\n * `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and\n * `nlink`. Note that `mtime` is still included, because this is necessary\n * for other time-based operations such as `tar.update`. Additionally, `mode`\n * is set to a \"reasonable default\" for mose unix systems, based on an\n * effective `umask` of `0o22`.\n *\n * This also defaults the `portable` option in the gzip configs when creating\n * a compressed archive, in order to produce deterministic archives that are\n * not operating-system specific.\n */\n portable?: boolean\n\n /**\n * When creating archives, do not recursively archive the contents of\n * directories. By default, archiving a directory archives all of its\n * contents as well.\n */\n noDirRecurse?: boolean\n\n /**\n * Suppress Pax extended headers when creating archives. Note that this means\n * long paths and linkpaths will be truncated, and large or negative numeric\n * values may be interpreted incorrectly.\n */\n noPax?: boolean\n\n /**\n * Set to a `Date` object to force a specific `mtime` value for everything\n * written to an archive.\n *\n * This is useful when creating archives that are intended to be\n * deterministic based on their contents, irrespective of the file's last\n * modification time.\n *\n * Overridden by `noMtime`.\n */\n mtime?: Date\n\n /**\n * A path portion to prefix onto the entries added to an archive.\n */\n prefix?: string\n\n /**\n * The mode to set on any created file archive, defaults to 0o666\n * masked by the process umask, often resulting in 0o644.\n *\n * This does *not* affect the mode fields of individual entries, or the\n * mode status of extracted entries on the filesystem.\n */\n mode?: number\n\n //////////////////////////\n // internal options\n\n /**\n * A cache of mtime values, to avoid having to stat the same file repeatedly.\n *\n * @internal\n */\n mtimeCache?: Map<string, Date>\n\n /**\n * maximum buffer size for `fs.read()` operations.\n *\n * @internal\n */\n maxReadSize?: number\n\n /**\n * Filter modes of entries being unpacked, like `process.umask()`\n *\n * @internal\n */\n umask?: number\n\n /**\n * Default mode for directories. Used for all implicitly created directories,\n * and any directories in the archive that do not have a mode field.\n *\n * @internal\n */\n dmode?: number\n\n /**\n * default mode for files\n *\n * @internal\n */\n fmode?: number\n\n /**\n * Map that tracks which directories already exist, for extraction\n *\n * @internal\n */\n dirCache?: Map<string, boolean>\n /**\n * maximum supported size of meta entries. Defaults to 1MB\n *\n * @internal\n */\n maxMetaEntrySize?: number\n\n /**\n * A Map object containing the device and inode value for any file whose\n * `nlink` value is greater than 1, to identify hard links when creating\n * archives.\n *\n * @internal\n */\n linkCache?: Map<LinkCacheKey, string>\n\n /**\n * A map object containing the results of `fs.readdir()` calls.\n *\n * @internal\n */\n readdirCache?: Map<string, string[]>\n\n /**\n * A cache of all `lstat` results, for use in creating archives.\n *\n * @internal\n */\n statCache?: Map<string, Stats>\n\n /**\n * Number of concurrent jobs to run when creating archives.\n *\n * Defaults to 4.\n *\n * @internal\n */\n jobs?: number\n\n /**\n * Automatically set to true on Windows systems.\n *\n * When extracting, causes behavior where filenames containing `<|>?:`\n * characters are converted to windows-compatible escape sequences in the\n * created filesystem entries.\n *\n * When packing, causes behavior where paths replace `\\` with `/`, and\n * filenames containing the windows-compatible escaped forms of `<|>?:` are\n * converted to actual `<|>?:` characters in the archive.\n *\n * @internal\n */\n win32?: boolean\n\n /**\n * For `WriteEntry` objects, the absolute path to the entry on the\n * filesystem. By default, this is `resolve(cwd, entry.path)`, but it can be\n * overridden explicitly.\n *\n * @internal\n */\n absolute?: string\n\n /**\n * Used with Parser stream interface, to attach and take over when the\n * stream is completely parsed. If this is set, then the prefinish,\n * finish, and end events will not fire, and are the responsibility of\n * the ondone method to emit properly.\n *\n * @internal\n */\n ondone?: () => void\n\n /**\n * Mostly for testing, but potentially useful in some cases.\n * Forcibly trigger a chown on every entry, no matter what.\n */\n forceChown?: boolean\n\n /**\n * ambiguous deprecated name for {@link onReadEntry}\n *\n * @deprecated\n */\n onentry?: (entry: ReadEntry) => any\n}\n\nexport type TarOptionsSync = TarOptions & { sync: true }\nexport type TarOptionsAsync = TarOptions & { sync?: false }\nexport type TarOptionsFile = TarOptions & { file: string }\nexport type TarOptionsNoFile = TarOptions & { file?: undefined }\nexport type TarOptionsSyncFile = TarOptionsSync & TarOptionsFile\nexport type TarOptionsAsyncFile = TarOptionsAsync & TarOptionsFile\nexport type TarOptionsSyncNoFile = TarOptionsSync & TarOptionsNoFile\nexport type TarOptionsAsyncNoFile = TarOptionsAsync & TarOptionsNoFile\n\nexport type LinkCacheKey = `${number}:${number}`\n\nexport interface TarOptionsWithAliases extends TarOptions {\n /**\n * The effective current working directory for this tar command\n */\n C?: TarOptions['cwd']\n /**\n * The tar file to be read and/or written. When this is set, a stream\n * is not returned. Asynchronous commands will return a promise indicating\n * when the operation is completed, and synchronous commands will return\n * immediately.\n */\n f?: TarOptions['file']\n /**\n * When creating a tar archive, this can be used to compress it as well.\n * Set to `true` to use the default gzip options, or customize them as\n * needed.\n *\n * When reading, if this is unset, then the compression status will be\n * inferred from the archive data. This is generally best, unless you are\n * sure of the compression settings in use to create the archive, and want to\n * fail if the archive doesn't match expectations.\n */\n z?: TarOptions['gzip']\n /**\n * When creating archives, preserve absolute and `..` paths in the archive,\n * rather than sanitizing them under the cwd.\n *\n * When extracting, allow absolute paths, paths containing `..`, and\n * extracting through symbolic links. By default, the root `/` is stripped\n * from absolute paths (eg, turning `/x/y/z` into `x/y/z`), paths containing\n * `..` are not extracted, and any file whose location would be modified by a\n * symbolic link is not extracted.\n *\n * **WARNING** This is almost always unsafe, and must NEVER be used on\n * archives from untrusted sources, such as user input, and every entry must\n * be validated to ensure it is safe to write. Even if the input is not\n * malicious, mistakes can cause a lot of damage!\n */\n P?: TarOptions['preservePaths']\n /**\n * When extracting, unlink files before creating them. Without this option,\n * tar overwrites existing files, which preserves existing hardlinks. With\n * this option, existing hardlinks will be broken, as will any symlink that\n * would affect the location of an extracted file.\n */\n U?: TarOptions['unlink']\n /**\n * When extracting, strip the specified number of path portions from the\n * entry path. For example, with `{strip: 2}`, the entry `a/b/c/d` would be\n * extracted to `{cwd}/c/d`.\n */\n 'strip-components'?: TarOptions['strip']\n /**\n * When extracting, strip the specified number of path portions from the\n * entry path. For example, with `{strip: 2}`, the entry `a/b/c/d` would be\n * extracted to `{cwd}/c/d`.\n */\n stripComponents?: TarOptions['strip']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n 'keep-newer'?: TarOptions['newer']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n keepNewer?: TarOptions['newer']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n 'keep-newer-files'?: TarOptions['newer']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n keepNewerFiles?: TarOptions['newer']\n /**\n * When extracting, do not overwrite existing files at all.\n */\n k?: TarOptions['keep']\n /**\n * When extracting, do not overwrite existing files at all.\n */\n 'keep-existing'?: TarOptions['keep']\n /**\n * When extracting, do not overwrite existing files at all.\n */\n keepExisting?: TarOptions['keep']\n /**\n * When extracting, do not set the `mtime` value for extracted entries to\n * match the `mtime` in the archive.\n *\n * When creating archives, do not store the `mtime` value in the entry. Note\n * that this prevents properly using other mtime-based features (such as\n * `tar.update` or the `newer` option) with the resulting archive.\n */\n m?: TarOptions['noMtime']\n /**\n * When extracting, do not set the `mtime` value for extracted entries to\n * match the `mtime` in the archive.\n *\n * When creating archives, do not store the `mtime` value in the entry. Note\n * that this prevents properly using other mtime-based features (such as\n * `tar.update` or the `newer` option) with the resulting archive.\n */\n 'no-mtime'?: TarOptions['noMtime']\n /**\n * When extracting, set the `uid` and `gid` of extracted entries to the `uid`\n * and `gid` fields in the archive. Defaults to true when run as root, and\n * false otherwise.\n *\n * If false, then files and directories will be set with the owner and group\n * of the user running the process. This is similar to `-p` in `tar(1)`, but\n * ACLs and other system-specific data is never unpacked in this\n * implementation, and modes are set by default already.\n */\n p?: TarOptions['preserveOwner']\n /**\n * Pack the targets of symbolic links rather than the link itself.\n */\n L?: TarOptions['follow']\n /**\n * Pack the targets of symbolic links rather than the link itself.\n */\n h?: TarOptions['follow']\n\n /**\n * Deprecated option. Set explicitly false to set `chmod: true`. Ignored\n * if {@link TarOptions#chmod} is set to any boolean value.\n *\n * @deprecated\n */\n noChmod?: boolean\n}\n\nexport type TarOptionsWithAliasesSync = TarOptionsWithAliases & {\n sync: true\n}\nexport type TarOptionsWithAliasesAsync = TarOptionsWithAliases & {\n sync?: false\n}\nexport type TarOptionsWithAliasesFile =\n | (TarOptionsWithAliases & {\n file: string\n })\n | (TarOptionsWithAliases & { f: string })\nexport type TarOptionsWithAliasesSyncFile =\n TarOptionsWithAliasesSync & TarOptionsWithAliasesFile\nexport type TarOptionsWithAliasesAsyncFile =\n TarOptionsWithAliasesAsync & TarOptionsWithAliasesFile\n\nexport type TarOptionsWithAliasesNoFile = TarOptionsWithAliases & {\n f?: undefined\n file?: undefined\n}\n\nexport type TarOptionsWithAliasesSyncNoFile =\n TarOptionsWithAliasesSync & TarOptionsWithAliasesNoFile\nexport type TarOptionsWithAliasesAsyncNoFile =\n TarOptionsWithAliasesAsync & TarOptionsWithAliasesNoFile\n\nexport const isSyncFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsSyncFile => !!o.sync && !!o.file\nexport const isAsyncFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsAsyncFile => !o.sync && !!o.file\nexport const isSyncNoFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsSyncNoFile => !!o.sync && !o.file\nexport const isAsyncNoFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsAsyncNoFile => !o.sync && !o.file\nexport const isSync = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsSync => !!o.sync\nexport const isAsync = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsAsync => !o.sync\nexport const isFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsFile => !!o.file\nexport const isNoFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsNoFile => !o.file\n\nconst dealiasKey = (\n k: keyof TarOptionsWithAliases,\n): keyof TarOptions => {\n const d = argmap.get(k)\n if (d) return d\n return k as keyof TarOptions\n}\n\nexport const dealias = (\n opt: TarOptionsWithAliases = {},\n): TarOptions => {\n if (!opt) return {}\n const result: Record<string, any> = {}\n for (const [key, v] of Object.entries(opt) as [\n keyof TarOptionsWithAliases,\n any,\n ][]) {\n // TS doesn't know that aliases are going to always be the same type\n const k = dealiasKey(key)\n result[k] = v\n }\n // affordance for deprecated noChmod -> chmod\n if (result.chmod === undefined && result.noChmod === false) {\n result.chmod = true\n }\n delete result.noChmod\n return result as TarOptions\n}\n", "import {\n dealias,\n isAsyncFile,\n isAsyncNoFile,\n isSyncFile,\n isSyncNoFile,\n TarOptions,\n TarOptionsAsyncFile,\n TarOptionsAsyncNoFile,\n TarOptionsSyncFile,\n TarOptionsSyncNoFile,\n TarOptionsWithAliases,\n TarOptionsWithAliasesAsync,\n TarOptionsWithAliasesAsyncFile,\n TarOptionsWithAliasesAsyncNoFile,\n TarOptionsWithAliasesFile,\n TarOptionsWithAliasesNoFile,\n TarOptionsWithAliasesSync,\n TarOptionsWithAliasesSyncFile,\n TarOptionsWithAliasesSyncNoFile,\n} from './options.js'\n\nexport type CB = (er?: Error) => any\n\nexport type TarCommand<\n AsyncClass,\n SyncClass extends { sync: true },\n> = {\n // async and no file specified\n (): AsyncClass\n (opt: TarOptionsWithAliasesAsyncNoFile): AsyncClass\n (entries: string[]): AsyncClass\n (\n opt: TarOptionsWithAliasesAsyncNoFile,\n entries: string[],\n ): AsyncClass\n} & {\n // sync and no file\n (opt: TarOptionsWithAliasesSyncNoFile): SyncClass\n (opt: TarOptionsWithAliasesSyncNoFile, entries: string[]): SyncClass\n} & {\n // async and file\n (opt: TarOptionsWithAliasesAsyncFile): Promise<void>\n (\n opt: TarOptionsWithAliasesAsyncFile,\n entries: string[],\n ): Promise<void>\n (opt: TarOptionsWithAliasesAsyncFile, cb: CB): Promise<void>\n (\n opt: TarOptionsWithAliasesAsyncFile,\n entries: string[],\n cb: CB,\n ): Promise<void>\n} & {\n // sync and file\n (opt: TarOptionsWithAliasesSyncFile): void\n (opt: TarOptionsWithAliasesSyncFile, entries: string[]): void\n} & {\n // sync, maybe file\n (opt: TarOptionsWithAliasesSync): typeof opt extends (\n TarOptionsWithAliasesFile\n ) ?\n void\n : typeof opt extends TarOptionsWithAliasesNoFile ? SyncClass\n : void | SyncClass\n (\n opt: TarOptionsWithAliasesSync,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesFile ? void\n : typeof opt extends TarOptionsWithAliasesNoFile ? SyncClass\n : void | SyncClass\n} & {\n // async, maybe file\n (opt: TarOptionsWithAliasesAsync): typeof opt extends (\n TarOptionsWithAliasesFile\n ) ?\n Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ? AsyncClass\n : Promise<void> | AsyncClass\n (\n opt: TarOptionsWithAliasesAsync,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesFile ? Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ? AsyncClass\n : Promise<void> | AsyncClass\n (opt: TarOptionsWithAliasesAsync, cb: CB): Promise<void>\n (\n opt: TarOptionsWithAliasesAsync,\n entries: string[],\n cb: CB,\n ): typeof opt extends TarOptionsWithAliasesFile ? Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ? never\n : Promise<void>\n} & {\n // maybe sync, file\n (opt: TarOptionsWithAliasesFile): Promise<void> | void\n (\n opt: TarOptionsWithAliasesFile,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesSync ? void\n : typeof opt extends TarOptionsWithAliasesAsync ? Promise<void>\n : Promise<void> | void\n (opt: TarOptionsWithAliasesFile, cb: CB): Promise<void>\n (\n opt: TarOptionsWithAliasesFile,\n entries: string[],\n cb: CB,\n ): typeof opt extends TarOptionsWithAliasesSync ? never\n : typeof opt extends TarOptionsWithAliasesAsync ? Promise<void>\n : Promise<void>\n} & {\n // maybe sync, no file\n (opt: TarOptionsWithAliasesNoFile): typeof opt extends (\n TarOptionsWithAliasesSync\n ) ?\n SyncClass\n : typeof opt extends TarOptionsWithAliasesAsync ? AsyncClass\n : SyncClass | AsyncClass\n (\n opt: TarOptionsWithAliasesNoFile,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesSync ? SyncClass\n : typeof opt extends TarOptionsWithAliasesAsync ? AsyncClass\n : SyncClass | AsyncClass\n} & {\n // maybe sync, maybe file\n (opt: TarOptionsWithAliases): typeof opt extends (\n TarOptionsWithAliasesFile\n ) ?\n typeof opt extends TarOptionsWithAliasesSync ? void\n : typeof opt extends TarOptionsWithAliasesAsync ? Promise<void>\n : void | Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ?\n typeof opt extends TarOptionsWithAliasesSync ? SyncClass\n : typeof opt extends TarOptionsWithAliasesAsync ? AsyncClass\n : SyncClass | AsyncClass\n : typeof opt extends TarOptionsWithAliasesSync ? SyncClass | void\n : typeof opt extends TarOptionsWithAliasesAsync ?\n AsyncClass | Promise<void>\n : SyncClass | void | AsyncClass | Promise<void>\n} & {\n // extras\n syncFile: (opt: TarOptionsSyncFile, entries: string[]) => void\n asyncFile: (\n opt: TarOptionsAsyncFile,\n entries: string[],\n cb?: CB,\n ) => Promise<void>\n syncNoFile: (\n opt: TarOptionsSyncNoFile,\n entries: string[],\n ) => SyncClass\n asyncNoFile: (\n opt: TarOptionsAsyncNoFile,\n entries: string[],\n ) => AsyncClass\n validate?: (opt: TarOptions, entries?: string[]) => void\n}\n\nexport const makeCommand = <\n AsyncClass,\n SyncClass extends { sync: true },\n>(\n syncFile: (opt: TarOptionsSyncFile, entries: string[]) => void,\n asyncFile: (\n opt: TarOptionsAsyncFile,\n entries: string[],\n cb?: CB,\n ) => Promise<void>,\n syncNoFile: (\n opt: TarOptionsSyncNoFile,\n entries: string[],\n ) => SyncClass,\n asyncNoFile: (\n opt: TarOptionsAsyncNoFile,\n entries: string[],\n ) => AsyncClass,\n validate?: (opt: TarOptions, entries?: string[]) => void,\n): TarCommand<AsyncClass, SyncClass> => {\n return Object.assign(\n (\n opt_: TarOptionsWithAliases | string[] = [],\n entries?: string[] | CB,\n cb?: CB,\n ) => {\n if (Array.isArray(opt_)) {\n entries = opt_\n opt_ = {}\n }\n\n if (typeof entries === 'function') {\n cb = entries\n entries = undefined\n }\n\n if (!entries) {\n entries = []\n } else {\n entries = Array.from(entries)\n }\n\n const opt = dealias(opt_)\n\n validate?.(opt, entries)\n\n if (isSyncFile(opt)) {\n if (typeof cb === 'function') {\n throw new TypeError(\n 'callback not supported for sync tar functions',\n )\n }\n return syncFile(opt, entries)\n } else if (isAsyncFile(opt)) {\n const p = asyncFile(opt, entries)\n // weirdness to make TS happy\n const c = cb ? cb : undefined\n return c ? p.then(() => c(), c) : p\n } else if (isSyncNoFile(opt)) {\n if (typeof cb === 'function') {\n throw new TypeError(\n 'callback not supported for sync tar functions',\n )\n }\n return syncNoFile(opt, entries)\n } else if (isAsyncNoFile(opt)) {\n if (typeof cb === 'function') {\n throw new TypeError(\n 'callback only supported with file option',\n )\n }\n return asyncNoFile(opt, entries)\n /* c8 ignore start */\n } else {\n throw new Error('impossible options??')\n }\n /* c8 ignore stop */\n },\n {\n syncFile,\n asyncFile,\n syncNoFile,\n asyncNoFile,\n validate,\n },\n ) as TarCommand<AsyncClass, SyncClass>\n}\n", "// this[BUFFER] is the remainder of a chunk if we're waiting for\n// the full 512 bytes of a header to come in. We will Buffer.concat()\n// it to the next write(), which is a mem copy, but a small one.\n//\n// this[QUEUE] is a list of entries that haven't been emitted\n// yet this can only get filled up if the user keeps write()ing after\n// a write() returns false, or does a write() with more than one entry\n//\n// We don't buffer chunks, we always parse them and either create an\n// entry, or push it into the active entry. The ReadEntry class knows\n// to throw data away if .ignore=true\n//\n// Shift entry off the buffer when it emits 'end', and emit 'entry' for\n// the next one in the list.\n//\n// At any time, we're pushing body chunks into the entry at WRITEENTRY,\n// and waiting for 'end' on the entry at READENTRY\n//\n// ignored entries get .resume() called on them straight away\n\nimport { EventEmitter as EE } from 'events'\nimport { BrotliDecompress, Unzip, ZstdDecompress } from 'minizlib'\nimport { Header } from './header.js'\nimport { TarOptions } from './options.js'\nimport { Pax } from './pax.js'\nimport { ReadEntry } from './read-entry.js'\nimport {\n warnMethod,\n type WarnData,\n type Warner,\n} from './warn-method.js'\n\nconst maxMetaEntrySize = 1024 * 1024\nconst gzipHeader = Buffer.from([0x1f, 0x8b])\nconst zstdHeader = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])\nconst ZIP_HEADER_LEN = Math.max(gzipHeader.length, zstdHeader.length)\n\nconst STATE = Symbol('state')\nconst WRITEENTRY = Symbol('writeEntry')\nconst READENTRY = Symbol('readEntry')\nconst NEXTENTRY = Symbol('nextEntry')\nconst PROCESSENTRY = Symbol('processEntry')\nconst EX = Symbol('extendedHeader')\nconst GEX = Symbol('globalExtendedHeader')\nconst META = Symbol('meta')\nconst EMITMETA = Symbol('emitMeta')\nconst BUFFER = Symbol('buffer')\nconst QUEUE = Symbol('queue')\nconst ENDED = Symbol('ended')\nconst EMITTEDEND = Symbol('emittedEnd')\nconst EMIT = Symbol('emit')\nconst UNZIP = Symbol('unzip')\nconst CONSUMECHUNK = Symbol('consumeChunk')\nconst CONSUMECHUNKSUB = Symbol('consumeChunkSub')\nconst CONSUMEBODY = Symbol('consumeBody')\nconst CONSUMEMETA = Symbol('consumeMeta')\nconst CONSUMEHEADER = Symbol('consumeHeader')\nconst CONSUMING = Symbol('consuming')\nconst BUFFERCONCAT = Symbol('bufferConcat')\nconst MAYBEEND = Symbol('maybeEnd')\nconst WRITING = Symbol('writing')\nconst ABORTED = Symbol('aborted')\nconst DONE = Symbol('onDone')\nconst SAW_VALID_ENTRY = Symbol('sawValidEntry')\nconst SAW_NULL_BLOCK = Symbol('sawNullBlock')\nconst SAW_EOF = Symbol('sawEOF')\nconst CLOSESTREAM = Symbol('closeStream')\n\nconst noop = () => true\n\nexport type State = 'begin' | 'header' | 'ignore' | 'meta' | 'body'\n\nexport class Parser extends EE implements Warner {\n file: string\n strict: boolean\n maxMetaEntrySize: number\n filter: Exclude<TarOptions['filter'], undefined>\n brotli?: TarOptions['brotli']\n zstd?: TarOptions['zstd']\n\n writable: true = true\n readable: false = false;\n\n [QUEUE]: (ReadEntry | [string | symbol, any, any])[] = [];\n [BUFFER]?: Buffer;\n [READENTRY]?: ReadEntry;\n [WRITEENTRY]?: ReadEntry;\n [STATE]: State = 'begin';\n [META]: string = '';\n [EX]?: Pax;\n [GEX]?: Pax;\n [ENDED]: boolean = false;\n [UNZIP]?: false | Unzip | BrotliDecompress | ZstdDecompress;\n [ABORTED]: boolean = false;\n [SAW_VALID_ENTRY]?: boolean;\n [SAW_NULL_BLOCK]: boolean = false;\n [SAW_EOF]: boolean = false;\n [WRITING]: boolean = false;\n [CONSUMING]: boolean = false;\n [EMITTEDEND]: boolean = false\n\n constructor(opt: TarOptions = {}) {\n super()\n\n this.file = opt.file || ''\n\n // these BADARCHIVE errors can't be detected early. listen on DONE.\n this.on(DONE, () => {\n if (\n this[STATE] === 'begin' ||\n this[SAW_VALID_ENTRY] === false\n ) {\n // either less than 1 block of data, or all entries were invalid.\n // Either way, probably not even a tarball.\n this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format')\n }\n })\n\n if (opt.ondone) {\n this.on(DONE, opt.ondone)\n } else {\n this.on(DONE, () => {\n this.emit('prefinish')\n this.emit('finish')\n this.emit('end')\n })\n }\n\n this.strict = !!opt.strict\n this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize\n this.filter = typeof opt.filter === 'function' ? opt.filter : noop\n // Unlike gzip, brotli doesn't have any magic bytes to identify it\n // Users need to explicitly tell us they're extracting a brotli file\n // Or we infer from the file extension\n const isTBR =\n opt.file &&\n (opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr'))\n // if it's a tbr file it MIGHT be brotli, but we don't know until\n // we look at it and verify it's not a valid tar file.\n this.brotli =\n !(opt.gzip || opt.zstd) && opt.brotli !== undefined ? opt.brotli\n : isTBR ? undefined\n : false\n\n // zstd has magic bytes to identify it, but we also support explicit options\n // and file extension detection\n const isTZST =\n opt.file &&\n (opt.file.endsWith('.tar.zst') || opt.file.endsWith('.tzst'))\n this.zstd =\n !(opt.gzip || opt.brotli) && opt.zstd !== undefined ? opt.zstd\n : isTZST ? true\n : undefined\n\n // have to set this so that streams are ok piping into it\n this.on('end', () => this[CLOSESTREAM]())\n\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n if (typeof opt.onReadEntry === 'function') {\n this.on('entry', opt.onReadEntry)\n }\n }\n\n warn(\n code: string,\n message: string | Error,\n data: WarnData = {},\n ): void {\n warnMethod(this, code, message, data)\n }\n\n [CONSUMEHEADER](chunk: Buffer, position: number) {\n if (this[SAW_VALID_ENTRY] === undefined) {\n this[SAW_VALID_ENTRY] = false\n }\n let header\n try {\n header = new Header(chunk, position, this[EX], this[GEX])\n } catch (er) {\n return this.warn('TAR_ENTRY_INVALID', er as Error)\n }\n\n if (header.nullBlock) {\n if (this[SAW_NULL_BLOCK]) {\n this[SAW_EOF] = true\n // ending an archive with no entries. pointless, but legal.\n if (this[STATE] === 'begin') {\n this[STATE] = 'header'\n }\n this[EMIT]('eof')\n } else {\n this[SAW_NULL_BLOCK] = true\n this[EMIT]('nullBlock')\n }\n } else {\n this[SAW_NULL_BLOCK] = false\n if (!header.cksumValid) {\n this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header })\n } else if (!header.path) {\n this.warn('TAR_ENTRY_INVALID', 'path is required', { header })\n } else {\n const type = header.type\n if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) {\n this.warn('TAR_ENTRY_INVALID', 'linkpath required', {\n header,\n })\n } else if (\n !/^(Symbolic)?Link$/.test(type) &&\n !/^(Global)?ExtendedHeader$/.test(type) &&\n header.linkpath\n ) {\n this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {\n header,\n })\n } else {\n const entry = (this[WRITEENTRY] = new ReadEntry(\n header,\n this[EX],\n this[GEX],\n ))\n\n // we do this for meta & ignored entries as well, because they\n // are still valid tar, or else we wouldn't know to ignore them\n if (!this[SAW_VALID_ENTRY]) {\n if (entry.remain) {\n // this might be the one!\n const onend = () => {\n if (!entry.invalid) {\n this[SAW_VALID_ENTRY] = true\n }\n }\n entry.on('end', onend)\n } else {\n this[SAW_VALID_ENTRY] = true\n }\n }\n\n if (entry.meta) {\n if (entry.size > this.maxMetaEntrySize) {\n entry.ignore = true\n this[EMIT]('ignoredEntry', entry)\n this[STATE] = 'ignore'\n entry.resume()\n } else if (entry.size > 0) {\n this[META] = ''\n entry.on('data', c => (this[META] += c))\n this[STATE] = 'meta'\n }\n } else {\n this[EX] = undefined\n entry.ignore =\n entry.ignore || !this.filter(entry.path, entry)\n\n if (entry.ignore) {\n // probably valid, just not something we care about\n this[EMIT]('ignoredEntry', entry)\n this[STATE] = entry.remain ? 'ignore' : 'header'\n entry.resume()\n } else {\n if (entry.remain) {\n this[STATE] = 'body'\n } else {\n this[STATE] = 'header'\n entry.end()\n }\n\n if (!this[READENTRY]) {\n this[QUEUE].push(entry)\n this[NEXTENTRY]()\n } else {\n this[QUEUE].push(entry)\n }\n }\n }\n }\n }\n }\n }\n\n [CLOSESTREAM]() {\n queueMicrotask(() => this.emit('close'))\n }\n\n [PROCESSENTRY](entry?: ReadEntry | [string | symbol, any, any]) {\n let go = true\n\n if (!entry) {\n this[READENTRY] = undefined\n go = false\n } else if (Array.isArray(entry)) {\n const [ev, ...args]: [string | symbol, any, any] = entry\n this.emit(ev, ...args)\n } else {\n this[READENTRY] = entry\n this.emit('entry', entry)\n if (!entry.emittedEnd) {\n entry.on('end', () => this[NEXTENTRY]())\n go = false\n }\n }\n\n return go\n }\n\n [NEXTENTRY]() {\n do {} while (this[PROCESSENTRY](this[QUEUE].shift()))\n\n if (!this[QUEUE].length) {\n // At this point, there's nothing in the queue, but we may have an\n // entry which is being consumed (readEntry).\n // If we don't, then we definitely can handle more data.\n // If we do, and either it's flowing, or it has never had any data\n // written to it, then it needs more.\n // The only other possibility is that it has returned false from a\n // write() call, so we wait for the next drain to continue.\n const re = this[READENTRY]\n const drainNow = !re || re.flowing || re.size === re.remain\n if (drainNow) {\n if (!this[WRITING]) {\n this.emit('drain')\n }\n } else {\n re.once('drain', () => this.emit('drain'))\n }\n }\n }\n\n [CONSUMEBODY](chunk: Buffer, position: number) {\n // write up to but no more than writeEntry.blockRemain\n const entry = this[WRITEENTRY]\n /* c8 ignore start */\n if (!entry) {\n throw new Error('attempt to consume body without entry??')\n }\n const br = entry.blockRemain ?? 0\n /* c8 ignore stop */\n const c =\n br >= chunk.length && position === 0 ?\n chunk\n : chunk.subarray(position, position + br)\n\n entry.write(c)\n\n if (!entry.blockRemain) {\n this[STATE] = 'header'\n this[WRITEENTRY] = undefined\n entry.end()\n }\n\n return c.length\n }\n\n [CONSUMEMETA](chunk: Buffer, position: number) {\n const entry = this[WRITEENTRY]\n const ret = this[CONSUMEBODY](chunk, position)\n\n // if we finished, then the entry is reset\n if (!this[WRITEENTRY] && entry) {\n this[EMITMETA](entry)\n }\n\n return ret\n }\n\n [EMIT](ev: string | symbol, data?: any, extra?: any) {\n if (!this[QUEUE].length && !this[READENTRY]) {\n this.emit(ev, data, extra)\n } else {\n this[QUEUE].push([ev, data, extra])\n }\n }\n\n [EMITMETA](entry: ReadEntry) {\n this[EMIT]('meta', this[META])\n switch (entry.type) {\n case 'ExtendedHeader':\n case 'OldExtendedHeader':\n this[EX] = Pax.parse(this[META], this[EX], false)\n break\n\n case 'GlobalExtendedHeader':\n this[GEX] = Pax.parse(this[META], this[GEX], true)\n break\n\n case 'NextFileHasLongPath':\n case 'OldGnuLongPath': {\n const ex = this[EX] ?? Object.create(null)\n this[EX] = ex\n ex.path = this[META].replace(/\\0.*/, '')\n break\n }\n\n case 'NextFileHasLongLinkpath': {\n const ex = this[EX] || Object.create(null)\n this[EX] = ex\n ex.linkpath = this[META].replace(/\\0.*/, '')\n break\n }\n\n /* c8 ignore start */\n default:\n throw new Error('unknown meta: ' + entry.type)\n /* c8 ignore stop */\n }\n }\n\n abort(error: Error) {\n this[ABORTED] = true\n this.emit('abort', error)\n // always throws, even in non-strict mode\n this.warn('TAR_ABORT', error, { recoverable: false })\n }\n\n write(\n buffer: Uint8Array | string,\n cb?: (err?: Error | null) => void,\n ): boolean\n write(\n str: string,\n encoding?: BufferEncoding,\n cb?: (err?: Error | null) => void,\n ): boolean\n write(\n chunk: Buffer | string,\n encoding?: BufferEncoding | (() => any),\n cb?: () => any,\n ): boolean {\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(\n chunk,\n /* c8 ignore next */\n typeof encoding === 'string' ? encoding : 'utf8',\n )\n }\n if (this[ABORTED]) {\n /* c8 ignore next */\n cb?.()\n return false\n }\n\n // first write, might be gzipped, zstd, or brotli compressed\n const needSniff =\n this[UNZIP] === undefined ||\n (this.brotli === undefined && this[UNZIP] === false)\n if (needSniff && chunk) {\n if (this[BUFFER]) {\n chunk = Buffer.concat([this[BUFFER], chunk])\n this[BUFFER] = undefined\n }\n if (chunk.length < ZIP_HEADER_LEN) {\n this[BUFFER] = chunk\n /* c8 ignore next */\n cb?.()\n return true\n }\n\n // look for gzip header\n for (\n let i = 0;\n this[UNZIP] === undefined && i < gzipHeader.length;\n i++\n ) {\n if (chunk[i] !== gzipHeader[i]) {\n this[UNZIP] = false\n }\n }\n\n // look for zstd header if gzip header not found\n let isZstd = false\n if (this[UNZIP] === false && this.zstd !== false) {\n isZstd = true\n for (let i = 0; i < zstdHeader.length; i++) {\n if (chunk[i] !== zstdHeader[i]) {\n isZstd = false\n break\n }\n }\n }\n\n const maybeBrotli = this.brotli === undefined && !isZstd\n if (this[UNZIP] === false && maybeBrotli) {\n // read the first header to see if it's a valid tar file. If so,\n // we can safely assume that it's not actually brotli, despite the\n // .tbr or .tar.br file extension.\n // if we ended before getting a full chunk, yes, def brotli\n if (chunk.length < 512) {\n if (this[ENDED]) {\n this.brotli = true\n } else {\n this[BUFFER] = chunk\n /* c8 ignore next */\n cb?.()\n return true\n }\n } else {\n // if it's tar, it's pretty reliably not brotli, chances of\n // that happening are astronomical.\n try {\n new Header(chunk.subarray(0, 512))\n this.brotli = false\n } catch (_) {\n this.brotli = true\n }\n }\n }\n\n if (\n this[UNZIP] === undefined ||\n (this[UNZIP] === false && (this.brotli || isZstd))\n ) {\n const ended = this[ENDED]\n this[ENDED] = false\n this[UNZIP] =\n this[UNZIP] === undefined ? new Unzip({})\n : isZstd ? new ZstdDecompress({})\n : new BrotliDecompress({})\n this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk))\n this[UNZIP].on('error', er => this.abort(er as Error))\n this[UNZIP].on('end', () => {\n this[ENDED] = true\n this[CONSUMECHUNK]()\n })\n this[WRITING] = true\n const ret = !!this[UNZIP][ended ? 'end' : 'write'](chunk)\n this[WRITING] = false\n cb?.()\n return ret\n }\n }\n\n this[WRITING] = true\n if (this[UNZIP]) {\n this[UNZIP].write(chunk)\n } else {\n this[CONSUMECHUNK](chunk)\n }\n this[WRITING] = false\n\n // return false if there's a queue, or if the current entry isn't flowing\n const ret =\n this[QUEUE].length ? false\n : this[READENTRY] ? this[READENTRY].flowing\n : true\n\n // if we have no queue, then that means a clogged READENTRY\n if (!ret && !this[QUEUE].length) {\n this[READENTRY]?.once('drain', () => this.emit('drain'))\n }\n\n /* c8 ignore next */\n cb?.()\n return ret\n }\n\n [BUFFERCONCAT](c: Buffer) {\n if (c && !this[ABORTED]) {\n this[BUFFER] =\n this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c\n }\n }\n\n [MAYBEEND]() {\n if (\n this[ENDED] &&\n !this[EMITTEDEND] &&\n !this[ABORTED] &&\n !this[CONSUMING]\n ) {\n this[EMITTEDEND] = true\n const entry = this[WRITEENTRY]\n if (entry && entry.blockRemain) {\n // truncated, likely a damaged file\n const have = this[BUFFER] ? this[BUFFER].length : 0\n this.warn(\n 'TAR_BAD_ARCHIVE',\n `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`,\n { entry },\n )\n if (this[BUFFER]) {\n entry.write(this[BUFFER])\n }\n entry.end()\n }\n this[EMIT](DONE)\n }\n }\n\n [CONSUMECHUNK](chunk?: Buffer) {\n if (this[CONSUMING] && chunk) {\n this[BUFFERCONCAT](chunk)\n } else if (!chunk && !this[BUFFER]) {\n this[MAYBEEND]()\n } else if (chunk) {\n this[CONSUMING] = true\n if (this[BUFFER]) {\n this[BUFFERCONCAT](chunk)\n const c = this[BUFFER]\n this[BUFFER] = undefined\n this[CONSUMECHUNKSUB](c)\n } else {\n this[CONSUMECHUNKSUB](chunk)\n }\n\n while (\n this[BUFFER] &&\n (this[BUFFER] as Buffer)?.length >= 512 &&\n !this[ABORTED] &&\n !this[SAW_EOF]\n ) {\n const c = this[BUFFER]\n this[BUFFER] = undefined\n this[CONSUMECHUNKSUB](c)\n }\n this[CONSUMING] = false\n }\n\n if (!this[BUFFER] || this[ENDED]) {\n this[MAYBEEND]()\n }\n }\n\n [CONSUMECHUNKSUB](chunk: Buffer) {\n // we know that we are in CONSUMING mode, so anything written goes into\n // the buffer. Advance the position and put any remainder in the buffer.\n let position = 0\n const length = chunk.length\n while (\n position + 512 <= length &&\n !this[ABORTED] &&\n !this[SAW_EOF]\n ) {\n switch (this[STATE]) {\n case 'begin':\n case 'header':\n this[CONSUMEHEADER](chunk, position)\n position += 512\n break\n\n case 'ignore':\n case 'body':\n position += this[CONSUMEBODY](chunk, position)\n break\n\n case 'meta':\n position += this[CONSUMEMETA](chunk, position)\n break\n\n /* c8 ignore start */\n default:\n throw new Error('invalid state: ' + this[STATE])\n /* c8 ignore stop */\n }\n }\n\n if (position < length) {\n if (this[BUFFER]) {\n this[BUFFER] = Buffer.concat([\n chunk.subarray(position),\n this[BUFFER],\n ])\n } else {\n this[BUFFER] = chunk.subarray(position)\n }\n }\n }\n\n end(cb?: () => void): this\n end(data: string | Buffer, cb?: () => void): this\n end(str: string, encoding?: BufferEncoding, cb?: () => void): this\n end(\n chunk?: string | Buffer | (() => void),\n encoding?: BufferEncoding | (() => void),\n cb?: () => void,\n ) {\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding)\n }\n if (cb) this.once('finish', cb)\n if (!this[ABORTED]) {\n if (this[UNZIP]) {\n /* c8 ignore start */\n if (chunk) this[UNZIP].write(chunk)\n /* c8 ignore stop */\n this[UNZIP].end()\n } else {\n this[ENDED] = true\n if (this.brotli === undefined || this.zstd === undefined)\n chunk = chunk || Buffer.alloc(0)\n if (chunk) this.write(chunk)\n this[MAYBEEND]()\n }\n }\n return this\n }\n}\n", "import assert from 'assert'\nimport { Buffer } from 'buffer'\nimport { Minipass } from 'minipass'\nimport * as realZlib from 'zlib'\nimport { constants } from './constants.js'\nexport { constants } from './constants.js'\n\nconst OriginalBufferConcat = Buffer.concat\nconst desc = Object.getOwnPropertyDescriptor(Buffer, 'concat')\nconst noop = (args: Buffer[]) => args as unknown as Buffer\nconst passthroughBufferConcat =\n desc?.writable === true || desc?.set !== undefined\n ? (makeNoOp: boolean) => {\n Buffer.concat = makeNoOp ? noop : OriginalBufferConcat\n }\n : (_: boolean) => {}\n\nconst _superWrite = Symbol('_superWrite')\n\nexport class ZlibError extends Error {\n code?: string\n errno?: number\n constructor(err: NodeJS.ErrnoException | Error, origin?: Function) {\n super('zlib: ' + err.message, { cause: err })\n this.code = (err as NodeJS.ErrnoException).code\n this.errno = (err as NodeJS.ErrnoException).errno\n /* c8 ignore next */\n if (!this.code) this.code = 'ZLIB_ERROR'\n\n this.message = 'zlib: ' + err.message\n Error.captureStackTrace(this, origin ?? this.constructor)\n }\n\n get name() {\n return 'ZlibError'\n }\n}\n\n// the Zlib class they all inherit from\n// This thing manages the queue of requests, and returns\n// true or false if there is anything in the queue when\n// you call the .write() method.\nconst _flushFlag = Symbol('flushFlag')\n\nexport type ChunkWithFlushFlag = Minipass.ContiguousData & {\n [_flushFlag]?: number\n}\n\nexport type ZlibBaseOptions = Minipass.Options<Minipass.ContiguousData> & {\n flush?: number\n finishFlush?: number\n fullFlushFlag?: number\n}\n\nexport type ZlibHandle =\n | realZlib.Gzip\n | realZlib.Gunzip\n | realZlib.Deflate\n | realZlib.Inflate\n | realZlib.DeflateRaw\n | realZlib.InflateRaw\n | realZlib.BrotliCompress\n | realZlib.BrotliDecompress\n | realZlib.ZstdCompress\n | realZlib.ZstdDecompress\nexport type ZlibMode =\n | 'Gzip'\n | 'Gunzip'\n | 'Deflate'\n | 'Inflate'\n | 'DeflateRaw'\n | 'InflateRaw'\n | 'Unzip'\nexport type BrotliMode = 'BrotliCompress' | 'BrotliDecompress'\nexport type ZstdMode = 'ZstdCompress' | 'ZstdDecompress'\n\nabstract class ZlibBase extends Minipass<Buffer, ChunkWithFlushFlag> {\n #sawError: boolean = false\n #ended: boolean = false\n #flushFlag: number\n #finishFlushFlag: number\n #fullFlushFlag: number\n #handle?: ZlibHandle\n #onError: (err: ZlibError) => any\n\n get sawError() {\n return this.#sawError\n }\n get handle() {\n return this.#handle\n }\n /* c8 ignore start */\n get flushFlag() {\n return this.#flushFlag\n }\n /* c8 ignore stop */\n\n constructor(opts: ZlibBaseOptions, mode: ZlibMode | BrotliMode | ZstdMode) {\n if (!opts || typeof opts !== 'object')\n throw new TypeError('invalid options for ZlibBase constructor')\n\n //@ts-ignore\n super(opts)\n\n /* c8 ignore start */\n this.#flushFlag = opts.flush ?? 0\n this.#finishFlushFlag = opts.finishFlush ?? 0\n this.#fullFlushFlag = opts.fullFlushFlag ?? 0\n /* c8 ignore stop */\n\n //@ts-ignore\n if (typeof realZlib[mode] !== 'function') {\n throw new TypeError('Compression method not supported: ' + mode)\n }\n\n // this will throw if any options are invalid for the class selected\n try {\n // @types/node doesn't know that it exports the classes, but they're there\n //@ts-ignore\n this.#handle = new realZlib[mode](opts)\n } catch (er) {\n // make sure that all errors get decorated properly\n throw new ZlibError(er as NodeJS.ErrnoException, this.constructor)\n }\n\n this.#onError = err => {\n // no sense raising multiple errors, since we abort on the first one.\n if (this.#sawError) return\n\n this.#sawError = true\n\n // there is no way to cleanly recover.\n // continuing only obscures problems.\n this.close()\n this.emit('error', err)\n }\n\n this.#handle?.on('error', er => this.#onError(new ZlibError(er)))\n this.once('end', () => this.close)\n }\n\n close() {\n if (this.#handle) {\n this.#handle.close()\n this.#handle = undefined\n this.emit('close')\n }\n }\n\n reset() {\n if (!this.#sawError) {\n assert(this.#handle, 'zlib binding closed')\n //@ts-ignore\n return this.#handle.reset?.()\n }\n }\n\n flush(flushFlag?: number) {\n if (this.ended) return\n\n if (typeof flushFlag !== 'number') flushFlag = this.#fullFlushFlag\n\n this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }))\n }\n\n end(cb?: () => void): this\n end(chunk: ChunkWithFlushFlag, cb?: () => void): this\n end(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): this\n end(\n chunk?: ChunkWithFlushFlag | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n /* c8 ignore start */\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n /* c8 ignore stop */\n if (chunk) {\n if (encoding) this.write(chunk, encoding)\n else this.write(chunk)\n }\n this.flush(this.#finishFlushFlag)\n this.#ended = true\n return super.end(cb)\n }\n\n get ended() {\n return this.#ended\n }\n\n // overridden in the gzip classes to do portable writes\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n return super.write(data)\n }\n\n write(chunk: ChunkWithFlushFlag, cb?: () => void): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n // process the chunk using the sync process\n // then super.write() all the outputted chunks\n if (typeof encoding === 'function')\n (cb = encoding), (encoding = 'utf8')\n\n if (typeof chunk === 'string')\n chunk = Buffer.from(chunk as string, encoding as BufferEncoding)\n\n if (this.#sawError) return\n assert(this.#handle, 'zlib binding closed')\n\n // _processChunk tries to .close() the native handle after it's done, so we\n // intercept that by temporarily making it a no-op.\n // diving into the node:zlib internals a bit here\n const nativeHandle = (this.#handle as unknown as { _handle: any })\n ._handle\n const originalNativeClose = nativeHandle.close\n nativeHandle.close = () => {}\n const originalClose = this.#handle.close\n this.#handle.close = () => {}\n // It also calls `Buffer.concat()` at the end, which may be convenient\n // for some, but which we are not interested in as it slows us down.\n passthroughBufferConcat(true)\n let result: undefined | Buffer | Buffer[] = undefined\n try {\n const flushFlag =\n typeof chunk[_flushFlag] === 'number'\n ? chunk[_flushFlag]\n : this.#flushFlag\n result = (\n this.#handle as unknown as {\n _processChunk: (chunk: Buffer, flushFlag: number) => Buffer[]\n }\n )._processChunk(chunk as Buffer, flushFlag)\n // if we don't throw, reset it back how it was\n passthroughBufferConcat(false)\n } catch (err) {\n // or if we do, put Buffer.concat() back before we emit error\n // Error events call into user code, which may call Buffer.concat()\n passthroughBufferConcat(false)\n this.#onError(new ZlibError(err as NodeJS.ErrnoException, this.write))\n } finally {\n if (this.#handle) {\n // Core zlib resets `_handle` to null after attempting to close the\n // native handle. Our no-op handler prevented actual closure, but we\n // need to restore the `._handle` property.\n ;(this.#handle as unknown as { _handle: any })._handle =\n nativeHandle\n nativeHandle.close = originalNativeClose\n this.#handle.close = originalClose\n // `_processChunk()` adds an 'error' listener. If we don't remove it\n // after each call, these handlers start piling up.\n this.#handle.removeAllListeners('error')\n // make sure OUR error listener is still attached tho\n }\n }\n\n if (this.#handle)\n this.#handle.on('error', er => this.#onError(new ZlibError(er, this.write)))\n\n let writeReturn\n if (result) {\n if (Array.isArray(result) && result.length > 0) {\n const r = result[0]\n // The first buffer is always `handle._outBuffer`, which would be\n // re-used for later invocations; so, we always have to copy that one.\n writeReturn = this[_superWrite](Buffer.from(r as Buffer))\n for (let i = 1; i < result.length; i++) {\n writeReturn = this[_superWrite](result[i] as Buffer)\n }\n } else {\n // either a single Buffer or an empty array\n writeReturn = this[_superWrite](Buffer.from(result as Buffer | []))\n }\n }\n\n if (cb) cb()\n return writeReturn\n }\n}\n\nexport type ZlibOptions = ZlibBaseOptions & {\n level?: number\n strategy?: number\n}\n\nexport class Zlib extends ZlibBase {\n #level?: number\n #strategy?: number\n\n constructor(opts: ZlibOptions, mode: ZlibMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.Z_NO_FLUSH\n opts.finishFlush = opts.finishFlush || constants.Z_FINISH\n opts.fullFlushFlag = constants.Z_FULL_FLUSH\n super(opts, mode)\n\n this.#level = opts.level\n this.#strategy = opts.strategy\n }\n\n params(level: number, strategy: number) {\n if (this.sawError) return\n\n if (!this.handle)\n throw new Error('cannot switch params when binding is closed')\n\n // no way to test this without also not supporting params at all\n /* c8 ignore start */\n if (!(this.handle as { params?: any }).params)\n throw new Error('not supported in this implementation')\n /* c8 ignore stop */\n\n if (this.#level !== level || this.#strategy !== strategy) {\n this.flush(constants.Z_SYNC_FLUSH)\n assert(this.handle, 'zlib binding closed')\n // .params() calls .flush(), but the latter is always async in the\n // core zlib. We override .flush() temporarily to intercept that and\n // flush synchronously.\n const origFlush = this.handle.flush\n this.handle.flush = (\n flushFlag?: (() => void) | number,\n cb?: () => void,\n ) => {\n /* c8 ignore start */\n if (typeof flushFlag === 'function') {\n cb = flushFlag\n flushFlag = this.flushFlag\n }\n /* c8 ignore stop */\n this.flush(flushFlag)\n cb?.()\n }\n try {\n ;(\n this.handle as unknown as {\n params: (level?: number, strategy?: number) => void\n }\n ).params(level, strategy)\n } finally {\n this.handle.flush = origFlush\n }\n /* c8 ignore start */\n if (this.handle) {\n this.#level = level\n this.#strategy = strategy\n }\n /* c8 ignore stop */\n }\n }\n}\n\n// minimal 2-byte header\nexport class Deflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Deflate')\n }\n}\n\nexport class Inflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Inflate')\n }\n}\n\n// gzip - bigger header, same deflate compression\nexport type GzipOptions = ZlibOptions & { portable?: boolean }\nexport class Gzip extends Zlib {\n #portable: boolean\n constructor(opts: GzipOptions) {\n super(opts, 'Gzip')\n this.#portable = opts && !!opts.portable\n }\n\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n if (!this.#portable) return super[_superWrite](data)\n\n // we'll always get the header emitted in one first chunk\n // overwrite the OS indicator byte with 0xFF\n this.#portable = false\n data[9] = 255\n return super[_superWrite](data)\n }\n}\n\nexport class Gunzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Gunzip')\n }\n}\n\n// raw - no header\nexport class DeflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'DeflateRaw')\n }\n}\n\nexport class InflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'InflateRaw')\n }\n}\n\n// auto-detect header.\nexport class Unzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Unzip')\n }\n}\n\nclass Brotli extends ZlibBase {\n constructor(opts: ZlibOptions, mode: BrotliMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS\n opts.finishFlush =\n opts.finishFlush || constants.BROTLI_OPERATION_FINISH\n opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH\n super(opts, mode)\n }\n}\n\nexport class BrotliCompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliCompress')\n }\n}\n\nexport class BrotliDecompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliDecompress')\n }\n}\n\nclass Zstd extends ZlibBase {\n constructor(opts: ZlibOptions, mode: ZstdMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.ZSTD_e_continue\n opts.finishFlush = opts.finishFlush || constants.ZSTD_e_end\n opts.fullFlushFlag = constants.ZSTD_e_flush\n super(opts, mode)\n }\n}\n\nexport class ZstdCompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdCompress')\n }\n}\n\nexport class ZstdDecompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdDecompress')\n }\n}\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "// Update with any zlib constants that are added or changed in the future.\n// Node v6 didn't export this, so we just hard code the version and rely\n// on all the other hard-coded values from zlib v4736. When node v6\n// support drops, we can just export the realZlibConstants object.\nimport realZlib from 'zlib'\n/* c8 ignore start */\nconst realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 }\n/* c8 ignore stop */\n\nexport const constants = Object.freeze(\n Object.assign(\n Object.create(null),\n {\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n Z_VERSION_ERROR: -6,\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n DEFLATE: 1,\n INFLATE: 2,\n GZIP: 3,\n GUNZIP: 4,\n DEFLATERAW: 5,\n INFLATERAW: 6,\n UNZIP: 7,\n BROTLI_DECODE: 8,\n BROTLI_ENCODE: 9,\n Z_MIN_WINDOWBITS: 8,\n Z_MAX_WINDOWBITS: 15,\n Z_DEFAULT_WINDOWBITS: 15,\n Z_MIN_CHUNK: 64,\n Z_MAX_CHUNK: Infinity,\n Z_DEFAULT_CHUNK: 16384,\n Z_MIN_MEMLEVEL: 1,\n Z_MAX_MEMLEVEL: 9,\n Z_DEFAULT_MEMLEVEL: 8,\n Z_MIN_LEVEL: -1,\n Z_MAX_LEVEL: 9,\n Z_DEFAULT_LEVEL: -1,\n BROTLI_OPERATION_PROCESS: 0,\n BROTLI_OPERATION_FLUSH: 1,\n BROTLI_OPERATION_FINISH: 2,\n BROTLI_OPERATION_EMIT_METADATA: 3,\n BROTLI_MODE_GENERIC: 0,\n BROTLI_MODE_TEXT: 1,\n BROTLI_MODE_FONT: 2,\n BROTLI_DEFAULT_MODE: 0,\n BROTLI_MIN_QUALITY: 0,\n BROTLI_MAX_QUALITY: 11,\n BROTLI_DEFAULT_QUALITY: 11,\n BROTLI_MIN_WINDOW_BITS: 10,\n BROTLI_MAX_WINDOW_BITS: 24,\n BROTLI_LARGE_MAX_WINDOW_BITS: 30,\n BROTLI_DEFAULT_WINDOW: 22,\n BROTLI_MIN_INPUT_BLOCK_BITS: 16,\n BROTLI_MAX_INPUT_BLOCK_BITS: 24,\n BROTLI_PARAM_MODE: 0,\n BROTLI_PARAM_QUALITY: 1,\n BROTLI_PARAM_LGWIN: 2,\n BROTLI_PARAM_LGBLOCK: 3,\n BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,\n BROTLI_PARAM_SIZE_HINT: 5,\n BROTLI_PARAM_LARGE_WINDOW: 6,\n BROTLI_PARAM_NPOSTFIX: 7,\n BROTLI_PARAM_NDIRECT: 8,\n BROTLI_DECODER_RESULT_ERROR: 0,\n BROTLI_DECODER_RESULT_SUCCESS: 1,\n BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,\n BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,\n BROTLI_DECODER_NO_ERROR: 0,\n BROTLI_DECODER_SUCCESS: 1,\n BROTLI_DECODER_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,\n BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,\n BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,\n BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,\n BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,\n BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,\n BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,\n BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,\n BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,\n BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,\n BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,\n BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,\n BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,\n BROTLI_DECODER_ERROR_UNREACHABLE: -31,\n },\n realZlibConstants,\n ),\n)\n", "// parse a 512-byte header block to a data object, or vice-versa\n// encode returns `true` if a pax extended header is needed, because\n// the data could not be faithfully encoded in a simple header.\n// (Also, check header.needPax to see if it needs a pax header.)\n\nimport { posix as pathModule } from 'node:path'\nimport * as large from './large-numbers.js'\nimport type { EntryTypeCode, EntryTypeName } from './types.js'\nimport * as types from './types.js'\n\nexport type HeaderData = {\n path?: string\n mode?: number\n uid?: number\n gid?: number\n size?: number\n cksum?: number\n type?: EntryTypeName | 'Unsupported'\n linkpath?: string\n uname?: string\n gname?: string\n devmaj?: number\n devmin?: number\n atime?: Date\n ctime?: Date\n mtime?: Date\n\n // fields that are common in extended PAX headers, but not in the\n // \"standard\" tar header block\n charset?: string\n comment?: string\n dev?: number\n ino?: number\n nlink?: number\n}\n\nexport class Header implements HeaderData {\n cksumValid: boolean = false\n needPax: boolean = false\n nullBlock: boolean = false\n\n block?: Buffer\n path?: string\n mode?: number\n uid?: number\n gid?: number\n size?: number\n cksum?: number\n #type: EntryTypeCode | 'Unsupported' = 'Unsupported'\n linkpath?: string\n uname?: string\n gname?: string\n devmaj: number = 0\n devmin: number = 0\n atime?: Date\n ctime?: Date\n mtime?: Date\n\n charset?: string\n comment?: string\n\n constructor(\n data?: Buffer | HeaderData,\n off: number = 0,\n ex?: HeaderData,\n gex?: HeaderData,\n ) {\n if (Buffer.isBuffer(data)) {\n this.decode(data, off || 0, ex, gex)\n } else if (data) {\n this.#slurp(data)\n }\n }\n\n decode(\n buf: Buffer,\n off: number,\n ex?: HeaderData,\n gex?: HeaderData,\n ) {\n if (!off) {\n off = 0\n }\n\n if (!buf || !(buf.length >= off + 512)) {\n throw new Error('need 512 bytes for header')\n }\n\n this.path = ex?.path ?? decString(buf, off, 100)\n this.mode = ex?.mode ?? gex?.mode ?? decNumber(buf, off + 100, 8)\n this.uid = ex?.uid ?? gex?.uid ?? decNumber(buf, off + 108, 8)\n this.gid = ex?.gid ?? gex?.gid ?? decNumber(buf, off + 116, 8)\n this.size = ex?.size ?? gex?.size ?? decNumber(buf, off + 124, 12)\n this.mtime =\n ex?.mtime ?? gex?.mtime ?? decDate(buf, off + 136, 12)\n this.cksum = decNumber(buf, off + 148, 12)\n\n // if we have extended or global extended headers, apply them now\n // See https://github.com/npm/node-tar/pull/187\n // Apply global before local, so it overrides\n if (gex) this.#slurp(gex, true)\n if (ex) this.#slurp(ex)\n\n // old tar versions marked dirs as a file with a trailing /\n const t = decString(buf, off + 156, 1)\n if (types.isCode(t)) {\n this.#type = t || '0'\n }\n if (this.#type === '0' && this.path.slice(-1) === '/') {\n this.#type = '5'\n }\n\n // tar implementations sometimes incorrectly put the stat(dir).size\n // as the size in the tarball, even though Directory entries are\n // not able to have any body at all. In the very rare chance that\n // it actually DOES have a body, we weren't going to do anything with\n // it anyway, and it'll just be a warning about an invalid header.\n if (this.#type === '5') {\n this.size = 0\n }\n\n this.linkpath = decString(buf, off + 157, 100)\n if (\n buf.subarray(off + 257, off + 265).toString() ===\n 'ustar\\u000000'\n ) {\n /* c8 ignore start */\n this.uname =\n ex?.uname ?? gex?.uname ?? decString(buf, off + 265, 32)\n this.gname =\n ex?.gname ?? gex?.gname ?? decString(buf, off + 297, 32)\n this.devmaj =\n ex?.devmaj ?? gex?.devmaj ?? decNumber(buf, off + 329, 8) ?? 0\n this.devmin =\n ex?.devmin ?? gex?.devmin ?? decNumber(buf, off + 337, 8) ?? 0\n /* c8 ignore stop */\n if (buf[off + 475] !== 0) {\n // definitely a prefix, definitely >130 chars.\n const prefix = decString(buf, off + 345, 155)\n this.path = prefix + '/' + this.path\n } else {\n const prefix = decString(buf, off + 345, 130)\n if (prefix) {\n this.path = prefix + '/' + this.path\n }\n /* c8 ignore start */\n this.atime =\n ex?.atime ?? gex?.atime ?? decDate(buf, off + 476, 12)\n this.ctime =\n ex?.ctime ?? gex?.ctime ?? decDate(buf, off + 488, 12)\n /* c8 ignore stop */\n }\n }\n\n let sum = 8 * 0x20\n for (let i = off; i < off + 148; i++) {\n sum += buf[i] as number\n }\n\n for (let i = off + 156; i < off + 512; i++) {\n sum += buf[i] as number\n }\n\n this.cksumValid = sum === this.cksum\n if (this.cksum === undefined && sum === 8 * 0x20) {\n this.nullBlock = true\n }\n }\n\n #slurp(ex: HeaderData, gex: boolean = false) {\n Object.assign(\n this,\n Object.fromEntries(\n Object.entries(ex).filter(([k, v]) => {\n // we slurp in everything except for the path attribute in\n // a global extended header, because that's weird. Also, any\n // null/undefined values are ignored.\n return !(\n v === null ||\n v === undefined ||\n (k === 'path' && gex) ||\n (k === 'linkpath' && gex) ||\n k === 'global'\n )\n }),\n ),\n )\n }\n\n encode(buf?: Buffer, off: number = 0) {\n if (!buf) {\n buf = this.block = Buffer.alloc(512)\n }\n\n if (this.#type === 'Unsupported') {\n this.#type = '0'\n }\n\n if (!(buf.length >= off + 512)) {\n throw new Error('need 512 bytes for header')\n }\n\n const prefixSize = this.ctime || this.atime ? 130 : 155\n const split = splitPrefix(this.path || '', prefixSize)\n const path = split[0]\n const prefix = split[1]\n this.needPax = !!split[2]\n\n this.needPax = encString(buf, off, 100, path) || this.needPax\n this.needPax =\n encNumber(buf, off + 100, 8, this.mode) || this.needPax\n this.needPax =\n encNumber(buf, off + 108, 8, this.uid) || this.needPax\n this.needPax =\n encNumber(buf, off + 116, 8, this.gid) || this.needPax\n this.needPax =\n encNumber(buf, off + 124, 12, this.size) || this.needPax\n this.needPax =\n encDate(buf, off + 136, 12, this.mtime) || this.needPax\n buf[off + 156] = this.#type.charCodeAt(0)\n this.needPax =\n encString(buf, off + 157, 100, this.linkpath) || this.needPax\n buf.write('ustar\\u000000', off + 257, 8)\n this.needPax =\n encString(buf, off + 265, 32, this.uname) || this.needPax\n this.needPax =\n encString(buf, off + 297, 32, this.gname) || this.needPax\n this.needPax =\n encNumber(buf, off + 329, 8, this.devmaj) || this.needPax\n this.needPax =\n encNumber(buf, off + 337, 8, this.devmin) || this.needPax\n this.needPax =\n encString(buf, off + 345, prefixSize, prefix) || this.needPax\n if (buf[off + 475] !== 0) {\n this.needPax =\n encString(buf, off + 345, 155, prefix) || this.needPax\n } else {\n this.needPax =\n encString(buf, off + 345, 130, prefix) || this.needPax\n this.needPax =\n encDate(buf, off + 476, 12, this.atime) || this.needPax\n this.needPax =\n encDate(buf, off + 488, 12, this.ctime) || this.needPax\n }\n\n let sum = 8 * 0x20\n for (let i = off; i < off + 148; i++) {\n sum += buf[i] as number\n }\n\n for (let i = off + 156; i < off + 512; i++) {\n sum += buf[i] as number\n }\n\n this.cksum = sum\n encNumber(buf, off + 148, 8, this.cksum)\n this.cksumValid = true\n\n return this.needPax\n }\n\n get type(): EntryTypeName {\n return (\n this.#type === 'Unsupported' ?\n this.#type\n : types.name.get(this.#type)) as EntryTypeName\n }\n\n get typeKey(): EntryTypeCode | 'Unsupported' {\n return this.#type\n }\n\n set type(type: EntryTypeCode | EntryTypeName | 'Unsupported') {\n const c = String(types.code.get(type as EntryTypeName))\n if (types.isCode(c) || c === 'Unsupported') {\n this.#type = c\n } else if (types.isCode(type)) {\n this.#type = type\n } else {\n throw new TypeError('invalid entry type: ' + type)\n }\n }\n}\n\nconst splitPrefix = (\n p: string,\n prefixSize: number,\n): [string, string, boolean] => {\n const pathSize = 100\n let pp = p\n let prefix = ''\n let ret: undefined | [string, string, boolean] = undefined\n const root = pathModule.parse(p).root || '.'\n\n if (Buffer.byteLength(pp) < pathSize) {\n ret = [pp, prefix, false]\n } else {\n // first set prefix to the dir, and path to the base\n prefix = pathModule.dirname(pp)\n pp = pathModule.basename(pp)\n\n do {\n if (\n Buffer.byteLength(pp) <= pathSize &&\n Buffer.byteLength(prefix) <= prefixSize\n ) {\n // both fit!\n ret = [pp, prefix, false]\n } else if (\n Buffer.byteLength(pp) > pathSize &&\n Buffer.byteLength(prefix) <= prefixSize\n ) {\n // prefix fits in prefix, but path doesn't fit in path\n ret = [pp.slice(0, pathSize - 1), prefix, true]\n } else {\n // make path take a bit from prefix\n pp = pathModule.join(pathModule.basename(prefix), pp)\n prefix = pathModule.dirname(prefix)\n }\n } while (prefix !== root && ret === undefined)\n\n // at this point, found no resolution, just truncate\n if (!ret) {\n ret = [p.slice(0, pathSize - 1), '', true]\n }\n }\n return ret\n}\n\nconst decString = (buf: Buffer, off: number, size: number) =>\n buf\n .subarray(off, off + size)\n .toString('utf8')\n .replace(/\\0.*/, '')\n\nconst decDate = (buf: Buffer, off: number, size: number) =>\n numToDate(decNumber(buf, off, size))\n\nconst numToDate = (num?: number) =>\n num === undefined ? undefined : new Date(num * 1000)\n\nconst decNumber = (buf: Buffer, off: number, size: number) =>\n Number(buf[off]) & 0x80 ?\n large.parse(buf.subarray(off, off + size))\n : decSmallNumber(buf, off, size)\n\nconst nanUndef = (value: number) => (isNaN(value) ? undefined : value)\n\nconst decSmallNumber = (buf: Buffer, off: number, size: number) =>\n nanUndef(\n parseInt(\n buf\n .subarray(off, off + size)\n .toString('utf8')\n .replace(/\\0.*$/, '')\n .trim(),\n 8,\n ),\n )\n\n// the maximum encodable as a null-terminated octal, by field size\nconst MAXNUM = {\n 12: 0o77777777777,\n 8: 0o7777777,\n}\n\nconst encNumber = (\n buf: Buffer,\n off: number,\n size: 12 | 8,\n num?: number,\n) =>\n num === undefined ? false\n : num > MAXNUM[size] || num < 0 ?\n (large.encode(num, buf.subarray(off, off + size)), true)\n : (encSmallNumber(buf, off, size, num), false)\n\nconst encSmallNumber = (\n buf: Buffer,\n off: number,\n size: number,\n num: number,\n) => buf.write(octalString(num, size), off, size, 'ascii')\n\nconst octalString = (num: number, size: number) =>\n padOctal(Math.floor(num).toString(8), size)\n\nconst padOctal = (str: string, size: number) =>\n (str.length === size - 1 ?\n str\n : new Array(size - str.length - 1).join('0') + str + ' ') + '\\0'\n\nconst encDate = (\n buf: Buffer,\n off: number,\n size: 8 | 12,\n date?: Date,\n) =>\n date === undefined ? false : (\n encNumber(buf, off, size, date.getTime() / 1000)\n )\n\n// enough to fill the longest string we've got\nconst NULLS = new Array(156).join('\\0')\n// pad with nulls, return true if it's longer or non-ascii\nconst encString = (\n buf: Buffer,\n off: number,\n size: number,\n str?: string,\n) =>\n str === undefined ? false : (\n (buf.write(str + NULLS, off, size, 'utf8'),\n str.length !== Buffer.byteLength(str) || str.length > size)\n )\n", "// Tar can encode large and negative numbers using a leading byte of\n// 0xff for negative, and 0x80 for positive.\n\nexport const encode = (num: number, buf: Buffer) => {\n if (!Number.isSafeInteger(num)) {\n // The number is so large that javascript cannot represent it with integer\n // precision.\n throw Error(\n 'cannot encode number outside of javascript safe integer range',\n )\n } else if (num < 0) {\n encodeNegative(num, buf)\n } else {\n encodePositive(num, buf)\n }\n return buf\n}\n\nconst encodePositive = (num: number, buf: Buffer) => {\n buf[0] = 0x80\n\n for (var i = buf.length; i > 1; i--) {\n buf[i - 1] = num & 0xff\n num = Math.floor(num / 0x100)\n }\n}\n\nconst encodeNegative = (num: number, buf: Buffer) => {\n buf[0] = 0xff\n var flipped = false\n num = num * -1\n for (var i = buf.length; i > 1; i--) {\n var byte = num & 0xff\n num = Math.floor(num / 0x100)\n if (flipped) {\n buf[i - 1] = onesComp(byte)\n } else if (byte === 0) {\n buf[i - 1] = 0\n } else {\n flipped = true\n buf[i - 1] = twosComp(byte)\n }\n }\n}\n\nexport const parse = (buf: Buffer) => {\n const pre = buf[0]\n const value =\n pre === 0x80 ? pos(buf.subarray(1, buf.length))\n : pre === 0xff ? twos(buf)\n : null\n if (value === null) {\n throw Error('invalid base256 encoding')\n }\n\n if (!Number.isSafeInteger(value)) {\n // The number is so large that javascript cannot represent it with integer\n // precision.\n throw Error(\n 'parsed number outside of javascript safe integer range',\n )\n }\n\n return value\n}\n\nconst twos = (buf: Buffer) => {\n var len = buf.length\n var sum = 0\n var flipped = false\n for (var i = len - 1; i > -1; i--) {\n var byte = Number(buf[i])\n var f\n if (flipped) {\n f = onesComp(byte)\n } else if (byte === 0) {\n f = byte\n } else {\n flipped = true\n f = twosComp(byte)\n }\n if (f !== 0) {\n sum -= f * Math.pow(256, len - i - 1)\n }\n }\n return sum\n}\n\nconst pos = (buf: Buffer) => {\n var len = buf.length\n var sum = 0\n for (var i = len - 1; i > -1; i--) {\n var byte = Number(buf[i])\n if (byte !== 0) {\n sum += byte * Math.pow(256, len - i - 1)\n }\n }\n return sum\n}\n\nconst onesComp = (byte: number) => (0xff ^ byte) & 0xff\n\nconst twosComp = (byte: number) => ((0xff ^ byte) + 1) & 0xff\n", "export const isCode = (c: string): c is EntryTypeCode =>\n name.has(c as EntryTypeCode)\n\nexport const isName = (c: string): c is EntryTypeName =>\n code.has(c as EntryTypeName)\n\nexport type EntryTypeCode =\n | '0'\n | ''\n | '1'\n | '2'\n | '3'\n | '4'\n | '5'\n | '6'\n | '7'\n | 'g'\n | 'x'\n | 'A'\n | 'D'\n | 'I'\n | 'K'\n | 'L'\n | 'M'\n | 'N'\n | 'S'\n | 'V'\n | 'X'\n\nexport type EntryTypeName =\n | 'File'\n | 'OldFile'\n | 'Link'\n | 'SymbolicLink'\n | 'CharacterDevice'\n | 'BlockDevice'\n | 'Directory'\n | 'FIFO'\n | 'ContiguousFile'\n | 'GlobalExtendedHeader'\n | 'ExtendedHeader'\n | 'SolarisACL'\n | 'GNUDumpDir'\n | 'Inode'\n | 'NextFileHasLongLinkpath'\n | 'NextFileHasLongPath'\n | 'ContinuationFile'\n | 'OldGnuLongPath'\n | 'SparseFile'\n | 'TapeVolumeHeader'\n | 'OldExtendedHeader'\n | 'Unsupported'\n\n// map types from key to human-friendly name\nexport const name = new Map<EntryTypeCode, EntryTypeName>([\n ['0', 'File'],\n // same as File\n ['', 'OldFile'],\n ['1', 'Link'],\n ['2', 'SymbolicLink'],\n // Devices and FIFOs aren't fully supported\n // they are parsed, but skipped when unpacking\n ['3', 'CharacterDevice'],\n ['4', 'BlockDevice'],\n ['5', 'Directory'],\n ['6', 'FIFO'],\n // same as File\n ['7', 'ContiguousFile'],\n // pax headers\n ['g', 'GlobalExtendedHeader'],\n ['x', 'ExtendedHeader'],\n // vendor-specific stuff\n // skip\n ['A', 'SolarisACL'],\n // like 5, but with data, which should be skipped\n ['D', 'GNUDumpDir'],\n // metadata only, skip\n ['I', 'Inode'],\n // data = link path of next file\n ['K', 'NextFileHasLongLinkpath'],\n // data = path of next file\n ['L', 'NextFileHasLongPath'],\n // skip\n ['M', 'ContinuationFile'],\n // like L\n ['N', 'OldGnuLongPath'],\n // skip\n ['S', 'SparseFile'],\n // skip\n ['V', 'TapeVolumeHeader'],\n // like x\n ['X', 'OldExtendedHeader'],\n])\n\n// map the other direction\nexport const code = new Map<EntryTypeName, EntryTypeCode>(\n Array.from(name).map(kv => [kv[1], kv[0]]),\n)\n", "import { basename } from 'node:path'\nimport { Header, HeaderData } from './header.js'\n\nexport class Pax implements HeaderData {\n atime?: Date\n mtime?: Date\n ctime?: Date\n\n charset?: string\n comment?: string\n\n gid?: number\n uid?: number\n\n gname?: string\n uname?: string\n linkpath?: string\n dev?: number\n ino?: number\n nlink?: number\n path?: string\n size?: number\n mode?: number\n\n global: boolean\n\n constructor(obj: HeaderData, global: boolean = false) {\n this.atime = obj.atime\n this.charset = obj.charset\n this.comment = obj.comment\n this.ctime = obj.ctime\n this.dev = obj.dev\n this.gid = obj.gid\n this.global = global\n this.gname = obj.gname\n this.ino = obj.ino\n this.linkpath = obj.linkpath\n this.mtime = obj.mtime\n this.nlink = obj.nlink\n this.path = obj.path\n this.size = obj.size\n this.uid = obj.uid\n this.uname = obj.uname\n }\n\n encode() {\n const body = this.encodeBody()\n if (body === '') {\n return Buffer.allocUnsafe(0)\n }\n\n const bodyLen = Buffer.byteLength(body)\n // round up to 512 bytes\n // add 512 for header\n const bufLen = 512 * Math.ceil(1 + bodyLen / 512)\n const buf = Buffer.allocUnsafe(bufLen)\n\n // 0-fill the header section, it might not hit every field\n for (let i = 0; i < 512; i++) {\n buf[i] = 0\n }\n\n new Header({\n // XXX split the path\n // then the path should be PaxHeader + basename, but less than 99,\n // prepend with the dirname\n /* c8 ignore start */\n path: ('PaxHeader/' + basename(this.path ?? '')).slice(0, 99),\n /* c8 ignore stop */\n mode: this.mode || 0o644,\n uid: this.uid,\n gid: this.gid,\n size: bodyLen,\n mtime: this.mtime,\n type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader',\n linkpath: '',\n uname: this.uname || '',\n gname: this.gname || '',\n devmaj: 0,\n devmin: 0,\n atime: this.atime,\n ctime: this.ctime,\n }).encode(buf)\n\n buf.write(body, 512, bodyLen, 'utf8')\n\n // null pad after the body\n for (let i = bodyLen + 512; i < buf.length; i++) {\n buf[i] = 0\n }\n\n return buf\n }\n\n encodeBody() {\n return (\n this.encodeField('path') +\n this.encodeField('ctime') +\n this.encodeField('atime') +\n this.encodeField('dev') +\n this.encodeField('ino') +\n this.encodeField('nlink') +\n this.encodeField('charset') +\n this.encodeField('comment') +\n this.encodeField('gid') +\n this.encodeField('gname') +\n this.encodeField('linkpath') +\n this.encodeField('mtime') +\n this.encodeField('size') +\n this.encodeField('uid') +\n this.encodeField('uname')\n )\n }\n\n encodeField(field: keyof Pax): string {\n if (this[field] === undefined) {\n return ''\n }\n const r = this[field]\n const v = r instanceof Date ? r.getTime() / 1000 : r\n const s =\n ' ' +\n (field === 'dev' || field === 'ino' || field === 'nlink' ?\n 'SCHILY.'\n : '') +\n field +\n '=' +\n v +\n '\\n'\n const byteLen = Buffer.byteLength(s)\n // the digits includes the length of the digits in ascii base-10\n // so if it's 9 characters, then adding 1 for the 9 makes it 10\n // which makes it 11 chars.\n let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1\n if (byteLen + digits >= Math.pow(10, digits)) {\n digits += 1\n }\n const len = digits + byteLen\n return len + s\n }\n\n static parse(str: string, ex?: HeaderData, g: boolean = false) {\n return new Pax(merge(parseKV(str), ex), g)\n }\n}\n\nconst merge = (a: HeaderData, b?: HeaderData) =>\n b ? Object.assign({}, b, a) : a\n\nconst parseKV = (str: string) =>\n str\n .replace(/\\n$/, '')\n .split('\\n')\n .reduce(parseKVLine, Object.create(null))\n\nconst parseKVLine = (set: Record<string, any>, line: string) => {\n const n = parseInt(line, 10)\n\n // XXX Values with \\n in them will fail this.\n // Refactor to not be a naive line-by-line parse.\n if (n !== Buffer.byteLength(line) + 1) {\n return set\n }\n\n line = line.slice((n + ' ').length)\n const kv = line.split('=')\n const r = kv.shift()\n\n if (!r) {\n return set\n }\n\n const k = r.replace(/^SCHILY\\.(dev|ino|nlink)/, '$1')\n\n const v = kv.join('=')\n set[k] =\n /^([A-Z]+\\.)?([mac]|birth|creation)time$/.test(k) ?\n new Date(Number(v) * 1000)\n : /^[0-9]+$/.test(v) ? +v\n : v\n return set\n}\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "// on windows, either \\ or / are valid directory separators.\n// on unix, \\ is a valid character in filenames.\n// so, on windows, and only on windows, we replace all \\ chars with /,\n// so that we can use / as our one and only directory separator char.\n\nconst platform =\n process.env.TESTING_TAR_FAKE_PLATFORM || process.platform\n\nexport const normalizeWindowsPath =\n platform !== 'win32' ?\n (p: string) => p\n : (p: string) => p && p.replace(/\\\\/g, '/')\n", "import { Minipass } from 'minipass'\nimport { Header } from './header.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { Pax } from './pax.js'\nimport { EntryTypeName } from './types.js'\n\nexport class ReadEntry extends Minipass<Buffer, Buffer> {\n extended?: Pax\n globalExtended?: Pax\n header: Header\n startBlockSize: number\n blockRemain: number\n remain: number\n type: EntryTypeName\n meta: boolean = false\n ignore: boolean = false\n path: string\n mode?: number\n uid?: number\n gid?: number\n uname?: string\n gname?: string\n size: number = 0\n mtime?: Date\n atime?: Date\n ctime?: Date\n linkpath?: string\n\n dev?: number\n ino?: number\n nlink?: number\n invalid: boolean = false\n absolute?: string\n unsupported: boolean = false\n\n constructor(header: Header, ex?: Pax, gex?: Pax) {\n super({})\n // read entries always start life paused. this is to avoid the\n // situation where Minipass's auto-ending empty streams results\n // in an entry ending before we're ready for it.\n this.pause()\n this.extended = ex\n this.globalExtended = gex\n this.header = header\n /* c8 ignore start */\n this.remain = header.size ?? 0\n /* c8 ignore stop */\n this.startBlockSize = 512 * Math.ceil(this.remain / 512)\n this.blockRemain = this.startBlockSize\n this.type = header.type\n switch (this.type) {\n case 'File':\n case 'OldFile':\n case 'Link':\n case 'SymbolicLink':\n case 'CharacterDevice':\n case 'BlockDevice':\n case 'Directory':\n case 'FIFO':\n case 'ContiguousFile':\n case 'GNUDumpDir':\n break\n\n case 'NextFileHasLongLinkpath':\n case 'NextFileHasLongPath':\n case 'OldGnuLongPath':\n case 'GlobalExtendedHeader':\n case 'ExtendedHeader':\n case 'OldExtendedHeader':\n this.meta = true\n break\n\n // NOTE: gnutar and bsdtar treat unrecognized types as 'File'\n // it may be worth doing the same, but with a warning.\n default:\n this.ignore = true\n }\n\n /* c8 ignore start */\n if (!header.path) {\n throw new Error('no path provided for tar.ReadEntry')\n }\n /* c8 ignore stop */\n\n this.path = normalizeWindowsPath(header.path) as string\n this.mode = header.mode\n if (this.mode) {\n this.mode = this.mode & 0o7777\n }\n this.uid = header.uid\n this.gid = header.gid\n this.uname = header.uname\n this.gname = header.gname\n this.size = this.remain\n this.mtime = header.mtime\n this.atime = header.atime\n this.ctime = header.ctime\n /* c8 ignore start */\n this.linkpath =\n header.linkpath ?\n normalizeWindowsPath(header.linkpath)\n : undefined\n /* c8 ignore stop */\n this.uname = header.uname\n this.gname = header.gname\n\n if (ex) {\n this.#slurp(ex)\n }\n if (gex) {\n this.#slurp(gex, true)\n }\n }\n\n write(data: Buffer) {\n const writeLen = data.length\n if (writeLen > this.blockRemain) {\n throw new Error('writing more to entry than is appropriate')\n }\n\n const r = this.remain\n const br = this.blockRemain\n this.remain = Math.max(0, r - writeLen)\n this.blockRemain = Math.max(0, br - writeLen)\n if (this.ignore) {\n return true\n }\n\n if (r >= writeLen) {\n return super.write(data)\n }\n\n // r < writeLen\n return super.write(data.subarray(0, r))\n }\n\n #slurp(ex: Pax, gex: boolean = false) {\n if (ex.path) ex.path = normalizeWindowsPath(ex.path)\n if (ex.linkpath) ex.linkpath = normalizeWindowsPath(ex.linkpath)\n Object.assign(\n this,\n Object.fromEntries(\n Object.entries(ex).filter(([k, v]) => {\n // we slurp in everything except for the path attribute in\n // a global extended header, because that's weird. Also, any\n // null/undefined values are ignored.\n return !(\n v === null ||\n v === undefined ||\n (k === 'path' && gex)\n )\n }),\n ),\n )\n }\n}\n", "import { type Minipass } from 'minipass'\n\n/** has a warn method */\nexport type Warner = {\n warn(code: string, message: string | Error, data: any): void\n file?: string\n cwd?: string\n strict?: boolean\n\n emit(\n event: 'warn',\n code: string,\n message: string,\n data?: WarnData,\n ): void\n emit(event: 'error', error: TarError): void\n}\n\nexport type WarnEvent<T = Buffer> = Minipass.Events<T> & {\n warn: [code: string, message: string, data: WarnData]\n}\n\nexport type WarnData = {\n file?: string\n cwd?: string\n code?: string\n tarCode?: string\n recoverable?: boolean\n [k: string]: any\n}\n\nexport type TarError = Error & WarnData\n\nexport const warnMethod = (\n self: Warner,\n code: string,\n message: string | Error,\n data: WarnData = {},\n) => {\n if (self.file) {\n data.file = self.file\n }\n if (self.cwd) {\n data.cwd = self.cwd\n }\n data.code =\n (message instanceof Error &&\n (message as NodeJS.ErrnoException).code) ||\n code\n data.tarCode = code\n if (!self.strict && data.recoverable !== false) {\n if (message instanceof Error) {\n data = Object.assign(message, data)\n message = message.message\n }\n self.emit('warn', code, message, data)\n } else if (message instanceof Error) {\n self.emit('error', Object.assign(message, data))\n } else {\n self.emit(\n 'error',\n Object.assign(new Error(`${code}: ${message}`), data),\n )\n }\n}\n", "// warning: extremely hot code path.\n// This has been meticulously optimized for use\n// within npm install on large package trees.\n// Do not edit without careful benchmarking.\nexport const stripTrailingSlashes = (str: string) => {\n let i = str.length - 1\n let slashesStart = -1\n while (i > -1 && str.charAt(i) === '/') {\n slashesStart = i\n i--\n }\n return slashesStart === -1 ? str : str.slice(0, slashesStart)\n}\n", "// A readable tar stream creator\n// Technically, this is a transform stream that you write paths into,\n// and tar format comes out of.\n// The `add()` method is like `write()` but returns this,\n// and end() return `this` as well, so you can\n// do `new Pack(opt).add('files').add('dir').end().pipe(output)\n// You could also do something like:\n// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))\n\nimport fs, { type Stats } from 'fs'\nimport {\n WriteEntry,\n WriteEntrySync,\n WriteEntryTar,\n} from './write-entry.js'\n\nexport class PackJob {\n path: string\n absolute: string\n entry?: WriteEntry | WriteEntryTar\n stat?: Stats\n readdir?: string[]\n pending: boolean = false\n ignore: boolean = false\n piped: boolean = false\n constructor(path: string, absolute: string) {\n this.path = path || './'\n this.absolute = absolute\n }\n}\n\nimport { Minipass } from 'minipass'\nimport * as zlib from 'minizlib'\nimport { Yallist } from 'yallist'\nimport { ReadEntry } from './read-entry.js'\nimport {\n WarnEvent,\n warnMethod,\n type WarnData,\n type Warner,\n} from './warn-method.js'\n\nconst EOF = Buffer.alloc(1024)\nconst ONSTAT = Symbol('onStat')\nconst ENDED = Symbol('ended')\nconst QUEUE = Symbol('queue')\nconst CURRENT = Symbol('current')\nconst PROCESS = Symbol('process')\nconst PROCESSING = Symbol('processing')\nconst PROCESSJOB = Symbol('processJob')\nconst JOBS = Symbol('jobs')\nconst JOBDONE = Symbol('jobDone')\nconst ADDFSENTRY = Symbol('addFSEntry')\nconst ADDTARENTRY = Symbol('addTarEntry')\nconst STAT = Symbol('stat')\nconst READDIR = Symbol('readdir')\nconst ONREADDIR = Symbol('onreaddir')\nconst PIPE = Symbol('pipe')\nconst ENTRY = Symbol('entry')\nconst ENTRYOPT = Symbol('entryOpt')\nconst WRITEENTRYCLASS = Symbol('writeEntryClass')\nconst WRITE = Symbol('write')\nconst ONDRAIN = Symbol('ondrain')\n\nimport path from 'path'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { TarOptions } from './options.js'\n\nexport class Pack\n extends Minipass<Buffer, ReadEntry | string, WarnEvent<Buffer>>\n implements Warner\n{\n sync: boolean = false\n opt: TarOptions\n cwd: string\n maxReadSize?: number\n preservePaths: boolean\n strict: boolean\n noPax: boolean\n prefix: string\n linkCache: Exclude<TarOptions['linkCache'], undefined>\n statCache: Exclude<TarOptions['statCache'], undefined>\n file: string\n portable: boolean\n zip?: zlib.BrotliCompress | zlib.Gzip | zlib.ZstdCompress\n readdirCache: Exclude<TarOptions['readdirCache'], undefined>\n noDirRecurse: boolean\n follow: boolean\n noMtime: boolean\n mtime?: Date\n filter: Exclude<TarOptions['filter'], undefined>\n jobs: number;\n\n [WRITEENTRYCLASS]: typeof WriteEntry | typeof WriteEntrySync\n onWriteEntry?: (entry: WriteEntry) => void;\n // Note: we actually DO need a linked list here, because we\n // shift() to update the head of the list where we start, but still\n // while that happens, need to know what the next item in the queue\n // will be. Since we do multiple jobs in parallel, it's not as simple\n // as just an Array.shift(), since that would lose the information about\n // the next job in the list. We could add a .next field on the PackJob\n // class, but then we'd have to be tracking the tail of the queue the\n // whole time, and Yallist just does that for us anyway.\n [QUEUE]: Yallist<PackJob>;\n [JOBS]: number = 0;\n [PROCESSING]: boolean = false;\n [ENDED]: boolean = false\n\n constructor(opt: TarOptions = {}) {\n //@ts-ignore\n super()\n this.opt = opt\n this.file = opt.file || ''\n this.cwd = opt.cwd || process.cwd()\n this.maxReadSize = opt.maxReadSize\n this.preservePaths = !!opt.preservePaths\n this.strict = !!opt.strict\n this.noPax = !!opt.noPax\n this.prefix = normalizeWindowsPath(opt.prefix || '')\n this.linkCache = opt.linkCache || new Map()\n this.statCache = opt.statCache || new Map()\n this.readdirCache = opt.readdirCache || new Map()\n this.onWriteEntry = opt.onWriteEntry\n\n this[WRITEENTRYCLASS] = WriteEntry\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n\n this.portable = !!opt.portable\n\n if (opt.gzip || opt.brotli || opt.zstd) {\n if (\n (opt.gzip ? 1 : 0) +\n (opt.brotli ? 1 : 0) +\n (opt.zstd ? 1 : 0) >\n 1\n ) {\n throw new TypeError(\n 'gzip, brotli, zstd are mutually exclusive',\n )\n }\n if (opt.gzip) {\n if (typeof opt.gzip !== 'object') {\n opt.gzip = {}\n }\n if (this.portable) {\n opt.gzip.portable = true\n }\n this.zip = new zlib.Gzip(opt.gzip)\n }\n if (opt.brotli) {\n if (typeof opt.brotli !== 'object') {\n opt.brotli = {}\n }\n this.zip = new zlib.BrotliCompress(opt.brotli)\n }\n if (opt.zstd) {\n if (typeof opt.zstd !== 'object') {\n opt.zstd = {}\n }\n this.zip = new zlib.ZstdCompress(opt.zstd)\n }\n /* c8 ignore next */\n if (!this.zip) throw new Error('impossible')\n const zip = this.zip\n zip.on('data', chunk => super.write(chunk as unknown as string))\n zip.on('end', () => super.end())\n zip.on('drain', () => this[ONDRAIN]())\n this.on('resume', () => zip.resume())\n } else {\n this.on('drain', this[ONDRAIN])\n }\n\n this.noDirRecurse = !!opt.noDirRecurse\n this.follow = !!opt.follow\n this.noMtime = !!opt.noMtime\n if (opt.mtime) this.mtime = opt.mtime\n\n this.filter =\n typeof opt.filter === 'function' ? opt.filter : () => true\n\n this[QUEUE] = new Yallist<PackJob>()\n this[JOBS] = 0\n this.jobs = Number(opt.jobs) || 4\n this[PROCESSING] = false\n this[ENDED] = false\n }\n\n [WRITE](chunk: Buffer) {\n return super.write(chunk as unknown as string)\n }\n\n add(path: string | ReadEntry) {\n this.write(path)\n return this\n }\n\n end(cb?: () => void): this\n end(path: string | ReadEntry, cb?: () => void): this\n end(\n path: string | ReadEntry,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): this\n end(\n path?: string | ReadEntry | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n /* c8 ignore start */\n if (typeof path === 'function') {\n cb = path\n path = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n /* c8 ignore stop */\n if (path) {\n this.add(path)\n }\n this[ENDED] = true\n this[PROCESS]()\n /* c8 ignore next */\n if (cb) cb()\n return this\n }\n\n write(path: string | ReadEntry) {\n if (this[ENDED]) {\n throw new Error('write after end')\n }\n\n if (path instanceof ReadEntry) {\n this[ADDTARENTRY](path)\n } else {\n this[ADDFSENTRY](path)\n }\n return this.flowing\n }\n\n [ADDTARENTRY](p: ReadEntry) {\n const absolute = normalizeWindowsPath(\n path.resolve(this.cwd, p.path),\n )\n // in this case, we don't have to wait for the stat\n if (!this.filter(p.path, p)) {\n p.resume()\n } else {\n const job = new PackJob(p.path, absolute)\n job.entry = new WriteEntryTar(p, this[ENTRYOPT](job))\n job.entry.on('end', () => this[JOBDONE](job))\n this[JOBS] += 1\n this[QUEUE].push(job)\n }\n\n this[PROCESS]()\n }\n\n [ADDFSENTRY](p: string) {\n const absolute = normalizeWindowsPath(path.resolve(this.cwd, p))\n this[QUEUE].push(new PackJob(p, absolute))\n this[PROCESS]()\n }\n\n [STAT](job: PackJob) {\n job.pending = true\n this[JOBS] += 1\n const stat = this.follow ? 'stat' : 'lstat'\n fs[stat](job.absolute, (er, stat) => {\n job.pending = false\n this[JOBS] -= 1\n if (er) {\n this.emit('error', er)\n } else {\n this[ONSTAT](job, stat)\n }\n })\n }\n\n [ONSTAT](job: PackJob, stat: Stats) {\n this.statCache.set(job.absolute, stat)\n job.stat = stat\n\n // now we have the stat, we can filter it.\n if (!this.filter(job.path, stat)) {\n job.ignore = true\n } else if (\n stat.isFile() &&\n stat.nlink > 1 &&\n job === this[CURRENT] &&\n !this.linkCache.get(`${stat.dev}:${stat.ino}`) &&\n !this.sync\n ) {\n // if it's not filtered, and it's a new File entry,\n // jump the queue in case any pending Link entries are about\n // to try to link to it. This prevents a hardlink from coming ahead\n // of its target in the archive.\n this[PROCESSJOB](job)\n }\n\n this[PROCESS]()\n }\n\n [READDIR](job: PackJob) {\n job.pending = true\n this[JOBS] += 1\n fs.readdir(job.absolute, (er, entries) => {\n job.pending = false\n this[JOBS] -= 1\n if (er) {\n return this.emit('error', er)\n }\n this[ONREADDIR](job, entries)\n })\n }\n\n [ONREADDIR](job: PackJob, entries: string[]) {\n this.readdirCache.set(job.absolute, entries)\n job.readdir = entries\n this[PROCESS]()\n }\n\n [PROCESS]() {\n if (this[PROCESSING]) {\n return\n }\n\n this[PROCESSING] = true\n for (\n let w = this[QUEUE].head;\n !!w && this[JOBS] < this.jobs;\n w = w.next\n ) {\n this[PROCESSJOB](w.value)\n if (w.value.ignore) {\n const p = w.next\n this[QUEUE].removeNode(w)\n w.next = p\n }\n }\n\n this[PROCESSING] = false\n\n if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) {\n if (this.zip) {\n this.zip.end(EOF)\n } else {\n super.write(EOF as unknown as string)\n super.end()\n }\n }\n }\n\n get [CURRENT]() {\n return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value\n }\n\n [JOBDONE](_job: PackJob) {\n this[QUEUE].shift()\n this[JOBS] -= 1\n this[PROCESS]()\n }\n\n [PROCESSJOB](job: PackJob) {\n if (job.pending) {\n return\n }\n\n if (job.entry) {\n if (job === this[CURRENT] && !job.piped) {\n this[PIPE](job)\n }\n return\n }\n\n if (!job.stat) {\n const sc = this.statCache.get(job.absolute)\n if (sc) {\n this[ONSTAT](job, sc)\n } else {\n this[STAT](job)\n }\n }\n if (!job.stat) {\n return\n }\n\n // filtered out!\n if (job.ignore) {\n return\n }\n\n if (\n !this.noDirRecurse &&\n job.stat.isDirectory() &&\n !job.readdir\n ) {\n const rc = this.readdirCache.get(job.absolute)\n if (rc) {\n this[ONREADDIR](job, rc)\n } else {\n this[READDIR](job)\n }\n if (!job.readdir) {\n return\n }\n }\n\n // we know it doesn't have an entry, because that got checked above\n job.entry = this[ENTRY](job)\n if (!job.entry) {\n job.ignore = true\n return\n }\n\n if (job === this[CURRENT] && !job.piped) {\n this[PIPE](job)\n }\n }\n\n [ENTRYOPT](job: PackJob): TarOptions {\n return {\n onwarn: (code, msg, data) => this.warn(code, msg, data),\n noPax: this.noPax,\n cwd: this.cwd,\n absolute: job.absolute,\n preservePaths: this.preservePaths,\n maxReadSize: this.maxReadSize,\n strict: this.strict,\n portable: this.portable,\n linkCache: this.linkCache,\n statCache: this.statCache,\n noMtime: this.noMtime,\n mtime: this.mtime,\n prefix: this.prefix,\n onWriteEntry: this.onWriteEntry,\n }\n }\n\n [ENTRY](job: PackJob) {\n this[JOBS] += 1\n try {\n const e = new this[WRITEENTRYCLASS](\n job.path,\n this[ENTRYOPT](job),\n )\n return e\n .on('end', () => this[JOBDONE](job))\n .on('error', er => this.emit('error', er))\n } catch (er) {\n this.emit('error', er)\n }\n }\n\n [ONDRAIN]() {\n if (this[CURRENT] && this[CURRENT].entry) {\n this[CURRENT].entry.resume()\n }\n }\n\n // like .pipe() but using super, because our write() is special\n [PIPE](job: PackJob) {\n job.piped = true\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = job.path\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n const source = job.entry\n const zip = this.zip\n /* c8 ignore start */\n if (!source) throw new Error('cannot pipe without source')\n /* c8 ignore stop */\n\n if (zip) {\n source.on('data', chunk => {\n if (!zip.write(chunk)) {\n source.pause()\n }\n })\n } else {\n source.on('data', chunk => {\n if (!super.write(chunk as unknown as string)) {\n source.pause()\n }\n })\n }\n }\n\n pause() {\n if (this.zip) {\n this.zip.pause()\n }\n return super.pause()\n }\n warn(\n code: string,\n message: string | Error,\n data: WarnData = {},\n ): void {\n warnMethod(this, code, message, data)\n }\n}\n\nexport class PackSync extends Pack {\n sync: true = true\n constructor(opt: TarOptions) {\n super(opt)\n this[WRITEENTRYCLASS] = WriteEntrySync\n }\n\n // pause/resume are no-ops in sync streams.\n pause() {}\n resume() {}\n\n [STAT](job: PackJob) {\n const stat = this.follow ? 'statSync' : 'lstatSync'\n this[ONSTAT](job, fs[stat](job.absolute))\n }\n\n [READDIR](job: PackJob) {\n this[ONREADDIR](job, fs.readdirSync(job.absolute))\n }\n\n // gotta get it all in this tick\n [PIPE](job: PackJob) {\n const source = job.entry\n const zip = this.zip\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = job.path\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n /* c8 ignore start */\n if (!source) throw new Error('Cannot pipe without source')\n /* c8 ignore stop */\n\n if (zip) {\n source.on('data', chunk => {\n zip.write(chunk)\n })\n } else {\n source.on('data', chunk => {\n super[WRITE](chunk)\n })\n }\n }\n}\n", "import fs, { type Stats } from 'fs'\nimport { Minipass } from 'minipass'\nimport path from 'path'\nimport { Header } from './header.js'\nimport { modeFix } from './mode-fix.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport {\n dealias,\n LinkCacheKey,\n TarOptions,\n TarOptionsWithAliases,\n} from './options.js'\nimport { Pax } from './pax.js'\nimport { ReadEntry } from './read-entry.js'\nimport { stripAbsolutePath } from './strip-absolute-path.js'\nimport { stripTrailingSlashes } from './strip-trailing-slashes.js'\nimport { EntryTypeName } from './types.js'\nimport {\n WarnData,\n Warner,\n WarnEvent,\n warnMethod,\n} from './warn-method.js'\nimport * as winchars from './winchars.js'\n\nconst prefixPath = (path: string, prefix?: string) => {\n if (!prefix) {\n return normalizeWindowsPath(path)\n }\n path = normalizeWindowsPath(path).replace(/^\\.(\\/|$)/, '')\n return stripTrailingSlashes(prefix) + '/' + path\n}\n\nconst maxReadSize = 16 * 1024 * 1024\n\nconst PROCESS = Symbol('process')\nconst FILE = Symbol('file')\nconst DIRECTORY = Symbol('directory')\nconst SYMLINK = Symbol('symlink')\nconst HARDLINK = Symbol('hardlink')\nconst HEADER = Symbol('header')\nconst READ = Symbol('read')\nconst LSTAT = Symbol('lstat')\nconst ONLSTAT = Symbol('onlstat')\nconst ONREAD = Symbol('onread')\nconst ONREADLINK = Symbol('onreadlink')\nconst OPENFILE = Symbol('openfile')\nconst ONOPENFILE = Symbol('onopenfile')\nconst CLOSE = Symbol('close')\nconst MODE = Symbol('mode')\nconst AWAITDRAIN = Symbol('awaitDrain')\nconst ONDRAIN = Symbol('ondrain')\nconst PREFIX = Symbol('prefix')\n\nexport class WriteEntry\n extends Minipass<Buffer, Minipass.ContiguousData, WarnEvent>\n implements Warner\n{\n path: string\n portable: boolean\n myuid: number = (process.getuid && process.getuid()) || 0\n // until node has builtin pwnam functions, this'll have to do\n myuser: string = process.env.USER || ''\n maxReadSize: number\n linkCache: Exclude<TarOptions['linkCache'], undefined>\n statCache: Exclude<TarOptions['statCache'], undefined>\n preservePaths: boolean\n cwd: string\n strict: boolean\n mtime?: Date\n noPax: boolean\n noMtime: boolean\n prefix?: string\n fd?: number\n\n blockLen: number = 0\n blockRemain: number = 0\n buf?: Buffer\n pos: number = 0\n remain: number = 0\n length: number = 0\n offset: number = 0\n\n win32: boolean\n absolute: string\n\n header?: Header\n type?: EntryTypeName | 'Unsupported'\n linkpath?: string\n stat?: Stats\n onWriteEntry?: (entry: WriteEntry) => any\n\n #hadError: boolean = false\n\n constructor(p: string, opt_: TarOptionsWithAliases = {}) {\n const opt = dealias(opt_)\n super()\n this.path = normalizeWindowsPath(p)\n // suppress atime, ctime, uid, gid, uname, gname\n this.portable = !!opt.portable\n this.maxReadSize = opt.maxReadSize || maxReadSize\n this.linkCache = opt.linkCache || new Map()\n this.statCache = opt.statCache || new Map()\n this.preservePaths = !!opt.preservePaths\n this.cwd = normalizeWindowsPath(opt.cwd || process.cwd())\n this.strict = !!opt.strict\n this.noPax = !!opt.noPax\n this.noMtime = !!opt.noMtime\n this.mtime = opt.mtime\n this.prefix =\n opt.prefix ? normalizeWindowsPath(opt.prefix) : undefined\n this.onWriteEntry = opt.onWriteEntry\n\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n\n let pathWarn: string | boolean = false\n if (!this.preservePaths) {\n const [root, stripped] = stripAbsolutePath(this.path)\n if (root && typeof stripped === 'string') {\n this.path = stripped\n pathWarn = root\n }\n }\n\n this.win32 = !!opt.win32 || process.platform === 'win32'\n if (this.win32) {\n // force the \\ to / normalization, since we might not *actually*\n // be on windows, but want \\ to be considered a path separator.\n this.path = winchars.decode(this.path.replace(/\\\\/g, '/'))\n p = p.replace(/\\\\/g, '/')\n }\n\n this.absolute = normalizeWindowsPath(\n opt.absolute || path.resolve(this.cwd, p),\n )\n\n if (this.path === '') {\n this.path = './'\n }\n\n if (pathWarn) {\n this.warn(\n 'TAR_ENTRY_INFO',\n `stripping ${pathWarn} from absolute path`,\n {\n entry: this,\n path: pathWarn + this.path,\n },\n )\n }\n\n const cs = this.statCache.get(this.absolute)\n if (cs) {\n this[ONLSTAT](cs)\n } else {\n this[LSTAT]()\n }\n }\n\n warn(code: string, message: string | Error, data: WarnData = {}) {\n return warnMethod(this, code, message, data)\n }\n\n emit(ev: keyof WarnEvent, ...data: any[]) {\n if (ev === 'error') {\n this.#hadError = true\n }\n return super.emit(ev, ...data)\n }\n\n [LSTAT]() {\n fs.lstat(this.absolute, (er, stat) => {\n if (er) {\n return this.emit('error', er)\n }\n this[ONLSTAT](stat)\n })\n }\n\n [ONLSTAT](stat: Stats) {\n this.statCache.set(this.absolute, stat)\n this.stat = stat\n if (!stat.isFile()) {\n stat.size = 0\n }\n this.type = getType(stat)\n this.emit('stat', stat)\n this[PROCESS]()\n }\n\n [PROCESS]() {\n switch (this.type) {\n case 'File':\n return this[FILE]()\n case 'Directory':\n return this[DIRECTORY]()\n case 'SymbolicLink':\n return this[SYMLINK]()\n // unsupported types are ignored.\n default:\n return this.end()\n }\n }\n\n [MODE](mode: number) {\n return modeFix(mode, this.type === 'Directory', this.portable)\n }\n\n [PREFIX](path: string) {\n return prefixPath(path, this.prefix)\n }\n\n [HEADER]() {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot write header before stat')\n }\n /* c8 ignore stop */\n\n if (this.type === 'Directory' && this.portable) {\n this.noMtime = true\n }\n\n this.onWriteEntry?.(this)\n this.header = new Header({\n path: this[PREFIX](this.path),\n // only apply the prefix to hard links.\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n // only the permissions and setuid/setgid/sticky bitflags\n // not the higher-order bits that specify file type\n mode: this[MODE](this.stat.mode),\n uid: this.portable ? undefined : this.stat.uid,\n gid: this.portable ? undefined : this.stat.gid,\n size: this.stat.size,\n mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime,\n /* c8 ignore next */\n type: this.type === 'Unsupported' ? undefined : this.type,\n uname:\n this.portable ? undefined\n : this.stat.uid === this.myuid ? this.myuser\n : '',\n atime: this.portable ? undefined : this.stat.atime,\n ctime: this.portable ? undefined : this.stat.ctime,\n })\n\n if (this.header.encode() && !this.noPax) {\n super.write(\n new Pax({\n atime: this.portable ? undefined : this.header.atime,\n ctime: this.portable ? undefined : this.header.ctime,\n gid: this.portable ? undefined : this.header.gid,\n mtime:\n this.noMtime ? undefined : (\n this.mtime || this.header.mtime\n ),\n path: this[PREFIX](this.path),\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n size: this.header.size,\n uid: this.portable ? undefined : this.header.uid,\n uname: this.portable ? undefined : this.header.uname,\n dev: this.portable ? undefined : this.stat.dev,\n ino: this.portable ? undefined : this.stat.ino,\n nlink: this.portable ? undefined : this.stat.nlink,\n }).encode(),\n )\n }\n const block = this.header?.block\n /* c8 ignore start */\n if (!block) {\n throw new Error('failed to encode header')\n }\n /* c8 ignore stop */\n super.write(block)\n }\n\n [DIRECTORY]() {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot create directory entry without stat')\n }\n /* c8 ignore stop */\n if (this.path.slice(-1) !== '/') {\n this.path += '/'\n }\n this.stat.size = 0\n this[HEADER]()\n this.end()\n }\n\n [SYMLINK]() {\n fs.readlink(this.absolute, (er, linkpath) => {\n if (er) {\n return this.emit('error', er)\n }\n this[ONREADLINK](linkpath)\n })\n }\n\n [ONREADLINK](linkpath: string) {\n this.linkpath = normalizeWindowsPath(linkpath)\n this[HEADER]()\n this.end()\n }\n\n [HARDLINK](linkpath: string) {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot create link entry without stat')\n }\n /* c8 ignore stop */\n this.type = 'Link'\n this.linkpath = normalizeWindowsPath(\n path.relative(this.cwd, linkpath),\n )\n this.stat.size = 0\n this[HEADER]()\n this.end()\n }\n\n [FILE]() {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot create file entry without stat')\n }\n /* c8 ignore stop */\n if (this.stat.nlink > 1) {\n const linkKey =\n `${this.stat.dev}:${this.stat.ino}` as LinkCacheKey\n const linkpath = this.linkCache.get(linkKey)\n if (linkpath?.indexOf(this.cwd) === 0) {\n return this[HARDLINK](linkpath)\n }\n this.linkCache.set(linkKey, this.absolute)\n }\n\n this[HEADER]()\n if (this.stat.size === 0) {\n return this.end()\n }\n\n this[OPENFILE]()\n }\n\n [OPENFILE]() {\n fs.open(this.absolute, 'r', (er, fd) => {\n if (er) {\n return this.emit('error', er)\n }\n this[ONOPENFILE](fd)\n })\n }\n\n [ONOPENFILE](fd: number) {\n this.fd = fd\n if (this.#hadError) {\n return this[CLOSE]()\n }\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('should stat before calling onopenfile')\n }\n /* c8 ignore start */\n\n this.blockLen = 512 * Math.ceil(this.stat.size / 512)\n this.blockRemain = this.blockLen\n const bufLen = Math.min(this.blockLen, this.maxReadSize)\n this.buf = Buffer.allocUnsafe(bufLen)\n this.offset = 0\n this.pos = 0\n this.remain = this.stat.size\n this.length = this.buf.length\n this[READ]()\n }\n\n [READ]() {\n const { fd, buf, offset, length, pos } = this\n if (fd === undefined || buf === undefined) {\n throw new Error('cannot read file without first opening')\n }\n fs.read(fd, buf, offset, length, pos, (er, bytesRead) => {\n if (er) {\n // ignoring the error from close(2) is a bad practice, but at\n // this point we already have an error, don't need another one\n return this[CLOSE](() => this.emit('error', er))\n }\n this[ONREAD](bytesRead)\n })\n }\n\n /* c8 ignore start */\n [CLOSE](\n cb: (er?: null | Error | NodeJS.ErrnoException) => any = () => {},\n ) {\n /* c8 ignore stop */\n if (this.fd !== undefined) fs.close(this.fd, cb)\n }\n\n [ONREAD](bytesRead: number) {\n if (bytesRead <= 0 && this.remain > 0) {\n const er = Object.assign(\n new Error('encountered unexpected EOF'),\n {\n path: this.absolute,\n syscall: 'read',\n code: 'EOF',\n },\n )\n return this[CLOSE](() => this.emit('error', er))\n }\n\n if (bytesRead > this.remain) {\n const er = Object.assign(\n new Error('did not encounter expected EOF'),\n {\n path: this.absolute,\n syscall: 'read',\n code: 'EOF',\n },\n )\n return this[CLOSE](() => this.emit('error', er))\n }\n\n /* c8 ignore start */\n if (!this.buf) {\n throw new Error('should have created buffer prior to reading')\n }\n /* c8 ignore stop */\n\n // null out the rest of the buffer, if we could fit the block padding\n // at the end of this loop, we've incremented bytesRead and this.remain\n // to be incremented up to the blockRemain level, as if we had expected\n // to get a null-padded file, and read it until the end. then we will\n // decrement both remain and blockRemain by bytesRead, and know that we\n // reached the expected EOF, without any null buffer to append.\n if (bytesRead === this.remain) {\n for (\n let i = bytesRead;\n i < this.length && bytesRead < this.blockRemain;\n i++\n ) {\n this.buf[i + this.offset] = 0\n bytesRead++\n this.remain++\n }\n }\n\n const chunk =\n this.offset === 0 && bytesRead === this.buf.length ?\n this.buf\n : this.buf.subarray(this.offset, this.offset + bytesRead)\n\n const flushed = this.write(chunk)\n if (!flushed) {\n this[AWAITDRAIN](() => this[ONDRAIN]())\n } else {\n this[ONDRAIN]()\n }\n }\n\n [AWAITDRAIN](cb: () => any) {\n this.once('drain', cb)\n }\n\n write(buffer: Buffer | string, cb?: () => void): boolean\n write(\n str: Buffer | string,\n encoding?: BufferEncoding | null,\n cb?: () => void,\n ): boolean\n write(\n chunk: Buffer | string,\n encoding?: BufferEncoding | (() => any) | null,\n cb?: () => any,\n ): boolean {\n /* c8 ignore start - just junk to comply with NodeJS.WritableStream */\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(\n chunk,\n typeof encoding === 'string' ? encoding : 'utf8',\n )\n }\n /* c8 ignore stop */\n\n if (this.blockRemain < chunk.length) {\n const er = Object.assign(\n new Error('writing more data than expected'),\n {\n path: this.absolute,\n },\n )\n return this.emit('error', er)\n }\n this.remain -= chunk.length\n this.blockRemain -= chunk.length\n this.pos += chunk.length\n this.offset += chunk.length\n return super.write(chunk, null, cb)\n }\n\n [ONDRAIN]() {\n if (!this.remain) {\n if (this.blockRemain) {\n super.write(Buffer.alloc(this.blockRemain))\n }\n return this[CLOSE](er =>\n er ? this.emit('error', er) : this.end(),\n )\n }\n\n /* c8 ignore start */\n if (!this.buf) {\n throw new Error('buffer lost somehow in ONDRAIN')\n }\n /* c8 ignore stop */\n\n if (this.offset >= this.length) {\n // if we only have a smaller bit left to read, alloc a smaller buffer\n // otherwise, keep it the same length it was before.\n this.buf = Buffer.allocUnsafe(\n Math.min(this.blockRemain, this.buf.length),\n )\n this.offset = 0\n }\n this.length = this.buf.length - this.offset\n this[READ]()\n }\n}\n\nexport class WriteEntrySync extends WriteEntry implements Warner {\n sync: true = true;\n\n [LSTAT]() {\n this[ONLSTAT](fs.lstatSync(this.absolute))\n }\n\n [SYMLINK]() {\n this[ONREADLINK](fs.readlinkSync(this.absolute))\n }\n\n [OPENFILE]() {\n this[ONOPENFILE](fs.openSync(this.absolute, 'r'))\n }\n\n [READ]() {\n let threw = true\n try {\n const { fd, buf, offset, length, pos } = this\n /* c8 ignore start */\n if (fd === undefined || buf === undefined) {\n throw new Error('fd and buf must be set in READ method')\n }\n /* c8 ignore stop */\n const bytesRead = fs.readSync(fd, buf, offset, length, pos)\n this[ONREAD](bytesRead)\n threw = false\n } finally {\n // ignoring the error from close(2) is a bad practice, but at\n // this point we already have an error, don't need another one\n if (threw) {\n try {\n this[CLOSE](() => {})\n } catch (er) {}\n }\n }\n }\n\n [AWAITDRAIN](cb: () => any) {\n cb()\n }\n\n /* c8 ignore start */\n [CLOSE](\n cb: (er?: null | Error | NodeJS.ErrnoException) => any = () => {},\n ) {\n /* c8 ignore stop */\n if (this.fd !== undefined) fs.closeSync(this.fd)\n cb()\n }\n}\n\nexport class WriteEntryTar\n extends Minipass<Buffer, Buffer | string, WarnEvent>\n implements Warner\n{\n blockLen: number = 0\n blockRemain: number = 0\n buf: number = 0\n pos: number = 0\n remain: number = 0\n length: number = 0\n preservePaths: boolean\n portable: boolean\n strict: boolean\n noPax: boolean\n noMtime: boolean\n readEntry: ReadEntry\n type: EntryTypeName\n prefix?: string\n path: string\n mode?: number\n uid?: number\n gid?: number\n uname?: string\n gname?: string\n header?: Header\n mtime?: Date\n atime?: Date\n ctime?: Date\n linkpath?: string\n size: number\n onWriteEntry?: (entry: WriteEntry) => any\n\n warn(code: string, message: string | Error, data: WarnData = {}) {\n return warnMethod(this, code, message, data)\n }\n\n constructor(\n readEntry: ReadEntry,\n opt_: TarOptionsWithAliases = {},\n ) {\n const opt = dealias(opt_)\n super()\n this.preservePaths = !!opt.preservePaths\n this.portable = !!opt.portable\n this.strict = !!opt.strict\n this.noPax = !!opt.noPax\n this.noMtime = !!opt.noMtime\n this.onWriteEntry = opt.onWriteEntry\n\n this.readEntry = readEntry\n const { type } = readEntry\n /* c8 ignore start */\n if (type === 'Unsupported') {\n throw new Error('writing entry that should be ignored')\n }\n /* c8 ignore stop */\n this.type = type\n if (this.type === 'Directory' && this.portable) {\n this.noMtime = true\n }\n\n this.prefix = opt.prefix\n\n this.path = normalizeWindowsPath(readEntry.path)\n this.mode =\n readEntry.mode !== undefined ?\n this[MODE](readEntry.mode)\n : undefined\n this.uid = this.portable ? undefined : readEntry.uid\n this.gid = this.portable ? undefined : readEntry.gid\n this.uname = this.portable ? undefined : readEntry.uname\n this.gname = this.portable ? undefined : readEntry.gname\n this.size = readEntry.size\n this.mtime =\n this.noMtime ? undefined : opt.mtime || readEntry.mtime\n this.atime = this.portable ? undefined : readEntry.atime\n this.ctime = this.portable ? undefined : readEntry.ctime\n this.linkpath =\n readEntry.linkpath !== undefined ?\n normalizeWindowsPath(readEntry.linkpath)\n : undefined\n\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n\n let pathWarn: false | string = false\n if (!this.preservePaths) {\n const [root, stripped] = stripAbsolutePath(this.path)\n if (root && typeof stripped === 'string') {\n this.path = stripped\n pathWarn = root\n }\n }\n\n this.remain = readEntry.size\n this.blockRemain = readEntry.startBlockSize\n\n this.onWriteEntry?.(this as unknown as WriteEntry)\n this.header = new Header({\n path: this[PREFIX](this.path),\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n // only the permissions and setuid/setgid/sticky bitflags\n // not the higher-order bits that specify file type\n mode: this.mode,\n uid: this.portable ? undefined : this.uid,\n gid: this.portable ? undefined : this.gid,\n size: this.size,\n mtime: this.noMtime ? undefined : this.mtime,\n type: this.type,\n uname: this.portable ? undefined : this.uname,\n atime: this.portable ? undefined : this.atime,\n ctime: this.portable ? undefined : this.ctime,\n })\n\n if (pathWarn) {\n this.warn(\n 'TAR_ENTRY_INFO',\n `stripping ${pathWarn} from absolute path`,\n {\n entry: this,\n path: pathWarn + this.path,\n },\n )\n }\n\n if (this.header.encode() && !this.noPax) {\n super.write(\n new Pax({\n atime: this.portable ? undefined : this.atime,\n ctime: this.portable ? undefined : this.ctime,\n gid: this.portable ? undefined : this.gid,\n mtime: this.noMtime ? undefined : this.mtime,\n path: this[PREFIX](this.path),\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n size: this.size,\n uid: this.portable ? undefined : this.uid,\n uname: this.portable ? undefined : this.uname,\n dev: this.portable ? undefined : this.readEntry.dev,\n ino: this.portable ? undefined : this.readEntry.ino,\n nlink: this.portable ? undefined : this.readEntry.nlink,\n }).encode(),\n )\n }\n\n const b = this.header?.block\n /* c8 ignore start */\n if (!b) throw new Error('failed to encode header')\n /* c8 ignore stop */\n super.write(b)\n readEntry.pipe(this)\n }\n\n [PREFIX](path: string) {\n return prefixPath(path, this.prefix)\n }\n\n [MODE](mode: number) {\n return modeFix(mode, this.type === 'Directory', this.portable)\n }\n\n write(buffer: Buffer | string, cb?: () => void): boolean\n write(\n str: Buffer | string,\n encoding?: BufferEncoding | null,\n cb?: () => void,\n ): boolean\n write(\n chunk: Buffer | string,\n encoding?: BufferEncoding | (() => any) | null,\n cb?: () => any,\n ): boolean {\n /* c8 ignore start - just junk to comply with NodeJS.WritableStream */\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(\n chunk,\n typeof encoding === 'string' ? encoding : 'utf8',\n )\n }\n /* c8 ignore stop */\n const writeLen = chunk.length\n if (writeLen > this.blockRemain) {\n throw new Error('writing more to entry than is appropriate')\n }\n this.blockRemain -= writeLen\n return super.write(chunk, cb)\n }\n\n end(cb?: () => void): this\n end(chunk: Buffer | string, cb?: () => void): this\n end(\n chunk: Buffer | string,\n encoding?: BufferEncoding,\n cb?: () => void,\n ): this\n end(\n chunk?: Buffer | string | (() => void),\n encoding?: BufferEncoding | (() => void),\n cb?: () => void,\n ): this {\n if (this.blockRemain) {\n super.write(Buffer.alloc(this.blockRemain))\n }\n /* c8 ignore start - just junk to comply with NodeJS.WritableStream */\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding ?? 'utf8')\n }\n if (cb) this.once('finish', cb)\n chunk ? super.end(chunk, cb) : super.end(cb)\n /* c8 ignore stop */\n return this\n }\n}\n\nconst getType = (stat: Stats): EntryTypeName | 'Unsupported' =>\n stat.isFile() ? 'File'\n : stat.isDirectory() ? 'Directory'\n : stat.isSymbolicLink() ? 'SymbolicLink'\n : 'Unsupported'\n", "export const modeFix = (\n mode: number,\n isDir: boolean,\n portable: boolean,\n) => {\n mode &= 0o7777\n\n // in portable mode, use the minimum reasonable umask\n // if this system creates files with 0o664 by default\n // (as some linux distros do), then we'll write the\n // archive with 0o644 instead. Also, don't ever create\n // a file that is not readable/writable by the owner.\n if (portable) {\n mode = (mode | 0o600) & ~0o22\n }\n\n // if dirs are readable, then they should be listable\n if (isDir) {\n if (mode & 0o400) {\n mode |= 0o100\n }\n if (mode & 0o40) {\n mode |= 0o10\n }\n if (mode & 0o4) {\n mode |= 0o1\n }\n }\n return mode\n}\n", "// unix absolute paths are also absolute on win32, so we use this for both\nimport { win32 } from 'node:path'\nconst { isAbsolute, parse } = win32\n\n// returns [root, stripped]\n// Note that windows will think that //x/y/z/a has a \"root\" of //x/y, and in\n// those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip /\n// explicitly if it's the first character.\n// drive-specific relative paths on Windows get their root stripped off even\n// though they are not absolute, so `c:../foo` becomes ['c:', '../foo']\nexport const stripAbsolutePath = (path: string) => {\n let r = ''\n\n let parsed = parse(path)\n while (isAbsolute(path) || parsed.root) {\n // windows will think that //x/y/z has a \"root\" of //x/y/\n // but strip the //?/C:/ off of //?/C:/path\n const root =\n path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ?\n '/'\n : parsed.root\n path = path.slice(root.length)\n r += root\n parsed = parse(path)\n }\n return [r, path]\n}\n", "// When writing files on Windows, translate the characters to their\n// 0xf000 higher-encoded versions.\n\nconst raw = ['|', '<', '>', '?', ':']\n\nconst win = raw.map(char =>\n String.fromCharCode(0xf000 + char.charCodeAt(0)),\n)\n\nconst toWin = new Map(raw.map((char, i) => [char, win[i]]))\nconst toRaw = new Map(win.map((char, i) => [char, raw[i]]))\n\nexport const encode = (s: string) =>\n raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s)\nexport const decode = (s: string) =>\n win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s)\n", "export class Yallist<T = unknown> {\n tail?: Node<T>\n head?: Node<T>\n length: number = 0\n\n static create<T = unknown>(list: Iterable<T> = []) {\n return new Yallist(list)\n }\n\n constructor(list: Iterable<T> = []) {\n for (const item of list) {\n this.push(item)\n }\n }\n\n *[Symbol.iterator]() {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n\n removeNode(node: Node<T>) {\n if (node.list !== this) {\n throw new Error(\n 'removing node which does not belong to this list',\n )\n }\n\n const next = node.next\n const prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n this.length--\n node.next = undefined\n node.prev = undefined\n node.list = undefined\n\n return next\n }\n\n unshiftNode(node: Node<T>) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n const head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n }\n\n pushNode(node: Node<T>) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n const tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n }\n\n push(...args: T[]) {\n for (let i = 0, l = args.length; i < l; i++) {\n push(this, args[i])\n }\n return this.length\n }\n\n unshift(...args: T[]) {\n for (var i = 0, l = args.length; i < l; i++) {\n unshift(this, args[i])\n }\n return this.length\n }\n\n pop() {\n if (!this.tail) {\n return undefined\n }\n\n const res = this.tail.value\n const t = this.tail\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = undefined\n } else {\n this.head = undefined\n }\n t.list = undefined\n this.length--\n return res\n }\n\n shift() {\n if (!this.head) {\n return undefined\n }\n\n const res = this.head.value\n const h = this.head\n this.head = this.head.next\n if (this.head) {\n this.head.prev = undefined\n } else {\n this.tail = undefined\n }\n h.list = undefined\n this.length--\n return res\n }\n\n forEach(\n fn: (value: T, i: number, list: Yallist<T>) => any,\n thisp?: any,\n ) {\n thisp = thisp || this\n for (let walker = this.head, i = 0; !!walker; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n }\n\n forEachReverse(\n fn: (value: T, i: number, list: Yallist<T>) => any,\n thisp?: any,\n ) {\n thisp = thisp || this\n for (let walker = this.tail, i = this.length - 1; !!walker; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n }\n\n get(n: number) {\n let i = 0\n let walker = this.head\n for (; !!walker && i < n; i++) {\n walker = walker.next\n }\n if (i === n && !!walker) {\n return walker.value\n }\n }\n\n getReverse(n: number) {\n let i = 0\n let walker = this.tail\n for (; !!walker && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && !!walker) {\n return walker.value\n }\n }\n\n map<R = any>(\n fn: (value: T, list: Yallist<T>) => R,\n thisp?: any,\n ): Yallist<R> {\n thisp = thisp || this\n const res = new Yallist<R>()\n for (let walker = this.head; !!walker; ) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n }\n\n mapReverse<R = any>(\n fn: (value: T, list: Yallist<T>) => R,\n thisp?: any,\n ): Yallist<R> {\n thisp = thisp || this\n var res = new Yallist<R>()\n for (let walker = this.tail; !!walker; ) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n }\n\n reduce(fn: (left: T, right: T, i: number) => T): T\n reduce<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial: R,\n ): R\n reduce<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial?: R,\n ): R {\n let acc: R | T\n let walker = this.head\n if (arguments.length > 1) {\n acc = initial as R\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError(\n 'Reduce of empty list with no initial value',\n )\n }\n\n for (var i = 0; !!walker; i++) {\n acc = fn(acc as R, walker.value, i)\n walker = walker.next\n }\n\n return acc as R\n }\n\n reduceReverse(fn: (left: T, right: T, i: number) => T): T\n reduceReverse<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial: R,\n ): R\n reduceReverse<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial?: R,\n ): R {\n let acc: R | T\n let walker = this.tail\n if (arguments.length > 1) {\n acc = initial as R\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError(\n 'Reduce of empty list with no initial value',\n )\n }\n\n for (let i = this.length - 1; !!walker; i--) {\n acc = fn(acc as R, walker.value, i)\n walker = walker.prev\n }\n\n return acc as R\n }\n\n toArray() {\n const arr = new Array(this.length)\n for (let i = 0, walker = this.head; !!walker; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n }\n\n toArrayReverse() {\n const arr = new Array(this.length)\n for (let i = 0, walker = this.tail; !!walker; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n }\n\n slice(from: number = 0, to: number = this.length) {\n if (to < 0) {\n to += this.length\n }\n if (from < 0) {\n from += this.length\n }\n const ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n let walker = this.head\n let i = 0\n for (i = 0; !!walker && i < from; i++) {\n walker = walker.next\n }\n for (; !!walker && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n }\n\n sliceReverse(from: number = 0, to: number = this.length) {\n if (to < 0) {\n to += this.length\n }\n if (from < 0) {\n from += this.length\n }\n const ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n let i = this.length\n let walker = this.tail\n for (; !!walker && i > to; i--) {\n walker = walker.prev\n }\n for (; !!walker && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n }\n\n splice(start: number, deleteCount: number = 0, ...nodes: T[]) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start\n }\n\n let walker = this.head\n\n for (let i = 0; !!walker && i < start; i++) {\n walker = walker.next\n }\n\n const ret: T[] = []\n for (let i = 0; !!walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (!walker) {\n walker = this.tail\n } else if (walker !== this.tail) {\n walker = walker.prev\n }\n\n for (const v of nodes) {\n walker = insertAfter<T>(this, walker, v)\n }\n\n return ret\n }\n\n reverse() {\n const head = this.head\n const tail = this.tail\n for (let walker = head; !!walker; walker = walker.prev) {\n const p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n }\n}\n\n// insertAfter undefined means \"make the node the new head of list\"\nfunction insertAfter<T>(\n self: Yallist<T>,\n node: Node<T> | undefined,\n value: T,\n) {\n const prev = node\n const next = node ? node.next : self.head\n const inserted = new Node<T>(value, prev, next, self)\n\n if (inserted.next === undefined) {\n self.tail = inserted\n }\n if (inserted.prev === undefined) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push<T>(self: Yallist<T>, item: T) {\n self.tail = new Node<T>(item, self.tail, undefined, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift<T>(self: Yallist<T>, item: T) {\n self.head = new Node<T>(item, undefined, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nexport class Node<T = unknown> {\n list?: Yallist<T>\n next?: Node<T>\n prev?: Node<T>\n value: T\n\n constructor(\n value: T,\n prev?: Node<T> | undefined,\n next?: Node<T> | undefined,\n list?: Yallist<T> | undefined,\n ) {\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = undefined\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = undefined\n }\n }\n}\n", "// tar -x\nimport * as fsm from '@isaacs/fs-minipass'\nimport fs from 'node:fs'\nimport { filesFilter } from './list.js'\nimport { makeCommand } from './make-command.js'\nimport { TarOptionsFile, TarOptionsSyncFile } from './options.js'\nimport { Unpack, UnpackSync } from './unpack.js'\n\nconst extractFileSync = (opt: TarOptionsSyncFile) => {\n const u = new UnpackSync(opt)\n const file = opt.file\n const stat = fs.statSync(file)\n // This trades a zero-byte read() syscall for a stat\n // However, it will usually result in less memory allocation\n const readSize = opt.maxReadSize || 16 * 1024 * 1024\n const stream = new fsm.ReadStreamSync(file, {\n readSize: readSize,\n size: stat.size,\n })\n stream.pipe(u)\n}\n\nconst extractFile = (opt: TarOptionsFile, _?: string[]) => {\n const u = new Unpack(opt)\n const readSize = opt.maxReadSize || 16 * 1024 * 1024\n\n const file = opt.file\n const p = new Promise<void>((resolve, reject) => {\n u.on('error', reject)\n u.on('close', resolve)\n\n // This trades a zero-byte read() syscall for a stat\n // However, it will usually result in less memory allocation\n fs.stat(file, (er, stat) => {\n if (er) {\n reject(er)\n } else {\n const stream = new fsm.ReadStream(file, {\n readSize: readSize,\n size: stat.size,\n })\n stream.on('error', reject)\n stream.pipe(u)\n }\n })\n })\n return p\n}\n\nexport const extract = makeCommand<Unpack, UnpackSync>(\n extractFileSync,\n extractFile,\n opt => new UnpackSync(opt),\n opt => new Unpack(opt),\n (opt, files) => {\n if (files?.length) filesFilter(opt, files)\n },\n)\n", "// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.\n// but the path reservations are required to avoid race conditions where\n// parallelized unpack ops may mess with one another, due to dependencies\n// (like a Link depending on its target) or destructive operations (like\n// clobbering an fs object to create one of a different type.)\n\nimport * as fsm from '@isaacs/fs-minipass'\nimport assert from 'node:assert'\nimport { randomBytes } from 'node:crypto'\nimport fs, { type Stats } from 'node:fs'\nimport path from 'node:path'\nimport { getWriteFlag } from './get-write-flag.js'\nimport { mkdir, MkdirError, mkdirSync } from './mkdir.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { Parser } from './parse.js'\nimport { stripAbsolutePath } from './strip-absolute-path.js'\nimport * as wc from './winchars.js'\n\nimport { TarOptions } from './options.js'\nimport { PathReservations } from './path-reservations.js'\nimport { ReadEntry } from './read-entry.js'\nimport { WarnData } from './warn-method.js'\n\nconst ONENTRY = Symbol('onEntry')\nconst CHECKFS = Symbol('checkFs')\nconst CHECKFS2 = Symbol('checkFs2')\nconst ISREUSABLE = Symbol('isReusable')\nconst MAKEFS = Symbol('makeFs')\nconst FILE = Symbol('file')\nconst DIRECTORY = Symbol('directory')\nconst LINK = Symbol('link')\nconst SYMLINK = Symbol('symlink')\nconst HARDLINK = Symbol('hardlink')\nconst UNSUPPORTED = Symbol('unsupported')\nconst CHECKPATH = Symbol('checkPath')\nconst STRIPABSOLUTEPATH = Symbol('stripAbsolutePath')\nconst MKDIR = Symbol('mkdir')\nconst ONERROR = Symbol('onError')\nconst PENDING = Symbol('pending')\nconst PEND = Symbol('pend')\nconst UNPEND = Symbol('unpend')\nconst ENDED = Symbol('ended')\nconst MAYBECLOSE = Symbol('maybeClose')\nconst SKIP = Symbol('skip')\nconst DOCHOWN = Symbol('doChown')\nconst UID = Symbol('uid')\nconst GID = Symbol('gid')\nconst CHECKED_CWD = Symbol('checkedCwd')\nconst platform =\n process.env.TESTING_TAR_FAKE_PLATFORM || process.platform\nconst isWindows = platform === 'win32'\nconst DEFAULT_MAX_DEPTH = 1024\n\n// Unlinks on Windows are not atomic.\n//\n// This means that if you have a file entry, followed by another\n// file entry with an identical name, and you cannot re-use the file\n// (because it's a hardlink, or because unlink:true is set, or it's\n// Windows, which does not have useful nlink values), then the unlink\n// will be committed to the disk AFTER the new file has been written\n// over the old one, deleting the new file.\n//\n// To work around this, on Windows systems, we rename the file and then\n// delete the renamed file. It's a sloppy kludge, but frankly, I do not\n// know of a better way to do this, given windows' non-atomic unlink\n// semantics.\n//\n// See: https://github.com/npm/node-tar/issues/183\n/* c8 ignore start */\nconst unlinkFile = (\n path: string,\n cb: (er?: Error | null) => void,\n) => {\n if (!isWindows) {\n return fs.unlink(path, cb)\n }\n\n const name = path + '.DELETE.' + randomBytes(16).toString('hex')\n fs.rename(path, name, er => {\n if (er) {\n return cb(er)\n }\n fs.unlink(name, cb)\n })\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */\nconst unlinkFileSync = (path: string) => {\n if (!isWindows) {\n return fs.unlinkSync(path)\n }\n\n const name = path + '.DELETE.' + randomBytes(16).toString('hex')\n fs.renameSync(path, name)\n fs.unlinkSync(name)\n}\n/* c8 ignore stop */\n\n// this.gid, entry.gid, this.processUid\nconst uint32 = (\n a: number | undefined,\n b: number | undefined,\n c: number | undefined,\n) =>\n a !== undefined && a === a >>> 0 ? a\n : b !== undefined && b === b >>> 0 ? b\n : c\n\nexport class Unpack extends Parser {\n [ENDED]: boolean = false;\n [CHECKED_CWD]: boolean = false;\n [PENDING]: number = 0\n\n reservations: PathReservations = new PathReservations()\n transform?: TarOptions['transform']\n writable: true = true\n readable: false = false\n uid?: number\n gid?: number\n setOwner: boolean\n preserveOwner: boolean\n processGid?: number\n processUid?: number\n maxDepth: number\n forceChown: boolean\n win32: boolean\n newer: boolean\n keep: boolean\n noMtime: boolean\n preservePaths: boolean\n unlink: boolean\n cwd: string\n strip: number\n processUmask: number\n umask: number\n dmode: number\n fmode: number\n chmod: boolean\n\n constructor(opt: TarOptions = {}) {\n opt.ondone = () => {\n this[ENDED] = true\n this[MAYBECLOSE]()\n }\n\n super(opt)\n\n this.transform = opt.transform\n\n this.chmod = !!opt.chmod\n\n if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {\n // need both or neither\n if (\n typeof opt.uid !== 'number' ||\n typeof opt.gid !== 'number'\n ) {\n throw new TypeError(\n 'cannot set owner without number uid and gid',\n )\n }\n if (opt.preserveOwner) {\n throw new TypeError(\n 'cannot preserve owner in archive and also set owner explicitly',\n )\n }\n this.uid = opt.uid\n this.gid = opt.gid\n this.setOwner = true\n } else {\n this.uid = undefined\n this.gid = undefined\n this.setOwner = false\n }\n\n // default true for root\n if (\n opt.preserveOwner === undefined &&\n typeof opt.uid !== 'number'\n ) {\n this.preserveOwner = !!(\n process.getuid && process.getuid() === 0\n )\n } else {\n this.preserveOwner = !!opt.preserveOwner\n }\n\n this.processUid =\n (this.preserveOwner || this.setOwner) && process.getuid ?\n process.getuid()\n : undefined\n this.processGid =\n (this.preserveOwner || this.setOwner) && process.getgid ?\n process.getgid()\n : undefined\n\n // prevent excessively deep nesting of subfolders\n // set to `Infinity` to remove this restriction\n this.maxDepth =\n typeof opt.maxDepth === 'number' ?\n opt.maxDepth\n : DEFAULT_MAX_DEPTH\n\n // mostly just for testing, but useful in some cases.\n // Forcibly trigger a chown on every entry, no matter what\n this.forceChown = opt.forceChown === true\n\n // turn ><?| in filenames into 0xf000-higher encoded forms\n this.win32 = !!opt.win32 || isWindows\n\n // do not unpack over files that are newer than what's in the archive\n this.newer = !!opt.newer\n\n // do not unpack over ANY files\n this.keep = !!opt.keep\n\n // do not set mtime/atime of extracted entries\n this.noMtime = !!opt.noMtime\n\n // allow .., absolute path entries, and unpacking through symlinks\n // without this, warn and skip .., relativize absolutes, and error\n // on symlinks in extraction path\n this.preservePaths = !!opt.preservePaths\n\n // unlink files and links before writing. This breaks existing hard\n // links, and removes symlink directories rather than erroring\n this.unlink = !!opt.unlink\n\n this.cwd = normalizeWindowsPath(\n path.resolve(opt.cwd || process.cwd()),\n )\n this.strip = Number(opt.strip) || 0\n // if we're not chmodding, then we don't need the process umask\n this.processUmask =\n !this.chmod ? 0\n : typeof opt.processUmask === 'number' ? opt.processUmask\n : process.umask()\n this.umask =\n typeof opt.umask === 'number' ? opt.umask : this.processUmask\n\n // default mode for dirs created as parents\n this.dmode = opt.dmode || 0o0777 & ~this.umask\n this.fmode = opt.fmode || 0o0666 & ~this.umask\n\n this.on('entry', entry => this[ONENTRY](entry))\n }\n\n // a bad or damaged archive is a warning for Parser, but an error\n // when extracting. Mark those errors as unrecoverable, because\n // the Unpack contract cannot be met.\n warn(code: string, msg: string | Error, data: WarnData = {}) {\n if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') {\n data.recoverable = false\n }\n return super.warn(code, msg, data)\n }\n\n [MAYBECLOSE]() {\n if (this[ENDED] && this[PENDING] === 0) {\n this.emit('prefinish')\n this.emit('finish')\n this.emit('end')\n }\n }\n\n // return false if we need to skip this file\n // return true if the field was successfully sanitized\n [STRIPABSOLUTEPATH](\n entry: ReadEntry,\n field: 'path' | 'linkpath',\n ): boolean {\n const p = entry[field]\n const { type } = entry\n if (!p || this.preservePaths) return true\n\n const parts = p.split('/')\n\n if (\n parts.includes('..') ||\n /* c8 ignore next */\n (isWindows && /^[a-z]:\\.\\.$/i.test(parts[0] ?? ''))\n ) {\n // For linkpath, check if the resolved path escapes cwd rather than\n // just rejecting any path with '..' - relative symlinks like\n // '../sibling/file' are valid if they resolve within the cwd.\n // For paths, they just simply may not ever use .. at all.\n if (field === 'path' || type === 'Link') {\n this.warn('TAR_ENTRY_ERROR', `${field} contains '..'`, {\n entry,\n [field]: p,\n })\n // not ok!\n return false\n } else {\n // Resolve linkpath relative to the entry's directory.\n // `path.posix` is safe to use because we're operating on\n // tar paths, not a filesystem.\n const entryDir = path.posix.dirname(entry.path)\n const resolved = path.posix.normalize(\n path.posix.join(entryDir, p),\n )\n // If the resolved path escapes (starts with ..), reject it\n if (resolved.startsWith('../') || resolved === '..') {\n this.warn(\n 'TAR_ENTRY_ERROR',\n `${field} escapes extraction directory`,\n {\n entry,\n [field]: p,\n },\n )\n return false\n }\n }\n }\n\n // strip off the root\n const [root, stripped] = stripAbsolutePath(p)\n if (root) {\n // ok, but triggers warning about stripping root\n entry[field] = String(stripped)\n this.warn(\n 'TAR_ENTRY_INFO',\n `stripping ${root} from absolute ${field}`,\n {\n entry,\n [field]: p,\n },\n )\n }\n return true\n }\n\n [CHECKPATH](entry: ReadEntry) {\n const p = normalizeWindowsPath(entry.path)\n const parts = p.split('/')\n\n if (this.strip) {\n if (parts.length < this.strip) {\n return false\n }\n if (entry.type === 'Link') {\n const linkparts = normalizeWindowsPath(\n String(entry.linkpath),\n ).split('/')\n if (linkparts.length >= this.strip) {\n entry.linkpath = linkparts.slice(this.strip).join('/')\n } else {\n return false\n }\n }\n parts.splice(0, this.strip)\n entry.path = parts.join('/')\n }\n\n if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {\n this.warn('TAR_ENTRY_ERROR', 'path excessively deep', {\n entry,\n path: p,\n depth: parts.length,\n maxDepth: this.maxDepth,\n })\n return false\n }\n\n if (\n !this[STRIPABSOLUTEPATH](entry, 'path') ||\n !this[STRIPABSOLUTEPATH](entry, 'linkpath')\n ) {\n return false\n }\n\n if (path.isAbsolute(entry.path)) {\n entry.absolute = normalizeWindowsPath(path.resolve(entry.path))\n } else {\n entry.absolute = normalizeWindowsPath(\n path.resolve(this.cwd, entry.path),\n )\n }\n\n // if we somehow ended up with a path that escapes the cwd, and we are\n // not in preservePaths mode, then something is fishy! This should have\n // been prevented above, so ignore this for coverage.\n /* c8 ignore start - defense in depth */\n if (\n !this.preservePaths &&\n typeof entry.absolute === 'string' &&\n entry.absolute.indexOf(this.cwd + '/') !== 0 &&\n entry.absolute !== this.cwd\n ) {\n this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', {\n entry,\n path: normalizeWindowsPath(entry.path),\n resolvedPath: entry.absolute,\n cwd: this.cwd,\n })\n return false\n }\n /* c8 ignore stop */\n\n // an archive can set properties on the extraction directory, but it\n // may not replace the cwd with a different kind of thing entirely.\n if (\n entry.absolute === this.cwd &&\n entry.type !== 'Directory' &&\n entry.type !== 'GNUDumpDir'\n ) {\n return false\n }\n\n // only encode : chars that aren't drive letter indicators\n if (this.win32) {\n const { root: aRoot } = path.win32.parse(String(entry.absolute))\n entry.absolute =\n aRoot + wc.encode(String(entry.absolute).slice(aRoot.length))\n const { root: pRoot } = path.win32.parse(entry.path)\n entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length))\n }\n\n return true\n }\n\n [ONENTRY](entry: ReadEntry) {\n if (!this[CHECKPATH](entry)) {\n return entry.resume()\n }\n\n assert.equal(typeof entry.absolute, 'string')\n\n switch (entry.type) {\n case 'Directory':\n case 'GNUDumpDir':\n if (entry.mode) {\n entry.mode = entry.mode | 0o700\n }\n\n // eslint-disable-next-line no-fallthrough\n case 'File':\n case 'OldFile':\n case 'ContiguousFile':\n case 'Link':\n case 'SymbolicLink':\n return this[CHECKFS](entry)\n\n case 'CharacterDevice':\n case 'BlockDevice':\n case 'FIFO':\n default:\n return this[UNSUPPORTED](entry)\n }\n }\n\n [ONERROR](er: Error, entry: ReadEntry) {\n // Cwd has to exist, or else nothing works. That's serious.\n // Other errors are warnings, which raise the error in strict\n // mode, but otherwise continue on.\n if (er.name === 'CwdError') {\n this.emit('error', er)\n } else {\n this.warn('TAR_ENTRY_ERROR', er, { entry })\n this[UNPEND]()\n entry.resume()\n }\n }\n\n [MKDIR](\n dir: string,\n mode: number,\n cb: (er?: null | MkdirError, made?: string) => void,\n ) {\n mkdir(\n normalizeWindowsPath(dir),\n {\n uid: this.uid,\n gid: this.gid,\n processUid: this.processUid,\n processGid: this.processGid,\n umask: this.processUmask,\n preserve: this.preservePaths,\n unlink: this.unlink,\n cwd: this.cwd,\n mode: mode,\n },\n cb,\n )\n }\n\n [DOCHOWN](entry: ReadEntry) {\n // in preserve owner mode, chown if the entry doesn't match process\n // in set owner mode, chown if setting doesn't match process\n return (\n this.forceChown ||\n (this.preserveOwner &&\n ((typeof entry.uid === 'number' &&\n entry.uid !== this.processUid) ||\n (typeof entry.gid === 'number' &&\n entry.gid !== this.processGid))) ||\n (typeof this.uid === 'number' &&\n this.uid !== this.processUid) ||\n (typeof this.gid === 'number' && this.gid !== this.processGid)\n )\n }\n\n [UID](entry: ReadEntry) {\n return uint32(this.uid, entry.uid, this.processUid)\n }\n\n [GID](entry: ReadEntry) {\n return uint32(this.gid, entry.gid, this.processGid)\n }\n\n [FILE](entry: ReadEntry, fullyDone: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.fmode\n const stream = new fsm.WriteStream(String(entry.absolute), {\n // slight lie, but it can be numeric flags\n flags: getWriteFlag(entry.size) as string,\n mode: mode,\n autoClose: false,\n })\n stream.on('error', (er: Error) => {\n if (stream.fd) {\n fs.close(stream.fd, () => {})\n }\n\n // flush all the data out so that we aren't left hanging\n // if the error wasn't actually fatal. otherwise the parse\n // is blocked, and we never proceed.\n stream.write = () => true\n this[ONERROR](er, entry)\n fullyDone()\n })\n\n let actions = 1\n const done = (er?: null | Error) => {\n if (er) {\n /* c8 ignore start - we should always have a fd by now */\n if (stream.fd) {\n fs.close(stream.fd, () => {})\n }\n /* c8 ignore stop */\n\n this[ONERROR](er, entry)\n fullyDone()\n return\n }\n\n if (--actions === 0) {\n if (stream.fd !== undefined) {\n fs.close(stream.fd, er => {\n if (er) {\n this[ONERROR](er, entry)\n } else {\n this[UNPEND]()\n }\n fullyDone()\n })\n }\n }\n }\n\n stream.on('finish', () => {\n // if futimes fails, try utimes\n // if utimes fails, fail with the original error\n // same for fchown/chown\n const abs = String(entry.absolute)\n const fd = stream.fd\n\n if (typeof fd === 'number' && entry.mtime && !this.noMtime) {\n actions++\n const atime = entry.atime || new Date()\n const mtime = entry.mtime\n fs.futimes(fd, atime, mtime, er =>\n er ?\n fs.utimes(abs, atime, mtime, er2 => done(er2 && er))\n : done(),\n )\n }\n\n if (typeof fd === 'number' && this[DOCHOWN](entry)) {\n actions++\n const uid = this[UID](entry)\n const gid = this[GID](entry)\n if (typeof uid === 'number' && typeof gid === 'number') {\n fs.fchown(fd, uid, gid, er =>\n er ?\n fs.chown(abs, uid, gid, er2 => done(er2 && er))\n : done(),\n )\n }\n }\n\n done()\n })\n\n const tx = this.transform ? this.transform(entry) || entry : entry\n if (tx !== entry) {\n tx.on('error', (er: Error) => {\n this[ONERROR](er, entry)\n fullyDone()\n })\n entry.pipe(tx)\n }\n tx.pipe(stream)\n }\n\n [DIRECTORY](entry: ReadEntry, fullyDone: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.dmode\n this[MKDIR](String(entry.absolute), mode, er => {\n if (er) {\n this[ONERROR](er, entry)\n fullyDone()\n return\n }\n\n let actions = 1\n const done = () => {\n if (--actions === 0) {\n fullyDone()\n this[UNPEND]()\n entry.resume()\n }\n }\n\n if (entry.mtime && !this.noMtime) {\n actions++\n fs.utimes(\n String(entry.absolute),\n entry.atime || new Date(),\n entry.mtime,\n done,\n )\n }\n\n if (this[DOCHOWN](entry)) {\n actions++\n fs.chown(\n String(entry.absolute),\n Number(this[UID](entry)),\n Number(this[GID](entry)),\n done,\n )\n }\n\n done()\n })\n }\n\n [UNSUPPORTED](entry: ReadEntry) {\n entry.unsupported = true\n this.warn(\n 'TAR_ENTRY_UNSUPPORTED',\n `unsupported entry type: ${entry.type}`,\n { entry },\n )\n entry.resume()\n }\n\n [SYMLINK](entry: ReadEntry, done: () => void) {\n this[LINK](entry, String(entry.linkpath), 'symlink', done)\n }\n\n [HARDLINK](entry: ReadEntry, done: () => void) {\n const linkpath = normalizeWindowsPath(\n path.resolve(this.cwd, String(entry.linkpath)),\n )\n this[LINK](entry, linkpath, 'link', done)\n }\n\n [PEND]() {\n this[PENDING]++\n }\n\n [UNPEND]() {\n this[PENDING]--\n this[MAYBECLOSE]()\n }\n\n [SKIP](entry: ReadEntry) {\n this[UNPEND]()\n entry.resume()\n }\n\n // Check if we can reuse an existing filesystem entry safely and\n // overwrite it, rather than unlinking and recreating\n // Windows doesn't report a useful nlink, so we just never reuse entries\n [ISREUSABLE](entry: ReadEntry, st: Stats) {\n return (\n entry.type === 'File' &&\n !this.unlink &&\n st.isFile() &&\n st.nlink <= 1 &&\n !isWindows\n )\n }\n\n // check if a thing is there, and if so, try to clobber it\n [CHECKFS](entry: ReadEntry) {\n this[PEND]()\n const paths = [entry.path]\n if (entry.linkpath) {\n paths.push(entry.linkpath)\n }\n this.reservations.reserve(paths, done =>\n this[CHECKFS2](entry, done),\n )\n }\n\n [CHECKFS2](entry: ReadEntry, fullyDone: (er?: Error) => void) {\n const done = (er?: Error) => {\n fullyDone(er)\n }\n\n const checkCwd = () => {\n this[MKDIR](this.cwd, this.dmode, er => {\n if (er) {\n this[ONERROR](er, entry)\n done()\n return\n }\n this[CHECKED_CWD] = true\n start()\n })\n }\n\n const start = () => {\n if (entry.absolute !== this.cwd) {\n const parent = normalizeWindowsPath(\n path.dirname(String(entry.absolute)),\n )\n if (parent !== this.cwd) {\n return this[MKDIR](parent, this.dmode, er => {\n if (er) {\n this[ONERROR](er, entry)\n done()\n return\n }\n afterMakeParent()\n })\n }\n }\n afterMakeParent()\n }\n\n const afterMakeParent = () => {\n fs.lstat(String(entry.absolute), (lstatEr, st) => {\n if (\n st &&\n (this.keep ||\n /* c8 ignore next */\n (this.newer && st.mtime > (entry.mtime ?? st.mtime)))\n ) {\n this[SKIP](entry)\n done()\n return\n }\n if (lstatEr || this[ISREUSABLE](entry, st)) {\n return this[MAKEFS](null, entry, done)\n }\n\n if (st.isDirectory()) {\n if (entry.type === 'Directory') {\n const needChmod =\n this.chmod &&\n entry.mode &&\n (st.mode & 0o7777) !== entry.mode\n const afterChmod = (er?: Error | null | undefined) =>\n this[MAKEFS](er ?? null, entry, done)\n if (!needChmod) {\n return afterChmod()\n }\n return fs.chmod(\n String(entry.absolute),\n Number(entry.mode),\n afterChmod,\n )\n }\n // Not a dir entry, have to remove it.\n // NB: the only way to end up with an entry that is the cwd\n // itself, in such a way that == does not detect, is a\n // tricky windows absolute path with UNC or 8.3 parts (and\n // preservePaths:true, or else it will have been stripped).\n // In that case, the user has opted out of path protections\n // explicitly, so if they blow away the cwd, c'est la vie.\n if (entry.absolute !== this.cwd) {\n return fs.rmdir(\n String(entry.absolute),\n (er?: null | Error) =>\n this[MAKEFS](er ?? null, entry, done),\n )\n }\n }\n\n // not a dir, and not reusable\n // don't remove if the cwd, we want that error\n if (entry.absolute === this.cwd) {\n return this[MAKEFS](null, entry, done)\n }\n\n unlinkFile(String(entry.absolute), er =>\n this[MAKEFS](er ?? null, entry, done),\n )\n })\n }\n\n if (this[CHECKED_CWD]) {\n start()\n } else {\n checkCwd()\n }\n }\n\n [MAKEFS](\n er: null | undefined | Error,\n entry: ReadEntry,\n done: () => void,\n ) {\n if (er) {\n this[ONERROR](er, entry)\n done()\n return\n }\n\n switch (entry.type) {\n case 'File':\n case 'OldFile':\n case 'ContiguousFile':\n return this[FILE](entry, done)\n\n case 'Link':\n return this[HARDLINK](entry, done)\n\n case 'SymbolicLink':\n return this[SYMLINK](entry, done)\n\n case 'Directory':\n case 'GNUDumpDir':\n return this[DIRECTORY](entry, done)\n }\n }\n\n [LINK](\n entry: ReadEntry,\n linkpath: string,\n link: 'link' | 'symlink',\n done: () => void,\n ) {\n // XXX: get the type ('symlink' or 'junction') for windows\n fs[link](linkpath, String(entry.absolute), er => {\n if (er) {\n this[ONERROR](er, entry)\n } else {\n this[UNPEND]()\n entry.resume()\n }\n done()\n })\n }\n}\n\nconst callSync = (fn: () => any) => {\n try {\n return [null, fn()]\n } catch (er) {\n return [er, null]\n }\n}\n\nexport class UnpackSync extends Unpack {\n sync: true = true;\n\n [MAKEFS](er: null | Error | undefined, entry: ReadEntry) {\n return super[MAKEFS](er, entry, () => {})\n }\n\n [CHECKFS](entry: ReadEntry) {\n if (!this[CHECKED_CWD]) {\n const er = this[MKDIR](this.cwd, this.dmode)\n if (er) {\n return this[ONERROR](er as Error, entry)\n }\n this[CHECKED_CWD] = true\n }\n\n // don't bother to make the parent if the current entry is the cwd,\n // we've already checked it.\n if (entry.absolute !== this.cwd) {\n const parent = normalizeWindowsPath(\n path.dirname(String(entry.absolute)),\n )\n if (parent !== this.cwd) {\n const mkParent = this[MKDIR](parent, this.dmode)\n if (mkParent) {\n return this[ONERROR](mkParent as Error, entry)\n }\n }\n }\n\n const [lstatEr, st] = callSync(() =>\n fs.lstatSync(String(entry.absolute)),\n )\n if (\n st &&\n (this.keep ||\n /* c8 ignore next */\n (this.newer && st.mtime > (entry.mtime ?? st.mtime)))\n ) {\n return this[SKIP](entry)\n }\n\n if (lstatEr || this[ISREUSABLE](entry, st)) {\n return this[MAKEFS](null, entry)\n }\n\n if (st.isDirectory()) {\n if (entry.type === 'Directory') {\n const needChmod =\n this.chmod &&\n entry.mode &&\n (st.mode & 0o7777) !== entry.mode\n const [er] =\n needChmod ?\n callSync(() => {\n fs.chmodSync(String(entry.absolute), Number(entry.mode))\n })\n : []\n return this[MAKEFS](er, entry)\n }\n // not a dir entry, have to remove it\n const [er] = callSync(() =>\n fs.rmdirSync(String(entry.absolute)),\n )\n this[MAKEFS](er, entry)\n }\n\n // not a dir, and not reusable.\n // don't remove if it's the cwd, since we want that error.\n const [er] =\n entry.absolute === this.cwd ?\n []\n : callSync(() => unlinkFileSync(String(entry.absolute)))\n this[MAKEFS](er, entry)\n }\n\n [FILE](entry: ReadEntry, done: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.fmode\n\n const oner = (er?: null | Error | undefined) => {\n let closeError\n try {\n fs.closeSync(fd)\n } catch (e) {\n closeError = e\n }\n if (er || closeError) {\n this[ONERROR]((er as Error) || closeError, entry)\n }\n done()\n }\n\n let fd: number\n try {\n fd = fs.openSync(\n String(entry.absolute),\n getWriteFlag(entry.size),\n mode,\n )\n /* c8 ignore start - This is only a problem if the file was successfully\n * statted, BUT failed to open. Testing this is annoying, and we\n * already have ample testint for other uses of oner() methods.\n */\n } catch (er) {\n return oner(er as Error)\n }\n /* c8 ignore stop */\n const tx = this.transform ? this.transform(entry) || entry : entry\n if (tx !== entry) {\n tx.on('error', (er: Error) => this[ONERROR](er, entry))\n entry.pipe(tx)\n }\n\n tx.on('data', (chunk: Buffer) => {\n try {\n fs.writeSync(fd, chunk, 0, chunk.length)\n } catch (er) {\n oner(er as Error)\n }\n })\n\n tx.on('end', () => {\n let er = null\n // try both, falling futimes back to utimes\n // if either fails, handle the first error\n if (entry.mtime && !this.noMtime) {\n const atime = entry.atime || new Date()\n const mtime = entry.mtime\n try {\n fs.futimesSync(fd, atime, mtime)\n } catch (futimeser) {\n try {\n fs.utimesSync(String(entry.absolute), atime, mtime)\n } catch (utimeser) {\n er = futimeser\n }\n }\n }\n\n if (this[DOCHOWN](entry)) {\n const uid = this[UID](entry)\n const gid = this[GID](entry)\n\n try {\n fs.fchownSync(fd, Number(uid), Number(gid))\n } catch (fchowner) {\n try {\n fs.chownSync(\n String(entry.absolute),\n Number(uid),\n Number(gid),\n )\n } catch (chowner) {\n er = er || fchowner\n }\n }\n }\n\n oner(er as Error)\n })\n }\n\n [DIRECTORY](entry: ReadEntry, done: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.dmode\n const er = this[MKDIR](String(entry.absolute), mode)\n if (er) {\n this[ONERROR](er as Error, entry)\n done()\n return\n }\n if (entry.mtime && !this.noMtime) {\n try {\n fs.utimesSync(\n String(entry.absolute),\n entry.atime || new Date(),\n entry.mtime,\n )\n /* c8 ignore next */\n } catch (er) {}\n }\n if (this[DOCHOWN](entry)) {\n try {\n fs.chownSync(\n String(entry.absolute),\n Number(this[UID](entry)),\n Number(this[GID](entry)),\n )\n } catch (er) {}\n }\n done()\n entry.resume()\n }\n\n [MKDIR](dir: string, mode: number) {\n try {\n return mkdirSync(normalizeWindowsPath(dir), {\n uid: this.uid,\n gid: this.gid,\n processUid: this.processUid,\n processGid: this.processGid,\n umask: this.processUmask,\n preserve: this.preservePaths,\n unlink: this.unlink,\n cwd: this.cwd,\n mode: mode,\n })\n } catch (er) {\n return er\n }\n }\n\n [LINK](\n entry: ReadEntry,\n linkpath: string,\n link: 'link' | 'symlink',\n done: () => void,\n ) {\n const ls: `${typeof link}Sync` = `${link}Sync`\n try {\n fs[ls](linkpath, String(entry.absolute))\n done()\n entry.resume()\n } catch (er) {\n return this[ONERROR](er as Error, entry)\n }\n }\n}\n", "// Get the appropriate flag to use for creating files\n// We use fmap on Windows platforms for files less than\n// 512kb. This is a fairly low limit, but avoids making\n// things slower in some cases. Since most of what this\n// library is used for is extracting tarballs of many\n// relatively small files in npm packages and the like,\n// it can be a big boost on Windows platforms.\n\nimport fs from 'fs'\n\nconst platform = process.env.__FAKE_PLATFORM__ || process.platform\nconst isWindows = platform === 'win32'\n\n/* c8 ignore start */\nconst { O_CREAT, O_TRUNC, O_WRONLY } = fs.constants\nconst UV_FS_O_FILEMAP =\n Number(process.env.__FAKE_FS_O_FILENAME__) ||\n fs.constants.UV_FS_O_FILEMAP ||\n 0\n/* c8 ignore stop */\n\nconst fMapEnabled = isWindows && !!UV_FS_O_FILEMAP\nconst fMapLimit = 512 * 1024\nconst fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY\nexport const getWriteFlag =\n !fMapEnabled ?\n () => 'w'\n : (size: number) => (size < fMapLimit ? fMapFlag : 'w')\n", "import fs, { type Dirent } from 'node:fs'\nimport path from 'node:path'\n\nconst lchownSync = (path: string, uid: number, gid: number) => {\n try {\n return fs.lchownSync(path, uid, gid)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code !== 'ENOENT') throw er\n }\n}\n\nconst chown = (\n cpath: string,\n uid: number,\n gid: number,\n cb: (er?: unknown) => any,\n) => {\n fs.lchown(cpath, uid, gid, er => {\n // Skip ENOENT error\n cb(er && (er as NodeJS.ErrnoException)?.code !== 'ENOENT' ? er : null)\n })\n}\n\nconst chownrKid = (\n p: string,\n child: Dirent,\n uid: number,\n gid: number,\n cb: (er?: unknown) => any,\n) => {\n if (child.isDirectory()) {\n chownr(path.resolve(p, child.name), uid, gid, (er: unknown) => {\n if (er) return cb(er)\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n })\n } else {\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n }\n}\n\nexport const chownr = (\n p: string,\n uid: number,\n gid: number,\n cb: (er?: unknown) => any,\n) => {\n fs.readdir(p, { withFileTypes: true }, (er, children) => {\n // any error other than ENOTDIR or ENOTSUP means it's not readable,\n // or doesn't exist. give up.\n if (er) {\n if (er.code === 'ENOENT') return cb()\n else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')\n return cb(er)\n }\n if (er || !children.length) return chown(p, uid, gid, cb)\n\n let len = children.length\n let errState: null | NodeJS.ErrnoException = null\n const then = (er?: unknown) => {\n /* c8 ignore start */\n if (errState) return\n /* c8 ignore stop */\n if (er) return cb((errState = er as NodeJS.ErrnoException))\n if (--len === 0) return chown(p, uid, gid, cb)\n }\n\n for (const child of children) {\n chownrKid(p, child, uid, gid, then)\n }\n })\n}\n\nconst chownrKidSync = (\n p: string,\n child: Dirent,\n uid: number,\n gid: number,\n) => {\n if (child.isDirectory())\n chownrSync(path.resolve(p, child.name), uid, gid)\n\n lchownSync(path.resolve(p, child.name), uid, gid)\n}\n\nexport const chownrSync = (p: string, uid: number, gid: number) => {\n let children: Dirent[]\n try {\n children = fs.readdirSync(p, { withFileTypes: true })\n } catch (er) {\n const e = er as NodeJS.ErrnoException\n if (e?.code === 'ENOENT') return\n else if (e?.code === 'ENOTDIR' || e?.code === 'ENOTSUP')\n return lchownSync(p, uid, gid)\n else throw e\n }\n\n for (const child of children) {\n chownrKidSync(p, child, uid, gid)\n }\n\n return lchownSync(p, uid, gid)\n}\n", "import { chownr, chownrSync } from 'chownr'\nimport fs from 'node:fs'\nimport fsp from 'node:fs/promises'\nimport path from 'node:path'\nimport { CwdError } from './cwd-error.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { SymlinkError } from './symlink-error.js'\n\nexport type MkdirOptions = {\n uid?: number\n gid?: number\n processUid?: number\n processGid?: number\n umask?: number\n preserve: boolean\n unlink: boolean\n cwd: string\n mode: number\n}\n\nexport type MkdirError =\n | NodeJS.ErrnoException\n | CwdError\n | SymlinkError\n\nconst checkCwd = (\n dir: string,\n cb: (er?: null | MkdirError) => any,\n) => {\n fs.stat(dir, (er, st) => {\n if (er || !st.isDirectory()) {\n er = new CwdError(\n dir,\n (er as NodeJS.ErrnoException)?.code || 'ENOTDIR',\n )\n }\n cb(er)\n })\n}\n\n/**\n * Wrapper around fs/promises.mkdir for tar's needs.\n *\n * The main purpose is to avoid creating directories if we know that\n * they already exist (and track which ones exist for this purpose),\n * and prevent entries from being extracted into symlinked folders,\n * if `preservePaths` is not set.\n */\nexport const mkdir = (\n dir: string,\n opt: MkdirOptions,\n cb: (er?: null | MkdirError, made?: string) => void,\n) => {\n dir = normalizeWindowsPath(dir)\n\n // if there's any overlap between mask and mode,\n // then we'll need an explicit chmod\n /* c8 ignore next */\n const umask = opt.umask ?? 0o22\n const mode = opt.mode | 0o0700\n const needChmod = (mode & umask) !== 0\n\n const uid = opt.uid\n const gid = opt.gid\n const doChown =\n typeof uid === 'number' &&\n typeof gid === 'number' &&\n (uid !== opt.processUid || gid !== opt.processGid)\n\n const preserve = opt.preserve\n const unlink = opt.unlink\n const cwd = normalizeWindowsPath(opt.cwd)\n\n const done = (er?: null | MkdirError, created?: string) => {\n if (er) {\n cb(er)\n } else {\n if (created && doChown) {\n chownr(created, uid, gid, er =>\n done(er as NodeJS.ErrnoException),\n )\n } else if (needChmod) {\n fs.chmod(dir, mode, cb)\n } else {\n cb()\n }\n }\n }\n\n if (dir === cwd) {\n return checkCwd(dir, done)\n }\n\n if (preserve) {\n return fsp.mkdir(dir, { mode, recursive: true }).then(\n made => done(null, made ?? undefined), // oh, ts\n done,\n )\n }\n\n const sub = normalizeWindowsPath(path.relative(cwd, dir))\n const parts = sub.split('/')\n mkdir_(cwd, parts, mode, unlink, cwd, undefined, done)\n}\n\nconst mkdir_ = (\n base: string,\n parts: string[],\n mode: number,\n unlink: boolean,\n cwd: string,\n created: string | undefined,\n cb: (er?: null | MkdirError, made?: string) => void,\n): void => {\n if (!parts.length) {\n return cb(null, created)\n }\n const p = parts.shift()\n const part = normalizeWindowsPath(path.resolve(base + '/' + p))\n fs.mkdir(\n part,\n mode,\n onmkdir(part, parts, mode, unlink, cwd, created, cb),\n )\n}\n\nconst onmkdir =\n (\n part: string,\n parts: string[],\n mode: number,\n unlink: boolean,\n cwd: string,\n created: string | undefined,\n cb: (er?: null | MkdirError, made?: string) => void,\n ) =>\n (er?: null | NodeJS.ErrnoException) => {\n if (er) {\n fs.lstat(part, (statEr, st) => {\n if (statEr) {\n statEr.path =\n statEr.path && normalizeWindowsPath(statEr.path)\n cb(statEr)\n } else if (st.isDirectory()) {\n mkdir_(part, parts, mode, unlink, cwd, created, cb)\n } else if (unlink) {\n fs.unlink(part, er => {\n if (er) {\n return cb(er)\n }\n fs.mkdir(\n part,\n mode,\n onmkdir(part, parts, mode, unlink, cwd, created, cb),\n )\n })\n } else if (st.isSymbolicLink()) {\n return cb(\n new SymlinkError(part, part + '/' + parts.join('/')),\n )\n } else {\n cb(er)\n }\n })\n } else {\n created = created || part\n mkdir_(part, parts, mode, unlink, cwd, created, cb)\n }\n }\n\nconst checkCwdSync = (dir: string) => {\n let ok = false\n let code: string | undefined = undefined\n try {\n ok = fs.statSync(dir).isDirectory()\n } catch (er) {\n code = (er as NodeJS.ErrnoException)?.code\n } finally {\n if (!ok) {\n throw new CwdError(dir, code ?? 'ENOTDIR')\n }\n }\n}\n\nexport const mkdirSync = (dir: string, opt: MkdirOptions) => {\n dir = normalizeWindowsPath(dir)\n // if there's any overlap between mask and mode,\n // then we'll need an explicit chmod\n /* c8 ignore next */\n const umask = opt.umask ?? 0o22\n const mode = opt.mode | 0o700\n const needChmod = (mode & umask) !== 0\n\n const uid = opt.uid\n const gid = opt.gid\n const doChown =\n typeof uid === 'number' &&\n typeof gid === 'number' &&\n (uid !== opt.processUid || gid !== opt.processGid)\n\n const preserve = opt.preserve\n const unlink = opt.unlink\n const cwd = normalizeWindowsPath(opt.cwd)\n\n const done = (created?: string | undefined) => {\n if (created && doChown) {\n chownrSync(created, uid, gid)\n }\n if (needChmod) {\n fs.chmodSync(dir, mode)\n }\n }\n\n if (dir === cwd) {\n checkCwdSync(cwd)\n return done()\n }\n\n if (preserve) {\n return done(\n fs.mkdirSync(dir, { mode, recursive: true }) ?? undefined,\n )\n }\n\n const sub = normalizeWindowsPath(path.relative(cwd, dir))\n const parts = sub.split('/')\n let created: string | undefined = undefined\n for (\n let p = parts.shift(), part = cwd;\n p && (part += '/' + p);\n p = parts.shift()\n ) {\n part = normalizeWindowsPath(path.resolve(part))\n\n try {\n fs.mkdirSync(part, mode)\n created = created || part\n } catch (er) {\n const st = fs.lstatSync(part)\n if (st.isDirectory()) {\n continue\n } else if (unlink) {\n fs.unlinkSync(part)\n fs.mkdirSync(part, mode)\n created = created || part\n continue\n } else if (st.isSymbolicLink()) {\n return new SymlinkError(part, part + '/' + parts.join('/'))\n }\n }\n }\n\n return done(created)\n}\n", "export class CwdError extends Error {\n path: string\n code: string\n syscall: 'chdir' = 'chdir'\n\n constructor(path: string, code: string) {\n super(`${code}: Cannot cd into '${path}'`)\n this.path = path\n this.code = code\n }\n\n get name() {\n return 'CwdError'\n }\n}\n", "export class SymlinkError extends Error {\n path: string\n symlink: string\n syscall: 'symlink' = 'symlink'\n code: 'TAR_SYMLINK_ERROR' = 'TAR_SYMLINK_ERROR'\n constructor(symlink: string, path: string) {\n super('TAR_SYMLINK_ERROR: Cannot extract through symbolic link')\n this.symlink = symlink\n this.path = path\n }\n get name() {\n return 'SymlinkError'\n }\n}\n", "// A path exclusive reservation system\n// reserve([list, of, paths], fn)\n// When the fn is first in line for all its paths, it\n// is called with a cb that clears the reservation.\n//\n// Used by async unpack to avoid clobbering paths in use,\n// while still allowing maximal safe parallelization.\n\nimport { join } from 'node:path'\nimport { normalizeUnicode } from './normalize-unicode.js'\nimport { stripTrailingSlashes } from './strip-trailing-slashes.js'\n\nconst platform =\n process.env.TESTING_TAR_FAKE_PLATFORM || process.platform\nconst isWindows = platform === 'win32'\n\nexport type Reservation = {\n paths: string[]\n dirs: Set<string>\n}\n\nexport type Handler = (clear: () => void) => void\n\n// return a set of parent dirs for a given path\n// '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d']\nconst getDirs = (path: string) => {\n const dirs = path\n .split('/')\n .slice(0, -1)\n .reduce((set: string[], path) => {\n const s = set[set.length - 1]\n if (s !== undefined) {\n path = join(s, path)\n }\n set.push(path || '/')\n return set\n }, [])\n return dirs\n}\n\nexport class PathReservations {\n // path => [function or Set]\n // A Set object means a directory reservation\n // A fn is a direct reservation on that path\n #queues = new Map<string, (Handler | Set<Handler>)[]>()\n\n // fn => {paths:[path,...], dirs:[path, ...]}\n #reservations = new Map<Handler, Reservation>()\n\n // functions currently running\n #running = new Set<Handler>()\n\n reserve(paths: string[], fn: Handler) {\n paths =\n isWindows ?\n ['win32 parallelization disabled']\n : paths.map(p => {\n // don't need normPath, because we skip this entirely for windows\n return stripTrailingSlashes(join(normalizeUnicode(p)))\n })\n\n const dirs = new Set<string>(\n paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)),\n )\n this.#reservations.set(fn, { dirs, paths })\n for (const p of paths) {\n const q = this.#queues.get(p)\n if (!q) {\n this.#queues.set(p, [fn])\n } else {\n q.push(fn)\n }\n }\n for (const dir of dirs) {\n const q = this.#queues.get(dir)\n if (!q) {\n this.#queues.set(dir, [new Set([fn])])\n } else {\n const l = q[q.length - 1]\n if (l instanceof Set) {\n l.add(fn)\n } else {\n q.push(new Set([fn]))\n }\n }\n }\n return this.#run(fn)\n }\n\n // return the queues for each path the function cares about\n // fn => {paths, dirs}\n #getQueues(fn: Handler): {\n paths: Handler[][]\n dirs: (Handler | Set<Handler>)[][]\n } {\n const res = this.#reservations.get(fn)\n /* c8 ignore start */\n if (!res) {\n throw new Error('function does not have any path reservations')\n }\n /* c8 ignore stop */\n return {\n paths: res.paths.map((path: string) =>\n this.#queues.get(path),\n ) as Handler[][],\n dirs: [...res.dirs].map(path => this.#queues.get(path)) as (\n | Handler\n | Set<Handler>\n )[][],\n }\n }\n\n // check if fn is first in line for all its paths, and is\n // included in the first set for all its dir queues\n check(fn: Handler) {\n const { paths, dirs } = this.#getQueues(fn)\n return (\n paths.every(q => q && q[0] === fn) &&\n dirs.every(q => q && q[0] instanceof Set && q[0].has(fn))\n )\n }\n\n // run the function if it's first in line and not already running\n #run(fn: Handler) {\n if (this.#running.has(fn) || !this.check(fn)) {\n return false\n }\n this.#running.add(fn)\n fn(() => this.#clear(fn))\n return true\n }\n\n #clear(fn: Handler) {\n if (!this.#running.has(fn)) {\n return false\n }\n const res = this.#reservations.get(fn)\n /* c8 ignore start */\n if (!res) {\n throw new Error('invalid reservation')\n }\n /* c8 ignore stop */\n const { paths, dirs } = res\n\n const next = new Set<Handler>()\n for (const path of paths) {\n const q = this.#queues.get(path)\n /* c8 ignore start */\n if (!q || q?.[0] !== fn) {\n continue\n }\n /* c8 ignore stop */\n const q0 = q[1]\n if (!q0) {\n this.#queues.delete(path)\n continue\n }\n q.shift()\n if (typeof q0 === 'function') {\n next.add(q0)\n } else {\n for (const f of q0) {\n next.add(f)\n }\n }\n }\n\n for (const dir of dirs) {\n const q = this.#queues.get(dir)\n const q0 = q?.[0]\n /* c8 ignore next - type safety only */\n if (!q || !(q0 instanceof Set)) continue\n if (q0.size === 1 && q.length === 1) {\n this.#queues.delete(dir)\n continue\n } else if (q0.size === 1) {\n q.shift()\n // next one must be a function,\n // or else the Set would've been reused\n const n = q[0]\n if (typeof n === 'function') {\n next.add(n)\n }\n } else {\n q0.delete(fn)\n }\n }\n\n this.#running.delete(fn)\n next.forEach(fn => this.#run(fn))\n return true\n }\n}\n", "// warning: extremely hot code path.\n// This has been meticulously optimized for use\n// within npm install on large package trees.\n// Do not edit without careful benchmarking.\nconst normalizeCache: Record<string, string> = Object.create(null)\n\n// Limit the size of this. Very low-sophistication LRU cache\nconst MAX = 10000\nconst cache = new Set<string>()\nexport const normalizeUnicode = (s: string): string => {\n if (!cache.has(s)) {\n // shake out identical accents and ligatures\n normalizeCache[s] = s\n .normalize('NFD')\n .toLocaleLowerCase('en')\n .toLocaleUpperCase('en')\n } else {\n cache.delete(s)\n }\n cache.add(s)\n\n const ret = normalizeCache[s] as string\n\n let i = cache.size - MAX\n // only prune when we're 10% over the max\n if (i > MAX / 10) {\n for (const s of cache) {\n cache.delete(s)\n delete normalizeCache[s]\n if (--i <= 0) break\n }\n }\n\n return ret\n}\n", "// tar -r\nimport { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass'\nimport { Minipass } from 'minipass'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { Header } from './header.js'\nimport { list } from './list.js'\nimport { makeCommand } from './make-command.js'\nimport {\n isFile,\n TarOptionsFile,\n TarOptionsSyncFile,\n} from './options.js'\nimport { Pack, PackSync } from './pack.js'\n\n// starting at the head of the file, read a Header\n// If the checksum is invalid, that's our position to start writing\n// If it is, jump forward by the specified size (round up to 512)\n// and try again.\n// Write the new Pack stream starting there.\n\nconst replaceSync = (opt: TarOptionsSyncFile, files: string[]) => {\n const p = new PackSync(opt)\n\n let threw = true\n let fd\n let position\n\n try {\n try {\n fd = fs.openSync(opt.file, 'r+')\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') {\n fd = fs.openSync(opt.file, 'w+')\n } else {\n throw er\n }\n }\n\n const st = fs.fstatSync(fd)\n const headBuf = Buffer.alloc(512)\n\n POSITION: for (\n position = 0;\n position < st.size;\n position += 512\n ) {\n for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {\n bytes = fs.readSync(\n fd,\n headBuf,\n bufPos,\n headBuf.length - bufPos,\n position + bufPos,\n )\n\n if (\n position === 0 &&\n headBuf[0] === 0x1f &&\n headBuf[1] === 0x8b\n ) {\n throw new Error('cannot append to compressed archives')\n }\n\n if (!bytes) {\n break POSITION\n }\n }\n\n const h = new Header(headBuf)\n if (!h.cksumValid) {\n break\n }\n const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512)\n if (position + entryBlockSize + 512 > st.size) {\n break\n }\n // the 512 for the header we just parsed will be added as well\n // also jump ahead all the blocks for the body\n position += entryBlockSize\n if (opt.mtimeCache && h.mtime) {\n opt.mtimeCache.set(String(h.path), h.mtime)\n }\n }\n threw = false\n\n streamSync(opt, p, position, fd, files)\n } finally {\n if (threw) {\n try {\n fs.closeSync(fd as number)\n } catch (er) {}\n }\n }\n}\n\nconst streamSync = (\n opt: TarOptionsSyncFile,\n p: Pack,\n position: number,\n fd: number,\n files: string[],\n) => {\n const stream = new WriteStreamSync(opt.file, {\n fd: fd,\n start: position,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n addFilesSync(p, files)\n}\n\nconst replaceAsync = (\n opt: TarOptionsFile,\n files: string[],\n): Promise<void> => {\n files = Array.from(files)\n const p = new Pack(opt)\n\n const getPos = (\n fd: number,\n size: number,\n cb_: (er?: null | Error, pos?: number) => void,\n ) => {\n const cb = (er?: Error | null, pos?: number) => {\n if (er) {\n fs.close(fd, _ => cb_(er))\n } else {\n cb_(null, pos)\n }\n }\n\n let position = 0\n if (size === 0) {\n return cb(null, 0)\n }\n\n let bufPos = 0\n const headBuf = Buffer.alloc(512)\n const onread = (er?: null | Error, bytes?: number): void => {\n if (er || typeof bytes === 'undefined') {\n return cb(er)\n }\n bufPos += bytes\n if (bufPos < 512 && bytes) {\n return fs.read(\n fd,\n headBuf,\n bufPos,\n headBuf.length - bufPos,\n position + bufPos,\n onread,\n )\n }\n\n if (\n position === 0 &&\n headBuf[0] === 0x1f &&\n headBuf[1] === 0x8b\n ) {\n return cb(new Error('cannot append to compressed archives'))\n }\n\n // truncated header\n if (bufPos < 512) {\n return cb(null, position)\n }\n\n const h = new Header(headBuf)\n if (!h.cksumValid) {\n return cb(null, position)\n }\n\n /* c8 ignore next */\n const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512)\n if (position + entryBlockSize + 512 > size) {\n return cb(null, position)\n }\n\n position += entryBlockSize + 512\n if (position >= size) {\n return cb(null, position)\n }\n\n if (opt.mtimeCache && h.mtime) {\n opt.mtimeCache.set(String(h.path), h.mtime)\n }\n bufPos = 0\n fs.read(fd, headBuf, 0, 512, position, onread)\n }\n fs.read(fd, headBuf, 0, 512, position, onread)\n }\n\n const promise = new Promise<void>((resolve, reject) => {\n p.on('error', reject)\n let flag = 'r+'\n const onopen = (\n er?: NodeJS.ErrnoException | null,\n fd?: number,\n ) => {\n if (er && er.code === 'ENOENT' && flag === 'r+') {\n flag = 'w+'\n return fs.open(opt.file, flag, onopen)\n }\n\n if (er || !fd) {\n return reject(er)\n }\n\n fs.fstat(fd, (er, st) => {\n if (er) {\n return fs.close(fd, () => reject(er))\n }\n\n getPos(fd, st.size, (er, position) => {\n if (er) {\n return reject(er)\n }\n const stream = new WriteStream(opt.file, {\n fd: fd,\n start: position,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n stream.on('error', reject)\n stream.on('close', resolve)\n addFilesAsync(p, files)\n })\n })\n }\n fs.open(opt.file, flag, onopen)\n })\n\n return promise\n}\n\nconst addFilesSync = (p: Pack, files: string[]) => {\n files.forEach(file => {\n if (file.charAt(0) === '@') {\n list({\n file: path.resolve(p.cwd, file.slice(1)),\n sync: true,\n noResume: true,\n onReadEntry: entry => p.add(entry),\n })\n } else {\n p.add(file)\n }\n })\n p.end()\n}\n\nconst addFilesAsync = async (\n p: Pack,\n files: string[],\n): Promise<void> => {\n for (let i = 0; i < files.length; i++) {\n const file = String(files[i])\n if (file.charAt(0) === '@') {\n await list({\n file: path.resolve(String(p.cwd), file.slice(1)),\n noResume: true,\n onReadEntry: entry => p.add(entry),\n })\n } else {\n p.add(file)\n }\n }\n p.end()\n}\n\nexport const replace = makeCommand(\n replaceSync,\n replaceAsync,\n /* c8 ignore start */\n (): never => {\n throw new TypeError('file is required')\n },\n (): never => {\n throw new TypeError('file is required')\n },\n /* c8 ignore stop */\n (opt, entries) => {\n if (!isFile(opt)) {\n throw new TypeError('file is required')\n }\n\n if (\n opt.gzip ||\n opt.brotli ||\n opt.zstd ||\n opt.file.endsWith('.br') ||\n opt.file.endsWith('.tbr')\n ) {\n throw new TypeError('cannot append to compressed archives')\n }\n\n if (!entries?.length) {\n throw new TypeError('no paths specified to add/replace')\n }\n },\n)\n", "// tar -u\n\nimport { makeCommand } from './make-command.js'\nimport { type TarOptionsWithAliases } from './options.js'\n\nimport { replace as r } from './replace.js'\n\n// just call tar.r with the filter and mtimeCache\nexport const update = makeCommand(\n r.syncFile,\n r.asyncFile,\n r.syncNoFile,\n r.asyncNoFile,\n (opt, entries = []) => {\n r.validate?.(opt, entries)\n mtimeFilter(opt)\n },\n)\n\nconst mtimeFilter = (opt: TarOptionsWithAliases) => {\n const filter = opt.filter\n\n if (!opt.mtimeCache) {\n opt.mtimeCache = new Map()\n }\n\n opt.filter =\n filter ?\n (path, stat) =>\n filter(path, stat) &&\n !(\n /* c8 ignore start */\n (\n (opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >\n (stat.mtime ?? 0)\n )\n /* c8 ignore stop */\n )\n : (path, stat) =>\n !(\n /* c8 ignore start */\n (\n (opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >\n (stat.mtime ?? 0)\n )\n /* c8 ignore stop */\n )\n}\n", "import path from \"node:path\";\nimport { type PackageJson } from \"./types\";\n\nfunction normalize(name: string): string {\n\treturn name.replace(\"/\", \"-\").replace(/^@/, \"\");\n}\n\nexport function tarballLocation(pkg: PackageJson, pkgPath: string): string {\n\tconst name = normalize(pkg.name);\n\treturn path.join(path.dirname(pkgPath), `${name}-${pkg.version}.tgz`);\n}\n", "import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nconst enabled = os.platform() === \"linux\";\nconst cacheRoot = process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), \".cache\");\nlet cacheDir = path.join(cacheRoot, \"npm-pkg-lint\");\n\n/* istanbul ignore next */\nfunction getFilePath(key: string): string {\n\t/* eslint-disable-next-line sonarjs/hashing -- technical debt, should use a different algo but should not cause any issues as is either */\n\tconst hash = crypto.createHash(\"md5\").update(key).digest(\"hex\");\n\tconst filename = `${hash.slice(0, 2)}/${hash.slice(2)}.json`;\n\treturn path.join(cacheDir, filename);\n}\n\n/* istanbul ignore next */\nexport async function setCacheDirecory(directory: string): Promise<void> {\n\tawait fs.mkdir(directory, { recursive: true });\n\tcacheDir = directory;\n}\n\n/* istanbul ignore next */\nexport async function persistentCacheGet(key: string): Promise<unknown> {\n\tif (!enabled) {\n\t\treturn null;\n\t}\n\n\tconst filePath = getFilePath(key);\n\ttry {\n\t\tconst content = await fs.readFile(filePath, \"utf-8\");\n\t\treturn JSON.parse(content) as unknown;\n\t} catch (err: unknown) {\n\t\tif (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n\t\t\treturn null;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n/* istanbul ignore next */\nexport async function persistentCacheSet(key: string, data: unknown): Promise<void> {\n\tif (!enabled) {\n\t\treturn;\n\t}\n\n\tconst filePath = getFilePath(key);\n\tconst content = JSON.stringify(data, null, 2);\n\tawait fs.mkdir(path.dirname(filePath), { recursive: true });\n\tawait fs.writeFile(filePath, content, \"utf-8\");\n}\n", "import { type DocumentNode, type MemberNode, type ValueNode } from \"@humanwhocodes/momoa\";\n\ninterface Result {\n\tvalue: ValueNode;\n\tmember?: MemberNode;\n}\n\nfunction findNextNode(current: Result, segment: string, datapath: string[]): Result {\n\tconst { value } = current;\n\tswitch (value.type) {\n\t\tcase \"Object\": {\n\t\t\tconst found = value.members.find((it) => {\n\t\t\t\treturn it.name.type === \"String\" && it.name.value === segment;\n\t\t\t});\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(`Failed to find \"${datapath.join(\".\")}\" in JSON structure`);\n\t\t\t}\n\t\t\treturn { value: found.value, member: found };\n\t\t}\n\t\tdefault: {\n\t\t\tthrow new Error(\n\t\t\t\t`Dont know how to handle node type \"${value.type}\" when searching for \"${datapath.join(\n\t\t\t\t\t\".\",\n\t\t\t\t)}\" in JSON structure`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport function jsonLocation(\n\tast: DocumentNode,\n\tpick: \"member\" | \"value\",\n\t...datapath: string[]\n): { line: number; column: number } {\n\tconst result = datapath.reduce<Result>(\n\t\t(state, segment) => findNextNode(state, segment, datapath),\n\t\t{ value: ast.body },\n\t);\n\n\tswitch (pick) {\n\t\tcase \"member\":\n\t\t\treturn result.member?.loc.start ?? { line: 1, column: 1 };\n\t\tcase \"value\":\n\t\t\treturn result.value.loc.start;\n\t}\n}\n", "import process from 'node:process';\nimport {stripVTControlCharacters} from 'node:util';\n\nexport const getContext = raw => ({\n\tstart: process.hrtime.bigint(),\n\tcommand: raw.map(part => getCommandPart(stripVTControlCharacters(part))).join(' '),\n\tstate: {\n\t\tstdout: '', stderr: '', output: '', isIterating: {}, nonIterable: [false, false],\n\t},\n});\n\nconst getCommandPart = part => /[^\\w./-]/.test(part)\n\t? `'${part.replaceAll('\\'', '\\'\\\\\\'\\'')}'`\n\t: part;\n", "import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport process from 'node:process';\n\nexport const getOptions = ({\n\tstdin,\n\tstdout,\n\tstderr,\n\tstdio = [stdin, stdout, stderr],\n\tenv: envOption,\n\tpreferLocal,\n\tcwd: cwdOption = '.',\n\t...options\n}) => {\n\tconst cwd = cwdOption instanceof URL ? fileURLToPath(cwdOption) : path.resolve(cwdOption);\n\tconst env = envOption ? {...process.env, ...envOption} : undefined;\n\tconst input = stdio[0]?.string;\n\treturn {\n\t\t...options,\n\t\tinput,\n\t\tstdio: input === undefined ? stdio : ['pipe', ...stdio.slice(1)],\n\t\tenv: preferLocal ? addLocalPath(env ?? process.env, cwd) : env,\n\t\tcwd,\n\t};\n};\n\nconst addLocalPath = ({Path = '', PATH = Path, ...env}, cwd) => {\n\tconst pathParts = PATH.split(path.delimiter);\n\tconst localPaths = getLocalPaths([], path.resolve(cwd))\n\t\t.map(localPath => path.join(localPath, 'node_modules/.bin'))\n\t\t.filter(localPath => !pathParts.includes(localPath));\n\treturn {...env, PATH: [...localPaths, PATH].filter(Boolean).join(path.delimiter)};\n};\n\nconst getLocalPaths = (localPaths, localPath) => localPaths.at(-1) === localPath\n\t? localPaths\n\t: getLocalPaths([...localPaths, localPath], path.resolve(localPath, '..'));\n", "import {spawn} from 'node:child_process';\nimport {once} from 'node:events';\nimport process from 'node:process';\nimport {applyForceShell} from './windows.js';\nimport {getResultError} from './result.js';\n\nexport const spawnSubprocess = async (file, commandArguments, options, context) => {\n\ttry {\n\t\t// When running `node`, keep the current Node version and CLI flags.\n\t\t// Not applied with file paths to `.../node` since those indicate a clear intent to use a specific Node version.\n\t\t// This also provides a way to opting out, e.g. using `process.execPath` instead of `node` to discard current CLI flags.\n\t\t// Does not work with shebangs, but those don't work cross-platform anyway.\n\t\tif (['node', 'node.exe'].includes(file.toLowerCase())) {\n\t\t\tfile = process.execPath;\n\t\t\tcommandArguments = [...process.execArgv.filter(flag => !flag.startsWith('--inspect')), ...commandArguments];\n\t\t}\n\n\t\t[file, commandArguments, options] = await applyForceShell(file, commandArguments, options);\n\t\t[file, commandArguments, options] = concatenateShell(file, commandArguments, options);\n\t\tconst instance = spawn(file, commandArguments, options);\n\t\tbufferOutput(instance.stdout, context, 'stdout');\n\t\tbufferOutput(instance.stderr, context, 'stderr');\n\n\t\t// The `error` event is caught by `once(instance, 'spawn')` and `once(instance, 'close')`.\n\t\t// But it creates an uncaught exception if it happens exactly one tick after 'spawn'.\n\t\t// This prevents that.\n\t\tinstance.once('error', () => {});\n\n\t\tawait once(instance, 'spawn');\n\t\treturn instance;\n\t} catch (error) {\n\t\tthrow getResultError(error, {}, context);\n\t}\n};\n\n// When the `shell` option is set, any command argument is concatenated as a single string by Node.js:\n// https://github.com/nodejs/node/blob/e38ce27f3ca0a65f68a31cedd984cddb927d4002/lib/child_process.js#L614-L624\n// However, since Node 24, it also prints a deprecation warning.\n// To avoid this warning, we perform that same operation before calling `node:child_process`.\n// Shells only understand strings, which is why Node.js performs that concatenation.\n// However, we rely on users splitting command arguments as an array.\n// For example, this allows us to easily detect whether the binary file is `node` or `node.exe`.\n// So we do want users to pass array of arguments even with `shell: true`, but we also want to avoid any warning.\nconst concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0\n\t? [[file, ...commandArguments].join(' '), [], options]\n\t: [file, commandArguments, options];\n\nconst bufferOutput = (stream, {state}, streamName) => {\n\tif (stream) {\n\t\tstream.setEncoding('utf8');\n\t\tif (!state.isIterating[streamName]) {\n\t\t\tstate.isIterating[streamName] = false;\n\t\t\tstream.on('data', chunk => {\n\t\t\t\tstate[streamName] += chunk;\n\t\t\t\tstate.output += chunk;\n\t\t\t});\n\t\t}\n\t}\n};\n", "import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\n// When setting `shell: true` under-the-hood, we must manually escape the file and arguments.\n// This ensures arguments are properly split, and prevents command injection.\nexport const applyForceShell = async (file, commandArguments, options) => await shouldForceShell(file, options)\n\t? [escapeFile(file), commandArguments.map(argument => escapeArgument(argument)), {...options, shell: true}]\n\t: [file, commandArguments, options];\n\n// On Windows, running most executable files (except *.exe and *.com) requires using a shell.\n// This includes *.cmd and *.bat, which itself includes Node modules binaries.\n// We detect this situation and automatically:\n// - Set the `shell: true` option\n// - Escape shell-specific characters\nconst shouldForceShell = async (file, {shell, cwd, env = process.env}) => process.platform === 'win32'\n\t&& !shell\n\t&& !(await isExe(file, cwd, env));\n\n// Detect whether the executable file is a *.exe or *.com file.\n// Windows allows omitting file extensions (present in the `PATHEXT` environment variable).\n// Therefore we must use the `PATH` environment variable and make `access` calls to check this.\n// Environment variables are case-insensitive on Windows, so we check both `PATH` and `Path`.\nconst isExe = (file, cwd, {Path = '', PATH = Path}) =>\n\t// If the *.exe or *.com file extension was not omitted.\n\t// Windows common file systems are case-insensitive.\n\texeExtensions.some(extension => file.toLowerCase().endsWith(extension))\n\t|| mIsExe(file, cwd, PATH);\n\n// Memoize the `mIsExe` and `fs.access`, for performance\nconst EXE_MEMO = {};\n// eslint-disable-next-line no-return-assign\nconst memoize = function_ => (...arguments_) =>\n\t// Use returned assignment to keep code small\n\tEXE_MEMO[arguments_.join('\\0')] ??= function_(...arguments_);\n\nconst access = memoize(fs.access);\nconst mIsExe = memoize(async (file, cwd, PATH) => {\n\tconst parts = PATH\n\t\t// `PATH` is ;-separated on Windows\n\t\t.split(path.delimiter)\n\t\t// `PATH` allows leading/trailing ; on Windows\n\t\t.filter(Boolean)\n\t\t// `PATH` parts can be double quoted on Windows\n\t\t.map(part => part.replace(/^\"(.*)\"$/, '$1'));\n\n\t// For performance, parallelize and stop iteration as soon as an *.exe or *.com file is found\n\ttry {\n\t\tawait Promise.any(\n\t\t\t[cwd, ...parts].flatMap(part => exeExtensions\n\t\t\t\t.map(extension => access(`${path.resolve(part, file)}${extension}`)),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n\n\treturn true;\n});\n\n// Other file extensions require using a shell\nconst exeExtensions = ['.exe', '.com'];\n\n// `cmd.exe` escaping for arguments.\n// Taken from https://github.com/moxystudio/node-cross-spawn\nconst escapeArgument = argument => escapeFile(escapeFile(`\"${argument\n\t.replaceAll(/(\\\\*)\"/g, '$1$1\\\\\"')\n\t.replace(/(\\\\*)$/, '$1$1')}\"`));\n\n// `cmd.exe` escaping for file and arguments.\nconst escapeFile = file => file.replaceAll(/([()\\][%!^\"`<>&|;, *?])/g, '^$1');\n", "import {once, on} from 'node:events';\nimport process from 'node:process';\n\nexport const getResult = async (nodeChildProcess, {input}, context) => {\n\tconst instance = await nodeChildProcess;\n\tif (input !== undefined) {\n\t\tinstance.stdin.end(input);\n\t}\n\n\tconst onClose = once(instance, 'close');\n\n\ttry {\n\t\tawait Promise.race([\n\t\t\tonClose,\n\t\t\t...instance.stdio.filter(Boolean).map(stream => onStreamError(stream)),\n\t\t]);\n\t\tcheckFailure(context, getErrorOutput(instance));\n\t\treturn getOutputs(context);\n\t} catch (error) {\n\t\tawait Promise.allSettled([onClose]);\n\t\tthrow getResultError(error, instance, context);\n\t}\n};\n\nconst onStreamError = async stream => {\n\tfor await (const [error] of on(stream, 'error')) {\n\t\t// Ignore errors that are due to closing errors when the subprocesses exit normally, or due to piping\n\t\tif (!['ERR_STREAM_PREMATURE_CLOSE', 'EPIPE'].includes(error?.code)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n\nconst checkFailure = ({command}, {exitCode, signalName}) => {\n\tif (signalName !== undefined) {\n\t\tthrow new SubprocessError(`Command was terminated with ${signalName}: ${command}`);\n\t}\n\n\tif (exitCode !== undefined) {\n\t\tthrow new SubprocessError(`Command failed with exit code ${exitCode}: ${command}`);\n\t}\n};\n\nexport const getResultError = (error, instance, context) => Object.assign(\n\tgetErrorInstance(error, context),\n\tgetErrorOutput(instance),\n\tgetOutputs(context),\n);\n\nconst getErrorInstance = (error, {command}) => error instanceof SubprocessError\n\t? error\n\t: new SubprocessError(`Command failed: ${command}`, {cause: error});\n\nexport class SubprocessError extends Error {\n\tname = 'SubprocessError';\n}\n\nconst getErrorOutput = ({exitCode, signalCode}) => ({\n\t// `exitCode` can be a negative number (`errno`) when the `error` event is emitted on the `instance`\n\t...(exitCode < 1 ? {} : {exitCode}),\n\t...(signalCode === null ? {} : {signalName: signalCode}),\n});\n\nconst getOutputs = ({state: {stdout, stderr, output}, command, start}) => ({\n\tstdout: getOutput(stdout),\n\tstderr: getOutput(stderr),\n\toutput: getOutput(output),\n\tcommand,\n\tdurationMs: Number(process.hrtime.bigint() - start) / 1e6,\n});\n\nconst getOutput = output => output.at(-1) === '\\n'\n\t? output.slice(0, output.at(-2) === '\\r' ? -2 : -1)\n\t: output;\n", "import {pipeline} from 'node:stream/promises';\n\nexport const handlePipe = async subprocesses => {\n\t// Ensure both subprocesses have exited before resolving, and that we handle errors from both\n\tconst [[from, to]] = await Promise.all([Promise.allSettled(subprocesses), pipeStreams(subprocesses)]);\n\n\t// If both subprocesses fail, throw destination error to use a predictable order and avoid race conditions\n\tif (to.reason) {\n\t\tto.reason.pipedFrom = from.reason ?? from.value;\n\t\tthrow to.reason;\n\t}\n\n\tif (from.reason) {\n\t\tthrow from.reason;\n\t}\n\n\treturn {...to.value, pipedFrom: from.value};\n};\n\nconst pipeStreams = async subprocesses => {\n\ttry {\n\t\tconst [{stdout}, {stdin}] = await Promise.all(subprocesses.map(({nodeChildProcess}) => nodeChildProcess));\n\t\tif (stdin === null) {\n\t\t\tthrow new Error('The \"stdin\" option must be set on the first \"spawn()\" call in the pipeline.');\n\t\t}\n\n\t\tif (stdout === null) {\n\t\t\tthrow new Error('The \"stdout\" option must be set on the last \"spawn()\" call in the pipeline.');\n\t\t}\n\n\t\t// Do not `await` nor handle stream errors since this is already done by each subprocess\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\tpipeline(stdout, stdin).catch(() => {});\n\t} catch (error) {\n\t\tawait Promise.allSettled(subprocesses.map(({nodeChildProcess}) => closeStdin(nodeChildProcess)));\n\t\tthrow error;\n\t}\n};\n\nconst closeStdin = async nodeChildProcess => {\n\tconst {stdin} = await nodeChildProcess;\n\tstdin.end();\n};\n", "import * as readline from 'node:readline/promises';\n\nexport const lineIterator = async function * (subprocess, {state}, streamName, index) {\n\t// Prevent buffering when iterating.\n\t// This would defeat one of the main goals of iterating: low memory consumption.\n\tif (state.isIterating[streamName] === false) {\n\t\tthrow new Error(`The subprocess must be iterated right away, for example:\n\tfor await (const line of spawn(...)) { ... }`);\n\t}\n\n\tstate.isIterating[streamName] = true;\n\n\ttry {\n\t\tconst {[streamName]: stream} = await subprocess.nodeChildProcess;\n\t\tif (!stream) {\n\t\t\tstate.nonIterable[index] = true;\n\t\t\tconst message = state.nonIterable.every(Boolean)\n\t\t\t\t? 'either the option `stdout` or `stderr`'\n\t\t\t\t: `the option \\`${streamName}\\``;\n\t\t\tthrow new TypeError(\n\t\t\t\t`The subprocess cannot be iterated unless ${message} is 'pipe'.`,\n\t\t\t);\n\t\t}\n\n\t\thandleErrors(subprocess);\n\t\tyield * readline.createInterface({input: stream});\n\t} finally {\n\t\tawait subprocess;\n\t}\n};\n\n// When the `subprocess` promise is rejected, we await it in the `finally`\n// block. However, this might not happen right away, so an `unhandledRejection`\n// error is emitted first, crashing the process. This prevents it.\n// This is safe since we are guaranteed to propagate the `subprocess` error\n// with the `finally` block.\n// See https://github.com/sindresorhus/nano-spawn/issues/104\nconst handleErrors = async subprocess => {\n\ttry {\n\t\tawait subprocess;\n\t} catch {}\n};\n\n// Merge two async iterators into one\nexport const combineAsyncIterators = async function * ({state}, ...iterators) {\n\ttry {\n\t\tlet promises = [];\n\t\twhile (iterators.length > 0) {\n\t\t\tpromises = iterators.map((iterator, index) => promises[index] ?? getNext(iterator, index, state));\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst [{value, done}, index] = await Promise.race(promises\n\t\t\t\t.map((promise, index) => Promise.all([promise, index])));\n\n\t\t\tconst [iterator] = iterators.splice(index, 1);\n\t\t\tpromises.splice(index, 1);\n\n\t\t\tif (!done) {\n\t\t\t\titerators.push(iterator);\n\t\t\t\tyield value;\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait Promise.all(iterators.map(iterator => iterator.return()));\n\t}\n};\n\nconst getNext = async (iterator, index, {nonIterable}) => {\n\ttry {\n\t\treturn await iterator.next();\n\t} catch (error) {\n\t\treturn shouldIgnoreError(nonIterable, index)\n\t\t\t? iterator.return()\n\t\t\t: iterator.throw(error);\n\t}\n};\n\nconst shouldIgnoreError = (nonIterable, index) => nonIterable.every(Boolean)\n\t? index !== nonIterable.length - 1\n\t: nonIterable[index];\n", "import {getContext} from './context.js';\nimport {getOptions} from './options.js';\nimport {spawnSubprocess} from './spawn.js';\nimport {getResult} from './result.js';\nimport {handlePipe} from './pipe.js';\nimport {lineIterator, combineAsyncIterators} from './iterable.js';\n\nexport {SubprocessError} from './result.js';\n\nexport default function spawn(file, second, third, previous) {\n\tconst [commandArguments = [], options = {}] = Array.isArray(second) ? [second, third] : [[], second];\n\tconst context = getContext([file, ...commandArguments]);\n\tconst spawnOptions = getOptions(options);\n\tconst nodeChildProcess = spawnSubprocess(file, commandArguments, spawnOptions, context);\n\tlet subprocess = getResult(nodeChildProcess, spawnOptions, context);\n\tObject.assign(subprocess, {nodeChildProcess});\n\tsubprocess = previous ? handlePipe([previous, subprocess]) : subprocess;\n\n\tconst stdout = lineIterator(subprocess, context, 'stdout', 0);\n\tconst stderr = lineIterator(subprocess, context, 'stderr', 1);\n\treturn Object.assign(subprocess, {\n\t\tnodeChildProcess,\n\t\tstdout,\n\t\tstderr,\n\t\t[Symbol.asyncIterator]: () => combineAsyncIterators(context, stdout, stderr),\n\t\tpipe: (file, second, third) => spawn(file, second, third, subprocess),\n\t});\n}\n", "import spawn from \"nano-spawn\";\nimport { type PackageJson } from \"../types\";\nimport { persistentCacheGet, persistentCacheSet } from \"./persistent-cache\";\n\nexport interface NpmInfo {\n\tdeprecated?: string;\n}\n\nexport interface NpmInfoError {\n\tcode: string;\n\tsummary: string;\n\tdetail: string;\n}\n\nexport interface ExecaError extends Error {\n\tstdout: string;\n}\n\nconst cache = new Map<string, PackageJson | null>();\n\nfunction isExecaError(error: unknown): error is ExecaError {\n\treturn Boolean(error && error instanceof Error && \"stdout\" in error);\n}\n\nexport function isNpmInfoError(error: unknown): error is NpmInfoError {\n\treturn Boolean(error && error instanceof Error && \"summary\" in error);\n}\n\nfunction tryParse(maybeJson: string): { error: NpmInfoError } | null {\n\ttry {\n\t\treturn JSON.parse(maybeJson) as { error: NpmInfoError };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function npmInfo(pkg: string): Promise<PackageJson & NpmInfo>;\nexport async function npmInfo(\n\tpkg: string,\n\toptions: { ignoreUnpublished: true },\n): Promise<(PackageJson & NpmInfo) | null>;\n/* eslint-disable-next-line complexity -- technical debt */\nexport async function npmInfo(\n\tpkg: string,\n\toptions: { ignoreUnpublished: boolean } = { ignoreUnpublished: false },\n): Promise<(PackageJson & NpmInfo) | null> {\n\tconst { ignoreUnpublished } = options;\n\tconst cached = cache.get(pkg);\n\tif (cached === null) {\n\t\tif (ignoreUnpublished) {\n\t\t\treturn null;\n\t\t}\n\t} else if (cached) {\n\t\treturn cached;\n\t}\n\n\tconst persistent = await persistentCacheGet(pkg);\n\tif (persistent) {\n\t\treturn persistent as PackageJson;\n\t}\n\n\ttry {\n\t\tconst result = await spawn(\"npm\", [\"info\", \"--json\", pkg]);\n\t\tconst pkgData = JSON.parse(result.stdout) as PackageJson;\n\t\tcache.set(pkg, pkgData);\n\t\tawait persistentCacheSet(pkg, pkgData);\n\t\treturn pkgData;\n\t} catch (err: unknown) {\n\t\tif (!isExecaError(err)) {\n\t\t\tthrow err;\n\t\t}\n\t\tconst parsed = tryParse(err.stdout);\n\t\tif (!parsed) {\n\t\t\tthrow err;\n\t\t}\n\t\tconst { code, summary, detail } = parsed.error;\n\n\t\t/* cache for this session but don't store in persistent cache as this\n\t\t * error might be temporary */\n\t\tcache.set(pkg, null);\n\n\t\tif (ignoreUnpublished && code === \"E404\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst wrappedError = new Error(summary, { cause: err }) as Error & NpmInfoError;\n\t\twrappedError.code = code;\n\t\twrappedError.summary = summary;\n\t\twrappedError.detail = detail;\n\t\tthrow wrappedError;\n\t}\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"conflicting-types-typings\";\nconst severity = Severity.ERROR;\n\n/**\n * Yields an error if both the `types` and `typings` field are set.\n *\n * @param pkg - Parsed `package.json\"`.\n * @param pkgAst - JSON syntax tree for the `pkg` parameter.\n */\nexport function* conflictingTypesTypings(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n): Generator<Message> {\n\tif (!pkg.types || !pkg.typings) {\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"typings\");\n\tyield {\n\t\truleId,\n\t\tseverity,\n\t\tmessage: `Duplicate \"typings\" and \"types\" field`,\n\t\tline,\n\t\tcolumn,\n\t};\n}\n", "import { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport semver from \"semver\";\nimport { type Message } from \"../message\";\nimport { type VerifyPackageJsonOptions } from \"../package-json\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation, npmInfo } from \"../utils\";\nimport { isNpmInfoError } from \"../utils/npm-info\";\n\nconst ruleId = \"no-deprecated-dependency\";\n\ninterface Dependency {\n\tname: string;\n\tversion: string;\n\tspec: string;\n\tsource: \"dependencies\" | \"devDependencies\" | \"peerDependencies\";\n}\n\nfunction createEntry(\n\tkey: string,\n\tversion: string,\n\tsource: Dependency[\"source\"],\n): Dependency | null {\n\t/* ignore packages with file: prefix */\n\tif (version.startsWith(\"file:\")) {\n\t\treturn null;\n\t}\n\n\t/* handle npm: prefix */\n\tif (version.startsWith(\"npm:\")) {\n\t\tconst [newKey, newVersion] = version.slice(\"npm:\".length).split(\"@\", 2);\n\t\tkey = newKey;\n\t\tversion = newVersion;\n\t}\n\n\t/* ignore this as this package is sometimes is present as version \"*\" which\n\t * just yields way to many versions to handle causing MaxBuffer errors and\n\t * there is another rule to make sure the outermost @types/node package\n\t * matches the configured engines */\n\tif (key === \"@types/node\") {\n\t\treturn null;\n\t}\n\n\tconst minVersion = semver.minVersion(version);\n\treturn {\n\t\tname: key,\n\t\tversion,\n\t\tspec: `${key}@${minVersion ? minVersion.version : version}`,\n\t\tsource,\n\t};\n}\n\nfunction* getDependencies(pkg: PackageJson): Generator<Dependency> {\n\tconst { dependencies = {}, devDependencies = {}, peerDependencies = {} } = pkg;\n\tfor (const [key, version] of Object.entries(dependencies)) {\n\t\tconst entry = createEntry(key, version, \"dependencies\");\n\t\tif (entry) {\n\t\t\tyield entry;\n\t\t}\n\t}\n\tfor (const [key, version] of Object.entries(devDependencies)) {\n\t\tconst entry = createEntry(key, version, \"devDependencies\");\n\t\tif (entry) {\n\t\t\tyield entry;\n\t\t}\n\t}\n\tfor (const [key, version] of Object.entries(peerDependencies)) {\n\t\tconst entry = createEntry(key, version, \"peerDependencies\");\n\t\tif (entry) {\n\t\t\tyield entry;\n\t\t}\n\t}\n}\n\nexport async function deprecatedDependency(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\toptions: VerifyPackageJsonOptions,\n): Promise<Message[]> {\n\tconst { allowedDependencies } = options;\n\tconst messages: Message[] = [];\n\n\tfor (const dependency of getDependencies(pkg)) {\n\t\t/* allow explicitly allowed dependencies */\n\t\tif (allowedDependencies.has(dependency.name)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst { deprecated } = await npmInfo(dependency.spec);\n\t\t\tif (!deprecated) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", dependency.source, dependency.name);\n\t\t\tmessages.push({\n\t\t\t\truleId,\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `\"${dependency.spec}\" is deprecated and must not be used`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t});\n\t\t} catch (err: unknown) {\n\t\t\tif (isNpmInfoError(err) && err.code === \"E404\") {\n\t\t\t\tif (dependency.source === \"devDependencies\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", dependency.source, dependency.name);\n\t\t\t\tmessages.push({\n\t\t\t\t\truleId,\n\t\t\t\t\tseverity: 1,\n\t\t\t\t\tmessage: `\"${dependency.spec}\" is not published to the NPM registry`,\n\t\t\t\t\tline,\n\t\t\t\t\tcolumn,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\treturn messages;\n}\n", "/* eslint-disable security/detect-non-literal-regexp -- expected to be non-literal */\n\nimport { type PackageJson } from \"../types\";\n\nfunction exact(name: string): RegExp {\n\treturn new RegExp(`^${name}$`);\n}\nfunction scope(scope: string): RegExp {\n\treturn new RegExp(`^${scope}/`);\n}\n\nfunction prefix(prefix: string): RegExp {\n\treturn new RegExp(`^${prefix}(-.+)?`);\n}\n\nfunction scopedPrefix(prefix: string): RegExp {\n\treturn new RegExp(`^(.*)/${prefix}(-.+)?`);\n}\n\nconst disallowedDependencies: RegExp[] = [\n\texact(\"ava\"),\n\texact(\"jake\"),\n\texact(\"tsd\"),\n\texact(\"typescript\"),\n\texact(\"xo\"),\n\tprefix(\"babel-core\"),\n\tprefix(\"cypress\"),\n\tprefix(\"grunt\"),\n\tprefix(\"gulp\"),\n\tprefix(\"html-validate\"),\n\tprefix(\"jasmine\"),\n\tprefix(\"mocha\"),\n\tprefix(\"nyc\"),\n\tprefix(\"protractor\"),\n\tprefix(\"ts-node\"),\n\tprefix(\"webpack\"),\n\tscope(\"@babel\"),\n\tscope(\"@tsconfig\"),\n\tscope(\"@types\"),\n];\n\nconst disallowedEslint: RegExp[] = [\n\texact(\"eslint\"),\n\texact(\"typescript-eslint\"),\n\tprefix(\"eslint-config\"),\n\tprefix(\"eslint-formatter\"),\n\tprefix(\"eslint-plugin\"),\n\tscope(\"@typescript-eslint\"),\n\tscopedPrefix(\"eslint-config\"),\n\tscopedPrefix(\"eslint-formatter\"),\n\tscopedPrefix(\"eslint-plugin\"),\n];\n\nconst disallowedJest: RegExp[] = [\n\texact(\"jest\"),\n\texact(\"babel-jest\"),\n\texact(\"ts-jest\"),\n\tprefix(\"jest-\"),\n\tscope(\"@jest\"),\n];\n\nconst disallowedPrettier: RegExp[] = [\n\texact(\"prettier\"),\n\tprefix(\"prettier-\"),\n\tscopedPrefix(\"prettier-\"),\n];\n\nconst allowedDependencies: string[] = [\n\t\"@babel/code-frame\",\n\t\"@babel/polyfill\",\n\t\"@babel/runtime\",\n\t\"gulp-utils\",\n\t\"jest-diff\",\n\t\"webpack-sources\",\n];\n\nfunction match(list: RegExp[], dependency: string): boolean {\n\treturn list.some((it) => dependency.match(it));\n}\n\nexport function isDisallowedDependency(pkg: PackageJson, dependency: string): boolean {\n\t/* test if dependency is explicitly listed as allowed */\n\tif (allowedDependencies.includes(dependency)) {\n\t\treturn false;\n\t}\n\n\tconst keywords = pkg.keywords ?? [];\n\n\t/* eslint-* is allowed only if keywords includes \"eslint\" */\n\tif (!keywords.includes(\"eslint\") && match(disallowedEslint, dependency)) {\n\t\treturn true;\n\t}\n\n\t/* jest-* is allowed only if keywords includes \"jest\" */\n\tif (!keywords.includes(\"jest\") && match(disallowedJest, dependency)) {\n\t\treturn true;\n\t}\n\n\t/* prettier-* is allowed only if keywords includes \"prettier\" */\n\tif (!keywords.includes(\"prettier\") && match(disallowedPrettier, dependency)) {\n\t\treturn true;\n\t}\n\n\t/* test if dependency is explicitly listed as disallowed */\n\treturn match(disallowedDependencies, dependency);\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson, type PackageJsonExports } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"exports-types-order\";\nconst severity = Severity.ERROR;\n\nfunction* validateOrder(\n\tpkgAst: DocumentNode,\n\tvalue: string | PackageJsonExports | null,\n\tpath: string[],\n): Generator<Message> {\n\tif (!value || typeof value === \"string\") {\n\t\treturn;\n\t}\n\n\tconst keys = Object.keys(value);\n\tif (keys.length === 0) {\n\t\treturn;\n\t}\n\n\tif (keys.includes(\"types\") && keys[0] !== \"types\") {\n\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"exports\", ...path, \"types\");\n\t\tconst property = path.map((it) => `[\"${it}\"]`).join(\"\");\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage: `\"types\" must be the first condition in \"exports${property}\"`,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t}\n\n\tfor (const key of keys) {\n\t\tyield* validateOrder(pkgAst, value[key], [...path, key]);\n\t}\n}\n\nexport function* exportsTypesOrder(pkg: PackageJson, pkgAst: DocumentNode): Generator<Message> {\n\tif (pkg.exports) {\n\t\tyield* validateOrder(pkgAst, pkg.exports, []);\n\t}\n}\n", "export interface ObsoleteDependency {\n\tpackage: string;\n\tmessage: string;\n}\n\nconst obsolete: ObsoleteDependency[] = [\n\t{ package: \"make-dir\", message: `use native \"fs.mkdir(..., { recursive: true })\" instead` },\n\t{ package: \"mkdirp\", message: `use native \"fs.mkdir(..., { recursive: true })\" instead` },\n\t{ package: \"stable\", message: `Array#sort is stable in all current implementations` },\n\t{ package: \"querystring\", message: `use native \"URLSearchParams\" instead` },\n];\n\nexport function isObsoleteDependency(dependency: string): ObsoleteDependency | false {\n\treturn obsolete.find((it) => it.package === dependency) ?? false;\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport semver from \"semver\";\nimport { type Message } from \"../message\";\nimport { nodeVersions } from \"../node-versions\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"outdated-engines\";\nconst severity = Severity.ERROR;\n\n/* eslint-disable-next-line complexity -- technical debt */\nexport function* outdatedEngines(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\tignoreNodeVersion: boolean | number,\n): Generator<Message> {\n\tif (!pkg.engines?.node) {\n\t\tconst { line, column } = pkg.engines\n\t\t\t? jsonLocation(pkgAst, \"member\", \"engines\")\n\t\t\t: { line: 1, column: 1 };\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage: \"Missing engines.node field\",\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"value\", \"engines\", \"node\");\n\n\tconst range = pkg.engines.node;\n\tif (!semver.validRange(range)) {\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage: `engines.node \"${range}\" is not a valid semver range`,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t\treturn;\n\t}\n\n\tif (ignoreNodeVersion === true) {\n\t\treturn;\n\t}\n\n\tfor (const [version, descriptor] of nodeVersions) {\n\t\t/* assume the list of versions are sorted: when a version not EOL is found\n\t\t * we stop processing the list, e.g. `>= 18` is OK while Node 18 is not EOL\n\t\t * even if Node 19 is EOL. */\n\t\tif (!descriptor.eol) {\n\t\t\tbreak;\n\t\t}\n\n\t\tconst expanded = version.replace(/[xX*]/g, \"999\");\n\t\tif (!semver.satisfies(expanded, range)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- parsing hardcoded values and covered by unit tests */\n\t\tconst parsed = semver.parse(expanded)!;\n\n\t\tconst { major, minor } = parsed;\n\t\tif (ignoreNodeVersion === major) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst nodeRelease = major > 0 ? major : `0.${String(minor)}`;\n\t\tconst message = `engines.node is satisfied by Node ${String(nodeRelease)} (EOL since ${\n\t\t\tdescriptor.eol\n\t\t})`;\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t\treturn;\n\t}\n\n\t/* if we reached this far there was no error silenced by ignoreNodeVersion so\n\t * we yield a new error informing that the ignore is no longer needed */\n\tif (typeof ignoreNodeVersion === \"number\") {\n\t\tconst option = String(ignoreNodeVersion);\n\t\tconst version = `v${String(ignoreNodeVersion)}.x`;\n\t\tconst message = `--ignore-node-version=${option} used but engines.node=\"${range}\" does not match ${version} or the version is not EOL yet`;\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t}\n}\n", "interface NodeVersionDescriptor {\n\t/** If set this version is EOL since given date */\n\teol?: string;\n}\n\n/* https://github.com/nodejs/Release/blob/main/schedule.json */\nexport const nodeVersions: Array<[string, NodeVersionDescriptor]> = [\n\t[\"0.10.x\", { eol: \"2016-10-31\" }],\n\t[\"0.12.x\", { eol: \"2016-12-31\" }],\n\t[\"4.x.x\", { eol: \"2018-04-30\" }],\n\t[\"5.x.x\", { eol: \"2016-06-30\" }],\n\t[\"6.x.x\", { eol: \"2019-04-30\" }],\n\t[\"7.x.x\", { eol: \"2017-06-30\" }],\n\t[\"8.x.x\", { eol: \"2019-12-31\" }],\n\t[\"9.x.x\", { eol: \"2018-06-30\" }],\n\t[\"10.x.x\", { eol: \"2021-04-30\" }],\n\t[\"11.x.x\", { eol: \"2019-06-01\" }],\n\t[\"12.x.x\", { eol: \"2022-04-30\" }],\n\t[\"13.x.x\", { eol: \"2020-06-01\" }],\n\t[\"14.x.x\", { eol: \"2023-04-30\" }],\n\t[\"15.x.x\", { eol: \"2021-06-01\" }],\n\t[\"16.x.x\", { eol: \"2023-09-11\" }],\n\t[\"17.x.x\", { eol: \"2022-06-01\" }],\n\t[\"18.x.x\", { eol: \"2025-04-30\" }],\n\t[\"19.x.x\", { eol: \"2023-06-01\" }],\n\t[\"20.x.x\", {}],\n\t[\"21.x.x\", { eol: \"2024-06-01\" }],\n\t[\"22.x.x\", {}],\n];\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"prefer-types\";\nconst severity = Severity.ERROR;\n\n/**\n * Yields an error if the `typings` field is present instead of `types`.\n *\n * @param pkg - Parsed `package.json\"`.\n * @param pkgAst - JSON syntax tree for the `pkg` parameter.\n */\nexport function* preferTypes(pkg: PackageJson, pkgAst: DocumentNode): Generator<Message> {\n\tif (!pkg.typings || pkg.types) {\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"typings\");\n\tyield {\n\t\truleId,\n\t\tseverity,\n\t\tmessage: `Prefer \"types\" over \"typings\"`,\n\t\tline,\n\t\tcolumn,\n\t};\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson, type PackageJsonExports } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"shadowed-types\";\nconst severity = Severity.ERROR;\n\nfunction walkConditions(conditions: PackageJsonExports | string | null): string[] {\n\tif (!conditions || typeof conditions === \"string\") {\n\t\treturn [];\n\t}\n\n\tconst types = conditions.types;\n\tif (typeof types === \"string\") {\n\t\treturn [types];\n\t}\n\n\treturn Object.values(conditions).reduce<string[]>((subpaths, it) => {\n\t\treturn [...subpaths, ...walkConditions(it)];\n\t}, []);\n}\n\n/**\n * Given the value of the \"exports\" field get all \"types\" conditions.\n *\n * @internal\n */\nexport function getTypesConditions(exports: PackageJsonExports | string | null): string[] {\n\tif (exports === null || typeof exports === \"string\") {\n\t\treturn [];\n\t}\n\n\tconst dot = exports[\".\"];\n\tif (dot) {\n\t\treturn walkConditions(dot);\n\t}\n\n\tconst types = exports.types;\n\tif (types && typeof types === \"string\") {\n\t\treturn [types];\n\t}\n\n\treturn [];\n}\n\n/**\n * Compare \"types\" from \"exports\" with the \"types\" or \"typings\" field and yields\n * an error if there is a mismatch.\n *\n * @param pkgAst - JSON syntax tree to get error location from.\n * @param subpaths - The resolved value from exports \".\".\n * @param field - Which field holds the value parameter.\n * @param value - The value of the \"types\" or \"typings\" field.\n */\nfunction* validateTypeSubpath(\n\tpkgAst: DocumentNode,\n\tsubpaths: string[],\n\tfield: \"types\" | \"typings\",\n\tvalue: string,\n): Generator<Message> {\n\t/* normalize types/typings value to always start with ./ as required by the exports field */\n\tconst normalizedValue = value.startsWith(\"./\") ? value : `./${value}`;\n\n\t/* test if the types value matches one or more subpath export */\n\tif (subpaths.some((it) => it === normalizedValue)) {\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"member\", field);\n\tyield {\n\t\truleId,\n\t\tseverity,\n\t\tmessage: `\"${field}\" cannot be resolved when respecting \"exports\" field`,\n\t\tline,\n\t\tcolumn,\n\t};\n}\n\n/**\n * Validates the `\"types\"` or `\"typings\"` field against the `\"exports\"` field to\n * ensure all versions of TypeScript can resolve the types.\n *\n * @param pkg - Parsed `package.json\"`.\n * @param pkgAst - JSON syntax tree for the `pkg` parameter.\n */\nexport function* shadowedTypes(pkg: PackageJson, pkgAst: DocumentNode): Generator<Message> {\n\tconst { exports } = pkg;\n\tif (!exports) {\n\t\treturn;\n\t}\n\n\tconst subpaths = getTypesConditions(exports);\n\n\tif (pkg.types) {\n\t\tyield* validateTypeSubpath(pkgAst, subpaths, \"types\", pkg.types);\n\t}\n\n\tif (pkg.typings) {\n\t\tyield* validateTypeSubpath(pkgAst, subpaths, \"typings\", pkg.typings);\n\t}\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport semver from \"semver\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"types-node-matching-engine\";\nconst severity = Severity.ERROR;\n\nexport function* typesNodeMatchingEngine(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n): Generator<Message> {\n\tif (!pkg.engines?.node) {\n\t\treturn;\n\t}\n\n\tfor (const source of [\"dependencies\", \"devDependencies\", \"peerDependencies\"] as const) {\n\t\tconst dependencies = pkg[source] ?? {};\n\t\tif (!dependencies[\"@types/node\"]) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst declaredVersion = dependencies[\"@types/node\"];\n\t\tif (declaredVersion === \"latest\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst nodeVersion = semver.minVersion(pkg.engines.node);\n\t\tconst typesVersion = semver.minVersion(declaredVersion);\n\n\t\tif (!nodeVersion || !typesVersion) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typesVersion.major !== nodeVersion.major) {\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"value\", source, \"@types/node\");\n\t\t\tconst actualVersion = `v${String(typesVersion.major)}`;\n\t\t\tconst expectedVersion = `v${String(nodeVersion.major)}`;\n\t\t\tyield {\n\t\t\t\truleId,\n\t\t\t\tseverity,\n\t\t\t\tmessage: `@types/node ${actualVersion} does not equal engines.node ${expectedVersion}`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t};\n\t\t}\n\t}\n}\n", "import semver, { type SemVer } from \"semver\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { isNpmInfoError, npmInfo } from \"../utils\";\n\nconst ruleId = \"invalid-engine-constraint\";\n\nasync function* getDeepDependencies(\n\tpkg: PackageJson,\n\tvisited: Set<string>,\n\tdependency?: string,\n): AsyncGenerator<string> {\n\tif (dependency) {\n\t\tif (visited.has(dependency)) {\n\t\t\treturn;\n\t\t}\n\t\tvisited.add(dependency);\n\t}\n\n\tconst pkgData = dependency ? await npmInfo(dependency, { ignoreUnpublished: true }) : pkg;\n\tif (!pkgData) {\n\t\treturn;\n\t}\n\tfor (let [key, version] of Object.entries(pkgData.dependencies ?? {})) {\n\t\t/* handle npm: prefix */\n\t\tif (version.startsWith(\"npm:\")) {\n\t\t\tconst [newKey, newVersion] = version.slice(\"npm:\".length).split(\"@\", 2);\n\t\t\tkey = newKey; // eslint-disable-line sonarjs/updated-loop-counter -- technical debt\n\t\t\tversion = newVersion; // eslint-disable-line sonarjs/updated-loop-counter -- technical debt\n\t\t}\n\n\t\t/* ignore this as this package is sometimes is present as version \"*\" which\n\t\t * just yields way to many versions to handle causing MaxBuffer errors and\n\t\t * there is another rule to make sure the outermost @types/node package\n\t\t * matches the configured engines */\n\t\tif (key === \"@types/node\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst minVersion = semver.minVersion(version);\n\t\tconst deep = `${key}@${minVersion ? minVersion.version : version}`;\n\n\t\tyield deep;\n\t\tyield* getDeepDependencies(pkg, visited, deep);\n\t}\n}\n\nasync function verifyDependency(\n\tdependency: string,\n\tminDeclared: SemVer,\n\tdeclaredConstraint: string,\n): Promise<Message | null> {\n\tconst pkgData = await npmInfo(dependency, { ignoreUnpublished: true });\n\tif (!pkgData) {\n\t\treturn null;\n\t}\n\tconst constraint = pkgData.engines?.node;\n\tif (!constraint) {\n\t\treturn null;\n\t}\n\n\tif (!semver.satisfies(minDeclared, constraint)) {\n\t\treturn {\n\t\t\truleId,\n\t\t\tseverity: 2,\n\t\t\tmessage: `the transitive dependency \"${dependency}\" (node ${constraint}) does not satisfy the declared node engine \"${declaredConstraint}\"`,\n\t\t\tline: 1,\n\t\t\tcolumn: 1,\n\t\t};\n\t}\n\n\treturn null;\n}\n\nexport async function verifyEngineConstraint(pkg: PackageJson): Promise<Message[]> {\n\tconst declaredConstraint = pkg.engines?.node;\n\tif (!declaredConstraint) {\n\t\treturn [];\n\t}\n\n\tconst minDeclared = semver.minVersion(declaredConstraint);\n\tif (!minDeclared) {\n\t\tthrow new Error(`Failed to parse engine constraint \"${declaredConstraint}\"`);\n\t}\n\n\tconst messages: Message[] = [];\n\tconst visited = new Set<string>();\n\n\tfor await (const dependency of getDeepDependencies(pkg, visited)) {\n\t\ttry {\n\t\t\tconst message = await verifyDependency(dependency, minDeclared, declaredConstraint);\n\t\t\tif (message) {\n\t\t\t\tmessages.push(message);\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tif (isNpmInfoError(err) && err.code === \"E404\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\truleId,\n\t\t\t\t\tseverity: 1,\n\t\t\t\t\tmessage: `the transitive dependency \"${dependency}\" is not published to the NPM registry`,\n\t\t\t\t\tline: 1,\n\t\t\t\t\tcolumn: 1,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\treturn messages;\n}\n", "export class ValidationError extends Error {\n\tpublic validator: string;\n\n\tpublic constructor(validator: string, message: string) {\n\t\tsuper(message);\n\t\tthis.validator = validator;\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nfunction isEmpty(value: unknown): boolean {\n\t/* undefined, null and empty string is considered empty */\n\treturn typeof value === \"undefined\" || value === null || value === \"\";\n}\n\nexport function nonempty(key: string, value: unknown): void {\n\tif (isEmpty(value)) {\n\t\tthrow new ValidationError(nonempty.name, `\"${key}\" must not be empty`);\n\t}\n\n\t/* any number is considered set, even 0 */\n\tif (typeof value === \"number\") {\n\t\treturn;\n\t}\n\n\t/* for arrays the array must be populated and each entry but be non-empty */\n\tif (Array.isArray(value)) {\n\t\tif (value.length === 0) {\n\t\t\tthrow new ValidationError(nonempty.name, `\"${key}\" must not be empty`);\n\t\t}\n\t\t/* eslint-disable-next-line @typescript-eslint/no-for-in-array -- technical debt */\n\t\tfor (const index in value) {\n\t\t\tnonempty(`${key}[${index}]`, value[index]);\n\t\t}\n\t\treturn;\n\t}\n\n\t/* object must have at least one one property set */\n\tif (value && typeof value === \"object\") {\n\t\tconst values = Object.values(value);\n\t\tif (values.length === 0) {\n\t\t\tthrow new ValidationError(nonempty.name, `\"${key}\" must not be empty`);\n\t\t}\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function present(key: string, value: unknown): void {\n\tif (typeof value === \"undefined\" || value === null) {\n\t\tthrow new ValidationError(present.name, `\"${key}\" must be set`);\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function typeArray(key: string, value: unknown): void {\n\tif (!Array.isArray(value)) {\n\t\tthrow new ValidationError(typeArray.name, `\"${key}\" must be array`);\n\t}\n\t/* eslint-disable-next-line @typescript-eslint/no-for-in-array -- technical debt */\n\tfor (const index in value) {\n\t\tif (typeof value[index] !== \"string\") {\n\t\t\tthrow new ValidationError(typeArray.name, `\"${key}[${index}]\" must be string`);\n\t\t}\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function typeString(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(typeString.name, `\"${key}\" must be string`);\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nfunction validateType(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.type\" must be a string`);\n\t}\n\tif (value !== \"git\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.type\" must be \"git\"`);\n\t}\n}\n\nfunction validateUrl(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" must be a string`);\n\t}\n\tif (value.trim() === \"\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" must not be empty`);\n\t}\n\tif (value !== value.trim()) {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}.url\" must not have leading or trailing whitespace`,\n\t\t);\n\t}\n\tconst url = new URL(value);\n\tif (url.protocol === \"git+http:\" || url.protocol === \"http:\") {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}.url\" must use \"git+https://\" instead of \"http://\"`,\n\t\t);\n\t}\n\tif (url.protocol !== \"git+https:\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" must use \"git+https://\" protocol`);\n\t}\n\tif (url.host === \"\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" be a valid url`);\n\t}\n}\n\nfunction validateDirectory(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.directory\" must be a string`);\n\t}\n\tif (value.trim() === \"\") {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}.directory\" must be set to non-empty string or the property must be removed`,\n\t\t);\n\t}\n}\n\nexport function validRepoUrl(key: string, value: unknown): void {\n\tif (value === undefined) {\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}\" must be an object with \"type\" and \"url\"`,\n\t\t);\n\t}\n\tif (\"type\" in value) {\n\t\tvalidateType(key, value.type);\n\t} else {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}\" is missing required \"type\" property`);\n\t}\n\tif (\"url\" in value) {\n\t\tvalidateUrl(key, value.url);\n\t} else {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}\" is missing required \"url\" property`);\n\t}\n\tif (\"directory\" in value) {\n\t\tvalidateDirectory(key, value.directory);\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function validUrl(key: string, value: unknown): void {\n\tif (typeof value === \"string\" && /^https:\\/\\/.+$/.exec(value)) {\n\t\treturn;\n\t} else if (value && typeof value === \"object\" && \"url\" in value) {\n\t\tvalidUrl(`${key}.url`, value.url);\n\t} else {\n\t\tthrow new ValidationError(validUrl.name, `\"${key}\" must be a valid url (https only)`);\n\t}\n}\n", "import { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"./message\";\nimport { type Result } from \"./result\";\nimport { conflictingTypesTypings } from \"./rules/conflicting-types-typings\";\nimport { deprecatedDependency } from \"./rules/deprecated-dependency\";\nimport { isDisallowedDependency } from \"./rules/disallowed-dependency\";\nimport { exportsTypesOrder } from \"./rules/exports-types-order\";\nimport { isObsoleteDependency } from \"./rules/obsolete-dependency\";\nimport { outdatedEngines } from \"./rules/outdated-engines\";\nimport { preferTypes } from \"./rules/prefer-types\";\nimport { shadowedTypes } from \"./rules/shadowed-types\";\nimport { typesNodeMatchingEngine } from \"./rules/types-node-matching-engine\";\nimport { verifyEngineConstraint } from \"./rules/verify-engine-constraint\";\nimport { type PackageJson } from \"./types\";\nimport { jsonLocation } from \"./utils\";\nimport {\n\tValidationError,\n\tnonempty,\n\tpresent,\n\ttypeArray,\n\ttypeString,\n\tvalidRepoUrl,\n\tvalidUrl,\n} from \"./validators\";\n\nexport interface VerifyPackageJsonOptions {\n\tallowedDependencies: Set<string>;\n\tallowTypesDependencies?: boolean | undefined;\n\tignoreMissingFields?: boolean | undefined;\n\tignoreNodeVersion: boolean | number;\n}\n\ntype validator = (key: string, value: unknown) => void;\n\nconst fields: Record<string, validator[]> = {\n\tdescription: [present, typeString, nonempty],\n\tkeywords: [present, typeArray, nonempty],\n\thomepage: [present, typeString, validUrl],\n\tbugs: [present, validUrl],\n\tlicense: [present, typeString, nonempty],\n\tauthor: [present, nonempty],\n\trepository: [present, validRepoUrl],\n};\n\nfunction verifyFields(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\toptions: VerifyPackageJsonOptions,\n): Message[] {\n\tconst messages: Message[] = [];\n\n\tfor (const [field, validators] of Object.entries(fields)) {\n\t\ttry {\n\t\t\tfor (const validator of validators) {\n\t\t\t\tvalidator(field, pkg[field]);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// istanbul ignore next\n\t\t\tif (!(error instanceof ValidationError)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (error.validator === present.name && options.ignoreMissingFields) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst { line, column } =\n\t\t\t\terror.validator !== present.name\n\t\t\t\t\t? jsonLocation(pkgAst, \"value\", field)\n\t\t\t\t\t: { line: 1, column: 1 };\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessages.push({\n\t\t\t\t\truleId: \"package-json-fields\",\n\t\t\t\t\tseverity: 2,\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tline,\n\t\t\t\t\tcolumn,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn messages;\n}\n\nfunction getActualDependency(key: string, version: string): string {\n\t/* handle npm: prefix */\n\tif (version.startsWith(\"npm:\")) {\n\t\tconst [name] = version.slice(\"npm:\".length).split(\"@\", 2);\n\t\treturn name;\n\t}\n\n\treturn key;\n}\n\n/* eslint-disable-next-line complexity -- technical debt */\nfunction verifyDependencies(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\toptions: VerifyPackageJsonOptions,\n): Message[] {\n\tconst messages: Message[] = [];\n\tconst { dependencies = {}, devDependencies = {}, peerDependencies = {} } = pkg;\n\n\tfor (const [key, version] of Object.entries(dependencies)) {\n\t\tconst dependency = getActualDependency(key, version);\n\n\t\t/* skip dependencies explicitly allowed by the user */\n\t\tif (options.allowedDependencies.has(dependency)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* skip @types/* if explicitly allowed by user */\n\t\tif (options.allowTypesDependencies && /^@types\\//.exec(dependency)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isDisallowedDependency(pkg, dependency)) {\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"dependencies\", key);\n\t\t\tconst name = key === dependency ? `\"${dependency}\"` : `\"${key}\" (\"npm:${dependency}\")`;\n\t\t\tmessages.push({\n\t\t\t\truleId: \"disallowed-dependency\",\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `${name} should be a devDependency`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t});\n\t\t}\n\t}\n\n\tfunction verifyObsolete(\n\t\tdependency: string,\n\t\tsource: \"dependencies\" | \"devDependencies\" | \"peerDependencies\",\n\t): void {\n\t\tconst obsolete = isObsoleteDependency(dependency);\n\t\tif (obsolete) {\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", source, dependency);\n\t\t\tmessages.push({\n\t\t\t\truleId: \"obsolete-dependency\",\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `\"${dependency}\" is obsolete and should no longer be used: ${obsolete.message}`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const dependency of Object.keys(dependencies)) {\n\t\tverifyObsolete(dependency, \"dependencies\");\n\t}\n\n\tfor (const dependency of Object.keys(devDependencies)) {\n\t\tverifyObsolete(dependency, \"devDependencies\");\n\t}\n\n\tfor (const dependency of Object.keys(peerDependencies)) {\n\t\tverifyObsolete(dependency, \"peerDependencies\");\n\t}\n\n\treturn messages;\n}\n\nexport async function verifyPackageJson(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\tfilePath: string,\n\toptions: VerifyPackageJsonOptions = { allowedDependencies: new Set(), ignoreNodeVersion: false },\n): Promise<Result[]> {\n\tconst { ignoreNodeVersion } = options;\n\n\tconst messages: Message[] = [\n\t\t...conflictingTypesTypings(pkg, pkgAst),\n\t\t...(await deprecatedDependency(pkg, pkgAst, options)),\n\t\t...(await verifyEngineConstraint(pkg)),\n\t\t...exportsTypesOrder(pkg, pkgAst),\n\t\t...verifyFields(pkg, pkgAst, options),\n\t\t...verifyDependencies(pkg, pkgAst, options),\n\t\t...outdatedEngines(pkg, pkgAst, ignoreNodeVersion),\n\t\t...preferTypes(pkg, pkgAst),\n\t\t...shadowedTypes(pkg, pkgAst),\n\t\t...typesNodeMatchingEngine(pkg, pkgAst),\n\t];\n\n\tif (messages.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [\n\t\t{\n\t\t\tmessages,\n\t\t\tfilePath,\n\t\t\terrorCount: messages.filter((it) => it.severity === 2).length,\n\t\t\twarningCount: messages.filter((it) => it.severity === 1).length,\n\t\t\tfixableErrorCount: 0,\n\t\t\tfixableWarningCount: 0,\n\t\t},\n\t];\n}\n", "import { type Result } from \"./result\";\nimport { type TarballMeta, getFileContent } from \"./tarball\";\nimport { type PackageJson } from \"./types\";\n\nfunction getBinaries(pkg: PackageJson): string[] {\n\tif (!pkg.bin) {\n\t\treturn [];\n\t}\n\treturn typeof pkg.bin === \"string\" ? [pkg.bin] : Object.values(pkg.bin);\n}\n\nexport async function verifyShebang(pkg: PackageJson, tarball: TarballMeta): Promise<Result[]> {\n\tconst results: Result[] = [];\n\tconst binaries = getBinaries(pkg);\n\tconst contents = await getFileContent(tarball, binaries);\n\n\tfor (const [filePath, content] of Object.entries(contents)) {\n\t\tconst text = content.toString(\"utf-8\");\n\t\tif (/^#!.+?\\r?\\n/.exec(text)) {\n\t\t\tcontinue;\n\t\t}\n\t\tresults.push({\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\truleId: \"no-missing-shebang\",\n\t\t\t\t\tseverity: 2,\n\t\t\t\t\tmessage: `first line must contain shebang to be executable`,\n\t\t\t\t\tline: 1,\n\t\t\t\t\tcolumn: 1,\n\t\t\t\t},\n\t\t\t],\n\t\t\tfilePath,\n\t\t\terrorCount: 1,\n\t\t\twarningCount: 0,\n\t\t\tfixableErrorCount: 0,\n\t\t\tfixableWarningCount: 0,\n\t\t});\n\t}\n\n\treturn results;\n}\n", "import { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type VerifyPackageJsonOptions, verifyPackageJson } from \"./package-json\";\nimport { type Result } from \"./result\";\nimport { verifyShebang } from \"./shebang\";\nimport { type TarballMeta, verifyTarball } from \"./tarball\";\nimport { type PackageJson } from \"./types\";\n\nexport type VerifyOptions = VerifyPackageJsonOptions;\n\nexport async function verify(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\tpkgPath: string,\n\ttarball: TarballMeta,\n\toptions: VerifyOptions,\n): Promise<Result[]> {\n\treturn [\n\t\t...(await verifyTarball(pkg, tarball)),\n\t\t...(await verifyPackageJson(pkg, pkgAst, pkgPath, options)),\n\t\t...(await verifyShebang(pkg, tarball)),\n\t];\n}\n"],
4
+ "sourcesContent": ["// Limited implementation of python % string operator, supports only %s and %r for now\n// (other formats are not used here, but may appear in custom templates)\n\n'use strict'\n\nconst { inspect } = require('util')\n\n\nmodule.exports = function sub(pattern, ...values) {\n let regex = /%(?:(%)|(-)?(\\*)?(?:\\((\\w+)\\))?([A-Za-z]))/g\n\n let result = pattern.replace(regex, function (_, is_literal, is_left_align, is_padded, name, format) {\n if (is_literal) return '%'\n\n let padded_count = 0\n if (is_padded) {\n if (values.length === 0) throw new TypeError('not enough arguments for format string')\n padded_count = values.shift()\n if (!Number.isInteger(padded_count)) throw new TypeError('* wants int')\n }\n\n let str\n if (name !== undefined) {\n let dict = values[0]\n if (typeof dict !== 'object' || dict === null) throw new TypeError('format requires a mapping')\n if (!(name in dict)) throw new TypeError(`no such key: '${name}'`)\n str = dict[name]\n } else {\n if (values.length === 0) throw new TypeError('not enough arguments for format string')\n str = values.shift()\n }\n\n switch (format) {\n case 's':\n str = String(str)\n break\n case 'r':\n str = inspect(str)\n break\n case 'd':\n case 'i':\n if (typeof str !== 'number') {\n throw new TypeError(`%${format} format: a number is required, not ${typeof str}`)\n }\n str = String(str.toFixed(0))\n break\n default:\n throw new TypeError(`unsupported format character '${format}'`)\n }\n\n if (padded_count > 0) {\n return is_left_align ? str.padEnd(padded_count) : str.padStart(padded_count)\n } else {\n return str\n }\n })\n\n if (values.length) {\n if (values.length === 1 && typeof values[0] === 'object' && values[0] !== null) {\n // mapping\n } else {\n throw new TypeError('not all arguments converted during string formatting')\n }\n }\n\n return result\n}\n", "// Partial port of python's argparse module, version 3.9.0 (only wrap and fill functions):\n// https://github.com/python/cpython/blob/v3.9.0b4/Lib/textwrap.py\n\n'use strict'\n\n/*\n * Text wrapping and filling.\n */\n\n// Copyright (C) 1999-2001 Gregory P. Ward.\n// Copyright (C) 2002, 2003 Python Software Foundation.\n// Copyright (C) 2020 argparse.js authors\n// Originally written by Greg Ward <gward@python.net>\n\n// Hardcode the recognized whitespace characters to the US-ASCII\n// whitespace characters. The main reason for doing this is that\n// some Unicode spaces (like \\u00a0) are non-breaking whitespaces.\n//\n// This less funky little regex just split on recognized spaces. E.g.\n// \"Hello there -- you goof-ball, use the -b option!\"\n// splits into\n// Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/\nconst wordsep_simple_re = /([\\t\\n\\x0b\\x0c\\r ]+)/\n\nclass TextWrapper {\n /*\n * Object for wrapping/filling text. The public interface consists of\n * the wrap() and fill() methods; the other methods are just there for\n * subclasses to override in order to tweak the default behaviour.\n * If you want to completely replace the main wrapping algorithm,\n * you'll probably have to override _wrap_chunks().\n *\n * Several instance attributes control various aspects of wrapping:\n * width (default: 70)\n * the maximum width of wrapped lines (unless break_long_words\n * is false)\n * initial_indent (default: \"\")\n * string that will be prepended to the first line of wrapped\n * output. Counts towards the line's width.\n * subsequent_indent (default: \"\")\n * string that will be prepended to all lines save the first\n * of wrapped output; also counts towards each line's width.\n * expand_tabs (default: true)\n * Expand tabs in input text to spaces before further processing.\n * Each tab will become 0 .. 'tabsize' spaces, depending on its position\n * in its line. If false, each tab is treated as a single character.\n * tabsize (default: 8)\n * Expand tabs in input text to 0 .. 'tabsize' spaces, unless\n * 'expand_tabs' is false.\n * replace_whitespace (default: true)\n * Replace all whitespace characters in the input text by spaces\n * after tab expansion. Note that if expand_tabs is false and\n * replace_whitespace is true, every tab will be converted to a\n * single space!\n * fix_sentence_endings (default: false)\n * Ensure that sentence-ending punctuation is always followed\n * by two spaces. Off by default because the algorithm is\n * (unavoidably) imperfect.\n * break_long_words (default: true)\n * Break words longer than 'width'. If false, those words will not\n * be broken, and some lines might be longer than 'width'.\n * break_on_hyphens (default: true)\n * Allow breaking hyphenated words. If true, wrapping will occur\n * preferably on whitespaces and right after hyphens part of\n * compound words.\n * drop_whitespace (default: true)\n * Drop leading and trailing whitespace from lines.\n * max_lines (default: None)\n * Truncate wrapped lines.\n * placeholder (default: ' [...]')\n * Append to the last line of truncated text.\n */\n\n constructor(options = {}) {\n let {\n width = 70,\n initial_indent = '',\n subsequent_indent = '',\n expand_tabs = true,\n replace_whitespace = true,\n fix_sentence_endings = false,\n break_long_words = true,\n drop_whitespace = true,\n break_on_hyphens = true,\n tabsize = 8,\n max_lines = undefined,\n placeholder=' [...]'\n } = options\n\n this.width = width\n this.initial_indent = initial_indent\n this.subsequent_indent = subsequent_indent\n this.expand_tabs = expand_tabs\n this.replace_whitespace = replace_whitespace\n this.fix_sentence_endings = fix_sentence_endings\n this.break_long_words = break_long_words\n this.drop_whitespace = drop_whitespace\n this.break_on_hyphens = break_on_hyphens\n this.tabsize = tabsize\n this.max_lines = max_lines\n this.placeholder = placeholder\n }\n\n\n // -- Private methods -----------------------------------------------\n // (possibly useful for subclasses to override)\n\n _munge_whitespace(text) {\n /*\n * _munge_whitespace(text : string) -> string\n *\n * Munge whitespace in text: expand tabs and convert all other\n * whitespace characters to spaces. Eg. \" foo\\\\tbar\\\\n\\\\nbaz\"\n * becomes \" foo bar baz\".\n */\n if (this.expand_tabs) {\n text = text.replace(/\\t/g, ' '.repeat(this.tabsize)) // not strictly correct in js\n }\n if (this.replace_whitespace) {\n text = text.replace(/[\\t\\n\\x0b\\x0c\\r]/g, ' ')\n }\n return text\n }\n\n _split(text) {\n /*\n * _split(text : string) -> [string]\n *\n * Split the text to wrap into indivisible chunks. Chunks are\n * not quite the same as words; see _wrap_chunks() for full\n * details. As an example, the text\n * Look, goof-ball -- use the -b option!\n * breaks into the following chunks:\n * 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',\n * 'use', ' ', 'the', ' ', '-b', ' ', 'option!'\n * if break_on_hyphens is True, or in:\n * 'Look,', ' ', 'goof-ball', ' ', '--', ' ',\n * 'use', ' ', 'the', ' ', '-b', ' ', option!'\n * otherwise.\n */\n let chunks = text.split(wordsep_simple_re)\n chunks = chunks.filter(Boolean)\n return chunks\n }\n\n _handle_long_word(reversed_chunks, cur_line, cur_len, width) {\n /*\n * _handle_long_word(chunks : [string],\n * cur_line : [string],\n * cur_len : int, width : int)\n *\n * Handle a chunk of text (most likely a word, not whitespace) that\n * is too long to fit in any line.\n */\n // Figure out when indent is larger than the specified width, and make\n // sure at least one character is stripped off on every pass\n let space_left\n if (width < 1) {\n space_left = 1\n } else {\n space_left = width - cur_len\n }\n\n // If we're allowed to break long words, then do so: put as much\n // of the next chunk onto the current line as will fit.\n if (this.break_long_words) {\n cur_line.push(reversed_chunks[reversed_chunks.length - 1].slice(0, space_left))\n reversed_chunks[reversed_chunks.length - 1] = reversed_chunks[reversed_chunks.length - 1].slice(space_left)\n\n // Otherwise, we have to preserve the long word intact. Only add\n // it to the current line if there's nothing already there --\n // that minimizes how much we violate the width constraint.\n } else if (!cur_line) {\n cur_line.push(...reversed_chunks.pop())\n }\n\n // If we're not allowed to break long words, and there's already\n // text on the current line, do nothing. Next time through the\n // main loop of _wrap_chunks(), we'll wind up here again, but\n // cur_len will be zero, so the next line will be entirely\n // devoted to the long word that we can't handle right now.\n }\n\n _wrap_chunks(chunks) {\n /*\n * _wrap_chunks(chunks : [string]) -> [string]\n *\n * Wrap a sequence of text chunks and return a list of lines of\n * length 'self.width' or less. (If 'break_long_words' is false,\n * some lines may be longer than this.) Chunks correspond roughly\n * to words and the whitespace between them: each chunk is\n * indivisible (modulo 'break_long_words'), but a line break can\n * come between any two chunks. Chunks should not have internal\n * whitespace; ie. a chunk is either all whitespace or a \"word\".\n * Whitespace chunks will be removed from the beginning and end of\n * lines, but apart from that whitespace is preserved.\n */\n let lines = []\n let indent\n if (this.width <= 0) {\n throw Error(`invalid width ${this.width} (must be > 0)`)\n }\n if (this.max_lines !== undefined) {\n if (this.max_lines > 1) {\n indent = this.subsequent_indent\n } else {\n indent = this.initial_indent\n }\n if (indent.length + this.placeholder.trimStart().length > this.width) {\n throw Error('placeholder too large for max width')\n }\n }\n\n // Arrange in reverse order so items can be efficiently popped\n // from a stack of chucks.\n chunks = chunks.reverse()\n\n while (chunks.length > 0) {\n\n // Start the list of chunks that will make up the current line.\n // cur_len is just the length of all the chunks in cur_line.\n let cur_line = []\n let cur_len = 0\n\n // Figure out which static string will prefix this line.\n let indent\n if (lines) {\n indent = this.subsequent_indent\n } else {\n indent = this.initial_indent\n }\n\n // Maximum width for this line.\n let width = this.width - indent.length\n\n // First chunk on line is whitespace -- drop it, unless this\n // is the very beginning of the text (ie. no lines started yet).\n if (this.drop_whitespace && chunks[chunks.length - 1].trim() === '' && lines.length > 0) {\n chunks.pop()\n }\n\n while (chunks.length > 0) {\n let l = chunks[chunks.length - 1].length\n\n // Can at least squeeze this chunk onto the current line.\n if (cur_len + l <= width) {\n cur_line.push(chunks.pop())\n cur_len += l\n\n // Nope, this line is full.\n } else {\n break\n }\n }\n\n // The current line is full, and the next chunk is too big to\n // fit on *any* line (not just this one).\n if (chunks.length && chunks[chunks.length - 1].length > width) {\n this._handle_long_word(chunks, cur_line, cur_len, width)\n cur_len = cur_line.map(l => l.length).reduce((a, b) => a + b, 0)\n }\n\n // If the last chunk on this line is all whitespace, drop it.\n if (this.drop_whitespace && cur_line.length > 0 && cur_line[cur_line.length - 1].trim() === '') {\n cur_len -= cur_line[cur_line.length - 1].length\n cur_line.pop()\n }\n\n if (cur_line) {\n if (this.max_lines === undefined ||\n lines.length + 1 < this.max_lines ||\n (chunks.length === 0 ||\n this.drop_whitespace &&\n chunks.length === 1 &&\n !chunks[0].trim()) && cur_len <= width) {\n // Convert current line back to a string and store it in\n // list of all lines (return value).\n lines.push(indent + cur_line.join(''))\n } else {\n let had_break = false\n while (cur_line) {\n if (cur_line[cur_line.length - 1].trim() &&\n cur_len + this.placeholder.length <= width) {\n cur_line.push(this.placeholder)\n lines.push(indent + cur_line.join(''))\n had_break = true\n break\n }\n cur_len -= cur_line[-1].length\n cur_line.pop()\n }\n if (!had_break) {\n if (lines) {\n let prev_line = lines[lines.length - 1].trimEnd()\n if (prev_line.length + this.placeholder.length <=\n this.width) {\n lines[lines.length - 1] = prev_line + this.placeholder\n break\n }\n }\n lines.push(indent + this.placeholder.lstrip())\n }\n break\n }\n }\n }\n\n return lines\n }\n\n _split_chunks(text) {\n text = this._munge_whitespace(text)\n return this._split(text)\n }\n\n // -- Public interface ----------------------------------------------\n\n wrap(text) {\n /*\n * wrap(text : string) -> [string]\n *\n * Reformat the single paragraph in 'text' so it fits in lines of\n * no more than 'self.width' columns, and return a list of wrapped\n * lines. Tabs in 'text' are expanded with string.expandtabs(),\n * and all other whitespace characters (including newline) are\n * converted to space.\n */\n let chunks = this._split_chunks(text)\n // not implemented in js\n //if (this.fix_sentence_endings) {\n // this._fix_sentence_endings(chunks)\n //}\n return this._wrap_chunks(chunks)\n }\n\n fill(text) {\n /*\n * fill(text : string) -> string\n *\n * Reformat the single paragraph in 'text' to fit in lines of no\n * more than 'self.width' columns, and return a new string\n * containing the entire wrapped paragraph.\n */\n return this.wrap(text).join('\\n')\n }\n}\n\n\n// -- Convenience interface ---------------------------------------------\n\nfunction wrap(text, options = {}) {\n /*\n * Wrap a single paragraph of text, returning a list of wrapped lines.\n *\n * Reformat the single paragraph in 'text' so it fits in lines of no\n * more than 'width' columns, and return a list of wrapped lines. By\n * default, tabs in 'text' are expanded with string.expandtabs(), and\n * all other whitespace characters (including newline) are converted to\n * space. See TextWrapper class for available keyword args to customize\n * wrapping behaviour.\n */\n let { width = 70, ...kwargs } = options\n let w = new TextWrapper(Object.assign({ width }, kwargs))\n return w.wrap(text)\n}\n\nfunction fill(text, options = {}) {\n /*\n * Fill a single paragraph of text, returning a new string.\n *\n * Reformat the single paragraph in 'text' to fit in lines of no more\n * than 'width' columns, and return a new string containing the entire\n * wrapped paragraph. As with wrap(), tabs are expanded and other\n * whitespace characters converted to space. See TextWrapper class for\n * available keyword args to customize wrapping behaviour.\n */\n let { width = 70, ...kwargs } = options\n let w = new TextWrapper(Object.assign({ width }, kwargs))\n return w.fill(text)\n}\n\n// -- Loosely related functionality -------------------------------------\n\nlet _whitespace_only_re = /^[ \\t]+$/mg\nlet _leading_whitespace_re = /(^[ \\t]*)(?:[^ \\t\\n])/mg\n\nfunction dedent(text) {\n /*\n * Remove any common leading whitespace from every line in `text`.\n *\n * This can be used to make triple-quoted strings line up with the left\n * edge of the display, while still presenting them in the source code\n * in indented form.\n *\n * Note that tabs and spaces are both treated as whitespace, but they\n * are not equal: the lines \" hello\" and \"\\\\thello\" are\n * considered to have no common leading whitespace.\n *\n * Entirely blank lines are normalized to a newline character.\n */\n // Look for the longest leading string of spaces and tabs common to\n // all lines.\n let margin = undefined\n text = text.replace(_whitespace_only_re, '')\n let indents = text.match(_leading_whitespace_re) || []\n for (let indent of indents) {\n indent = indent.slice(0, -1)\n\n if (margin === undefined) {\n margin = indent\n\n // Current line more deeply indented than previous winner:\n // no change (previous winner is still on top).\n } else if (indent.startsWith(margin)) {\n // pass\n\n // Current line consistent with and no deeper than previous winner:\n // it's the new winner.\n } else if (margin.startsWith(indent)) {\n margin = indent\n\n // Find the largest common whitespace between current line and previous\n // winner.\n } else {\n for (let i = 0; i < margin.length && i < indent.length; i++) {\n if (margin[i] !== indent[i]) {\n margin = margin.slice(0, i)\n break\n }\n }\n }\n }\n\n if (margin) {\n text = text.replace(new RegExp('^' + margin, 'mg'), '')\n }\n return text\n}\n\nmodule.exports = { wrap, fill, dedent }\n", "// Port of python's argparse module, version 3.9.0:\n// https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py\n\n'use strict'\n\n// Copyright (C) 2010-2020 Python Software Foundation.\n// Copyright (C) 2020 argparse.js authors\n\n/*\n * Command-line parsing library\n *\n * This module is an optparse-inspired command-line parsing library that:\n *\n * - handles both optional and positional arguments\n * - produces highly informative usage messages\n * - supports parsers that dispatch to sub-parsers\n *\n * The following is a simple usage example that sums integers from the\n * command-line and writes the result to a file::\n *\n * parser = argparse.ArgumentParser(\n * description='sum the integers at the command line')\n * parser.add_argument(\n * 'integers', metavar='int', nargs='+', type=int,\n * help='an integer to be summed')\n * parser.add_argument(\n * '--log', default=sys.stdout, type=argparse.FileType('w'),\n * help='the file where the sum should be written')\n * args = parser.parse_args()\n * args.log.write('%s' % sum(args.integers))\n * args.log.close()\n *\n * The module contains the following public classes:\n *\n * - ArgumentParser -- The main entry point for command-line parsing. As the\n * example above shows, the add_argument() method is used to populate\n * the parser with actions for optional and positional arguments. Then\n * the parse_args() method is invoked to convert the args at the\n * command-line into an object with attributes.\n *\n * - ArgumentError -- The exception raised by ArgumentParser objects when\n * there are errors with the parser's actions. Errors raised while\n * parsing the command-line are caught by ArgumentParser and emitted\n * as command-line messages.\n *\n * - FileType -- A factory for defining types of files to be created. As the\n * example above shows, instances of FileType are typically passed as\n * the type= argument of add_argument() calls.\n *\n * - Action -- The base class for parser actions. Typically actions are\n * selected by passing strings like 'store_true' or 'append_const' to\n * the action= argument of add_argument(). However, for greater\n * customization of ArgumentParser actions, subclasses of Action may\n * be defined and passed as the action= argument.\n *\n * - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,\n * ArgumentDefaultsHelpFormatter -- Formatter classes which\n * may be passed as the formatter_class= argument to the\n * ArgumentParser constructor. HelpFormatter is the default,\n * RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser\n * not to change the formatting for help text, and\n * ArgumentDefaultsHelpFormatter adds information about argument defaults\n * to the help.\n *\n * All other classes in this module are considered implementation details.\n * (Also note that HelpFormatter and RawDescriptionHelpFormatter are only\n * considered public as object names -- the API of the formatter objects is\n * still considered an implementation detail.)\n */\n\nconst SUPPRESS = '==SUPPRESS=='\n\nconst OPTIONAL = '?'\nconst ZERO_OR_MORE = '*'\nconst ONE_OR_MORE = '+'\nconst PARSER = 'A...'\nconst REMAINDER = '...'\nconst _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'\n\n\n// ==================================\n// Utility functions used for porting\n// ==================================\nconst assert = require('assert')\nconst util = require('util')\nconst fs = require('fs')\nconst sub = require('./lib/sub')\nconst path = require('path')\nconst repr = util.inspect\n\nfunction get_argv() {\n // omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.)\n return process.argv.slice(1)\n}\n\nfunction get_terminal_size() {\n return {\n columns: +process.env.COLUMNS || process.stdout.columns || 80\n }\n}\n\nfunction hasattr(object, name) {\n return Object.prototype.hasOwnProperty.call(object, name)\n}\n\nfunction getattr(object, name, value) {\n return hasattr(object, name) ? object[name] : value\n}\n\nfunction setattr(object, name, value) {\n object[name] = value\n}\n\nfunction setdefault(object, name, value) {\n if (!hasattr(object, name)) object[name] = value\n return object[name]\n}\n\nfunction delattr(object, name) {\n delete object[name]\n}\n\nfunction range(from, to, step=1) {\n // range(10) is equivalent to range(0, 10)\n if (arguments.length === 1) [ to, from ] = [ from, 0 ]\n if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') {\n throw new TypeError('argument cannot be interpreted as an integer')\n }\n if (step === 0) throw new TypeError('range() arg 3 must not be zero')\n\n let result = []\n if (step > 0) {\n for (let i = from; i < to; i += step) result.push(i)\n } else {\n for (let i = from; i > to; i += step) result.push(i)\n }\n return result\n}\n\nfunction splitlines(str, keepends = false) {\n let result\n if (!keepends) {\n result = str.split(/\\r\\n|[\\n\\r\\v\\f\\x1c\\x1d\\x1e\\x85\\u2028\\u2029]/)\n } else {\n result = []\n let parts = str.split(/(\\r\\n|[\\n\\r\\v\\f\\x1c\\x1d\\x1e\\x85\\u2028\\u2029])/)\n for (let i = 0; i < parts.length; i += 2) {\n result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : ''))\n }\n }\n if (!result[result.length - 1]) result.pop()\n return result\n}\n\nfunction _string_lstrip(string, prefix_chars) {\n let idx = 0\n while (idx < string.length && prefix_chars.includes(string[idx])) idx++\n return idx ? string.slice(idx) : string\n}\n\nfunction _string_split(string, sep, maxsplit) {\n let result = string.split(sep)\n if (result.length > maxsplit) {\n result = result.slice(0, maxsplit).concat([ result.slice(maxsplit).join(sep) ])\n }\n return result\n}\n\nfunction _array_equal(array1, array2) {\n if (array1.length !== array2.length) return false\n for (let i = 0; i < array1.length; i++) {\n if (array1[i] !== array2[i]) return false\n }\n return true\n}\n\nfunction _array_remove(array, item) {\n let idx = array.indexOf(item)\n if (idx === -1) throw new TypeError(sub('%r not in list', item))\n array.splice(idx, 1)\n}\n\n// normalize choices to array;\n// this isn't required in python because `in` and `map` operators work with anything,\n// but in js dealing with multiple types here is too clunky\nfunction _choices_to_array(choices) {\n if (choices === undefined) {\n return []\n } else if (Array.isArray(choices)) {\n return choices\n } else if (choices !== null && typeof choices[Symbol.iterator] === 'function') {\n return Array.from(choices)\n } else if (typeof choices === 'object' && choices !== null) {\n return Object.keys(choices)\n } else {\n throw new Error(sub('invalid choices value: %r', choices))\n }\n}\n\n// decorator that allows a class to be called without new\nfunction _callable(cls) {\n let result = { // object is needed for inferred class name\n [cls.name]: function (...args) {\n let this_class = new.target === result || !new.target\n return Reflect.construct(cls, args, this_class ? cls : new.target)\n }\n }\n result[cls.name].prototype = cls.prototype\n // fix default tag for toString, e.g. [object Action] instead of [object Object]\n cls.prototype[Symbol.toStringTag] = cls.name\n return result[cls.name]\n}\n\nfunction _alias(object, from, to) {\n try {\n let name = object.constructor.name\n Object.defineProperty(object, from, {\n value: util.deprecate(object[to], sub('%s.%s() is renamed to %s.%s()',\n name, from, name, to)),\n enumerable: false\n })\n } catch {}\n}\n\n// decorator that allows snake_case class methods to be called with camelCase and vice versa\nfunction _camelcase_alias(_class) {\n for (let name of Object.getOwnPropertyNames(_class.prototype)) {\n let camelcase = name.replace(/\\w_[a-z]/g, s => s[0] + s[2].toUpperCase())\n if (camelcase !== name) _alias(_class.prototype, camelcase, name)\n }\n return _class\n}\n\nfunction _to_legacy_name(key) {\n key = key.replace(/\\w_[a-z]/g, s => s[0] + s[2].toUpperCase())\n if (key === 'default') key = 'defaultValue'\n if (key === 'const') key = 'constant'\n return key\n}\n\nfunction _to_new_name(key) {\n if (key === 'defaultValue') key = 'default'\n if (key === 'constant') key = 'const'\n key = key.replace(/[A-Z]/g, c => '_' + c.toLowerCase())\n return key\n}\n\n// parse options\nlet no_default = Symbol('no_default_value')\nfunction _parse_opts(args, descriptor) {\n function get_name() {\n let stack = new Error().stack.split('\\n')\n .map(x => x.match(/^ at (.*) \\(.*\\)$/))\n .filter(Boolean)\n .map(m => m[1])\n .map(fn => fn.match(/[^ .]*$/)[0])\n\n if (stack.length && stack[0] === get_name.name) stack.shift()\n if (stack.length && stack[0] === _parse_opts.name) stack.shift()\n return stack.length ? stack[0] : ''\n }\n\n args = Array.from(args)\n let kwargs = {}\n let result = []\n let last_opt = args.length && args[args.length - 1]\n\n if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) &&\n (!last_opt.constructor || last_opt.constructor.name === 'Object')) {\n kwargs = Object.assign({}, args.pop())\n }\n\n // LEGACY (v1 compatibility): camelcase\n let renames = []\n for (let key of Object.keys(descriptor)) {\n let old_name = _to_legacy_name(key)\n if (old_name !== key && (old_name in kwargs)) {\n if (key in kwargs) {\n // default and defaultValue specified at the same time, happens often in old tests\n //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key))\n } else {\n kwargs[key] = kwargs[old_name]\n }\n renames.push([ old_name, key ])\n delete kwargs[old_name]\n }\n }\n if (renames.length) {\n let name = get_name()\n deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s',\n name, renames.map(([ a, b ]) => sub('%r -> %r', a, b))))\n }\n // end\n\n let missing_positionals = []\n let positional_count = args.length\n\n for (let [ key, def ] of Object.entries(descriptor)) {\n if (key[0] === '*') {\n if (key.length > 0 && key[1] === '*') {\n // LEGACY (v1 compatibility): camelcase\n let renames = []\n for (let key of Object.keys(kwargs)) {\n let new_name = _to_new_name(key)\n if (new_name !== key && (key in kwargs)) {\n if (new_name in kwargs) {\n // default and defaultValue specified at the same time, happens often in old tests\n //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), new_name))\n } else {\n kwargs[new_name] = kwargs[key]\n }\n renames.push([ key, new_name ])\n delete kwargs[key]\n }\n }\n if (renames.length) {\n let name = get_name()\n deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s',\n name, renames.map(([ a, b ]) => sub('%r -> %r', a, b))))\n }\n // end\n result.push(kwargs)\n kwargs = {}\n } else {\n result.push(args)\n args = []\n }\n } else if (key in kwargs && args.length > 0) {\n throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key))\n } else if (key in kwargs) {\n result.push(kwargs[key])\n delete kwargs[key]\n } else if (args.length > 0) {\n result.push(args.shift())\n } else if (def !== no_default) {\n result.push(def)\n } else {\n missing_positionals.push(key)\n }\n }\n\n if (Object.keys(kwargs).length) {\n throw new TypeError(sub('%s() got an unexpected keyword argument %r',\n get_name(), Object.keys(kwargs)[0]))\n }\n\n if (args.length) {\n let from = Object.entries(descriptor).filter(([ k, v ]) => k[0] !== '*' && v !== no_default).length\n let to = Object.entries(descriptor).filter(([ k ]) => k[0] !== '*').length\n throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given',\n get_name(),\n from === to ? sub('from %s to %s', from, to) : to,\n from === to && to === 1 ? '' : 's',\n positional_count,\n positional_count === 1 ? 'was' : 'were'))\n }\n\n if (missing_positionals.length) {\n let strs = missing_positionals.map(repr)\n if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1]\n let str_joined = strs.join(strs.length === 2 ? '' : ', ')\n throw new TypeError(sub('%s() missing %i required positional argument%s: %s',\n get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined))\n }\n\n return result\n}\n\nlet _deprecations = {}\nfunction deprecate(id, string) {\n _deprecations[id] = _deprecations[id] || util.deprecate(() => {}, string)\n _deprecations[id]()\n}\n\n\n// =============================\n// Utility functions and classes\n// =============================\nfunction _AttributeHolder(cls = Object) {\n /*\n * Abstract base class that provides __repr__.\n *\n * The __repr__ method returns a string in the format::\n * ClassName(attr=name, attr=name, ...)\n * The attributes are determined either by a class-level attribute,\n * '_kwarg_names', or by inspecting the instance __dict__.\n */\n\n return class _AttributeHolder extends cls {\n [util.inspect.custom]() {\n let type_name = this.constructor.name\n let arg_strings = []\n let star_args = {}\n for (let arg of this._get_args()) {\n arg_strings.push(repr(arg))\n }\n for (let [ name, value ] of this._get_kwargs()) {\n if (/^[a-z_][a-z0-9_$]*$/i.test(name)) {\n arg_strings.push(sub('%s=%r', name, value))\n } else {\n star_args[name] = value\n }\n }\n if (Object.keys(star_args).length) {\n arg_strings.push(sub('**%s', repr(star_args)))\n }\n return sub('%s(%s)', type_name, arg_strings.join(', '))\n }\n\n toString() {\n return this[util.inspect.custom]()\n }\n\n _get_kwargs() {\n return Object.entries(this)\n }\n\n _get_args() {\n return []\n }\n }\n}\n\n\nfunction _copy_items(items) {\n if (items === undefined) {\n return []\n }\n return items.slice(0)\n}\n\n\n// ===============\n// Formatting Help\n// ===============\nconst HelpFormatter = _camelcase_alias(_callable(class HelpFormatter {\n /*\n * Formatter for generating usage messages and argument help strings.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n constructor() {\n let [\n prog,\n indent_increment,\n max_help_position,\n width\n ] = _parse_opts(arguments, {\n prog: no_default,\n indent_increment: 2,\n max_help_position: 24,\n width: undefined\n })\n\n // default setting for width\n if (width === undefined) {\n width = get_terminal_size().columns\n width -= 2\n }\n\n this._prog = prog\n this._indent_increment = indent_increment\n this._max_help_position = Math.min(max_help_position,\n Math.max(width - 20, indent_increment * 2))\n this._width = width\n\n this._current_indent = 0\n this._level = 0\n this._action_max_length = 0\n\n this._root_section = this._Section(this, undefined)\n this._current_section = this._root_section\n\n this._whitespace_matcher = /[ \\t\\n\\r\\f\\v]+/g // equivalent to python /\\s+/ with ASCII flag\n this._long_break_matcher = /\\n\\n\\n+/g\n }\n\n // ===============================\n // Section and indentation methods\n // ===============================\n _indent() {\n this._current_indent += this._indent_increment\n this._level += 1\n }\n\n _dedent() {\n this._current_indent -= this._indent_increment\n assert(this._current_indent >= 0, 'Indent decreased below 0.')\n this._level -= 1\n }\n\n _add_item(func, args) {\n this._current_section.items.push([ func, args ])\n }\n\n // ========================\n // Message building methods\n // ========================\n start_section(heading) {\n this._indent()\n let section = this._Section(this, this._current_section, heading)\n this._add_item(section.format_help.bind(section), [])\n this._current_section = section\n }\n\n end_section() {\n this._current_section = this._current_section.parent\n this._dedent()\n }\n\n add_text(text) {\n if (text !== SUPPRESS && text !== undefined) {\n this._add_item(this._format_text.bind(this), [text])\n }\n }\n\n add_usage(usage, actions, groups, prefix = undefined) {\n if (usage !== SUPPRESS) {\n let args = [ usage, actions, groups, prefix ]\n this._add_item(this._format_usage.bind(this), args)\n }\n }\n\n add_argument(action) {\n if (action.help !== SUPPRESS) {\n\n // find all invocations\n let invocations = [this._format_action_invocation(action)]\n for (let subaction of this._iter_indented_subactions(action)) {\n invocations.push(this._format_action_invocation(subaction))\n }\n\n // update the maximum item length\n let invocation_length = Math.max(...invocations.map(invocation => invocation.length))\n let action_length = invocation_length + this._current_indent\n this._action_max_length = Math.max(this._action_max_length,\n action_length)\n\n // add the item to the list\n this._add_item(this._format_action.bind(this), [action])\n }\n }\n\n add_arguments(actions) {\n for (let action of actions) {\n this.add_argument(action)\n }\n }\n\n // =======================\n // Help-formatting methods\n // =======================\n format_help() {\n let help = this._root_section.format_help()\n if (help) {\n help = help.replace(this._long_break_matcher, '\\n\\n')\n help = help.replace(/^\\n+|\\n+$/g, '') + '\\n'\n }\n return help\n }\n\n _join_parts(part_strings) {\n return part_strings.filter(part => part && part !== SUPPRESS).join('')\n }\n\n _format_usage(usage, actions, groups, prefix) {\n if (prefix === undefined) {\n prefix = 'usage: '\n }\n\n // if usage is specified, use that\n if (usage !== undefined) {\n usage = sub(usage, { prog: this._prog })\n\n // if no optionals or positionals are available, usage is just prog\n } else if (usage === undefined && !actions.length) {\n usage = sub('%(prog)s', { prog: this._prog })\n\n // if optionals and positionals are available, calculate usage\n } else if (usage === undefined) {\n let prog = sub('%(prog)s', { prog: this._prog })\n\n // split optionals from positionals\n let optionals = []\n let positionals = []\n for (let action of actions) {\n if (action.option_strings.length) {\n optionals.push(action)\n } else {\n positionals.push(action)\n }\n }\n\n // build full usage string\n let action_usage = this._format_actions_usage([].concat(optionals).concat(positionals), groups)\n usage = [ prog, action_usage ].map(String).join(' ')\n\n // wrap the usage parts if it's too long\n let text_width = this._width - this._current_indent\n if (prefix.length + usage.length > text_width) {\n\n // break usage into wrappable parts\n let part_regexp = /\\(.*?\\)+(?=\\s|$)|\\[.*?\\]+(?=\\s|$)|\\S+/g\n let opt_usage = this._format_actions_usage(optionals, groups)\n let pos_usage = this._format_actions_usage(positionals, groups)\n let opt_parts = opt_usage.match(part_regexp) || []\n let pos_parts = pos_usage.match(part_regexp) || []\n assert(opt_parts.join(' ') === opt_usage)\n assert(pos_parts.join(' ') === pos_usage)\n\n // helper for wrapping lines\n let get_lines = (parts, indent, prefix = undefined) => {\n let lines = []\n let line = []\n let line_len\n if (prefix !== undefined) {\n line_len = prefix.length - 1\n } else {\n line_len = indent.length - 1\n }\n for (let part of parts) {\n if (line_len + 1 + part.length > text_width && line) {\n lines.push(indent + line.join(' '))\n line = []\n line_len = indent.length - 1\n }\n line.push(part)\n line_len += part.length + 1\n }\n if (line.length) {\n lines.push(indent + line.join(' '))\n }\n if (prefix !== undefined) {\n lines[0] = lines[0].slice(indent.length)\n }\n return lines\n }\n\n let lines\n\n // if prog is short, follow it with optionals or positionals\n if (prefix.length + prog.length <= 0.75 * text_width) {\n let indent = ' '.repeat(prefix.length + prog.length + 1)\n if (opt_parts.length) {\n lines = get_lines([prog].concat(opt_parts), indent, prefix)\n lines = lines.concat(get_lines(pos_parts, indent))\n } else if (pos_parts.length) {\n lines = get_lines([prog].concat(pos_parts), indent, prefix)\n } else {\n lines = [prog]\n }\n\n // if prog is long, put it on its own line\n } else {\n let indent = ' '.repeat(prefix.length)\n let parts = [].concat(opt_parts).concat(pos_parts)\n lines = get_lines(parts, indent)\n if (lines.length > 1) {\n lines = []\n lines = lines.concat(get_lines(opt_parts, indent))\n lines = lines.concat(get_lines(pos_parts, indent))\n }\n lines = [prog].concat(lines)\n }\n\n // join lines into usage\n usage = lines.join('\\n')\n }\n }\n\n // prefix with 'usage:'\n return sub('%s%s\\n\\n', prefix, usage)\n }\n\n _format_actions_usage(actions, groups) {\n // find group indices and identify actions in groups\n let group_actions = new Set()\n let inserts = {}\n for (let group of groups) {\n let start = actions.indexOf(group._group_actions[0])\n if (start === -1) {\n continue\n } else {\n let end = start + group._group_actions.length\n if (_array_equal(actions.slice(start, end), group._group_actions)) {\n for (let action of group._group_actions) {\n group_actions.add(action)\n }\n if (!group.required) {\n if (start in inserts) {\n inserts[start] += ' ['\n } else {\n inserts[start] = '['\n }\n if (end in inserts) {\n inserts[end] += ']'\n } else {\n inserts[end] = ']'\n }\n } else {\n if (start in inserts) {\n inserts[start] += ' ('\n } else {\n inserts[start] = '('\n }\n if (end in inserts) {\n inserts[end] += ')'\n } else {\n inserts[end] = ')'\n }\n }\n for (let i of range(start + 1, end)) {\n inserts[i] = '|'\n }\n }\n }\n }\n\n // collect all actions format strings\n let parts = []\n for (let [ i, action ] of Object.entries(actions)) {\n\n // suppressed arguments are marked with None\n // remove | separators for suppressed arguments\n if (action.help === SUPPRESS) {\n parts.push(undefined)\n if (inserts[+i] === '|') {\n delete inserts[+i]\n } else if (inserts[+i + 1] === '|') {\n delete inserts[+i + 1]\n }\n\n // produce all arg strings\n } else if (!action.option_strings.length) {\n let default_value = this._get_default_metavar_for_positional(action)\n let part = this._format_args(action, default_value)\n\n // if it's in a group, strip the outer []\n if (group_actions.has(action)) {\n if (part[0] === '[' && part[part.length - 1] === ']') {\n part = part.slice(1, -1)\n }\n }\n\n // add the action string to the list\n parts.push(part)\n\n // produce the first way to invoke the option in brackets\n } else {\n let option_string = action.option_strings[0]\n let part\n\n // if the Optional doesn't take a value, format is:\n // -s or --long\n if (action.nargs === 0) {\n part = action.format_usage()\n\n // if the Optional takes a value, format is:\n // -s ARGS or --long ARGS\n } else {\n let default_value = this._get_default_metavar_for_optional(action)\n let args_string = this._format_args(action, default_value)\n part = sub('%s %s', option_string, args_string)\n }\n\n // make it look optional if it's not required or in a group\n if (!action.required && !group_actions.has(action)) {\n part = sub('[%s]', part)\n }\n\n // add the action string to the list\n parts.push(part)\n }\n }\n\n // insert things at the necessary indices\n for (let i of Object.keys(inserts).map(Number).sort((a, b) => b - a)) {\n parts.splice(+i, 0, inserts[+i])\n }\n\n // join all the action items with spaces\n let text = parts.filter(Boolean).join(' ')\n\n // clean up separators for mutually exclusive groups\n text = text.replace(/([\\[(]) /g, '$1')\n text = text.replace(/ ([\\])])/g, '$1')\n text = text.replace(/[\\[(] *[\\])]/g, '')\n text = text.replace(/\\(([^|]*)\\)/g, '$1', text)\n text = text.trim()\n\n // return the text\n return text\n }\n\n _format_text(text) {\n if (text.includes('%(prog)')) {\n text = sub(text, { prog: this._prog })\n }\n let text_width = Math.max(this._width - this._current_indent, 11)\n let indent = ' '.repeat(this._current_indent)\n return this._fill_text(text, text_width, indent) + '\\n\\n'\n }\n\n _format_action(action) {\n // determine the required width and the entry label\n let help_position = Math.min(this._action_max_length + 2,\n this._max_help_position)\n let help_width = Math.max(this._width - help_position, 11)\n let action_width = help_position - this._current_indent - 2\n let action_header = this._format_action_invocation(action)\n let indent_first\n\n // no help; start on same line and add a final newline\n if (!action.help) {\n let tup = [ this._current_indent, '', action_header ]\n action_header = sub('%*s%s\\n', ...tup)\n\n // short action name; start on the same line and pad two spaces\n } else if (action_header.length <= action_width) {\n let tup = [ this._current_indent, '', action_width, action_header ]\n action_header = sub('%*s%-*s ', ...tup)\n indent_first = 0\n\n // long action name; start on the next line\n } else {\n let tup = [ this._current_indent, '', action_header ]\n action_header = sub('%*s%s\\n', ...tup)\n indent_first = help_position\n }\n\n // collect the pieces of the action help\n let parts = [action_header]\n\n // if there was help for the action, add lines of help text\n if (action.help) {\n let help_text = this._expand_help(action)\n let help_lines = this._split_lines(help_text, help_width)\n parts.push(sub('%*s%s\\n', indent_first, '', help_lines[0]))\n for (let line of help_lines.slice(1)) {\n parts.push(sub('%*s%s\\n', help_position, '', line))\n }\n\n // or add a newline if the description doesn't end with one\n } else if (!action_header.endsWith('\\n')) {\n parts.push('\\n')\n }\n\n // if there are any sub-actions, add their help as well\n for (let subaction of this._iter_indented_subactions(action)) {\n parts.push(this._format_action(subaction))\n }\n\n // return a single string\n return this._join_parts(parts)\n }\n\n _format_action_invocation(action) {\n if (!action.option_strings.length) {\n let default_value = this._get_default_metavar_for_positional(action)\n let metavar = this._metavar_formatter(action, default_value)(1)[0]\n return metavar\n\n } else {\n let parts = []\n\n // if the Optional doesn't take a value, format is:\n // -s, --long\n if (action.nargs === 0) {\n parts = parts.concat(action.option_strings)\n\n // if the Optional takes a value, format is:\n // -s ARGS, --long ARGS\n } else {\n let default_value = this._get_default_metavar_for_optional(action)\n let args_string = this._format_args(action, default_value)\n for (let option_string of action.option_strings) {\n parts.push(sub('%s %s', option_string, args_string))\n }\n }\n\n return parts.join(', ')\n }\n }\n\n _metavar_formatter(action, default_metavar) {\n let result\n if (action.metavar !== undefined) {\n result = action.metavar\n } else if (action.choices !== undefined) {\n let choice_strs = _choices_to_array(action.choices).map(String)\n result = sub('{%s}', choice_strs.join(','))\n } else {\n result = default_metavar\n }\n\n function format(tuple_size) {\n if (Array.isArray(result)) {\n return result\n } else {\n return Array(tuple_size).fill(result)\n }\n }\n return format\n }\n\n _format_args(action, default_metavar) {\n let get_metavar = this._metavar_formatter(action, default_metavar)\n let result\n if (action.nargs === undefined) {\n result = sub('%s', ...get_metavar(1))\n } else if (action.nargs === OPTIONAL) {\n result = sub('[%s]', ...get_metavar(1))\n } else if (action.nargs === ZERO_OR_MORE) {\n let metavar = get_metavar(1)\n if (metavar.length === 2) {\n result = sub('[%s [%s ...]]', ...metavar)\n } else {\n result = sub('[%s ...]', ...metavar)\n }\n } else if (action.nargs === ONE_OR_MORE) {\n result = sub('%s [%s ...]', ...get_metavar(2))\n } else if (action.nargs === REMAINDER) {\n result = '...'\n } else if (action.nargs === PARSER) {\n result = sub('%s ...', ...get_metavar(1))\n } else if (action.nargs === SUPPRESS) {\n result = ''\n } else {\n let formats\n try {\n formats = range(action.nargs).map(() => '%s')\n } catch (err) {\n throw new TypeError('invalid nargs value')\n }\n result = sub(formats.join(' '), ...get_metavar(action.nargs))\n }\n return result\n }\n\n _expand_help(action) {\n let params = Object.assign({ prog: this._prog }, action)\n for (let name of Object.keys(params)) {\n if (params[name] === SUPPRESS) {\n delete params[name]\n }\n }\n for (let name of Object.keys(params)) {\n if (params[name] && params[name].name) {\n params[name] = params[name].name\n }\n }\n if (params.choices !== undefined) {\n let choices_str = _choices_to_array(params.choices).map(String).join(', ')\n params.choices = choices_str\n }\n // LEGACY (v1 compatibility): camelcase\n for (let key of Object.keys(params)) {\n let old_name = _to_legacy_name(key)\n if (old_name !== key) {\n params[old_name] = params[key]\n }\n }\n // end\n return sub(this._get_help_string(action), params)\n }\n\n * _iter_indented_subactions(action) {\n if (typeof action._get_subactions === 'function') {\n this._indent()\n yield* action._get_subactions()\n this._dedent()\n }\n }\n\n _split_lines(text, width) {\n text = text.replace(this._whitespace_matcher, ' ').trim()\n // The textwrap module is used only for formatting help.\n // Delay its import for speeding up the common usage of argparse.\n let textwrap = require('./lib/textwrap')\n return textwrap.wrap(text, { width })\n }\n\n _fill_text(text, width, indent) {\n text = text.replace(this._whitespace_matcher, ' ').trim()\n let textwrap = require('./lib/textwrap')\n return textwrap.fill(text, { width,\n initial_indent: indent,\n subsequent_indent: indent })\n }\n\n _get_help_string(action) {\n return action.help\n }\n\n _get_default_metavar_for_optional(action) {\n return action.dest.toUpperCase()\n }\n\n _get_default_metavar_for_positional(action) {\n return action.dest\n }\n}))\n\nHelpFormatter.prototype._Section = _callable(class _Section {\n\n constructor(formatter, parent, heading = undefined) {\n this.formatter = formatter\n this.parent = parent\n this.heading = heading\n this.items = []\n }\n\n format_help() {\n // format the indented section\n if (this.parent !== undefined) {\n this.formatter._indent()\n }\n let item_help = this.formatter._join_parts(this.items.map(([ func, args ]) => func.apply(null, args)))\n if (this.parent !== undefined) {\n this.formatter._dedent()\n }\n\n // return nothing if the section was empty\n if (!item_help) {\n return ''\n }\n\n // add the heading if the section was non-empty\n let heading\n if (this.heading !== SUPPRESS && this.heading !== undefined) {\n let current_indent = this.formatter._current_indent\n heading = sub('%*s%s:\\n', current_indent, '', this.heading)\n } else {\n heading = ''\n }\n\n // join the section-initial newline, the heading and the help\n return this.formatter._join_parts(['\\n', heading, item_help, '\\n'])\n }\n})\n\n\nconst RawDescriptionHelpFormatter = _camelcase_alias(_callable(class RawDescriptionHelpFormatter extends HelpFormatter {\n /*\n * Help message formatter which retains any formatting in descriptions.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _fill_text(text, width, indent) {\n return splitlines(text, true).map(line => indent + line).join('')\n }\n}))\n\n\nconst RawTextHelpFormatter = _camelcase_alias(_callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter {\n /*\n * Help message formatter which retains formatting of all help text.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _split_lines(text/*, width*/) {\n return splitlines(text)\n }\n}))\n\n\nconst ArgumentDefaultsHelpFormatter = _camelcase_alias(_callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter {\n /*\n * Help message formatter which adds default values to argument help.\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _get_help_string(action) {\n let help = action.help\n // LEGACY (v1 compatibility): additional check for defaultValue needed\n if (!action.help.includes('%(default)') && !action.help.includes('%(defaultValue)')) {\n if (action.default !== SUPPRESS) {\n let defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]\n if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) {\n help += ' (default: %(default)s)'\n }\n }\n }\n return help\n }\n}))\n\n\nconst MetavarTypeHelpFormatter = _camelcase_alias(_callable(class MetavarTypeHelpFormatter extends HelpFormatter {\n /*\n * Help message formatter which uses the argument 'type' as the default\n * metavar value (instead of the argument 'dest')\n *\n * Only the name of this class is considered a public API. All the methods\n * provided by the class are considered an implementation detail.\n */\n\n _get_default_metavar_for_optional(action) {\n return typeof action.type === 'function' ? action.type.name : action.type\n }\n\n _get_default_metavar_for_positional(action) {\n return typeof action.type === 'function' ? action.type.name : action.type\n }\n}))\n\n\n// =====================\n// Options and Arguments\n// =====================\nfunction _get_action_name(argument) {\n if (argument === undefined) {\n return undefined\n } else if (argument.option_strings.length) {\n return argument.option_strings.join('/')\n } else if (![ undefined, SUPPRESS ].includes(argument.metavar)) {\n return argument.metavar\n } else if (![ undefined, SUPPRESS ].includes(argument.dest)) {\n return argument.dest\n } else {\n return undefined\n }\n}\n\n\nconst ArgumentError = _callable(class ArgumentError extends Error {\n /*\n * An error from creating or using an argument (optional or positional).\n *\n * The string value of this exception is the message, augmented with\n * information about the argument that caused it.\n */\n\n constructor(argument, message) {\n super()\n this.name = 'ArgumentError'\n this._argument_name = _get_action_name(argument)\n this._message = message\n this.message = this.str()\n }\n\n str() {\n let format\n if (this._argument_name === undefined) {\n format = '%(message)s'\n } else {\n format = 'argument %(argument_name)s: %(message)s'\n }\n return sub(format, { message: this._message,\n argument_name: this._argument_name })\n }\n})\n\n\nconst ArgumentTypeError = _callable(class ArgumentTypeError extends Error {\n /*\n * An error from trying to convert a command line string to a type.\n */\n\n constructor(message) {\n super(message)\n this.name = 'ArgumentTypeError'\n }\n})\n\n\n// ==============\n// Action classes\n// ==============\nconst Action = _camelcase_alias(_callable(class Action extends _AttributeHolder(Function) {\n /*\n * Information about how to convert command line strings to Python objects.\n *\n * Action objects are used by an ArgumentParser to represent the information\n * needed to parse a single argument from one or more strings from the\n * command line. The keyword arguments to the Action constructor are also\n * all attributes of Action instances.\n *\n * Keyword Arguments:\n *\n * - option_strings -- A list of command-line option strings which\n * should be associated with this action.\n *\n * - dest -- The name of the attribute to hold the created object(s)\n *\n * - nargs -- The number of command-line arguments that should be\n * consumed. By default, one argument will be consumed and a single\n * value will be produced. Other values include:\n * - N (an integer) consumes N arguments (and produces a list)\n * - '?' consumes zero or one arguments\n * - '*' consumes zero or more arguments (and produces a list)\n * - '+' consumes one or more arguments (and produces a list)\n * Note that the difference between the default and nargs=1 is that\n * with the default, a single value will be produced, while with\n * nargs=1, a list containing a single value will be produced.\n *\n * - const -- The value to be produced if the option is specified and the\n * option uses an action that takes no values.\n *\n * - default -- The value to be produced if the option is not specified.\n *\n * - type -- A callable that accepts a single string argument, and\n * returns the converted value. The standard Python types str, int,\n * float, and complex are useful examples of such callables. If None,\n * str is used.\n *\n * - choices -- A container of values that should be allowed. If not None,\n * after a command-line argument has been converted to the appropriate\n * type, an exception will be raised if it is not a member of this\n * collection.\n *\n * - required -- True if the action must always be specified at the\n * command line. This is only meaningful for optional command-line\n * arguments.\n *\n * - help -- The help string describing the argument.\n *\n * - metavar -- The name to be used for the option's argument with the\n * help string. If None, the 'dest' value will be used as the name.\n */\n\n constructor() {\n let [\n option_strings,\n dest,\n nargs,\n const_value,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n nargs: undefined,\n const: undefined,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n // when this class is called as a function, redirect it to .call() method of itself\n super('return arguments.callee.call.apply(arguments.callee, arguments)')\n\n this.option_strings = option_strings\n this.dest = dest\n this.nargs = nargs\n this.const = const_value\n this.default = default_value\n this.type = type\n this.choices = choices\n this.required = required\n this.help = help\n this.metavar = metavar\n }\n\n _get_kwargs() {\n let names = [\n 'option_strings',\n 'dest',\n 'nargs',\n 'const',\n 'default',\n 'type',\n 'choices',\n 'help',\n 'metavar'\n ]\n return names.map(name => [ name, getattr(this, name) ])\n }\n\n format_usage() {\n return this.option_strings[0]\n }\n\n call(/*parser, namespace, values, option_string = undefined*/) {\n throw new Error('.call() not defined')\n }\n}))\n\n\nconst BooleanOptionalAction = _camelcase_alias(_callable(class BooleanOptionalAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n let _option_strings = []\n for (let option_string of option_strings) {\n _option_strings.push(option_string)\n\n if (option_string.startsWith('--')) {\n option_string = '--no-' + option_string.slice(2)\n _option_strings.push(option_string)\n }\n }\n\n if (help !== undefined && default_value !== undefined) {\n help += ` (default: ${default_value})`\n }\n\n super({\n option_strings: _option_strings,\n dest,\n nargs: 0,\n default: default_value,\n type,\n choices,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace, values, option_string = undefined) {\n if (this.option_strings.includes(option_string)) {\n setattr(namespace, this.dest, !option_string.startsWith('--no-'))\n }\n }\n\n format_usage() {\n return this.option_strings.join(' | ')\n }\n}))\n\n\nconst _StoreAction = _callable(class _StoreAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n nargs,\n const_value,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n nargs: undefined,\n const: undefined,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n if (nargs === 0) {\n throw new TypeError('nargs for store actions must be != 0; if you ' +\n 'have nothing to store, actions such as store ' +\n 'true or store const may be more appropriate')\n }\n if (const_value !== undefined && nargs !== OPTIONAL) {\n throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL))\n }\n super({\n option_strings,\n dest,\n nargs,\n const: const_value,\n default: default_value,\n type,\n choices,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace, values/*, option_string = undefined*/) {\n setattr(namespace, this.dest, values)\n }\n})\n\n\nconst _StoreConstAction = _callable(class _StoreConstAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n const_value,\n default_value,\n required,\n help\n //, metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n const: no_default,\n default: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n super({\n option_strings,\n dest,\n nargs: 0,\n const: const_value,\n default: default_value,\n required,\n help\n })\n }\n\n call(parser, namespace/*, values, option_string = undefined*/) {\n setattr(namespace, this.dest, this.const)\n }\n})\n\n\nconst _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n required,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: false,\n required: false,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n const: true,\n default: default_value,\n required,\n help\n })\n }\n})\n\n\nconst _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n required,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: true,\n required: false,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n const: false,\n default: default_value,\n required,\n help\n })\n }\n})\n\n\nconst _AppendAction = _callable(class _AppendAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n nargs,\n const_value,\n default_value,\n type,\n choices,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n nargs: undefined,\n const: undefined,\n default: undefined,\n type: undefined,\n choices: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n if (nargs === 0) {\n throw new TypeError('nargs for append actions must be != 0; if arg ' +\n 'strings are not supplying the value to append, ' +\n 'the append const action may be more appropriate')\n }\n if (const_value !== undefined && nargs !== OPTIONAL) {\n throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL))\n }\n super({\n option_strings,\n dest,\n nargs,\n const: const_value,\n default: default_value,\n type,\n choices,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace, values/*, option_string = undefined*/) {\n let items = getattr(namespace, this.dest, undefined)\n items = _copy_items(items)\n items.push(values)\n setattr(namespace, this.dest, items)\n }\n})\n\n\nconst _AppendConstAction = _callable(class _AppendConstAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n const_value,\n default_value,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n const: no_default,\n default: undefined,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n super({\n option_strings,\n dest,\n nargs: 0,\n const: const_value,\n default: default_value,\n required,\n help,\n metavar\n })\n }\n\n call(parser, namespace/*, values, option_string = undefined*/) {\n let items = getattr(namespace, this.dest, undefined)\n items = _copy_items(items)\n items.push(this.const)\n setattr(namespace, this.dest, items)\n }\n})\n\n\nconst _CountAction = _callable(class _CountAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n required,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: no_default,\n default: undefined,\n required: false,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n nargs: 0,\n default: default_value,\n required,\n help\n })\n }\n\n call(parser, namespace/*, values, option_string = undefined*/) {\n let count = getattr(namespace, this.dest, undefined)\n if (count === undefined) {\n count = 0\n }\n setattr(namespace, this.dest, count + 1)\n }\n})\n\n\nconst _HelpAction = _callable(class _HelpAction extends Action {\n\n constructor() {\n let [\n option_strings,\n dest,\n default_value,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n dest: SUPPRESS,\n default: SUPPRESS,\n help: undefined\n })\n\n super({\n option_strings,\n dest,\n default: default_value,\n nargs: 0,\n help\n })\n }\n\n call(parser/*, namespace, values, option_string = undefined*/) {\n parser.print_help()\n parser.exit()\n }\n})\n\n\nconst _VersionAction = _callable(class _VersionAction extends Action {\n\n constructor() {\n let [\n option_strings,\n version,\n dest,\n default_value,\n help\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n version: undefined,\n dest: SUPPRESS,\n default: SUPPRESS,\n help: \"show program's version number and exit\"\n })\n\n super({\n option_strings,\n dest,\n default: default_value,\n nargs: 0,\n help\n })\n this.version = version\n }\n\n call(parser/*, namespace, values, option_string = undefined*/) {\n let version = this.version\n if (version === undefined) {\n version = parser.version\n }\n let formatter = parser._get_formatter()\n formatter.add_text(version)\n parser._print_message(formatter.format_help(), process.stdout)\n parser.exit()\n }\n})\n\n\nconst _SubParsersAction = _camelcase_alias(_callable(class _SubParsersAction extends Action {\n\n constructor() {\n let [\n option_strings,\n prog,\n parser_class,\n dest,\n required,\n help,\n metavar\n ] = _parse_opts(arguments, {\n option_strings: no_default,\n prog: no_default,\n parser_class: no_default,\n dest: SUPPRESS,\n required: false,\n help: undefined,\n metavar: undefined\n })\n\n let name_parser_map = {}\n\n super({\n option_strings,\n dest,\n nargs: PARSER,\n choices: name_parser_map,\n required,\n help,\n metavar\n })\n\n this._prog_prefix = prog\n this._parser_class = parser_class\n this._name_parser_map = name_parser_map\n this._choices_actions = []\n }\n\n add_parser() {\n let [\n name,\n kwargs\n ] = _parse_opts(arguments, {\n name: no_default,\n '**kwargs': no_default\n })\n\n // set prog from the existing prefix\n if (kwargs.prog === undefined) {\n kwargs.prog = sub('%s %s', this._prog_prefix, name)\n }\n\n let aliases = getattr(kwargs, 'aliases', [])\n delete kwargs.aliases\n\n // create a pseudo-action to hold the choice help\n if ('help' in kwargs) {\n let help = kwargs.help\n delete kwargs.help\n let choice_action = this._ChoicesPseudoAction(name, aliases, help)\n this._choices_actions.push(choice_action)\n }\n\n // create the parser and add it to the map\n let parser = new this._parser_class(kwargs)\n this._name_parser_map[name] = parser\n\n // make parser available under aliases also\n for (let alias of aliases) {\n this._name_parser_map[alias] = parser\n }\n\n return parser\n }\n\n _get_subactions() {\n return this._choices_actions\n }\n\n call(parser, namespace, values/*, option_string = undefined*/) {\n let parser_name = values[0]\n let arg_strings = values.slice(1)\n\n // set the parser name if requested\n if (this.dest !== SUPPRESS) {\n setattr(namespace, this.dest, parser_name)\n }\n\n // select the parser\n if (hasattr(this._name_parser_map, parser_name)) {\n parser = this._name_parser_map[parser_name]\n } else {\n let args = {parser_name,\n choices: this._name_parser_map.join(', ')}\n let msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args)\n throw new ArgumentError(this, msg)\n }\n\n // parse all the remaining options into the namespace\n // store any unrecognized options on the object, so that the top\n // level parser can decide what to do with them\n\n // In case this subparser defines new defaults, we parse them\n // in a new namespace object and then update the original\n // namespace for the relevant parts.\n let subnamespace\n [ subnamespace, arg_strings ] = parser.parse_known_args(arg_strings, undefined)\n for (let [ key, value ] of Object.entries(subnamespace)) {\n setattr(namespace, key, value)\n }\n\n if (arg_strings.length) {\n setdefault(namespace, _UNRECOGNIZED_ARGS_ATTR, [])\n getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings)\n }\n }\n}))\n\n\n_SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action {\n constructor(name, aliases, help) {\n let metavar = name, dest = name\n if (aliases.length) {\n metavar += sub(' (%s)', aliases.join(', '))\n }\n super({ option_strings: [], dest, help, metavar })\n }\n})\n\n\nconst _ExtendAction = _callable(class _ExtendAction extends _AppendAction {\n call(parser, namespace, values/*, option_string = undefined*/) {\n let items = getattr(namespace, this.dest, undefined)\n items = _copy_items(items)\n items = items.concat(values)\n setattr(namespace, this.dest, items)\n }\n})\n\n\n// ==============\n// Type classes\n// ==============\nconst FileType = _callable(class FileType extends Function {\n /*\n * Factory for creating file object types\n *\n * Instances of FileType are typically passed as type= arguments to the\n * ArgumentParser add_argument() method.\n *\n * Keyword Arguments:\n * - mode -- A string indicating how the file is to be opened. Accepts the\n * same values as the builtin open() function.\n * - bufsize -- The file's desired buffer size. Accepts the same values as\n * the builtin open() function.\n * - encoding -- The file's encoding. Accepts the same values as the\n * builtin open() function.\n * - errors -- A string indicating how encoding and decoding errors are to\n * be handled. Accepts the same value as the builtin open() function.\n */\n\n constructor() {\n let [\n flags,\n encoding,\n mode,\n autoClose,\n emitClose,\n start,\n end,\n highWaterMark,\n fs\n ] = _parse_opts(arguments, {\n flags: 'r',\n encoding: undefined,\n mode: undefined, // 0o666\n autoClose: undefined, // true\n emitClose: undefined, // false\n start: undefined, // 0\n end: undefined, // Infinity\n highWaterMark: undefined, // 64 * 1024\n fs: undefined\n })\n\n // when this class is called as a function, redirect it to .call() method of itself\n super('return arguments.callee.call.apply(arguments.callee, arguments)')\n\n Object.defineProperty(this, 'name', {\n get() {\n return sub('FileType(%r)', flags)\n }\n })\n this._flags = flags\n this._options = {}\n if (encoding !== undefined) this._options.encoding = encoding\n if (mode !== undefined) this._options.mode = mode\n if (autoClose !== undefined) this._options.autoClose = autoClose\n if (emitClose !== undefined) this._options.emitClose = emitClose\n if (start !== undefined) this._options.start = start\n if (end !== undefined) this._options.end = end\n if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark\n if (fs !== undefined) this._options.fs = fs\n }\n\n call(string) {\n // the special argument \"-\" means sys.std{in,out}\n if (string === '-') {\n if (this._flags.includes('r')) {\n return process.stdin\n } else if (this._flags.includes('w')) {\n return process.stdout\n } else {\n let msg = sub('argument \"-\" with mode %r', this._flags)\n throw new TypeError(msg)\n }\n }\n\n // all other arguments are used as file names\n let fd\n try {\n fd = fs.openSync(string, this._flags, this._options.mode)\n } catch (e) {\n let args = { filename: string, error: e.message }\n let message = \"can't open '%(filename)s': %(error)s\"\n throw new ArgumentTypeError(sub(message, args))\n }\n\n let options = Object.assign({ fd, flags: this._flags }, this._options)\n if (this._flags.includes('r')) {\n return fs.createReadStream(undefined, options)\n } else if (this._flags.includes('w')) {\n return fs.createWriteStream(undefined, options)\n } else {\n let msg = sub('argument \"%s\" with mode %r', string, this._flags)\n throw new TypeError(msg)\n }\n }\n\n [util.inspect.custom]() {\n let args = [ this._flags ]\n let kwargs = Object.entries(this._options).map(([ k, v ]) => {\n if (k === 'mode') v = { value: v, [util.inspect.custom]() { return '0o' + this.value.toString(8) } }\n return [ k, v ]\n })\n let args_str = []\n .concat(args.filter(arg => arg !== -1).map(repr))\n .concat(kwargs.filter(([/*kw*/, arg]) => arg !== undefined)\n .map(([kw, arg]) => sub('%s=%r', kw, arg)))\n .join(', ')\n return sub('%s(%s)', this.constructor.name, args_str)\n }\n\n toString() {\n return this[util.inspect.custom]()\n }\n})\n\n// ===========================\n// Optional and Positional Parsing\n// ===========================\nconst Namespace = _callable(class Namespace extends _AttributeHolder() {\n /*\n * Simple object for storing attributes.\n *\n * Implements equality by attribute names and values, and provides a simple\n * string representation.\n */\n\n constructor(options = {}) {\n super()\n Object.assign(this, options)\n }\n})\n\n// unset string tag to mimic plain object\nNamespace.prototype[Symbol.toStringTag] = undefined\n\n\nconst _ActionsContainer = _camelcase_alias(_callable(class _ActionsContainer {\n\n constructor() {\n let [\n description,\n prefix_chars,\n argument_default,\n conflict_handler\n ] = _parse_opts(arguments, {\n description: no_default,\n prefix_chars: no_default,\n argument_default: no_default,\n conflict_handler: no_default\n })\n\n this.description = description\n this.argument_default = argument_default\n this.prefix_chars = prefix_chars\n this.conflict_handler = conflict_handler\n\n // set up registries\n this._registries = {}\n\n // register actions\n this.register('action', undefined, _StoreAction)\n this.register('action', 'store', _StoreAction)\n this.register('action', 'store_const', _StoreConstAction)\n this.register('action', 'store_true', _StoreTrueAction)\n this.register('action', 'store_false', _StoreFalseAction)\n this.register('action', 'append', _AppendAction)\n this.register('action', 'append_const', _AppendConstAction)\n this.register('action', 'count', _CountAction)\n this.register('action', 'help', _HelpAction)\n this.register('action', 'version', _VersionAction)\n this.register('action', 'parsers', _SubParsersAction)\n this.register('action', 'extend', _ExtendAction)\n // LEGACY (v1 compatibility): camelcase variants\n ;[ 'storeConst', 'storeTrue', 'storeFalse', 'appendConst' ].forEach(old_name => {\n let new_name = _to_new_name(old_name)\n this.register('action', old_name, util.deprecate(this._registry_get('action', new_name),\n sub('{action: \"%s\"} is renamed to {action: \"%s\"}', old_name, new_name)))\n })\n // end\n\n // raise an exception if the conflict handler is invalid\n this._get_handler()\n\n // action storage\n this._actions = []\n this._option_string_actions = {}\n\n // groups\n this._action_groups = []\n this._mutually_exclusive_groups = []\n\n // defaults storage\n this._defaults = {}\n\n // determines whether an \"option\" looks like a negative number\n this._negative_number_matcher = /^-\\d+$|^-\\d*\\.\\d+$/\n\n // whether or not there are any optionals that look like negative\n // numbers -- uses a list so it can be shared and edited\n this._has_negative_number_optionals = []\n }\n\n // ====================\n // Registration methods\n // ====================\n register(registry_name, value, object) {\n let registry = setdefault(this._registries, registry_name, {})\n registry[value] = object\n }\n\n _registry_get(registry_name, value, default_value = undefined) {\n return getattr(this._registries[registry_name], value, default_value)\n }\n\n // ==================================\n // Namespace default accessor methods\n // ==================================\n set_defaults(kwargs) {\n Object.assign(this._defaults, kwargs)\n\n // if these defaults match any existing arguments, replace\n // the previous default on the object with the new one\n for (let action of this._actions) {\n if (action.dest in kwargs) {\n action.default = kwargs[action.dest]\n }\n }\n }\n\n get_default(dest) {\n for (let action of this._actions) {\n if (action.dest === dest && action.default !== undefined) {\n return action.default\n }\n }\n return this._defaults[dest]\n }\n\n\n // =======================\n // Adding argument actions\n // =======================\n add_argument() {\n /*\n * add_argument(dest, ..., name=value, ...)\n * add_argument(option_string, option_string, ..., name=value, ...)\n */\n let [\n args,\n kwargs\n ] = _parse_opts(arguments, {\n '*args': no_default,\n '**kwargs': no_default\n })\n // LEGACY (v1 compatibility), old-style add_argument([ args ], { options })\n if (args.length === 1 && Array.isArray(args[0])) {\n args = args[0]\n deprecate('argument-array',\n sub('use add_argument(%(args)s, {...}) instead of add_argument([ %(args)s ], { ... })', {\n args: args.map(repr).join(', ')\n }))\n }\n // end\n\n // if no positional args are supplied or only one is supplied and\n // it doesn't look like an option string, parse a positional\n // argument\n let chars = this.prefix_chars\n if (!args.length || args.length === 1 && !chars.includes(args[0][0])) {\n if (args.length && 'dest' in kwargs) {\n throw new TypeError('dest supplied twice for positional argument')\n }\n kwargs = this._get_positional_kwargs(...args, kwargs)\n\n // otherwise, we're adding an optional argument\n } else {\n kwargs = this._get_optional_kwargs(...args, kwargs)\n }\n\n // if no default was supplied, use the parser-level default\n if (!('default' in kwargs)) {\n let dest = kwargs.dest\n if (dest in this._defaults) {\n kwargs.default = this._defaults[dest]\n } else if (this.argument_default !== undefined) {\n kwargs.default = this.argument_default\n }\n }\n\n // create the action object, and add it to the parser\n let action_class = this._pop_action_class(kwargs)\n if (typeof action_class !== 'function') {\n throw new TypeError(sub('unknown action \"%s\"', action_class))\n }\n // eslint-disable-next-line new-cap\n let action = new action_class(kwargs)\n\n // raise an error if the action type is not callable\n let type_func = this._registry_get('type', action.type, action.type)\n if (typeof type_func !== 'function') {\n throw new TypeError(sub('%r is not callable', type_func))\n }\n\n if (type_func === FileType) {\n throw new TypeError(sub('%r is a FileType class object, instance of it' +\n ' must be passed', type_func))\n }\n\n // raise an error if the metavar does not match the type\n if ('_get_formatter' in this) {\n try {\n this._get_formatter()._format_args(action, undefined)\n } catch (err) {\n // check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same\n if (err instanceof TypeError && err.message !== 'invalid nargs value') {\n throw new TypeError('length of metavar tuple does not match nargs')\n } else {\n throw err\n }\n }\n }\n\n return this._add_action(action)\n }\n\n add_argument_group() {\n let group = _ArgumentGroup(this, ...arguments)\n this._action_groups.push(group)\n return group\n }\n\n add_mutually_exclusive_group() {\n // eslint-disable-next-line no-use-before-define\n let group = _MutuallyExclusiveGroup(this, ...arguments)\n this._mutually_exclusive_groups.push(group)\n return group\n }\n\n _add_action(action) {\n // resolve any conflicts\n this._check_conflict(action)\n\n // add to actions list\n this._actions.push(action)\n action.container = this\n\n // index the action by any option strings it has\n for (let option_string of action.option_strings) {\n this._option_string_actions[option_string] = action\n }\n\n // set the flag if any option strings look like negative numbers\n for (let option_string of action.option_strings) {\n if (this._negative_number_matcher.test(option_string)) {\n if (!this._has_negative_number_optionals.length) {\n this._has_negative_number_optionals.push(true)\n }\n }\n }\n\n // return the created action\n return action\n }\n\n _remove_action(action) {\n _array_remove(this._actions, action)\n }\n\n _add_container_actions(container) {\n // collect groups by titles\n let title_group_map = {}\n for (let group of this._action_groups) {\n if (group.title in title_group_map) {\n let msg = 'cannot merge actions - two groups are named %r'\n throw new TypeError(sub(msg, group.title))\n }\n title_group_map[group.title] = group\n }\n\n // map each action to its group\n let group_map = new Map()\n for (let group of container._action_groups) {\n\n // if a group with the title exists, use that, otherwise\n // create a new group matching the container's group\n if (!(group.title in title_group_map)) {\n title_group_map[group.title] = this.add_argument_group({\n title: group.title,\n description: group.description,\n conflict_handler: group.conflict_handler\n })\n }\n\n // map the actions to their new group\n for (let action of group._group_actions) {\n group_map.set(action, title_group_map[group.title])\n }\n }\n\n // add container's mutually exclusive groups\n // NOTE: if add_mutually_exclusive_group ever gains title= and\n // description= then this code will need to be expanded as above\n for (let group of container._mutually_exclusive_groups) {\n let mutex_group = this.add_mutually_exclusive_group({\n required: group.required\n })\n\n // map the actions to their new mutex group\n for (let action of group._group_actions) {\n group_map.set(action, mutex_group)\n }\n }\n\n // add all actions to this container or their group\n for (let action of container._actions) {\n group_map.get(action)._add_action(action)\n }\n }\n\n _get_positional_kwargs() {\n let [\n dest,\n kwargs\n ] = _parse_opts(arguments, {\n dest: no_default,\n '**kwargs': no_default\n })\n\n // make sure required is not specified\n if ('required' in kwargs) {\n let msg = \"'required' is an invalid argument for positionals\"\n throw new TypeError(msg)\n }\n\n // mark positional arguments as required if at least one is\n // always required\n if (![OPTIONAL, ZERO_OR_MORE].includes(kwargs.nargs)) {\n kwargs.required = true\n }\n if (kwargs.nargs === ZERO_OR_MORE && !('default' in kwargs)) {\n kwargs.required = true\n }\n\n // return the keyword arguments with no option strings\n return Object.assign(kwargs, { dest, option_strings: [] })\n }\n\n _get_optional_kwargs() {\n let [\n args,\n kwargs\n ] = _parse_opts(arguments, {\n '*args': no_default,\n '**kwargs': no_default\n })\n\n // determine short and long option strings\n let option_strings = []\n let long_option_strings = []\n let option_string\n for (option_string of args) {\n // error on strings that don't start with an appropriate prefix\n if (!this.prefix_chars.includes(option_string[0])) {\n let args = {option: option_string,\n prefix_chars: this.prefix_chars}\n let msg = 'invalid option string %(option)r: ' +\n 'must start with a character %(prefix_chars)r'\n throw new TypeError(sub(msg, args))\n }\n\n // strings starting with two prefix characters are long options\n option_strings.push(option_string)\n if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) {\n long_option_strings.push(option_string)\n }\n }\n\n // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'\n let dest = kwargs.dest\n delete kwargs.dest\n if (dest === undefined) {\n let dest_option_string\n if (long_option_strings.length) {\n dest_option_string = long_option_strings[0]\n } else {\n dest_option_string = option_strings[0]\n }\n dest = _string_lstrip(dest_option_string, this.prefix_chars)\n if (!dest) {\n let msg = 'dest= is required for options like %r'\n throw new TypeError(sub(msg, option_string))\n }\n dest = dest.replace(/-/g, '_')\n }\n\n // return the updated keyword arguments\n return Object.assign(kwargs, { dest, option_strings })\n }\n\n _pop_action_class(kwargs, default_value = undefined) {\n let action = getattr(kwargs, 'action', default_value)\n delete kwargs.action\n return this._registry_get('action', action, action)\n }\n\n _get_handler() {\n // determine function from conflict handler string\n let handler_func_name = sub('_handle_conflict_%s', this.conflict_handler)\n if (typeof this[handler_func_name] === 'function') {\n return this[handler_func_name]\n } else {\n let msg = 'invalid conflict_resolution value: %r'\n throw new TypeError(sub(msg, this.conflict_handler))\n }\n }\n\n _check_conflict(action) {\n\n // find all options that conflict with this option\n let confl_optionals = []\n for (let option_string of action.option_strings) {\n if (hasattr(this._option_string_actions, option_string)) {\n let confl_optional = this._option_string_actions[option_string]\n confl_optionals.push([ option_string, confl_optional ])\n }\n }\n\n // resolve any conflicts\n if (confl_optionals.length) {\n let conflict_handler = this._get_handler()\n conflict_handler.call(this, action, confl_optionals)\n }\n }\n\n _handle_conflict_error(action, conflicting_actions) {\n let message = conflicting_actions.length === 1 ?\n 'conflicting option string: %s' :\n 'conflicting option strings: %s'\n let conflict_string = conflicting_actions.map(([ option_string/*, action*/ ]) => option_string).join(', ')\n throw new ArgumentError(action, sub(message, conflict_string))\n }\n\n _handle_conflict_resolve(action, conflicting_actions) {\n\n // remove all conflicting options\n for (let [ option_string, action ] of conflicting_actions) {\n\n // remove the conflicting option\n _array_remove(action.option_strings, option_string)\n delete this._option_string_actions[option_string]\n\n // if the option now has no option string, remove it from the\n // container holding it\n if (!action.option_strings.length) {\n action.container._remove_action(action)\n }\n }\n }\n}))\n\n\nconst _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer {\n\n constructor() {\n let [\n container,\n title,\n description,\n kwargs\n ] = _parse_opts(arguments, {\n container: no_default,\n title: undefined,\n description: undefined,\n '**kwargs': no_default\n })\n\n // add any missing keyword arguments by checking the container\n setdefault(kwargs, 'conflict_handler', container.conflict_handler)\n setdefault(kwargs, 'prefix_chars', container.prefix_chars)\n setdefault(kwargs, 'argument_default', container.argument_default)\n super(Object.assign({ description }, kwargs))\n\n // group attributes\n this.title = title\n this._group_actions = []\n\n // share most attributes with the container\n this._registries = container._registries\n this._actions = container._actions\n this._option_string_actions = container._option_string_actions\n this._defaults = container._defaults\n this._has_negative_number_optionals =\n container._has_negative_number_optionals\n this._mutually_exclusive_groups = container._mutually_exclusive_groups\n }\n\n _add_action(action) {\n action = super._add_action(action)\n this._group_actions.push(action)\n return action\n }\n\n _remove_action(action) {\n super._remove_action(action)\n _array_remove(this._group_actions, action)\n }\n})\n\n\nconst _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup {\n\n constructor() {\n let [\n container,\n required\n ] = _parse_opts(arguments, {\n container: no_default,\n required: false\n })\n\n super(container)\n this.required = required\n this._container = container\n }\n\n _add_action(action) {\n if (action.required) {\n let msg = 'mutually exclusive arguments must be optional'\n throw new TypeError(msg)\n }\n action = this._container._add_action(action)\n this._group_actions.push(action)\n return action\n }\n\n _remove_action(action) {\n this._container._remove_action(action)\n _array_remove(this._group_actions, action)\n }\n})\n\n\nconst ArgumentParser = _camelcase_alias(_callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) {\n /*\n * Object for parsing command line strings into Python objects.\n *\n * Keyword Arguments:\n * - prog -- The name of the program (default: sys.argv[0])\n * - usage -- A usage message (default: auto-generated from arguments)\n * - description -- A description of what the program does\n * - epilog -- Text following the argument descriptions\n * - parents -- Parsers whose arguments should be copied into this one\n * - formatter_class -- HelpFormatter class for printing help messages\n * - prefix_chars -- Characters that prefix optional arguments\n * - fromfile_prefix_chars -- Characters that prefix files containing\n * additional arguments\n * - argument_default -- The default value for all arguments\n * - conflict_handler -- String indicating how to handle conflicts\n * - add_help -- Add a -h/-help option\n * - allow_abbrev -- Allow long options to be abbreviated unambiguously\n * - exit_on_error -- Determines whether or not ArgumentParser exits with\n * error info when an error occurs\n */\n\n constructor() {\n let [\n prog,\n usage,\n description,\n epilog,\n parents,\n formatter_class,\n prefix_chars,\n fromfile_prefix_chars,\n argument_default,\n conflict_handler,\n add_help,\n allow_abbrev,\n exit_on_error,\n debug, // LEGACY (v1 compatibility), debug mode\n version // LEGACY (v1 compatibility), version\n ] = _parse_opts(arguments, {\n prog: undefined,\n usage: undefined,\n description: undefined,\n epilog: undefined,\n parents: [],\n formatter_class: HelpFormatter,\n prefix_chars: '-',\n fromfile_prefix_chars: undefined,\n argument_default: undefined,\n conflict_handler: 'error',\n add_help: true,\n allow_abbrev: true,\n exit_on_error: true,\n debug: undefined, // LEGACY (v1 compatibility), debug mode\n version: undefined // LEGACY (v1 compatibility), version\n })\n\n // LEGACY (v1 compatibility)\n if (debug !== undefined) {\n deprecate('debug',\n 'The \"debug\" argument to ArgumentParser is deprecated. Please ' +\n 'override ArgumentParser.exit function instead.'\n )\n }\n\n if (version !== undefined) {\n deprecate('version',\n 'The \"version\" argument to ArgumentParser is deprecated. Please use ' +\n \"add_argument(..., { action: 'version', version: 'N', ... }) instead.\"\n )\n }\n // end\n\n super({\n description,\n prefix_chars,\n argument_default,\n conflict_handler\n })\n\n // default setting for prog\n if (prog === undefined) {\n prog = path.basename(get_argv()[0] || '')\n }\n\n this.prog = prog\n this.usage = usage\n this.epilog = epilog\n this.formatter_class = formatter_class\n this.fromfile_prefix_chars = fromfile_prefix_chars\n this.add_help = add_help\n this.allow_abbrev = allow_abbrev\n this.exit_on_error = exit_on_error\n // LEGACY (v1 compatibility), debug mode\n this.debug = debug\n // end\n\n this._positionals = this.add_argument_group('positional arguments')\n this._optionals = this.add_argument_group('optional arguments')\n this._subparsers = undefined\n\n // register types\n function identity(string) {\n return string\n }\n this.register('type', undefined, identity)\n this.register('type', null, identity)\n this.register('type', 'auto', identity)\n this.register('type', 'int', function (x) {\n let result = Number(x)\n if (!Number.isInteger(result)) {\n throw new TypeError(sub('could not convert string to int: %r', x))\n }\n return result\n })\n this.register('type', 'float', function (x) {\n let result = Number(x)\n if (isNaN(result)) {\n throw new TypeError(sub('could not convert string to float: %r', x))\n }\n return result\n })\n this.register('type', 'str', String)\n // LEGACY (v1 compatibility): custom types\n this.register('type', 'string',\n util.deprecate(String, 'use {type:\"str\"} or {type:String} instead of {type:\"string\"}'))\n // end\n\n // add help argument if necessary\n // (using explicit default to override global argument_default)\n let default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0]\n if (this.add_help) {\n this.add_argument(\n default_prefix + 'h',\n default_prefix.repeat(2) + 'help',\n {\n action: 'help',\n default: SUPPRESS,\n help: 'show this help message and exit'\n }\n )\n }\n // LEGACY (v1 compatibility), version\n if (version) {\n this.add_argument(\n default_prefix + 'v',\n default_prefix.repeat(2) + 'version',\n {\n action: 'version',\n default: SUPPRESS,\n version: this.version,\n help: \"show program's version number and exit\"\n }\n )\n }\n // end\n\n // add parent arguments and defaults\n for (let parent of parents) {\n this._add_container_actions(parent)\n Object.assign(this._defaults, parent._defaults)\n }\n }\n\n // =======================\n // Pretty __repr__ methods\n // =======================\n _get_kwargs() {\n let names = [\n 'prog',\n 'usage',\n 'description',\n 'formatter_class',\n 'conflict_handler',\n 'add_help'\n ]\n return names.map(name => [ name, getattr(this, name) ])\n }\n\n // ==================================\n // Optional/Positional adding methods\n // ==================================\n add_subparsers() {\n let [\n kwargs\n ] = _parse_opts(arguments, {\n '**kwargs': no_default\n })\n\n if (this._subparsers !== undefined) {\n this.error('cannot have multiple subparser arguments')\n }\n\n // add the parser class to the arguments if it's not present\n setdefault(kwargs, 'parser_class', this.constructor)\n\n if ('title' in kwargs || 'description' in kwargs) {\n let title = getattr(kwargs, 'title', 'subcommands')\n let description = getattr(kwargs, 'description', undefined)\n delete kwargs.title\n delete kwargs.description\n this._subparsers = this.add_argument_group(title, description)\n } else {\n this._subparsers = this._positionals\n }\n\n // prog defaults to the usage message of this parser, skipping\n // optional arguments and with no \"usage:\" prefix\n if (kwargs.prog === undefined) {\n let formatter = this._get_formatter()\n let positionals = this._get_positional_actions()\n let groups = this._mutually_exclusive_groups\n formatter.add_usage(this.usage, positionals, groups, '')\n kwargs.prog = formatter.format_help().trim()\n }\n\n // create the parsers action and add it to the positionals list\n let parsers_class = this._pop_action_class(kwargs, 'parsers')\n // eslint-disable-next-line new-cap\n let action = new parsers_class(Object.assign({ option_strings: [] }, kwargs))\n this._subparsers._add_action(action)\n\n // return the created parsers action\n return action\n }\n\n _add_action(action) {\n if (action.option_strings.length) {\n this._optionals._add_action(action)\n } else {\n this._positionals._add_action(action)\n }\n return action\n }\n\n _get_optional_actions() {\n return this._actions.filter(action => action.option_strings.length)\n }\n\n _get_positional_actions() {\n return this._actions.filter(action => !action.option_strings.length)\n }\n\n // =====================================\n // Command line argument parsing methods\n // =====================================\n parse_args(args = undefined, namespace = undefined) {\n let argv\n [ args, argv ] = this.parse_known_args(args, namespace)\n if (argv && argv.length > 0) {\n let msg = 'unrecognized arguments: %s'\n this.error(sub(msg, argv.join(' ')))\n }\n return args\n }\n\n parse_known_args(args = undefined, namespace = undefined) {\n if (args === undefined) {\n args = get_argv().slice(1)\n }\n\n // default Namespace built from parser defaults\n if (namespace === undefined) {\n namespace = new Namespace()\n }\n\n // add any action defaults that aren't present\n for (let action of this._actions) {\n if (action.dest !== SUPPRESS) {\n if (!hasattr(namespace, action.dest)) {\n if (action.default !== SUPPRESS) {\n setattr(namespace, action.dest, action.default)\n }\n }\n }\n }\n\n // add any parser defaults that aren't present\n for (let dest of Object.keys(this._defaults)) {\n if (!hasattr(namespace, dest)) {\n setattr(namespace, dest, this._defaults[dest])\n }\n }\n\n // parse the arguments and exit if there are any errors\n if (this.exit_on_error) {\n try {\n [ namespace, args ] = this._parse_known_args(args, namespace)\n } catch (err) {\n if (err instanceof ArgumentError) {\n this.error(err.message)\n } else {\n throw err\n }\n }\n } else {\n [ namespace, args ] = this._parse_known_args(args, namespace)\n }\n\n if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) {\n args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))\n delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)\n }\n\n return [ namespace, args ]\n }\n\n _parse_known_args(arg_strings, namespace) {\n // replace arg strings that are file references\n if (this.fromfile_prefix_chars !== undefined) {\n arg_strings = this._read_args_from_files(arg_strings)\n }\n\n // map all mutually exclusive arguments to the other arguments\n // they can't occur with\n let action_conflicts = new Map()\n for (let mutex_group of this._mutually_exclusive_groups) {\n let group_actions = mutex_group._group_actions\n for (let [ i, mutex_action ] of Object.entries(mutex_group._group_actions)) {\n let conflicts = action_conflicts.get(mutex_action) || []\n conflicts = conflicts.concat(group_actions.slice(0, +i))\n conflicts = conflicts.concat(group_actions.slice(+i + 1))\n action_conflicts.set(mutex_action, conflicts)\n }\n }\n\n // find all option indices, and determine the arg_string_pattern\n // which has an 'O' if there is an option at an index,\n // an 'A' if there is an argument, or a '-' if there is a '--'\n let option_string_indices = {}\n let arg_string_pattern_parts = []\n let arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]()\n for (let [ i, arg_string ] of arg_strings_iter) {\n\n // all args after -- are non-options\n if (arg_string === '--') {\n arg_string_pattern_parts.push('-')\n for ([ i, arg_string ] of arg_strings_iter) {\n arg_string_pattern_parts.push('A')\n }\n\n // otherwise, add the arg to the arg strings\n // and note the index if it was an option\n } else {\n let option_tuple = this._parse_optional(arg_string)\n let pattern\n if (option_tuple === undefined) {\n pattern = 'A'\n } else {\n option_string_indices[i] = option_tuple\n pattern = 'O'\n }\n arg_string_pattern_parts.push(pattern)\n }\n }\n\n // join the pieces together to form the pattern\n let arg_strings_pattern = arg_string_pattern_parts.join('')\n\n // converts arg strings to the appropriate and then takes the action\n let seen_actions = new Set()\n let seen_non_default_actions = new Set()\n let extras\n\n let take_action = (action, argument_strings, option_string = undefined) => {\n seen_actions.add(action)\n let argument_values = this._get_values(action, argument_strings)\n\n // error if this argument is not allowed with other previously\n // seen arguments, assuming that actions that use the default\n // value don't really count as \"present\"\n if (argument_values !== action.default) {\n seen_non_default_actions.add(action)\n for (let conflict_action of action_conflicts.get(action) || []) {\n if (seen_non_default_actions.has(conflict_action)) {\n let msg = 'not allowed with argument %s'\n let action_name = _get_action_name(conflict_action)\n throw new ArgumentError(action, sub(msg, action_name))\n }\n }\n }\n\n // take the action if we didn't receive a SUPPRESS value\n // (e.g. from a default)\n if (argument_values !== SUPPRESS) {\n action(this, namespace, argument_values, option_string)\n }\n }\n\n // function to convert arg_strings into an optional action\n let consume_optional = start_index => {\n\n // get the optional identified at this index\n let option_tuple = option_string_indices[start_index]\n let [ action, option_string, explicit_arg ] = option_tuple\n\n // identify additional optionals in the same arg string\n // (e.g. -xyz is the same as -x -y -z if no args are required)\n let action_tuples = []\n let stop\n for (;;) {\n\n // if we found no optional action, skip it\n if (action === undefined) {\n extras.push(arg_strings[start_index])\n return start_index + 1\n }\n\n // if there is an explicit argument, try to match the\n // optional's string arguments to only this\n if (explicit_arg !== undefined) {\n let arg_count = this._match_argument(action, 'A')\n\n // if the action is a single-dash option and takes no\n // arguments, try to parse more single-dash options out\n // of the tail of the option string\n let chars = this.prefix_chars\n if (arg_count === 0 && !chars.includes(option_string[1])) {\n action_tuples.push([ action, [], option_string ])\n let char = option_string[0]\n option_string = char + explicit_arg[0]\n let new_explicit_arg = explicit_arg.slice(1) || undefined\n let optionals_map = this._option_string_actions\n if (hasattr(optionals_map, option_string)) {\n action = optionals_map[option_string]\n explicit_arg = new_explicit_arg\n } else {\n let msg = 'ignored explicit argument %r'\n throw new ArgumentError(action, sub(msg, explicit_arg))\n }\n\n // if the action expect exactly one argument, we've\n // successfully matched the option; exit the loop\n } else if (arg_count === 1) {\n stop = start_index + 1\n let args = [ explicit_arg ]\n action_tuples.push([ action, args, option_string ])\n break\n\n // error if a double-dash option did not use the\n // explicit argument\n } else {\n let msg = 'ignored explicit argument %r'\n throw new ArgumentError(action, sub(msg, explicit_arg))\n }\n\n // if there is no explicit argument, try to match the\n // optional's string arguments with the following strings\n // if successful, exit the loop\n } else {\n let start = start_index + 1\n let selected_patterns = arg_strings_pattern.slice(start)\n let arg_count = this._match_argument(action, selected_patterns)\n stop = start + arg_count\n let args = arg_strings.slice(start, stop)\n action_tuples.push([ action, args, option_string ])\n break\n }\n }\n\n // add the Optional to the list and return the index at which\n // the Optional's string args stopped\n assert(action_tuples.length)\n for (let [ action, args, option_string ] of action_tuples) {\n take_action(action, args, option_string)\n }\n return stop\n }\n\n // the list of Positionals left to be parsed; this is modified\n // by consume_positionals()\n let positionals = this._get_positional_actions()\n\n // function to convert arg_strings into positional actions\n let consume_positionals = start_index => {\n // match as many Positionals as possible\n let selected_pattern = arg_strings_pattern.slice(start_index)\n let arg_counts = this._match_arguments_partial(positionals, selected_pattern)\n\n // slice off the appropriate arg strings for each Positional\n // and add the Positional and its args to the list\n for (let i = 0; i < positionals.length && i < arg_counts.length; i++) {\n let action = positionals[i]\n let arg_count = arg_counts[i]\n let args = arg_strings.slice(start_index, start_index + arg_count)\n start_index += arg_count\n take_action(action, args)\n }\n\n // slice off the Positionals that we just parsed and return the\n // index at which the Positionals' string args stopped\n positionals = positionals.slice(arg_counts.length)\n return start_index\n }\n\n // consume Positionals and Optionals alternately, until we have\n // passed the last option string\n extras = []\n let start_index = 0\n let max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number))\n while (start_index <= max_option_string_index) {\n\n // consume any Positionals preceding the next option\n let next_option_string_index = Math.min(\n // eslint-disable-next-line no-loop-func\n ...Object.keys(option_string_indices).map(Number).filter(index => index >= start_index)\n )\n if (start_index !== next_option_string_index) {\n let positionals_end_index = consume_positionals(start_index)\n\n // only try to parse the next optional if we didn't consume\n // the option string during the positionals parsing\n if (positionals_end_index > start_index) {\n start_index = positionals_end_index\n continue\n } else {\n start_index = positionals_end_index\n }\n }\n\n // if we consumed all the positionals we could and we're not\n // at the index of an option string, there were extra arguments\n if (!(start_index in option_string_indices)) {\n let strings = arg_strings.slice(start_index, next_option_string_index)\n extras = extras.concat(strings)\n start_index = next_option_string_index\n }\n\n // consume the next optional and any arguments for it\n start_index = consume_optional(start_index)\n }\n\n // consume any positionals following the last Optional\n let stop_index = consume_positionals(start_index)\n\n // if we didn't consume all the argument strings, there were extras\n extras = extras.concat(arg_strings.slice(stop_index))\n\n // make sure all required actions were present and also convert\n // action defaults which were not given as arguments\n let required_actions = []\n for (let action of this._actions) {\n if (!seen_actions.has(action)) {\n if (action.required) {\n required_actions.push(_get_action_name(action))\n } else {\n // Convert action default now instead of doing it before\n // parsing arguments to avoid calling convert functions\n // twice (which may fail) if the argument was given, but\n // only if it was defined already in the namespace\n if (action.default !== undefined &&\n typeof action.default === 'string' &&\n hasattr(namespace, action.dest) &&\n action.default === getattr(namespace, action.dest)) {\n setattr(namespace, action.dest,\n this._get_value(action, action.default))\n }\n }\n }\n }\n\n if (required_actions.length) {\n this.error(sub('the following arguments are required: %s',\n required_actions.join(', ')))\n }\n\n // make sure all required groups had one option present\n for (let group of this._mutually_exclusive_groups) {\n if (group.required) {\n let no_actions_used = true\n for (let action of group._group_actions) {\n if (seen_non_default_actions.has(action)) {\n no_actions_used = false\n break\n }\n }\n\n // if no actions were used, report the error\n if (no_actions_used) {\n let names = group._group_actions\n .filter(action => action.help !== SUPPRESS)\n .map(action => _get_action_name(action))\n let msg = 'one of the arguments %s is required'\n this.error(sub(msg, names.join(' ')))\n }\n }\n }\n\n // return the updated namespace and the extra arguments\n return [ namespace, extras ]\n }\n\n _read_args_from_files(arg_strings) {\n // expand arguments referencing files\n let new_arg_strings = []\n for (let arg_string of arg_strings) {\n\n // for regular arguments, just add them back into the list\n if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) {\n new_arg_strings.push(arg_string)\n\n // replace arguments referencing files with the file content\n } else {\n try {\n let args_file = fs.readFileSync(arg_string.slice(1), 'utf8')\n let arg_strings = []\n for (let arg_line of splitlines(args_file)) {\n for (let arg of this.convert_arg_line_to_args(arg_line)) {\n arg_strings.push(arg)\n }\n }\n arg_strings = this._read_args_from_files(arg_strings)\n new_arg_strings = new_arg_strings.concat(arg_strings)\n } catch (err) {\n this.error(err.message)\n }\n }\n }\n\n // return the modified argument list\n return new_arg_strings\n }\n\n convert_arg_line_to_args(arg_line) {\n return [arg_line]\n }\n\n _match_argument(action, arg_strings_pattern) {\n // match the pattern for this action to the arg strings\n let nargs_pattern = this._get_nargs_pattern(action)\n let match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern))\n\n // raise an exception if we weren't able to find a match\n if (match === null) {\n let nargs_errors = {\n undefined: 'expected one argument',\n [OPTIONAL]: 'expected at most one argument',\n [ONE_OR_MORE]: 'expected at least one argument'\n }\n let msg = nargs_errors[action.nargs]\n if (msg === undefined) {\n msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs)\n }\n throw new ArgumentError(action, msg)\n }\n\n // return the number of arguments matched\n return match[1].length\n }\n\n _match_arguments_partial(actions, arg_strings_pattern) {\n // progressively shorten the actions list by slicing off the\n // final actions until we find a match\n let result = []\n for (let i of range(actions.length, 0, -1)) {\n let actions_slice = actions.slice(0, i)\n let pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('')\n let match = arg_strings_pattern.match(new RegExp('^' + pattern))\n if (match !== null) {\n result = result.concat(match.slice(1).map(string => string.length))\n break\n }\n }\n\n // return the list of arg string counts\n return result\n }\n\n _parse_optional(arg_string) {\n // if it's an empty string, it was meant to be a positional\n if (!arg_string) {\n return undefined\n }\n\n // if it doesn't start with a prefix, it was meant to be positional\n if (!this.prefix_chars.includes(arg_string[0])) {\n return undefined\n }\n\n // if the option string is present in the parser, return the action\n if (arg_string in this._option_string_actions) {\n let action = this._option_string_actions[arg_string]\n return [ action, arg_string, undefined ]\n }\n\n // if it's just a single character, it was meant to be positional\n if (arg_string.length === 1) {\n return undefined\n }\n\n // if the option string before the \"=\" is present, return the action\n if (arg_string.includes('=')) {\n let [ option_string, explicit_arg ] = _string_split(arg_string, '=', 1)\n if (option_string in this._option_string_actions) {\n let action = this._option_string_actions[option_string]\n return [ action, option_string, explicit_arg ]\n }\n }\n\n // search through all possible prefixes of the option string\n // and all actions in the parser for possible interpretations\n let option_tuples = this._get_option_tuples(arg_string)\n\n // if multiple actions match, the option string was ambiguous\n if (option_tuples.length > 1) {\n let options = option_tuples.map(([ /*action*/, option_string/*, explicit_arg*/ ]) => option_string).join(', ')\n let args = {option: arg_string, matches: options}\n let msg = 'ambiguous option: %(option)s could match %(matches)s'\n this.error(sub(msg, args))\n\n // if exactly one action matched, this segmentation is good,\n // so return the parsed action\n } else if (option_tuples.length === 1) {\n let [ option_tuple ] = option_tuples\n return option_tuple\n }\n\n // if it was not found as an option, but it looks like a negative\n // number, it was meant to be positional\n // unless there are negative-number-like options\n if (this._negative_number_matcher.test(arg_string)) {\n if (!this._has_negative_number_optionals.length) {\n return undefined\n }\n }\n\n // if it contains a space, it was meant to be a positional\n if (arg_string.includes(' ')) {\n return undefined\n }\n\n // it was meant to be an optional but there is no such option\n // in this parser (though it might be a valid option in a subparser)\n return [ undefined, arg_string, undefined ]\n }\n\n _get_option_tuples(option_string) {\n let result = []\n\n // option strings starting with two prefix characters are only\n // split at the '='\n let chars = this.prefix_chars\n if (chars.includes(option_string[0]) && chars.includes(option_string[1])) {\n if (this.allow_abbrev) {\n let option_prefix, explicit_arg\n if (option_string.includes('=')) {\n [ option_prefix, explicit_arg ] = _string_split(option_string, '=', 1)\n } else {\n option_prefix = option_string\n explicit_arg = undefined\n }\n for (let option_string of Object.keys(this._option_string_actions)) {\n if (option_string.startsWith(option_prefix)) {\n let action = this._option_string_actions[option_string]\n let tup = [ action, option_string, explicit_arg ]\n result.push(tup)\n }\n }\n }\n\n // single character options can be concatenated with their arguments\n // but multiple character options always have to have their argument\n // separate\n } else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) {\n let option_prefix = option_string\n let explicit_arg = undefined\n let short_option_prefix = option_string.slice(0, 2)\n let short_explicit_arg = option_string.slice(2)\n\n for (let option_string of Object.keys(this._option_string_actions)) {\n if (option_string === short_option_prefix) {\n let action = this._option_string_actions[option_string]\n let tup = [ action, option_string, short_explicit_arg ]\n result.push(tup)\n } else if (option_string.startsWith(option_prefix)) {\n let action = this._option_string_actions[option_string]\n let tup = [ action, option_string, explicit_arg ]\n result.push(tup)\n }\n }\n\n // shouldn't ever get here\n } else {\n this.error(sub('unexpected option string: %s', option_string))\n }\n\n // return the collected option tuples\n return result\n }\n\n _get_nargs_pattern(action) {\n // in all examples below, we have to allow for '--' args\n // which are represented as '-' in the pattern\n let nargs = action.nargs\n let nargs_pattern\n\n // the default (None) is assumed to be a single argument\n if (nargs === undefined) {\n nargs_pattern = '(-*A-*)'\n\n // allow zero or one arguments\n } else if (nargs === OPTIONAL) {\n nargs_pattern = '(-*A?-*)'\n\n // allow zero or more arguments\n } else if (nargs === ZERO_OR_MORE) {\n nargs_pattern = '(-*[A-]*)'\n\n // allow one or more arguments\n } else if (nargs === ONE_OR_MORE) {\n nargs_pattern = '(-*A[A-]*)'\n\n // allow any number of options or arguments\n } else if (nargs === REMAINDER) {\n nargs_pattern = '([-AO]*)'\n\n // allow one argument followed by any number of options or arguments\n } else if (nargs === PARSER) {\n nargs_pattern = '(-*A[-AO]*)'\n\n // suppress action, like nargs=0\n } else if (nargs === SUPPRESS) {\n nargs_pattern = '(-*-*)'\n\n // all others should be integers\n } else {\n nargs_pattern = sub('(-*%s-*)', 'A'.repeat(nargs).split('').join('-*'))\n }\n\n // if this is an optional action, -- is not allowed\n if (action.option_strings.length) {\n nargs_pattern = nargs_pattern.replace(/-\\*/g, '')\n nargs_pattern = nargs_pattern.replace(/-/g, '')\n }\n\n // return the pattern\n return nargs_pattern\n }\n\n // ========================\n // Alt command line argument parsing, allowing free intermix\n // ========================\n\n parse_intermixed_args(args = undefined, namespace = undefined) {\n let argv\n [ args, argv ] = this.parse_known_intermixed_args(args, namespace)\n if (argv.length) {\n let msg = 'unrecognized arguments: %s'\n this.error(sub(msg, argv.join(' ')))\n }\n return args\n }\n\n parse_known_intermixed_args(args = undefined, namespace = undefined) {\n // returns a namespace and list of extras\n //\n // positional can be freely intermixed with optionals. optionals are\n // first parsed with all positional arguments deactivated. The 'extras'\n // are then parsed. If the parser definition is incompatible with the\n // intermixed assumptions (e.g. use of REMAINDER, subparsers) a\n // TypeError is raised.\n //\n // positionals are 'deactivated' by setting nargs and default to\n // SUPPRESS. This blocks the addition of that positional to the\n // namespace\n\n let extras\n let positionals = this._get_positional_actions()\n let a = positionals.filter(action => [ PARSER, REMAINDER ].includes(action.nargs))\n if (a.length) {\n throw new TypeError(sub('parse_intermixed_args: positional arg' +\n ' with nargs=%s', a[0].nargs))\n }\n\n for (let group of this._mutually_exclusive_groups) {\n for (let action of group._group_actions) {\n if (positionals.includes(action)) {\n throw new TypeError('parse_intermixed_args: positional in' +\n ' mutuallyExclusiveGroup')\n }\n }\n }\n\n let save_usage\n try {\n save_usage = this.usage\n let remaining_args\n try {\n if (this.usage === undefined) {\n // capture the full usage for use in error messages\n this.usage = this.format_usage().slice(7)\n }\n for (let action of positionals) {\n // deactivate positionals\n action.save_nargs = action.nargs\n // action.nargs = 0\n action.nargs = SUPPRESS\n action.save_default = action.default\n action.default = SUPPRESS\n }\n [ namespace, remaining_args ] = this.parse_known_args(args,\n namespace)\n for (let action of positionals) {\n // remove the empty positional values from namespace\n let attr = getattr(namespace, action.dest)\n if (Array.isArray(attr) && attr.length === 0) {\n // eslint-disable-next-line no-console\n console.warn(sub('Do not expect %s in %s', action.dest, namespace))\n delattr(namespace, action.dest)\n }\n }\n } finally {\n // restore nargs and usage before exiting\n for (let action of positionals) {\n action.nargs = action.save_nargs\n action.default = action.save_default\n }\n }\n let optionals = this._get_optional_actions()\n try {\n // parse positionals. optionals aren't normally required, but\n // they could be, so make sure they aren't.\n for (let action of optionals) {\n action.save_required = action.required\n action.required = false\n }\n for (let group of this._mutually_exclusive_groups) {\n group.save_required = group.required\n group.required = false\n }\n [ namespace, extras ] = this.parse_known_args(remaining_args,\n namespace)\n } finally {\n // restore parser values before exiting\n for (let action of optionals) {\n action.required = action.save_required\n }\n for (let group of this._mutually_exclusive_groups) {\n group.required = group.save_required\n }\n }\n } finally {\n this.usage = save_usage\n }\n return [ namespace, extras ]\n }\n\n // ========================\n // Value conversion methods\n // ========================\n _get_values(action, arg_strings) {\n // for everything but PARSER, REMAINDER args, strip out first '--'\n if (![PARSER, REMAINDER].includes(action.nargs)) {\n try {\n _array_remove(arg_strings, '--')\n } catch (err) {}\n }\n\n let value\n // optional argument produces a default when not present\n if (!arg_strings.length && action.nargs === OPTIONAL) {\n if (action.option_strings.length) {\n value = action.const\n } else {\n value = action.default\n }\n if (typeof value === 'string') {\n value = this._get_value(action, value)\n this._check_value(action, value)\n }\n\n // when nargs='*' on a positional, if there were no command-line\n // args, use the default if it is anything other than None\n } else if (!arg_strings.length && action.nargs === ZERO_OR_MORE &&\n !action.option_strings.length) {\n if (action.default !== undefined) {\n value = action.default\n } else {\n value = arg_strings\n }\n this._check_value(action, value)\n\n // single argument or optional argument produces a single value\n } else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) {\n let arg_string = arg_strings[0]\n value = this._get_value(action, arg_string)\n this._check_value(action, value)\n\n // REMAINDER arguments convert all values, checking none\n } else if (action.nargs === REMAINDER) {\n value = arg_strings.map(v => this._get_value(action, v))\n\n // PARSER arguments convert all values, but check only the first\n } else if (action.nargs === PARSER) {\n value = arg_strings.map(v => this._get_value(action, v))\n this._check_value(action, value[0])\n\n // SUPPRESS argument does not put anything in the namespace\n } else if (action.nargs === SUPPRESS) {\n value = SUPPRESS\n\n // all other types of nargs produce a list\n } else {\n value = arg_strings.map(v => this._get_value(action, v))\n for (let v of value) {\n this._check_value(action, v)\n }\n }\n\n // return the converted value\n return value\n }\n\n _get_value(action, arg_string) {\n let type_func = this._registry_get('type', action.type, action.type)\n if (typeof type_func !== 'function') {\n let msg = '%r is not callable'\n throw new ArgumentError(action, sub(msg, type_func))\n }\n\n // convert the value to the appropriate type\n let result\n try {\n try {\n result = type_func(arg_string)\n } catch (err) {\n // Dear TC39, why would you ever consider making es6 classes not callable?\n // We had one universal interface, [[Call]], which worked for anything\n // (with familiar this-instanceof guard for classes). Now we have two.\n if (err instanceof TypeError &&\n /Class constructor .* cannot be invoked without 'new'/.test(err.message)) {\n // eslint-disable-next-line new-cap\n result = new type_func(arg_string)\n } else {\n throw err\n }\n }\n\n } catch (err) {\n // ArgumentTypeErrors indicate errors\n if (err instanceof ArgumentTypeError) {\n //let name = getattr(action.type, 'name', repr(action.type))\n let msg = err.message\n throw new ArgumentError(action, msg)\n\n // TypeErrors or ValueErrors also indicate errors\n } else if (err instanceof TypeError) {\n let name = getattr(action.type, 'name', repr(action.type))\n let args = {type: name, value: arg_string}\n let msg = 'invalid %(type)s value: %(value)r'\n throw new ArgumentError(action, sub(msg, args))\n } else {\n throw err\n }\n }\n\n // return the converted value\n return result\n }\n\n _check_value(action, value) {\n // converted value must be one of the choices (if specified)\n if (action.choices !== undefined && !_choices_to_array(action.choices).includes(value)) {\n let args = {value,\n choices: _choices_to_array(action.choices).map(repr).join(', ')}\n let msg = 'invalid choice: %(value)r (choose from %(choices)s)'\n throw new ArgumentError(action, sub(msg, args))\n }\n }\n\n // =======================\n // Help-formatting methods\n // =======================\n format_usage() {\n let formatter = this._get_formatter()\n formatter.add_usage(this.usage, this._actions,\n this._mutually_exclusive_groups)\n return formatter.format_help()\n }\n\n format_help() {\n let formatter = this._get_formatter()\n\n // usage\n formatter.add_usage(this.usage, this._actions,\n this._mutually_exclusive_groups)\n\n // description\n formatter.add_text(this.description)\n\n // positionals, optionals and user-defined groups\n for (let action_group of this._action_groups) {\n formatter.start_section(action_group.title)\n formatter.add_text(action_group.description)\n formatter.add_arguments(action_group._group_actions)\n formatter.end_section()\n }\n\n // epilog\n formatter.add_text(this.epilog)\n\n // determine help from format above\n return formatter.format_help()\n }\n\n _get_formatter() {\n // eslint-disable-next-line new-cap\n return new this.formatter_class({ prog: this.prog })\n }\n\n // =====================\n // Help-printing methods\n // =====================\n print_usage(file = undefined) {\n if (file === undefined) file = process.stdout\n this._print_message(this.format_usage(), file)\n }\n\n print_help(file = undefined) {\n if (file === undefined) file = process.stdout\n this._print_message(this.format_help(), file)\n }\n\n _print_message(message, file = undefined) {\n if (message) {\n if (file === undefined) file = process.stderr\n file.write(message)\n }\n }\n\n // ===============\n // Exiting methods\n // ===============\n exit(status = 0, message = undefined) {\n if (message) {\n this._print_message(message, process.stderr)\n }\n process.exit(status)\n }\n\n error(message) {\n /*\n * error(message: string)\n *\n * Prints a usage message incorporating the message to stderr and\n * exits.\n *\n * If you override this in a subclass, it should not return -- it\n * should either exit or raise an exception.\n */\n\n // LEGACY (v1 compatibility), debug mode\n if (this.debug === true) throw new Error(message)\n // end\n this.print_usage(process.stderr)\n let args = {prog: this.prog, message: message}\n this.exit(2, sub('%(prog)s: error: %(message)s\\n', args))\n }\n}))\n\n\nmodule.exports = {\n ArgumentParser,\n ArgumentError,\n ArgumentTypeError,\n BooleanOptionalAction,\n FileType,\n HelpFormatter,\n ArgumentDefaultsHelpFormatter,\n RawDescriptionHelpFormatter,\n RawTextHelpFormatter,\n MetavarTypeHelpFormatter,\n Namespace,\n Action,\n ONE_OR_MORE,\n OPTIONAL,\n PARSER,\n REMAINDER,\n SUPPRESS,\n ZERO_OR_MORE\n}\n\n// LEGACY (v1 compatibility), Const alias\nObject.defineProperty(module.exports, 'Const', {\n get() {\n let result = {}\n Object.entries({ ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE }).forEach(([ n, v ]) => {\n Object.defineProperty(result, n, {\n get() {\n deprecate(n, sub('use argparse.%s instead of argparse.Const.%s', n, n))\n return v\n }\n })\n })\n Object.entries({ _UNRECOGNIZED_ARGS_ATTR }).forEach(([ n, v ]) => {\n Object.defineProperty(result, n, {\n get() {\n deprecate(n, sub('argparse.Const.%s is an internal symbol and will no longer be available', n))\n return v\n }\n })\n })\n return result\n },\n enumerable: false\n})\n// end\n", "/*!\n * Tmp\n *\n * Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>\n *\n * MIT Licensed\n */\n\n/*\n * Module dependencies.\n */\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\nconst crypto = require('crypto');\nconst _c = { fs: fs.constants, os: os.constants };\n\n/*\n * The working inner variables.\n */\nconst // the random characters to choose from\n RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n TEMPLATE_PATTERN = /XXXXXX/,\n DEFAULT_TRIES = 3,\n CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR),\n // constants are off on the windows platform and will not match the actual errno codes\n IS_WIN32 = os.platform() === 'win32',\n EBADF = _c.EBADF || _c.os.errno.EBADF,\n ENOENT = _c.ENOENT || _c.os.errno.ENOENT,\n DIR_MODE = 0o700 /* 448 */,\n FILE_MODE = 0o600 /* 384 */,\n EXIT = 'exit',\n // this will hold the objects need to be removed on exit\n _removeObjects = [],\n // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback\n FN_RMDIR_SYNC = fs.rmdirSync.bind(fs);\n\nlet _gracefulCleanup = false;\n\n/**\n * Recursively remove a directory and its contents.\n *\n * @param {string} dirPath path of directory to remove\n * @param {Function} callback\n * @private\n */\nfunction rimraf(dirPath, callback) {\n return fs.rm(dirPath, { recursive: true }, callback);\n}\n\n/**\n * Recursively remove a directory and its contents, synchronously.\n *\n * @param {string} dirPath path of directory to remove\n * @private\n */\nfunction FN_RIMRAF_SYNC(dirPath) {\n return fs.rmSync(dirPath, { recursive: true });\n}\n\n/**\n * Gets a temporary file name.\n *\n * @param {(Options|tmpNameCallback)} options options or callback\n * @param {?tmpNameCallback} callback the callback function\n */\nfunction tmpName(options, callback) {\n const args = _parseArguments(options, callback),\n opts = args[0],\n cb = args[1];\n\n _assertAndSanitizeOptions(opts, function (err, sanitizedOptions) {\n if (err) return cb(err);\n\n let tries = sanitizedOptions.tries;\n (function _getUniqueName() {\n try {\n const name = _generateTmpName(sanitizedOptions);\n\n // check whether the path exists then retry if needed\n fs.stat(name, function (err) {\n /* istanbul ignore else */\n if (!err) {\n /* istanbul ignore else */\n if (tries-- > 0) return _getUniqueName();\n\n return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));\n }\n\n cb(null, name);\n });\n } catch (err) {\n cb(err);\n }\n })();\n });\n}\n\n/**\n * Synchronous version of tmpName.\n *\n * @param {Object} options\n * @returns {string} the generated random name\n * @throws {Error} if the options are invalid or could not generate a filename\n */\nfunction tmpNameSync(options) {\n const args = _parseArguments(options),\n opts = args[0];\n\n const sanitizedOptions = _assertAndSanitizeOptionsSync(opts);\n\n let tries = sanitizedOptions.tries;\n do {\n const name = _generateTmpName(sanitizedOptions);\n try {\n fs.statSync(name);\n } catch (e) {\n return name;\n }\n } while (tries-- > 0);\n\n throw new Error('Could not get a unique tmp filename, max tries reached');\n}\n\n/**\n * Creates and opens a temporary file.\n *\n * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined\n * @param {?fileCallback} callback\n */\nfunction file(options, callback) {\n const args = _parseArguments(options, callback),\n opts = args[0],\n cb = args[1];\n\n // gets a temporary filename\n tmpName(opts, function _tmpNameCreated(err, name) {\n /* istanbul ignore else */\n if (err) return cb(err);\n\n // create and open the file\n fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) {\n /* istanbu ignore else */\n if (err) return cb(err);\n\n if (opts.discardDescriptor) {\n return fs.close(fd, function _discardCallback(possibleErr) {\n // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only\n return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false));\n });\n } else {\n // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care\n // about the descriptor\n const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;\n cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false));\n }\n });\n });\n}\n\n/**\n * Synchronous version of file.\n *\n * @param {Options} options\n * @returns {FileSyncObject} object consists of name, fd and removeCallback\n * @throws {Error} if cannot create a file\n */\nfunction fileSync(options) {\n const args = _parseArguments(options),\n opts = args[0];\n\n const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;\n const name = tmpNameSync(opts);\n let fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);\n /* istanbul ignore else */\n if (opts.discardDescriptor) {\n fs.closeSync(fd);\n fd = undefined;\n }\n\n return {\n name: name,\n fd: fd,\n removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true)\n };\n}\n\n/**\n * Creates a temporary directory.\n *\n * @param {(Options|dirCallback)} options the options or the callback function\n * @param {?dirCallback} callback\n */\nfunction dir(options, callback) {\n const args = _parseArguments(options, callback),\n opts = args[0],\n cb = args[1];\n\n // gets a temporary filename\n tmpName(opts, function _tmpNameCreated(err, name) {\n /* istanbul ignore else */\n if (err) return cb(err);\n\n // create the directory\n fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {\n /* istanbul ignore else */\n if (err) return cb(err);\n\n cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false));\n });\n });\n}\n\n/**\n * Synchronous version of dir.\n *\n * @param {Options} options\n * @returns {DirSyncObject} object consists of name and removeCallback\n * @throws {Error} if it cannot create a directory\n */\nfunction dirSync(options) {\n const args = _parseArguments(options),\n opts = args[0];\n\n const name = tmpNameSync(opts);\n fs.mkdirSync(name, opts.mode || DIR_MODE);\n\n return {\n name: name,\n removeCallback: _prepareTmpDirRemoveCallback(name, opts, true)\n };\n}\n\n/**\n * Removes files asynchronously.\n *\n * @param {Object} fdPath\n * @param {Function} next\n * @private\n */\nfunction _removeFileAsync(fdPath, next) {\n const _handler = function (err) {\n if (err && !_isENOENT(err)) {\n // reraise any unanticipated error\n return next(err);\n }\n next();\n };\n\n if (0 <= fdPath[0])\n fs.close(fdPath[0], function () {\n fs.unlink(fdPath[1], _handler);\n });\n else fs.unlink(fdPath[1], _handler);\n}\n\n/**\n * Removes files synchronously.\n *\n * @param {Object} fdPath\n * @private\n */\nfunction _removeFileSync(fdPath) {\n let rethrownException = null;\n try {\n if (0 <= fdPath[0]) fs.closeSync(fdPath[0]);\n } catch (e) {\n // reraise any unanticipated error\n if (!_isEBADF(e) && !_isENOENT(e)) throw e;\n } finally {\n try {\n fs.unlinkSync(fdPath[1]);\n } catch (e) {\n // reraise any unanticipated error\n if (!_isENOENT(e)) rethrownException = e;\n }\n }\n if (rethrownException !== null) {\n throw rethrownException;\n }\n}\n\n/**\n * Prepares the callback for removal of the temporary file.\n *\n * Returns either a sync callback or a async callback depending on whether\n * fileSync or file was called, which is expressed by the sync parameter.\n *\n * @param {string} name the path of the file\n * @param {number} fd file descriptor\n * @param {Object} opts\n * @param {boolean} sync\n * @returns {fileCallback | fileCallbackSync}\n * @private\n */\nfunction _prepareTmpFileRemoveCallback(name, fd, opts, sync) {\n const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync);\n const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync);\n\n if (!opts.keep) _removeObjects.unshift(removeCallbackSync);\n\n return sync ? removeCallbackSync : removeCallback;\n}\n\n/**\n * Prepares the callback for removal of the temporary directory.\n *\n * Returns either a sync callback or a async callback depending on whether\n * tmpFileSync or tmpFile was called, which is expressed by the sync parameter.\n *\n * @param {string} name\n * @param {Object} opts\n * @param {boolean} sync\n * @returns {Function} the callback\n * @private\n */\nfunction _prepareTmpDirRemoveCallback(name, opts, sync) {\n const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs);\n const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC;\n const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync);\n const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync);\n if (!opts.keep) _removeObjects.unshift(removeCallbackSync);\n\n return sync ? removeCallbackSync : removeCallback;\n}\n\n/**\n * Creates a guarded function wrapping the removeFunction call.\n *\n * The cleanup callback is save to be called multiple times.\n * Subsequent invocations will be ignored.\n *\n * @param {Function} removeFunction\n * @param {string} fileOrDirName\n * @param {boolean} sync\n * @param {cleanupCallbackSync?} cleanupCallbackSync\n * @returns {cleanupCallback | cleanupCallbackSync}\n * @private\n */\nfunction _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) {\n let called = false;\n\n // if sync is true, the next parameter will be ignored\n return function _cleanupCallback(next) {\n /* istanbul ignore else */\n if (!called) {\n // remove cleanupCallback from cache\n const toRemove = cleanupCallbackSync || _cleanupCallback;\n const index = _removeObjects.indexOf(toRemove);\n /* istanbul ignore else */\n if (index >= 0) _removeObjects.splice(index, 1);\n\n called = true;\n if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) {\n return removeFunction(fileOrDirName);\n } else {\n return removeFunction(fileOrDirName, next || function () {});\n }\n }\n };\n}\n\n/**\n * The garbage collector.\n *\n * @private\n */\nfunction _garbageCollector() {\n /* istanbul ignore else */\n if (!_gracefulCleanup) return;\n\n // the function being called removes itself from _removeObjects,\n // loop until _removeObjects is empty\n while (_removeObjects.length) {\n try {\n _removeObjects[0]();\n } catch (e) {\n // already removed?\n }\n }\n}\n\n/**\n * Random name generator based on crypto.\n * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript\n *\n * @param {number} howMany\n * @returns {string} the generated random name\n * @private\n */\nfunction _randomChars(howMany) {\n let value = [],\n rnd = null;\n\n // make sure that we do not fail because we ran out of entropy\n try {\n rnd = crypto.randomBytes(howMany);\n } catch (e) {\n rnd = crypto.pseudoRandomBytes(howMany);\n }\n\n for (let i = 0; i < howMany; i++) {\n value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);\n }\n\n return value.join('');\n}\n\n/**\n * Checks whether the `obj` parameter is defined or not.\n *\n * @param {Object} obj\n * @returns {boolean} true if the object is undefined\n * @private\n */\nfunction _isUndefined(obj) {\n return typeof obj === 'undefined';\n}\n\n/**\n * Parses the function arguments.\n *\n * This function helps to have optional arguments.\n *\n * @param {(Options|null|undefined|Function)} options\n * @param {?Function} callback\n * @returns {Array} parsed arguments\n * @private\n */\nfunction _parseArguments(options, callback) {\n /* istanbul ignore else */\n if (typeof options === 'function') {\n return [{}, options];\n }\n\n /* istanbul ignore else */\n if (_isUndefined(options)) {\n return [{}, callback];\n }\n\n // copy options so we do not leak the changes we make internally\n const actualOptions = {};\n for (const key of Object.getOwnPropertyNames(options)) {\n actualOptions[key] = options[key];\n }\n\n return [actualOptions, callback];\n}\n\n/**\n * Resolve the specified path name in respect to tmpDir.\n *\n * The specified name might include relative path components, e.g. ../\n * so we need to resolve in order to be sure that is is located inside tmpDir\n *\n * @private\n */\nfunction _resolvePath(name, tmpDir, cb) {\n const pathToResolve = path.isAbsolute(name) ? name : path.join(tmpDir, name);\n\n fs.stat(pathToResolve, function (err) {\n if (err) {\n fs.realpath(path.dirname(pathToResolve), function (err, parentDir) {\n if (err) return cb(err);\n\n cb(null, path.join(parentDir, path.basename(pathToResolve)));\n });\n } else {\n fs.realpath(pathToResolve, cb);\n }\n });\n}\n\n/**\n * Resolve the specified path name in respect to tmpDir.\n *\n * The specified name might include relative path components, e.g. ../\n * so we need to resolve in order to be sure that is is located inside tmpDir\n *\n * @private\n */\nfunction _resolvePathSync(name, tmpDir) {\n const pathToResolve = path.isAbsolute(name) ? name : path.join(tmpDir, name);\n\n try {\n fs.statSync(pathToResolve);\n return fs.realpathSync(pathToResolve);\n } catch (_err) {\n const parentDir = fs.realpathSync(path.dirname(pathToResolve));\n\n return path.join(parentDir, path.basename(pathToResolve));\n }\n}\n\n/**\n * Generates a new temporary name.\n *\n * @param {Object} opts\n * @returns {string} the new random name according to opts\n * @private\n */\nfunction _generateTmpName(opts) {\n const tmpDir = opts.tmpdir;\n\n /* istanbul ignore else */\n if (!_isUndefined(opts.name)) {\n return path.join(tmpDir, opts.dir, opts.name);\n }\n\n /* istanbul ignore else */\n if (!_isUndefined(opts.template)) {\n return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6));\n }\n\n // prefix and postfix\n const name = [\n opts.prefix ? opts.prefix : 'tmp',\n '-',\n process.pid,\n '-',\n _randomChars(12),\n opts.postfix ? '-' + opts.postfix : ''\n ].join('');\n\n return path.join(tmpDir, opts.dir, name);\n}\n\n/**\n * Asserts and sanitizes the basic options.\n *\n * @private\n */\nfunction _assertOptionsBase(options) {\n if (!_isUndefined(options.name)) {\n const name = options.name;\n\n // assert that name is not absolute and does not contain a path\n if (path.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found \"${name}\".`);\n\n // must not fail on valid .<name> or ..<name> or similar such constructs\n const basename = path.basename(name);\n if (basename === '..' || basename === '.' || basename !== name)\n throw new Error(`name option must not contain a path, found \"${name}\".`);\n }\n\n /* istanbul ignore else */\n if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) {\n throw new Error(`Invalid template, found \"${options.template}\".`);\n }\n\n /* istanbul ignore else */\n if ((!_isUndefined(options.tries) && isNaN(options.tries)) || options.tries < 0) {\n throw new Error(`Invalid tries, found \"${options.tries}\".`);\n }\n\n // if a name was specified we will try once\n options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1;\n options.keep = !!options.keep;\n options.detachDescriptor = !!options.detachDescriptor;\n options.discardDescriptor = !!options.discardDescriptor;\n options.unsafeCleanup = !!options.unsafeCleanup;\n\n // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to\n options.prefix = _isUndefined(options.prefix) ? '' : options.prefix;\n options.postfix = _isUndefined(options.postfix) ? '' : options.postfix;\n}\n\n/**\n * Gets the relative directory to tmpDir.\n *\n * @private\n */\nfunction _getRelativePath(option, name, tmpDir, cb) {\n if (_isUndefined(name)) return cb(null);\n\n _resolvePath(name, tmpDir, function (err, resolvedPath) {\n if (err) return cb(err);\n\n const relativePath = path.relative(tmpDir, resolvedPath);\n\n if (!resolvedPath.startsWith(tmpDir)) {\n return cb(new Error(`${option} option must be relative to \"${tmpDir}\", found \"${relativePath}\".`));\n }\n\n cb(null, relativePath);\n });\n}\n\n/**\n * Gets the relative path to tmpDir.\n *\n * @private\n */\nfunction _getRelativePathSync(option, name, tmpDir) {\n if (_isUndefined(name)) return;\n\n const resolvedPath = _resolvePathSync(name, tmpDir);\n const relativePath = path.relative(tmpDir, resolvedPath);\n\n if (!resolvedPath.startsWith(tmpDir)) {\n throw new Error(`${option} option must be relative to \"${tmpDir}\", found \"${relativePath}\".`);\n }\n\n return relativePath;\n}\n\n/**\n * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing\n * options.\n *\n * @private\n */\nfunction _assertAndSanitizeOptions(options, cb) {\n _getTmpDir(options, function (err, tmpDir) {\n if (err) return cb(err);\n\n options.tmpdir = tmpDir;\n\n try {\n _assertOptionsBase(options, tmpDir);\n } catch (err) {\n return cb(err);\n }\n\n // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to\n _getRelativePath('dir', options.dir, tmpDir, function (err, dir) {\n if (err) return cb(err);\n\n options.dir = _isUndefined(dir) ? '' : dir;\n\n // sanitize further if template is relative to options.dir\n _getRelativePath('template', options.template, tmpDir, function (err, template) {\n if (err) return cb(err);\n\n options.template = template;\n\n cb(null, options);\n });\n });\n });\n}\n\n/**\n * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing\n * options.\n *\n * @private\n */\nfunction _assertAndSanitizeOptionsSync(options) {\n const tmpDir = (options.tmpdir = _getTmpDirSync(options));\n\n _assertOptionsBase(options, tmpDir);\n\n const dir = _getRelativePathSync('dir', options.dir, tmpDir);\n options.dir = _isUndefined(dir) ? '' : dir;\n\n options.template = _getRelativePathSync('template', options.template, tmpDir);\n\n return options;\n}\n\n/**\n * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows.\n *\n * @private\n */\nfunction _isEBADF(error) {\n return _isExpectedError(error, -EBADF, 'EBADF');\n}\n\n/**\n * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows.\n *\n * @private\n */\nfunction _isENOENT(error) {\n return _isExpectedError(error, -ENOENT, 'ENOENT');\n}\n\n/**\n * Helper to determine whether the expected error code matches the actual code and errno,\n * which will differ between the supported node versions.\n *\n * - Node >= 7.0:\n * error.code {string}\n * error.errno {number} any numerical value will be negated\n *\n * CAVEAT\n *\n * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT\n * is no different here.\n *\n * @param {SystemError} error\n * @param {number} errno\n * @param {string} code\n * @private\n */\nfunction _isExpectedError(error, errno, code) {\n return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno;\n}\n\n/**\n * Sets the graceful cleanup.\n *\n * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the\n * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary\n * object removals.\n */\nfunction setGracefulCleanup() {\n _gracefulCleanup = true;\n}\n\n/**\n * Returns the currently configured tmp dir from os.tmpdir().\n *\n * @private\n */\nfunction _getTmpDir(options, cb) {\n return fs.realpath((options && options.tmpdir) || os.tmpdir(), cb);\n}\n\n/**\n * Returns the currently configured tmp dir from os.tmpdir().\n *\n * @private\n */\nfunction _getTmpDirSync(options) {\n return fs.realpathSync((options && options.tmpdir) || os.tmpdir());\n}\n\n// Install process exit listener\nprocess.addListener(EXIT, _garbageCollector);\n\n/**\n * Configuration options.\n *\n * @typedef {Object} Options\n * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected\n * @property {?number} tries the number of tries before give up the name generation\n * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files\n * @property {?string} template the \"mkstemp\" like filename template\n * @property {?string} name fixed name relative to tmpdir or the specified dir option\n * @property {?string} dir tmp directory relative to the root tmp directory in use\n * @property {?string} prefix prefix for the generated name\n * @property {?string} postfix postfix for the generated name\n * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir\n * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty\n * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection\n * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection\n */\n\n/**\n * @typedef {Object} FileSyncObject\n * @property {string} name the name of the file\n * @property {string} fd the file descriptor or -1 if the fd has been discarded\n * @property {fileCallback} removeCallback the callback function to remove the file\n */\n\n/**\n * @typedef {Object} DirSyncObject\n * @property {string} name the name of the directory\n * @property {fileCallback} removeCallback the callback function to remove the directory\n */\n\n/**\n * @callback tmpNameCallback\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n */\n\n/**\n * @callback fileCallback\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {number} fd the file descriptor or -1 if the fd had been discarded\n * @param {cleanupCallback} fn the cleanup callback function\n */\n\n/**\n * @callback fileCallbackSync\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {number} fd the file descriptor or -1 if the fd had been discarded\n * @param {cleanupCallbackSync} fn the cleanup callback function\n */\n\n/**\n * @callback dirCallback\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {cleanupCallback} fn the cleanup callback function\n */\n\n/**\n * @callback dirCallbackSync\n * @param {?Error} err the error object if anything goes wrong\n * @param {string} name the temporary file name\n * @param {cleanupCallbackSync} fn the cleanup callback function\n */\n\n/**\n * Removes the temporary created file or directory.\n *\n * @callback cleanupCallback\n * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed\n */\n\n/**\n * Removes the temporary created file or directory.\n *\n * @callback cleanupCallbackSync\n */\n\n/**\n * Callback function for function composition.\n * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57}\n *\n * @callback simpleCallback\n */\n\n// exporting all the needed methods\n\n// evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will\n// allow users to reconfigure the temporary directory\nObject.defineProperty(module.exports, 'tmpdir', {\n enumerable: true,\n configurable: false,\n get: function () {\n return _getTmpDirSync();\n }\n});\n\nmodule.exports.dir = dir;\nmodule.exports.dirSync = dirSync;\n\nmodule.exports.file = file;\nmodule.exports.fileSync = fileSync;\n\nmodule.exports.tmpName = tmpName;\nmodule.exports.tmpNameSync = tmpNameSync;\n\nmodule.exports.setGracefulCleanup = setGracefulCleanup;\n", "'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n", "'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // If the main part has no difference\n if (lowVersion.compareMain(highVersion) === 0) {\n if (lowVersion.minor && !lowVersion.patch) {\n return 'minor'\n }\n return 'patch'\n }\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are prereleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n", "'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n", "'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n", "'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If LT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n", "'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n", "/* eslint-disable no-console -- this is a cli tool */\n\nimport { createWriteStream, existsSync, promises as fs, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { stylish } from \"@html-validate/stylish\";\nimport { type DocumentNode, parse } from \"@humanwhocodes/momoa\";\nimport { ArgumentParser } from \"argparse\";\nimport { findUp } from \"find-up\";\nimport tmp from \"tmp\";\nimport { setupBlacklist } from \"./blacklist\";\nimport { type TarballMeta, getFileContent } from \"./tarball\";\nimport { tarballLocation } from \"./tarball-location\";\nimport { type PackageJson } from \"./types\";\nimport { setCacheDirecory } from \"./utils/persistent-cache\";\nimport { type VerifyOptions, verify } from \"./verify\";\n\nconst pkgFilepath = fileURLToPath(new URL(\"../package.json\", import.meta.url));\nconst { version } = JSON.parse(readFileSync(pkgFilepath, \"utf-8\")) as { version: string };\n\nconst PACKAGE_JSON = \"package.json\";\n\ninterface ParsedArgs {\n\tcache?: string;\n\tpkgfile: string;\n\ttarball?: string;\n\tignore_missing_fields?: boolean;\n\tignore_node_version: boolean | number;\n\tallow_dependency: string[];\n\tallow_types_dependencies?: boolean;\n}\n\ninterface GetPackageJsonResults {\n\tpkg: PackageJson;\n\tpkgAst: DocumentNode;\n\tpkgPath: string;\n}\n\nasync function preloadStdin(): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\ttmp.file((err, path, fd) => {\n\t\t\tif (err) {\n\t\t\t\treject(err);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst st = createWriteStream(\"\", { fd, autoClose: true });\n\t\t\tprocess.stdin.pipe(st);\n\t\t\tst.on(\"finish\", () => {\n\t\t\t\tresolve(path);\n\t\t\t});\n\t\t\tst.on(\"error\", (err) => {\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t});\n}\n\nasync function getPackageJson(\n\targs: ParsedArgs,\n\tregenerateReportName: boolean,\n): Promise<GetPackageJsonResults | { pkg: undefined; pkgAst: undefined; pkgPath: undefined }> {\n\t/* get from explicit path passed as argument */\n\tif (args.pkgfile) {\n\t\tconst content = await fs.readFile(args.pkgfile, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as PackageJson;\n\t\tconst pkgAst = parse(content);\n\t\treturn {\n\t\t\tpkg,\n\t\t\tpkgAst,\n\t\t\tpkgPath: args.pkgfile,\n\t\t};\n\t}\n\n\t/* extract package.json from explicit tarball location */\n\tif (args.tarball) {\n\t\tconst contents = await getFileContent({ filePath: args.tarball }, [PACKAGE_JSON]);\n\t\tconst content = contents[PACKAGE_JSON].toString(\"utf-8\");\n\t\tconst pkg = JSON.parse(content) as PackageJson;\n\t\tconst pkgAst = parse(content);\n\t\treturn {\n\t\t\tpkg,\n\t\t\tpkgAst,\n\t\t\tpkgPath: path.join(\n\t\t\t\tregenerateReportName ? `${pkg.name}-${pkg.version}.tgz` : args.tarball,\n\t\t\t\tPACKAGE_JSON,\n\t\t\t),\n\t\t};\n\t}\n\n\t/* try to locate package.json from file structure */\n\tconst pkgPath = await findUp(PACKAGE_JSON);\n\tif (pkgPath) {\n\t\tconst content = await fs.readFile(pkgPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as PackageJson;\n\t\tconst pkgAst = parse(content);\n\t\treturn {\n\t\t\tpkg,\n\t\t\tpkgAst,\n\t\t\tpkgPath,\n\t\t};\n\t}\n\n\treturn { pkg: undefined, pkgAst: undefined, pkgPath: undefined };\n}\n\nasync function run(): Promise<void> {\n\tconst parser = new ArgumentParser({\n\t\tdescription: \"Opiniated linter for NPM package tarball and package.json metadata\",\n\t});\n\n\tparser.add_argument(\"-v\", \"--version\", { action: \"version\", version });\n\tparser.add_argument(\"-t\", \"--tarball\", { help: \"specify tarball location\" });\n\tparser.add_argument(\"-p\", \"--pkgfile\", { help: \"specify package.json location\" });\n\tparser.add_argument(\"--cache\", { help: \"specify cache directory\" });\n\tparser.add_argument(\"--allow-dependency\", {\n\t\taction: \"append\",\n\t\tdefault: [],\n\t\tmetavar: \"DEPENDENCY\",\n\t\thelp: \"explicitly allow given dependency (can be given multiple times or as a comma-separated list)\",\n\t});\n\tparser.add_argument(\"--allow-types-dependencies\", {\n\t\taction: \"store_true\",\n\t\thelp: \"allow production dependencies to `@types/*`\",\n\t});\n\tparser.add_argument(\"--ignore-missing-fields\", {\n\t\taction: \"store_true\",\n\t\thelp: \"ignore errors for missing fields (but still checks for empty and valid)\",\n\t});\n\tparser.add_argument(\"--ignore-node-version\", {\n\t\tnargs: \"?\",\n\t\tmetavar: \"MAJOR\",\n\t\ttype: \"int\",\n\t\tdefault: false,\n\t\tconst: true,\n\t\thelp: \"ignore error for outdated node version (restricted to MAJOR version if given)\",\n\t});\n\n\tconst args = parser.parse_args() as ParsedArgs;\n\tconst allowedDependencies = new Set(args.allow_dependency.map((it) => it.split(\",\")).flat());\n\n\tif (args.cache) {\n\t\tawait setCacheDirecory(args.cache);\n\t}\n\n\t/* this library assumes the file source can be randomly accessed but with\n\t * stdin this is not possible so stdin is read into a temporary file which is\n\t * used instead */\n\tlet regenerateReportName = false;\n\tif (args.tarball === \"-\") {\n\t\targs.tarball = await preloadStdin();\n\t\tregenerateReportName = true;\n\t}\n\n\tconst { pkg, pkgAst, pkgPath } = await getPackageJson(args, regenerateReportName);\n\n\tif (!pkg) {\n\t\tconsole.error(\"Failed to locate package.json and no location was specificed with `--pkgfile'\");\n\t\tprocess.exitCode = 1;\n\t\treturn;\n\t}\n\n\tconst tarball: TarballMeta = {\n\t\tfilePath: args.tarball ?? tarballLocation(pkg, pkgPath),\n\t\treportPath: regenerateReportName ? `${pkg.name}-${pkg.version}.tgz` : undefined,\n\t};\n\tif (!existsSync(tarball.filePath)) {\n\t\tconsole.error(`\"${tarball.filePath}\" does not exist, did you forget to run \\`npm pack'?`);\n\t\tprocess.exitCode = 1;\n\t\treturn;\n\t}\n\n\tsetupBlacklist(pkg.name);\n\n\tconst options: VerifyOptions = {\n\t\tallowedDependencies,\n\t\tallowTypesDependencies: args.allow_types_dependencies,\n\t\tignoreMissingFields: args.ignore_missing_fields,\n\t\tignoreNodeVersion: args.ignore_node_version,\n\t};\n\n\tconst results = await verify(pkg, pkgAst, pkgPath, tarball, options);\n\n\tfor (const result of results) {\n\t\tresult.messages.sort((a, b) => {\n\t\t\tif (a.line !== b.line) {\n\t\t\t\treturn a.line - b.line;\n\t\t\t} else {\n\t\t\t\treturn a.column - b.column;\n\t\t\t}\n\t\t});\n\t}\n\n\tconst output = stylish(results);\n\tprocess.stdout.write(output);\n\n\tconst totalErrors = results.reduce((sum, result) => {\n\t\treturn sum + result.errorCount;\n\t}, 0);\n\n\tprocess.exitCode = totalErrors > 0 ? 1 : 0;\n}\n\nrun().catch((err: unknown) => {\n\tconsole.error(err);\n\tprocess.exitCode = 1;\n});\n", "let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;\nif (typeof process !== 'undefined') {\n\t({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});\n\tisTTY = process.stdout && process.stdout.isTTY;\n}\n\nexport const $ = {\n\tenabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (\n\t\tFORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY\n\t)\n}\n\nfunction init(x, y) {\n\tlet rgx = new RegExp(`\\\\x1b\\\\[${y}m`, 'g');\n\tlet open = `\\x1b[${x}m`, close = `\\x1b[${y}m`;\n\n\treturn function (txt) {\n\t\tif (!$.enabled || txt == null) return txt;\n\t\treturn open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;\n\t};\n}\n\n// modifiers\nexport const reset = init(0, 0);\nexport const bold = init(1, 22);\nexport const dim = init(2, 22);\nexport const italic = init(3, 23);\nexport const underline = init(4, 24);\nexport const inverse = init(7, 27);\nexport const hidden = init(8, 28);\nexport const strikethrough = init(9, 29);\n\n// colors\nexport const black = init(30, 39);\nexport const red = init(31, 39);\nexport const green = init(32, 39);\nexport const yellow = init(33, 39);\nexport const blue = init(34, 39);\nexport const magenta = init(35, 39);\nexport const cyan = init(36, 39);\nexport const white = init(37, 39);\nexport const gray = init(90, 39);\nexport const grey = init(90, 39);\n\n// background colors\nexport const bgBlack = init(40, 49);\nexport const bgRed = init(41, 49);\nexport const bgGreen = init(42, 49);\nexport const bgYellow = init(43, 49);\nexport const bgBlue = init(44, 49);\nexport const bgMagenta = init(45, 49);\nexport const bgCyan = init(46, 49);\nexport const bgWhite = init(47, 49);\n", "module.exports = function (rows_, opts) {\n if (!opts) opts = {};\n var hsep = opts.hsep === undefined ? ' ' : opts.hsep;\n var align = opts.align || [];\n var stringLength = opts.stringLength\n || function (s) { return String(s).length; }\n ;\n \n var dotsizes = reduce(rows_, function (acc, row) {\n forEach(row, function (c, ix) {\n var n = dotindex(c);\n if (!acc[ix] || n > acc[ix]) acc[ix] = n;\n });\n return acc;\n }, []);\n \n var rows = map(rows_, function (row) {\n return map(row, function (c_, ix) {\n var c = String(c_);\n if (align[ix] === '.') {\n var index = dotindex(c);\n var size = dotsizes[ix] + (/\\./.test(c) ? 1 : 2)\n - (stringLength(c) - index)\n ;\n return c + Array(size).join(' ');\n }\n else return c;\n });\n });\n \n var sizes = reduce(rows, function (acc, row) {\n forEach(row, function (c, ix) {\n var n = stringLength(c);\n if (!acc[ix] || n > acc[ix]) acc[ix] = n;\n });\n return acc;\n }, []);\n \n return map(rows, function (row) {\n return map(row, function (c, ix) {\n var n = (sizes[ix] - stringLength(c)) || 0;\n var s = Array(Math.max(n + 1, 1)).join(' ');\n if (align[ix] === 'r' || align[ix] === '.') {\n return s + c;\n }\n if (align[ix] === 'c') {\n return Array(Math.ceil(n / 2 + 1)).join(' ')\n + c + Array(Math.floor(n / 2 + 1)).join(' ')\n ;\n }\n \n return c + s;\n }).join(hsep).replace(/\\s+$/, '');\n }).join('\\n');\n};\n\nfunction dotindex (c) {\n var m = /\\.[^.]*$/.exec(c);\n return m ? m.index + 1 : c.length;\n}\n\nfunction reduce (xs, f, init) {\n if (xs.reduce) return xs.reduce(f, init);\n var i = 0;\n var acc = arguments.length >= 3 ? init : xs[i++];\n for (; i < xs.length; i++) {\n f(acc, xs[i], i);\n }\n return acc;\n}\n\nfunction forEach (xs, f) {\n if (xs.forEach) return xs.forEach(f);\n for (var i = 0; i < xs.length; i++) {\n f.call(xs, xs[i], i);\n }\n}\n\nfunction map (xs, f) {\n if (xs.map) return xs.map(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n res.push(f.call(xs, xs[i], i));\n }\n return res;\n}\n", "import table, { type Options } from \"text-table\";\nimport * as colors from \"./colors-node\";\nimport { type Result } from \"./result\";\nimport { Severity } from \"./severity\";\n\n/**\n * Given a word and a count, append an s if count is not one.\n * @param word - A word in its singular form.\n * @param count - A number controlling whether word should be pluralized.\n * @returns - The original word with an s on the end if count is not one.\n */\nfunction pluralize(word: string, count: number): string {\n\treturn count === 1 ? word : `${word}s`;\n}\n\n/**\n * Given a line with \" $\\{line\\} $\\{column\\} \" where line is right-aligned and\n * column is left-aligned it replaces the delimiter with a colon.\n */\nfunction centerLineColumn(el: string): string {\n\t/* eslint-disable-next-line sonarjs/slow-regex -- false positive? unless I'm missing something here */\n\treturn el.replace(/(\\d+)\\s+(\\d+)/u, (_m, p1: string, p2: string) => colors.dim(`${p1}:${p2}`));\n}\n\n/**\n * Strip ANSI color escape sequences from text.\n */\nfunction stripAnsi(text: string): string {\n\t/* eslint-disable-next-line no-control-regex -- expected to match control characters */\n\treturn text.replace(/\\u001B\\[[0-9;]*m/g, \"\");\n}\n\nexport function stylish(results: Result[]): string {\n\tlet output = \"\\n\";\n\tlet errorCount = 0;\n\tlet warningCount = 0;\n\tlet fixableErrorCount = 0;\n\tlet fixableWarningCount = 0;\n\tlet summaryColor: colors.Colorize = colors.yellow;\n\n\tresults.forEach((result) => {\n\t\tconst messages = result.messages;\n\n\t\tif (messages.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\terrorCount += result.errorCount;\n\t\twarningCount += result.warningCount;\n\t\tfixableErrorCount += result.fixableErrorCount;\n\t\tfixableWarningCount += result.fixableWarningCount;\n\n\t\tconst rows = messages.map((message) => {\n\t\t\tlet messageType;\n\n\t\t\tif (Boolean(message.fatal) || message.severity === Severity.ERROR) {\n\t\t\t\tmessageType = colors.red(\"error\");\n\t\t\t\tsummaryColor = colors.red;\n\t\t\t} else {\n\t\t\t\tmessageType = colors.yellow(\"warning\");\n\t\t\t}\n\n\t\t\treturn [\n\t\t\t\t\"\",\n\t\t\t\tmessage.line ?? 0,\n\t\t\t\tmessage.column ?? 0,\n\t\t\t\tmessageType,\n\t\t\t\tmessage.message.replace(/([^ ])\\.$/u, \"$1\"),\n\t\t\t\tmessage.ruleId ? colors.dim(message.ruleId) : \"\",\n\t\t\t];\n\t\t});\n\n\t\tconst options: Options = {\n\t\t\talign: [\"l\", \"r\", \"l\"],\n\t\t\tstringLength(str: string): number {\n\t\t\t\treturn stripAnsi(str).length;\n\t\t\t},\n\t\t};\n\t\tconst formattedTable = table(rows, options).split(\"\\n\").map(centerLineColumn).join(\"\\n\");\n\n\t\toutput += `${colors.underline(result.filePath)}\\n`;\n\t\toutput += `${formattedTable}\\n\\n`;\n\t});\n\n\tconst total = errorCount + warningCount;\n\n\tif (total > 0) {\n\t\toutput += summaryColor(\n\t\t\tcolors.bold(\n\t\t\t\t[\n\t\t\t\t\t\"\\u2716 \",\n\t\t\t\t\ttotal,\n\t\t\t\t\tpluralize(\" problem\", total),\n\t\t\t\t\t\" (\",\n\t\t\t\t\terrorCount,\n\t\t\t\t\tpluralize(\" error\", errorCount),\n\t\t\t\t\t\", \",\n\t\t\t\t\twarningCount,\n\t\t\t\t\tpluralize(\" warning\", warningCount),\n\t\t\t\t\t\")\\n\",\n\t\t\t\t].join(\"\"),\n\t\t\t),\n\t\t);\n\n\t\tif (fixableErrorCount > 0 || fixableWarningCount > 0) {\n\t\t\toutput += summaryColor(\n\t\t\t\tcolors.bold(\n\t\t\t\t\t[\n\t\t\t\t\t\t\" \",\n\t\t\t\t\t\tfixableErrorCount,\n\t\t\t\t\t\tpluralize(\" error\", fixableErrorCount),\n\t\t\t\t\t\t\" and \",\n\t\t\t\t\t\tfixableWarningCount,\n\t\t\t\t\t\tpluralize(\" warning\", fixableWarningCount),\n\t\t\t\t\t\t\" potentially fixable with the `--fix` option.\\n\",\n\t\t\t\t\t].join(\"\"),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Resets output color, for prevent change on top level\n\treturn total > 0 ? colors.reset(output) : \"\";\n}\n", "import * as kleur from \"kleur/colors\";\n\nexport type Colorize = kleur.Colorize;\n\nexport const reset = kleur.reset;\nexport const bold = kleur.bold;\nexport const dim = kleur.dim;\nexport const underline = kleur.underline;\n\nexport const yellow = kleur.yellow;\nexport const red = kleur.red;\n", "export enum Severity {\n\tOFF = 0,\n\tWARN = 1,\n\tERROR = 2,\n}\n", "/**\n * @fileoverview Character codes.\n * @author Nicholas C. Zakas\n */\n\nconst CHAR_0 = 48; // 0\nconst CHAR_1 = 49; // 1\nconst CHAR_9 = 57; // 9\nconst CHAR_BACKSLASH = 92; // \\\nconst CHAR_DOLLAR = 36; // $\nconst CHAR_DOT = 46; // .\nconst CHAR_DOUBLE_QUOTE = 34; // \"\nconst CHAR_LOWER_A = 97; // a\nconst CHAR_LOWER_E = 101; // e\nconst CHAR_LOWER_F = 102; // f\nconst CHAR_LOWER_N = 110; // n\nconst CHAR_LOWER_T = 116; // t\nconst CHAR_LOWER_U = 117; // u\nconst CHAR_LOWER_X = 120; // x\nconst CHAR_LOWER_Z = 122; // z\nconst CHAR_MINUS = 45; // -\nconst CHAR_NEWLINE = 10; // newline\nconst CHAR_PLUS = 43; // +\nconst CHAR_RETURN = 13; // return\nconst CHAR_SINGLE_QUOTE = 39; // '\nconst CHAR_SLASH = 47; // /\nconst CHAR_SPACE = 32; // space\nconst CHAR_TAB = 9; // tab\nconst CHAR_UNDERSCORE = 95; // _\nconst CHAR_UPPER_A = 65; // A\nconst CHAR_UPPER_E = 69; // E\nconst CHAR_UPPER_F = 70; // F\nconst CHAR_UPPER_N = 78; // N\nconst CHAR_UPPER_X = 88; // X\nconst CHAR_UPPER_Z = 90; // Z\nconst CHAR_LOWER_B = 98; // b\nconst CHAR_LOWER_R = 114; // r\nconst CHAR_LOWER_V = 118; // v\nconst CHAR_LINE_SEPARATOR = 0x2028;\nconst CHAR_PARAGRAPH_SEPARATOR = 0x2029;\nconst CHAR_UPPER_I = 73; // I\nconst CHAR_STAR = 42; // *\nconst CHAR_VTAB = 11; // U+000B Vertical tab\nconst CHAR_FORM_FEED = 12; // U+000C Form feed\nconst CHAR_NBSP = 160; // U+00A0 Non-breaking space\nconst CHAR_BOM = 65279; // U+FEFF\nconst CHAR_NON_BREAKING_SPACE = 160;\nconst CHAR_EN_QUAD = 8192;\nconst CHAR_EM_QUAD = 8193;\nconst CHAR_EN_SPACE = 8194;\nconst CHAR_EM_SPACE = 8195;\nconst CHAR_THREE_PER_EM_SPACE = 8196;\nconst CHAR_FOUR_PER_EM_SPACE = 8197;\nconst CHAR_SIX_PER_EM_SPACE = 8198;\nconst CHAR_FIGURE_SPACE = 8199;\nconst CHAR_PUNCTUATION_SPACE = 8200;\nconst CHAR_THIN_SPACE = 8201;\nconst CHAR_HAIR_SPACE = 8202;\nconst CHAR_NARROW_NO_BREAK_SPACE = 8239;\nconst CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287;\nconst CHAR_IDEOGRAPHIC_SPACE = 12288;\n\n/**\n * @fileoverview JSON syntax helpers\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Types\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").TokenType} TokenType */\n\n//-----------------------------------------------------------------------------\n// Predefined Tokens\n//-----------------------------------------------------------------------------\n\nconst LBRACKET = \"[\";\nconst RBRACKET = \"]\";\nconst LBRACE = \"{\";\nconst RBRACE = \"}\";\nconst COLON = \":\";\nconst COMMA = \",\";\n\nconst TRUE = \"true\";\nconst FALSE = \"false\";\nconst NULL = \"null\";\nconst NAN$1 = \"NaN\";\nconst INFINITY$1 = \"Infinity\";\nconst QUOTE = \"\\\"\";\n\nconst escapeToChar = new Map([\n [CHAR_DOUBLE_QUOTE, QUOTE],\n [CHAR_BACKSLASH, \"\\\\\"],\n [CHAR_SLASH, \"/\"],\n [CHAR_LOWER_B, \"\\b\"],\n [CHAR_LOWER_N, \"\\n\"],\n [CHAR_LOWER_F, \"\\f\"],\n [CHAR_LOWER_R, \"\\r\"],\n [CHAR_LOWER_T, \"\\t\"]\n]);\n\nconst json5EscapeToChar = new Map([\n ...escapeToChar,\n [CHAR_LOWER_V, \"\\v\"],\n [CHAR_0, \"\\0\"]\n]);\n\nconst charToEscape = new Map([\n [QUOTE, QUOTE],\n [\"\\\\\", \"\\\\\"],\n [\"/\", \"/\"],\n [\"\\b\", \"b\"],\n [\"\\n\", \"n\"],\n [\"\\f\", \"f\"],\n [\"\\r\", \"r\"],\n [\"\\t\", \"t\"]\n]);\n\nconst json5CharToEscape = new Map([\n ...charToEscape,\n [\"\\v\", \"v\"],\n [\"\\0\", \"0\"],\n [\"\\u2028\", \"u2028\"],\n [\"\\u2029\", \"u2029\"]\n]);\n\n/** @type {Map<string,TokenType>} */\nconst knownTokenTypes = new Map([\n [LBRACKET, \"LBracket\"],\n [RBRACKET, \"RBracket\"],\n [LBRACE, \"LBrace\"],\n [RBRACE, \"RBrace\"],\n [COLON, \"Colon\"],\n [COMMA, \"Comma\"],\n [TRUE, \"Boolean\"],\n [FALSE, \"Boolean\"],\n [NULL, \"Null\"]\n]);\n\n/** @type {Map<string,TokenType>} */\nconst knownJSON5TokenTypes = new Map([\n ...knownTokenTypes,\n [NAN$1, \"Number\"],\n [INFINITY$1, \"Number\"]\n]);\n\n// JSON5\nconst json5LineTerminators = new Set([\n CHAR_NEWLINE,\n CHAR_RETURN,\n CHAR_LINE_SEPARATOR,\n CHAR_PARAGRAPH_SEPARATOR\n]);\n\n/**\n * @fileoverview JSON tokenization/parsing errors\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Location} Location */\n/** @typedef {import(\"./typedefs.js\").Token} Token */\n\n//-----------------------------------------------------------------------------\n// Errors\n//-----------------------------------------------------------------------------\n\n/**\n * Base class that attaches location to an error.\n */\nclass ErrorWithLocation extends Error {\n\n /**\n * Creates a new instance.\n * @param {string} message The error message to report. \n * @param {Location} loc The location information for the error.\n */\n constructor(message, { line, column, offset }) {\n super(`${ message } (${ line }:${ column})`);\n\n /**\n * The line on which the error occurred.\n * @type {number}\n */\n this.line = line;\n\n /**\n * The column on which the error occurred.\n * @type {number}\n */\n this.column = column;\n \n /**\n * The index into the string where the error occurred.\n * @type {number}\n */\n this.offset = offset;\n }\n\n}\n\n/**\n * Error thrown when an unexpected character is found during tokenizing.\n */\nclass UnexpectedChar extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {number} unexpected The character that was found.\n * @param {Location} loc The location information for the found character.\n */\n constructor(unexpected, loc) {\n super(`Unexpected character '${ String.fromCharCode(unexpected) }' found.`, loc);\n }\n}\n\n/**\n * Error thrown when an unexpected identifier is found during tokenizing.\n */\nclass UnexpectedIdentifier extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {string} unexpected The character that was found.\n * @param {Location} loc The location information for the found character.\n */\n constructor(unexpected, loc) {\n super(`Unexpected identifier '${ unexpected }' found.`, loc);\n }\n}\n\n/**\n * Error thrown when an unexpected token is found during parsing.\n */\nclass UnexpectedToken extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {Token} token The token that was found. \n */\n constructor(token) {\n super(`Unexpected token ${ token.type } found.`, token.loc.start);\n }\n}\n\n/**\n * Error thrown when the end of input is found where it isn't expected.\n */\nclass UnexpectedEOF extends ErrorWithLocation {\n\n /**\n * Creates a new instance.\n * @param {Location} loc The location information for the found character.\n */\n constructor(loc) {\n super(\"Unexpected end of input found.\", loc);\n }\n}\n\n/*\n * The following is extracted from https://github.com/json5/json5/\n *\n * MIT License\n * \n * Copyright (c) 2012-2018 Aseem Kishore, and others.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\nconst ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE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-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE83\\uDE86-\\uDE89\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]/;\n// eslint-disable-next-line no-misleading-character-class\nconst ID_Continue = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09FC\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0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\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66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\uDC21\\uDC23\\uDC24\\uDC26-\\uDC2A]|\\uD83A[\\uDC00-\\uDCC4\\uDCD0-\\uDCD6\\uDD00-\\uDD4A\\uDD50-\\uDD59]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/;\n\n/**\n * @fileoverview A charactor code reader.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Type Definitions\n//-----------------------------------------------------------------------------\n\n\n//-----------------------------------------------------------------------------\n// Data\n//-----------------------------------------------------------------------------\n\nconst CHAR_CR = 13; // \\r\nconst CHAR_LF = 10; // \\n\n\n//-----------------------------------------------------------------------------\n// CharCodeReader\n//-----------------------------------------------------------------------------\n\n/**\n * A reader that reads character codes from a string.\n */\nclass CharCodeReader {\n\n /**\n * The text to read from.\n * @type {string}\n */\n #text = \"\";\n\n /**\n * The current line number.\n * @type {number}\n */\n #line = 1;\n\n /**\n * The current column number.\n * @type {number}\n */\n #column = 0;\n\n /**\n * The current offset in the text.\n * @type {number}\n */\n #offset = -1;\n\n /**\n * Whether the last character read was a new line.\n * @type {boolean}\n */\n #newLine = false;\n\n /**\n * The last character code read.\n * @type {number}\n */\n #last = -1;\n\n /**\n * Whether the reader has ended.\n * @type {boolean}\n */\n #ended = false;\n\n /**\n * Creates a new instance.\n * @param {string} text The text to read from\n */\n constructor(text) {\n this.#text = text;\n }\n\n /**\n * Ends the reader.\n * @returns {void}\n */\n #end() {\n if (this.#ended) {\n return;\n }\n\n this.#column++;\n this.#offset++;\n this.#last = -1;\n this.#ended = true;\n }\n\n /**\n * Returns the current position of the reader.\n * @returns {Location} An object with line, column, and offset properties.\n */\n locate() {\n return {\n line: this.#line,\n column: this.#column,\n offset: this.#offset\n };\n }\n\n /**\n * Reads the next character code in the text.\n * @returns {number} The next character code, or -1 if there are no more characters.\n */\n next() {\n if (this.#offset >= this.#text.length - 1) {\n this.#end();\n return -1;\n }\n\n this.#offset++;\n const charCode = this.#text.charCodeAt(this.#offset);\n\n if (this.#newLine) {\n this.#line++;\n this.#column = 1;\n this.#newLine = false;\n } else {\n this.#column++;\n }\n\n if (charCode === CHAR_CR) {\n this.#newLine = true;\n\n // if we already see a \\r, just ignore upcoming \\n\n if (this.peek() === CHAR_LF) {\n this.#offset++;\n }\n } else if (charCode === CHAR_LF) {\n this.#newLine = true;\n }\n\n this.#last = charCode;\n\n return charCode;\n }\n\n /**\n * Peeks at the next character code in the text.\n * @returns {number} The next character code, or -1 if there are no more characters.\n */\n peek() {\n if (this.#offset === this.#text.length - 1) {\n return -1;\n }\n\n return this.#text.charCodeAt(this.#offset + 1);\n }\n\n /**\n * Determines if the next character code in the text matches a specific character code.\n * @param {(number) => boolean} fn A function to call on the next character.\n * @returns {boolean} True if the next character code matches, false if not.\n */ \n match(fn) {\n if (fn(this.peek())) {\n this.next();\n return true;\n }\n\n return false;\n }\n\n /**\n * Returns the last character code read.\n * @returns {number} The last character code read.\n */\n current() {\n return this.#last;\n }\n\n\n}\n\n/**\n * @fileoverview JSON tokenizer\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Range} Range */\n/** @typedef {import(\"./typedefs.js\").TokenizeOptions} TokenizeOptions */\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\nconst INFINITY = \"Infinity\";\nconst NAN = \"NaN\";\n\nconst keywordStarts = new Set([CHAR_LOWER_T, CHAR_LOWER_F, CHAR_LOWER_N]);\nconst whitespace = new Set([CHAR_SPACE, CHAR_TAB, CHAR_NEWLINE, CHAR_RETURN]);\nconst json5Whitespace = new Set([\n ...whitespace,\n CHAR_VTAB,\n CHAR_FORM_FEED,\n CHAR_NBSP,\n CHAR_LINE_SEPARATOR,\n CHAR_PARAGRAPH_SEPARATOR,\n CHAR_BOM,\n CHAR_NON_BREAKING_SPACE,\n CHAR_EN_QUAD,\n CHAR_EM_QUAD,\n CHAR_EN_SPACE,\n CHAR_EM_SPACE,\n CHAR_THREE_PER_EM_SPACE,\n CHAR_FOUR_PER_EM_SPACE,\n CHAR_SIX_PER_EM_SPACE,\n CHAR_FIGURE_SPACE,\n CHAR_PUNCTUATION_SPACE,\n CHAR_THIN_SPACE,\n CHAR_HAIR_SPACE,\n CHAR_NARROW_NO_BREAK_SPACE,\n CHAR_MEDIUM_MATHEMATICAL_SPACE,\n CHAR_IDEOGRAPHIC_SPACE,\n]);\n\n\n/** @type {TokenizeOptions} */\nconst DEFAULT_OPTIONS$1 = {\n mode: \"json\",\n ranges: false\n};\n\nconst jsonKeywords = new Set([\"true\", \"false\", \"null\"]);\n\nconst tt = {\n EOF: 0,\n Number: 1,\n String: 2,\n Boolean: 3,\n Null: 4,\n NaN: 5,\n Infinity: 6,\n Identifier: 7,\n Colon: 20,\n LBrace: 21,\n RBrace: 22,\n LBracket: 23,\n RBracket: 24,\n Comma: 25,\n LineComment: 40,\n BlockComment: 41\n};\n\n\n// #region Helpers\n\n\n/**\n * Determines if a given character is a decimal digit.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a digit.\n */\nfunction isDigit(c) {\n return c >= CHAR_0 && c <= CHAR_9;\n}\n\n/**\n * Determines if a given character is a hexadecimal digit.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a hexadecimal digit.\n */\nfunction isHexDigit(c) {\n return isDigit(c) ||\n c >= CHAR_UPPER_A && c <= CHAR_UPPER_F ||\n c >= CHAR_LOWER_A && c <= CHAR_LOWER_F;\n}\n\n/**\n * Determines if a given character is a positive digit (1-9).\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a positive digit.\n */\nfunction isPositiveDigit(c) {\n return c >= CHAR_1 && c <= CHAR_9;\n}\n\n/**\n * Determines if a given character is the start of a keyword.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a keyword.\n */\nfunction isKeywordStart(c) {\n return keywordStarts.has(c);\n}\n\n/**\n * Determines if a given character is the start of a number.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a number.\n */\nfunction isNumberStart(c) {\n return isDigit(c) || c === CHAR_DOT || c === CHAR_MINUS;\n}\n\n/**\n * Determines if a given character is the start of a JSON5 number.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is the start of a JSON5 number.\n */\nfunction isJSON5NumberStart(c) {\n return isNumberStart(c) || c === CHAR_PLUS;\n}\n\n/**\n * Determines if a given character is the start of a string.\n * @param {number} c The character to check.\n * @param {boolean} json5 `true` if JSON5 mode is enabled.\n * @returns {boolean} `true` if the character is the start of a string.\n */\nfunction isStringStart(c, json5) {\n return c === CHAR_DOUBLE_QUOTE || (json5 && c === CHAR_SINGLE_QUOTE);\n}\n\n/**\n * Tests that a given character is a valid first character of a\n * JSON5 identifier\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a valid first character. \n */\nfunction isJSON5IdentifierStart(c) {\n\n // test simple cases first\n\n if (c === CHAR_DOLLAR || c === CHAR_UNDERSCORE || c === CHAR_BACKSLASH) {\n return true;\n }\n\n if (c >= CHAR_LOWER_A && c <= CHAR_LOWER_Z || c >= CHAR_UPPER_A && c <= CHAR_UPPER_Z) {\n return true;\n }\n\n if (c === 0x200C || c === 0x200D) {\n return true;\n }\n \n const ct = String.fromCharCode(c);\n return ID_Start.test(ct);\n}\n\n/**\n * Tests that a given character is a valid part of a JSON5 identifier.\n * @param {number} c The character to check.\n * @returns {boolean} `true` if the character is a valid part of an identifier.\n */\nfunction isJSON5IdentifierPart(c) {\n\n // fast path for simple cases\n if (isJSON5IdentifierStart(c) || isDigit(c)) {\n return true;\n }\n\n const ct = String.fromCharCode(c);\n return ID_Continue.test(ct);\n}\n\n\n// #endregion\n\nclass Tokenizer {\n\n /**\n * Options for the tokenizer.\n * @type {TokenizeOptions}\n */\n #options;\n\n /**\n * The source text to tokenize.\n * @type {string}\n */\n #text;\n\n /**\n * The reader for the source text.\n * @type {CharCodeReader}\n */\n #reader;\n\n /**\n * Indicates if the tokenizer is in JSON5 mode.\n * @type {boolean}\n */\n #json5;\n\n /**\n * Indicates if comments are allowed.\n * @type {boolean}\n */\n #allowComments;\n\n /**\n * Indicates if ranges should be included in the tokens.\n * @type {boolean}\n */\n #ranges;\n\n /**\n * The last token type read.\n * @type {Token}\n */\n #token;\n\n /**\n * Determines if a character is an escaped character.\n * @type {(c:number) => boolean}\n */\n #isEscapedCharacter;\n\n /**\n * Determines if a character is a JSON5 line terminator.\n * @type {(c:number) => boolean}\n */\n #isJSON5LineTerminator;\n\n\n /**\n * Determines if a character is a JSON5 hex escape.\n * @type {(c:number) => boolean}\n */\n #isJSON5HexEscape;\n\n /**\n * Determines if a character is whitespace.\n * @type {(c:number) => boolean}\n */\n #isWhitespace;\n\n /**\n * Creates a new instance of the tokenizer.\n * @param {string} text The source text\n * @param {TokenizeOptions} [options] Options for the tokenizer.\n */ \n constructor(text, options) {\n this.#text = text;\n this.#options = {\n ...DEFAULT_OPTIONS$1,\n ...options\n };\n\n this.#reader = new CharCodeReader(text);\n this.#json5 = this.#options.mode === \"json5\";\n this.#allowComments = this.#options.mode !== \"json\";\n this.#ranges = this.#options.ranges;\n\n // TODO: Clean this up\n this.#isEscapedCharacter = this.#json5 ? json5EscapeToChar.has.bind(json5EscapeToChar) : escapeToChar.has.bind(escapeToChar);\n this.#isJSON5LineTerminator = this.#json5 ? json5LineTerminators.has.bind(json5LineTerminators) : () => false;\n this.#isJSON5HexEscape = this.#json5 ? c => c === CHAR_LOWER_X : () => false;\n this.#isWhitespace = this.#json5 ? json5Whitespace.has.bind(json5Whitespace) : whitespace.has.bind(whitespace);\n }\n\n // #region Errors\n\n /**\n * Convenience function for throwing unexpected character errors.\n * @param {number} c The unexpected character.\n * @param {Location} [loc] The location of the unexpected character.\n * @returns {never}\n * @throws {UnexpectedChar} always.\n */\n #unexpected(c, loc = this.#reader.locate()) {\n throw new UnexpectedChar(c, loc);\n }\n\n /**\n * Convenience function for throwing unexpected identifier errors.\n * @param {string} identifier The unexpected identifier.\n * @param {Location} [loc] The location of the unexpected identifier.\n * @returns {never}\n * @throws {UnexpectedIdentifier} always.\n */\n #unexpectedIdentifier(identifier, loc = this.#reader.locate()) {\n throw new UnexpectedIdentifier(identifier, loc);\n }\n\n /**\n * Convenience function for throwing unexpected EOF errors.\n * @returns {never}\n * @throws {UnexpectedEOF} always.\n */\n #unexpectedEOF() {\n throw new UnexpectedEOF(this.#reader.locate());\n }\n\n // #endregion\n\n // #region Helpers\n\n /**\n * Creates a new token.\n * @param {TokenType} tokenType The type of token to create.\n * @param {number} length The length of the token.\n * @param {Location} startLoc The start location for the token.\n * @param {Location} [endLoc] The end location for the token.\n * @returns {Token} The token.\n */\n #createToken(tokenType, length, startLoc, endLoc) {\n\n const endOffset = startLoc.offset + length;\n\n let range = this.#options.ranges ? {\n range: /** @type {Range} */ ([startLoc.offset, endOffset])\n } : undefined;\n\n return {\n type: tokenType,\n loc: {\n start: startLoc,\n end: endLoc || {\n line: startLoc.line,\n column: startLoc.column + length,\n offset: endOffset\n }\n },\n ...range\n }; \n }\n\n /**\n * Reads in a specific number of hex digits.\n * @param {number} count The number of hex digits to read.\n * @returns {string} The hex digits read.\n */\n #readHexDigits(count) {\n let value = \"\";\n let c;\n\n for (let i = 0; i < count; i++) {\n c = this.#reader.peek();\n if (isHexDigit(c)) {\n this.#reader.next();\n value += String.fromCharCode(c);\n continue;\n }\n\n this.#unexpected(c);\n }\n\n return value;\n }\n\n /**\n * Reads in a JSON5 identifier. Also used for JSON but we validate\n * the identifier later.\n * @param {number} c The first character of the identifier.\n * @returns {string} The identifier read.\n * @throws {UnexpectedChar} when the identifier cannot be read.\n */\n #readIdentifier(c) {\n let value = \"\";\n\n do {\n\n value += String.fromCharCode(c);\n\n if (c === CHAR_BACKSLASH) {\n\n c = this.#reader.next();\n\n if (c !== CHAR_LOWER_U) {\n this.#unexpected(c);\n }\n\n value += String.fromCharCode(c);\n\n const hexDigits = this.#readHexDigits(4);\n\n // check for a valid character code\n const charCode = parseInt(hexDigits, 16);\n\n if (value.length === 2 && !isJSON5IdentifierStart(charCode)) {\n const loc = this.#reader.locate();\n this.#unexpected(CHAR_BACKSLASH, { line: loc.line, column: loc.column - 5, offset: loc.offset - 5 });\n } else if (!isJSON5IdentifierPart(charCode)) {\n const loc = this.#reader.locate();\n this.#unexpected(charCode, { line: loc.line, column: loc.column - 5, offset: loc.offset - 5 });\n }\n\n value += hexDigits;\n }\n\n c = this.#reader.peek();\n\n if (!isJSON5IdentifierPart(c)) {\n break;\n }\n\n this.#reader.next();\n\n } while (true); // eslint-disable-line no-constant-condition\n\n return value;\n }\n\n /**\n * Reads in a string. Works for both JSON and JSON5.\n * @param {number} c The first character of the string (either \" or ').\n * @returns {number} The length of the string.\n * @throws {UnexpectedChar} when the string cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the string is finalized.\n */\n #readString(c) {\n \n const delimiter = c;\n let length = 1;\n c = this.#reader.peek();\n\n while (c !== -1 && c !== delimiter) {\n\n this.#reader.next();\n length++;\n\n // escapes\n if (c === CHAR_BACKSLASH) {\n c = this.#reader.peek();\n\n if (this.#isEscapedCharacter(c) || this.#isJSON5LineTerminator(c)) {\n this.#reader.next();\n length++;\n } else if (c === CHAR_LOWER_U) {\n this.#reader.next();\n length++;\n\n const result = this.#readHexDigits(4);\n length += result.length;\n } else if (this.#isJSON5HexEscape(c)) {\n this.#reader.next();\n length++;\n\n // hex escapes: \\xHH\n const result = this.#readHexDigits(2);\n length += result.length;\n } else if (this.#json5) { // JSON doesn't allow anything else\n this.#reader.next();\n length++;\n } else {\n this.#unexpected(c);\n }\n }\n\n c = this.#reader.peek();\n }\n\n if (c === -1) {\n this.#reader.next();\n this.#unexpectedEOF();\n }\n\n // c is the delimiter\n this.#reader.next();\n length++;\n\n return length;\n \n \n }\n\n /**\n * Reads a number. Works for both JSON and JSON5.\n * @param {number} c The first character of the number.\n * @returns {number} The length of the number.\n * @throws {UnexpectedChar} when the number cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the number is finalized.\n */\n #readNumber(c) {\n \n // we've already read the first character\n let length = 1;\n\n // JSON number may start with a minus but not a plus\n // JSON5 allows a plus.\n if (c === CHAR_MINUS || this.#json5 && c === CHAR_PLUS) {\n \n c = this.#reader.peek();\n \n /*\n * JSON5 allows Infinity or NaN preceded by a sign.\n * This blocks handles +Infinity, -Infinity, +NaN, and -NaN.\n * Standalone Infinity and NaN are handled in `readJSON5Identifier()`\n */\n if (this.#json5) {\n\n if (c === CHAR_UPPER_I || c === CHAR_UPPER_N) {\n this.#reader.next();\n const identifier = this.#readIdentifier(c);\n\n if (identifier !== INFINITY && identifier !== NAN) {\n this.#unexpected(c);\n }\n\n return length + identifier.length;\n }\n }\n\n // Next digit cannot be zero\n if (!isDigit(c)) {\n this.#unexpected(c);\n }\n\n // if we made it here, we need to continue on, so register the character\n this.#reader.next();\n length++;\n }\n\n /*\n * In JSON, a zero must be followed by a decimal point or nothing.\n * In JSON5, a zero can additionally be followed by an `x` indicating\n * that it's a hexadecimal number.\n */\n if (c === CHAR_0) {\n\n // c = this.#reader.next();\n // length++;\n c = this.#reader.peek();\n\n // check for a hex number\n if (this.#json5 && (c === CHAR_LOWER_X || c === CHAR_UPPER_X)) {\n\n this.#reader.next();\n length++;\n\n c = this.#reader.peek();\n\n if (!isHexDigit(c)) {\n this.#reader.next();\n this.#unexpected(c);\n }\n\n do {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n } while (isHexDigit(c));\n\n } else if (isDigit(c)) {\n this.#unexpected(c);\n }\n\n } else {\n\n // JSON5 allows leading decimal points\n if (!this.#json5 || c !== CHAR_DOT) {\n if (!isPositiveDigit(c)) {\n this.#unexpected(c);\n }\n\n c = this.#reader.peek();\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n }\n }\n\n /*\n * In JSON, a decimal point must be followed by at least one digit.\n * In JSON5, a decimal point need not be followed by any digits.\n */\n if (c === CHAR_DOT) {\n \n let digitCount = -1;\n this.#reader.next();\n length++;\n digitCount++;\n\n c = this.#reader.peek();\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n digitCount++;\n c = this.#reader.peek();\n }\n\n if (!this.#json5 && digitCount === 0) {\n this.#reader.next();\n if (c) {\n this.#unexpected(c);\n } else {\n this.#unexpectedEOF();\n }\n }\n }\n\n // Exponent is always last\n if (c === CHAR_LOWER_E || c === CHAR_UPPER_E) {\n\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n\n if (c === CHAR_PLUS || c === CHAR_MINUS) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n\n /*\n * Must always have a digit in this position to avoid:\n * 5e\n * 12E+\n * 42e-\n */\n if (c === -1) {\n this.#reader.next();\n this.#unexpectedEOF();\n }\n\n if (!isDigit(c)) {\n this.#reader.next();\n this.#unexpected(c);\n }\n\n while (isDigit(c)) {\n this.#reader.next();\n length++;\n c = this.#reader.peek();\n }\n }\n\n return length;\n }\n\n /**\n * Reads a comment. Works for both JSON and JSON5.\n * @param {number} c The first character of the comment.\n * @returns {{length: number, multiline: boolean}} The length of the comment, and whether the comment is multi-line.\n * @throws {UnexpectedChar} when the comment cannot be read.\n * @throws {UnexpectedEOF} when EOF is reached before the comment is finalized.\n */ \n #readComment(c) {\n \n let length = 1;\n\n // next character determines single- or multi-line\n c = this.#reader.peek();\n\n // single-line comments\n if (c === CHAR_SLASH) {\n \n do {\n this.#reader.next();\n length += 1;\n c = this.#reader.peek();\n } while (c > -1 && c !== CHAR_RETURN && c !== CHAR_NEWLINE);\n\n return { length, multiline: false };\n }\n\n // multi-line comments\n if (c === CHAR_STAR) {\n\n this.#reader.next();\n length += 1;\n\n while (c > -1) {\n c = this.#reader.peek();\n\n // check for end of comment\n if (c === CHAR_STAR) {\n this.#reader.next();\n length += 1;\n c = this.#reader.peek();\n \n //end of comment\n if (c === CHAR_SLASH) {\n this.#reader.next();\n length += 1;\n\n return { length, multiline: true };\n }\n } else {\n this.#reader.next();\n length += 1;\n }\n }\n\n this.#reader.next();\n this.#unexpectedEOF();\n \n }\n\n // if we've made it here, there's an invalid character\n this.#reader.next();\n this.#unexpected(c); \n }\n // #endregion\n\n /**\n * Returns the next token in the source text.\n * @returns {number} The code for the next token.\n */\n next() {\n\n let c = this.#reader.next();\n\n while (this.#isWhitespace(c)) {\n c = this.#reader.next();\n }\n\n if (c === -1) {\n return tt.EOF;\n }\n\n const start = this.#reader.locate();\n const ct = String.fromCharCode(c);\n\n // check for JSON5 syntax only\n if (this.#json5) {\n \n if (knownJSON5TokenTypes.has(ct)) {\n this.#token = this.#createToken(knownJSON5TokenTypes.get(ct), 1, start);\n } else if (isJSON5IdentifierStart(c)) {\n const value = this.#readIdentifier(c);\n\n if (knownJSON5TokenTypes.has(value)) {\n this.#token = this.#createToken(knownJSON5TokenTypes.get(value), value.length, start);\n } else {\n this.#token = this.#createToken(\"Identifier\", value.length, start);\n }\n } else if (isJSON5NumberStart(c)) {\n const result = this.#readNumber(c);\n this.#token = this.#createToken(\"Number\", result, start);\n } else if (isStringStart(c, this.#json5)) {\n const result = this.#readString(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(\"String\", result, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else if (c === CHAR_SLASH && this.#allowComments) {\n const result = this.#readComment(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(!result.multiline ? \"LineComment\" : \"BlockComment\", result.length, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else {\n this.#unexpected(c);\n }\n\n } else {\n\n // check for JSON/JSONC syntax only\n if (knownTokenTypes.has(ct)) {\n this.#token = this.#createToken(knownTokenTypes.get(ct), 1, start);\n } else if (isKeywordStart(c)) {\n const value = this.#readIdentifier(c);\n\n if (!jsonKeywords.has(value)) {\n this.#unexpectedIdentifier(value, start);\n }\n\n this.#token = this.#createToken(knownTokenTypes.get(value), value.length, start);\n } else if (isNumberStart(c)) {\n const result = this.#readNumber(c);\n this.#token = this.#createToken(\"Number\", result, start);\n } else if (isStringStart(c, this.#json5)) {\n const result = this.#readString(c);\n this.#token = this.#createToken(\"String\", result, start);\n } else if (c === CHAR_SLASH && this.#allowComments) {\n const result = this.#readComment(c);\n const lastCharLoc = this.#reader.locate();\n this.#token = this.#createToken(!result.multiline ? \"LineComment\" : \"BlockComment\", result.length, start, {\n line: lastCharLoc.line,\n column: lastCharLoc.column + 1,\n offset: lastCharLoc.offset + 1\n });\n } else {\n this.#unexpected(c);\n }\n }\n return tt[this.#token.type];\n }\n\n /**\n * Returns the current token in the source text.\n * @returns {Token} The current token.\n */\n get token() {\n return this.#token;\n }\n}\n\n//-----------------------------------------------------------------------------\n// Main\n//-----------------------------------------------------------------------------\n\n/**\n * Creates an iterator over the tokens representing the source text.\n * @param {string} text The source text to tokenize.\n * @param {TokenizeOptions} [options] Options for doing the tokenization.\n * @returns {Array<Token>} An iterator over the tokens. \n */\nfunction tokenize(text, options) {\n\n const tokenizer = new Tokenizer(text, options);\n const tokens = [];\n\n while (tokenizer.next() !== tt.EOF) {\n tokens.push(tokenizer.token);\n }\n\n return tokens;\n\n}\n\n/**\n * @fileoverview JSON AST types\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").LocationRange} LocationRange */\n/** @typedef {import(\"./typedefs.js\").NodeParts} NodeParts */\n/** @typedef {import(\"./typedefs.js\").DocumentNode} DocumentNode */\n/** @typedef {import(\"./typedefs.js\").StringNode} StringNode */\n/** @typedef {import(\"./typedefs.js\").NumberNode} NumberNode */\n/** @typedef {import(\"./typedefs.js\").BooleanNode} BooleanNode */\n/** @typedef {import(\"./typedefs.js\").MemberNode} MemberNode */\n/** @typedef {import(\"./typedefs.js\").ObjectNode} ObjectNode */\n/** @typedef {import(\"./typedefs.js\").ElementNode} ElementNode */\n/** @typedef {import(\"./typedefs.js\").ArrayNode} ArrayNode */\n/** @typedef {import(\"./typedefs.js\").NullNode} NullNode */\n/** @typedef {import(\"./typedefs.js\").ValueNode} ValueNode */\n/** @typedef {import(\"./typedefs.js\").IdentifierNode} IdentifierNode */\n/** @typedef {import(\"./typedefs.js\").NaNNode} NaNNode */\n/** @typedef {import(\"./typedefs.js\").InfinityNode} InfinityNode */\n/** @typedef {import(\"./typedefs.js\").Sign} Sign */\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nconst types = {\n\n /**\n * Creates a document node.\n * @param {ValueNode} body The body of the document.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {DocumentNode} The document node.\n */\n document(body, parts = {}) {\n return {\n type: \"Document\",\n body,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a string node.\n * @param {string} value The value for the string.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {StringNode} The string node.\n */\n string(value, parts = {}) {\n return {\n type: \"String\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a number node.\n * @param {number} value The value for the number.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {NumberNode} The number node.\n */\n number(value, parts = {}) {\n return {\n type: \"Number\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a boolean node.\n * @param {boolean} value The value for the boolean.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {BooleanNode} The boolean node.\n */\n boolean(value, parts = {}) {\n return {\n type: \"Boolean\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a null node.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {NullNode} The null node.\n */\n null(parts = {}) {\n return {\n type: \"Null\",\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an array node.\n * @param {Array<ElementNode>} elements The elements to add.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ArrayNode} The array node.\n */\n array(elements, parts = {}) {\n return {\n type: \"Array\",\n elements,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an element node.\n * @param {ValueNode} value The value for the element.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ElementNode} The element node.\n */\n element(value, parts = {}) {\n return {\n type: \"Element\",\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an object node.\n * @param {Array<MemberNode>} members The members to add.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {ObjectNode} The object node.\n */\n object(members, parts = {}) {\n return {\n type: \"Object\",\n members,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a member node.\n * @param {StringNode|IdentifierNode} name The name for the member.\n * @param {ValueNode} value The value for the member.\n * @param {NodeParts} parts Additional properties for the node. \n * @returns {MemberNode} The member node.\n */\n member(name, value, parts = {}) {\n return {\n type: \"Member\",\n name,\n value,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an identifier node.\n * @param {string} name The name for the identifier.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {IdentifierNode} The identifier node.\n */\n identifier(name, parts = {}) {\n return {\n type: \"Identifier\",\n name,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates a NaN node.\n * @param {Sign} sign The sign for the Infinity.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {NaNNode} The NaN node.\n */ \n nan(sign = \"\", parts = {}) {\n return {\n type: \"NaN\",\n sign,\n loc: parts.loc,\n ...parts\n };\n },\n\n /**\n * Creates an Infinity node.\n * @param {Sign} sign The sign for the Infinity.\n * @param {NodeParts} parts Additional properties for the node.\n * @returns {InfinityNode} The Infinity node.\n */\n infinity(sign = \"\", parts = {}) {\n return {\n type: \"Infinity\",\n sign,\n loc: parts.loc,\n ...parts\n };\n },\n\n};\n\n/**\n * @fileoverview JSON parser\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").Node} Node */\n/** @typedef {import(\"./typedefs.js\").Mode} Mode */\n/** @typedef {import(\"./typedefs.js\").ParseOptions} ParseOptions */\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/** @type {ParseOptions} */\nconst DEFAULT_OPTIONS = {\n mode: \"json\",\n ranges: false,\n tokens: false,\n allowTrailingCommas: false\n};\n\nconst UNICODE_SEQUENCE = /\\\\u[\\da-fA-F]{4}/gu;\n\n/**\n * Normalizes a JSON5 identifier by converting Unicode escape sequences into\n * their corresponding characters.\n * @param {string} identifier The identifier to normalize.\n * @returns {string} The normalized identifier.\n */\nfunction normalizeIdentifier(identifier) {\n return identifier.replace(UNICODE_SEQUENCE, unicodeEscape => {\n return String.fromCharCode(parseInt(unicodeEscape.slice(2), 16));\n });\n}\n\n/**\n * Calculates the location at the end of the given text.\n * @param {string} text The text to calculate the end location for.\n * @returns {Location} The location at the end of the text.\n */\nfunction getEndLocation(text) {\n let line = 1;\n let column = 1;\n \n for (let i = 0; i < text.length; i++) {\n const char = text[i];\n if (char === \"\\n\") {\n line++;\n column = 1;\n } else if (char === \"\\r\") {\n // Handle \\r\\n as a single line ending\n if (text[i + 1] === \"\\n\") {\n i++; // Skip the \\n\n }\n line++;\n column = 1;\n } else {\n column++;\n }\n }\n \n return {\n line,\n column,\n offset: text.length\n };\n}\n\n/**\n * Converts a JSON-encoded string into a JavaScript string, interpreting each\n * escape sequence.\n * @param {string} value The text for the token.\n * @param {Token} token The string token to convert into a JavaScript string.\n * @param {boolean} json5 `true` if parsing JSON5, `false` otherwise.\n * @returns {string} A JavaScript string.\n */\nfunction getStringValue(value, token, json5 = false) {\n \n let result = \"\";\n let escapeIndex = value.indexOf(\"\\\\\");\n let lastIndex = 0;\n\n // While there are escapes, interpret them to build up the result\n while (escapeIndex >= 0) {\n\n // append the text that happened before the escape\n result += value.slice(lastIndex, escapeIndex);\n\n // get the character immediately after the \\\n const escapeChar = value.charAt(escapeIndex + 1);\n const escapeCharCode = escapeChar.charCodeAt(0);\n \n // check for the non-Unicode escape sequences first\n if (json5 && json5EscapeToChar.has(escapeCharCode)) {\n result += json5EscapeToChar.get(escapeCharCode);\n lastIndex = escapeIndex + 2;\n } else if (escapeToChar.has(escapeCharCode)) {\n result += escapeToChar.get(escapeCharCode);\n lastIndex = escapeIndex + 2;\n } else if (escapeChar === \"u\") {\n const hexCode = value.slice(escapeIndex + 2, escapeIndex + 6);\n if (hexCode.length < 4 || /[^0-9a-f]/i.test(hexCode)) {\n throw new ErrorWithLocation(\n `Invalid unicode escape \\\\u${ hexCode}.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n\n result += String.fromCharCode(parseInt(hexCode, 16));\n lastIndex = escapeIndex + 6;\n } else if (json5 && escapeChar === \"x\") {\n const hexCode = value.slice(escapeIndex + 2, escapeIndex + 4);\n if (hexCode.length < 2 || /[^0-9a-f]/i.test(hexCode)) {\n throw new ErrorWithLocation(\n `Invalid hex escape \\\\x${ hexCode}.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n\n result += String.fromCharCode(parseInt(hexCode, 16));\n lastIndex = escapeIndex + 4;\n } else if (json5 && json5LineTerminators.has(escapeCharCode)) {\n lastIndex = escapeIndex + 2;\n\n // we also need to skip \\n after a \\r\n if (escapeChar === \"\\r\" && value.charAt(lastIndex) === \"\\n\") {\n lastIndex++;\n }\n \n } else {\n // all characters can be escaped in JSON5\n if (json5) {\n result += escapeChar;\n lastIndex = escapeIndex + 2;\n } else {\n throw new ErrorWithLocation(\n `Invalid escape \\\\${ escapeChar }.`,\n {\n line: token.loc.start.line,\n column: token.loc.start.column + escapeIndex,\n offset: token.loc.start.offset + escapeIndex\n }\n );\n }\n }\n\n // find the next escape sequence\n escapeIndex = value.indexOf(\"\\\\\", lastIndex);\n }\n\n // get the last segment of the string value\n result += value.slice(lastIndex);\n\n return result;\n}\n\n/**\n * Gets the JavaScript value represented by a JSON token.\n * @param {string} value The text value of the token.\n * @param {Token} token The JSON token to get a value for.\n * @param {boolean} json5 `true` if parsing JSON5, `false` otherwise.\n * @returns {string|boolean|number} A number, string, or boolean.\n * @throws {TypeError} If an unknown token type is found. \n */\nfunction getLiteralValue(value, token, json5 = false) {\n switch (token.type) {\n case \"Boolean\":\n return value === \"true\";\n \n case \"Number\":\n if (json5) {\n\n /*\n * Numbers like -0x1 are converted to NaN by Number(), so we need\n * to handle them separately. Rather than checking for -0x, we can\n * just check if the first character is a minus sign. The same for\n * checking for +0x.\n */\n\n if (value.charCodeAt(0) === 45) { // 45 is the char code for '-'\n return -Number(value.slice(1));\n }\n\n if (value.charCodeAt(0) === 43) { // 43 is the char code for '+'\n return Number(value.slice(1));\n }\n }\n return Number(value);\n\n case \"String\":\n return getStringValue(value.slice(1, -1), token, json5);\n\n default:\n throw new TypeError(`Unknown token type \"${token.type}.`);\n }\n}\n\n//-----------------------------------------------------------------------------\n// Main Function\n//-----------------------------------------------------------------------------\n\n/**\n * \n * @param {string} text The text to parse.\n * @param {ParseOptions} [options] The options object.\n * @returns {DocumentNode} The AST representing the parsed JSON.\n * @throws {Error} When there is a parsing error. \n */\nfunction parse(text, options) {\n\n options = Object.freeze({\n ...DEFAULT_OPTIONS,\n ...options\n });\n\n const tokens = [];\n const tokenizer = new Tokenizer(text, {\n mode: options.mode,\n ranges: options.ranges\n });\n\n const json5 = options.mode === \"json5\";\n const allowTrailingCommas = options.allowTrailingCommas || json5;\n\n /**\n * Returns the next token knowing there are no comments.\n * @returns {number} The next token type or 0 if no next token.\n */\n function nextNoComments() {\n const nextType = tokenizer.next();\n\n if (nextType && options.tokens) {\n tokens.push(tokenizer.token);\n }\n return nextType;\n }\n \n /**\n * Returns the next token knowing there are comments to skip.\n * @returns {number} The next token type or 0 if no next token.\n */\n function nextSkipComments() {\n const nextType = tokenizer.next();\n if (nextType && options.tokens) {\n tokens.push(tokenizer.token);\n }\n\n if (nextType >= tt.LineComment) {\n return nextSkipComments();\n }\n\n return nextType;\n\n }\n\n // determine correct way to evaluate tokens based on presence of comments\n const next = options.mode === \"json\" ? nextNoComments : nextSkipComments;\n\n /**\n * Asserts a token has the given type.\n * @param {number} token The token to check.\n * @param {number} type The token type.\n * @throws {UnexpectedToken} If the token type isn't expected.\n * @returns {void}\n */\n function assertTokenType(token, type) {\n if (token !== type) {\n throw new UnexpectedToken(tokenizer.token);\n }\n }\n\n /**\n * Asserts a token has one of the given types.\n * @param {number} token The token to check.\n * @param {number[]} types The token types.\n * @returns {void}\n * @throws {UnexpectedToken} If the token type isn't expected.\n */ \n function assertTokenTypes(token, types) {\n if (!types.includes(token)) {\n throw new UnexpectedToken(tokenizer.token);\n }\n }\n\n /**\n * Creates a range only if ranges are specified.\n * @param {Location} start The start offset for the range.\n * @param {Location} end The end offset for the range.\n * @returns {{range:[number,number]}|undefined} An object with a \n */\n function createRange(start, end) {\n // @ts-ignore tsc incorrect - options might be undefined\n return options.ranges ? {\n range: [start.offset, end.offset]\n } : undefined;\n }\n\n /**\n * Creates a node for a string, boolean, or number.\n * @param {number} tokenType The token representing the literal. \n * @returns {StringNode|NumberNode|BooleanNode} The node representing\n * the value.\n */\n function createLiteralNode(tokenType) {\n const token = tokenizer.token;\n const range = createRange(token.loc.start, token.loc.end);\n const value = getLiteralValue(\n text.slice(token.loc.start.offset, token.loc.end.offset),\n token,\n json5\n );\n const loc = {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n };\n const parts = { loc, ...range };\n\n switch (tokenType) {\n case tt.String:\n return types.string(/** @type {string} */ (value), parts);\n\n case tt.Number:\n return types.number(/** @type {number} */ (value), parts);\n \n case tt.Boolean:\n return types.boolean(/** @type {boolean} */ (value), parts);\n\n default:\n throw new TypeError(`Unknown token type ${token.type}.`);\n }\n }\n\n /**\n * Creates a node for a JSON5 identifier.\n * @param {Token} token The token representing the identifer. \n * @returns {NaNNode|InfinityNode|IdentifierNode} The node representing\n * the value.\n */\n function createJSON5IdentifierNode(token) {\n const range = createRange(token.loc.start, token.loc.end);\n const identifier = text.slice(token.loc.start.offset, token.loc.end.offset);\n const loc = {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n };\n const parts = { loc, ...range };\n\n // Check for NaN or Infinity\n if (token.type !== \"Identifier\") {\n\n let sign = \"\";\n\n // check if the first character in the token is a plus or minus\n if (identifier[0] === \"+\" || identifier[0] === \"-\") {\n sign = identifier[0];\n }\n\n // check if the token is NaN or Infinity\n return types[identifier.includes(\"NaN\") ? \"nan\" : \"infinity\"](/** @type {Sign} */ (sign), parts);\n }\n return types.identifier(normalizeIdentifier(identifier), parts);\n }\n\n /**\n * Creates a node for a null.\n * @param {Token} token The token representing null. \n * @returns {NullNode} The node representing null.\n */\n function createNullNode(token) {\n const range = createRange(token.loc.start, token.loc.end);\n\n return types.null({\n loc: {\n start: {\n ...token.loc.start\n },\n end: {\n ...token.loc.end\n }\n },\n ...range\n });\n }\n\n\n /**\n * Parses a property in an object.\n * @param {number} tokenType The token representing the property.\n * @returns {MemberNode} The node representing the property.\n * @throws {UnexpectedToken} When an unexpected token is found.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n */\n function parseProperty(tokenType) {\n\n if (json5) {\n assertTokenTypes(tokenType, [tt.String, tt.Identifier, tt.Number]);\n } else {\n assertTokenType(tokenType, tt.String);\n }\n\n const token = tokenizer.token;\n\n // check for -NaN, +NaN, -Infinity, +Infinity, and any number\n if (json5 && tokenType === tt.Number && /[+\\-0-9]/.test(text[token.loc.start.offset])) {\n throw new UnexpectedToken(token);\n }\n\n // TODO: Clean this up a bit\n let key = tokenType === tt.String\n ? /** @type {StringNode} */ (createLiteralNode(tokenType))\n : /** @type {IdentifierNode|NaNNode|InfinityNode} */ (createJSON5IdentifierNode(token));\n\n // in JSON5, need to check for NaN and Infinity and create identifier nodes\n if (json5 && (key.type === \"NaN\" || key.type === \"Infinity\")) {\n\n // NaN and Infinity cannot be signed and be a property key\n if (key.sign !== \"\") {\n throw new UnexpectedToken(tokenizer.token);\n }\n\n key = types.identifier(key.type, { loc: key.loc, ...createRange(key.loc.start, key.loc.end) });\n }\n\n tokenType = next();\n assertTokenType(tokenType, tt.Colon);\n const value = parseValue();\n const range = createRange(key.loc.start, value.loc.end);\n\n return types.member(\n /** @type {StringNode|IdentifierNode} */ (key),\n /** @type {ValueNode} */ (value),\n {\n loc: {\n start: {\n ...key.loc.start\n },\n end: {\n ...value.loc.end\n }\n },\n ...range\n }\n );\n }\n\n /**\n * Parses an object literal.\n * @param {number} firstTokenType The first token type in the object.\n * @returns {ObjectNode} The object node.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n * @throws {UnexpectedToken} When an unexpected token is found.\n */\n function parseObject(firstTokenType) {\n\n // The first token must be a { or else it's an error\n assertTokenType(firstTokenType, tt.LBrace);\n\n const firstToken = tokenizer.token;\n const members = [];\n let tokenType = next();\n\n if (tokenType !== tt.RBrace) {\n do {\n \n // add the value into the array\n members.push(parseProperty(tokenType));\n \n tokenType = next();\n\n if (!tokenType) {\n throw new UnexpectedEOF(members[members.length-1].loc.end);\n }\n \n if (tokenType === tt.Comma) {\n tokenType = next();\n\n /*\n * Trailing commas.\n * So we need to check if the token is a comma,\n * and if so, then we need to check if the next\n * token is a RBrace. If it is, then we need to\n * break out of the loop.\n */\n if (allowTrailingCommas && tokenType === tt.RBrace) {\n break;\n } \n } else {\n break;\n }\n } while (tokenType);\n }\n\n assertTokenType(tokenType, tt.RBrace);\n const lastToken = tokenizer.token;\n const range = createRange(firstToken.loc.start, lastToken.loc.end);\n\n return types.object(members, {\n loc: {\n start: {\n ...firstToken.loc.start\n },\n end: {\n ...lastToken.loc.end\n }\n },\n ...range\n });\n\n }\n\n /**\n * Parses an array literal.\n * @param {number} firstTokenType The first token in the array.\n * @returns {ArrayNode} The array node.\n * @throws {UnexpectedToken} When an unexpected token is found.\n * @throws {UnexpectedEOF} When the end of the file is reached.\n */\n function parseArray(firstTokenType) {\n\n // The first token must be a [ or else it's an error\n assertTokenType(firstTokenType, tt.LBracket);\n\n const firstToken = tokenizer.token;\n const elements = [];\n let tokenType = next();\n \n if (tokenType !== tt.RBracket) {\n\n do {\n\n // add the value into the array\n const value = parseValue(tokenType);\n\n elements.push(types.element(\n /** @type {ValueNode} */ (value),\n { loc: value.loc }\n ));\n\n tokenType = next();\n \n if (tokenType === tt.Comma) {\n tokenType = next();\n\n /*\n * Trailing commas.\n * So we need to check if the token is a comma,\n * and if so, then we need to check if the next\n * token is a RBracket. If it is, then we need to\n * break out of the loop.\n */\n if (allowTrailingCommas && tokenType === tt.RBracket) {\n break;\n } \n } else {\n break;\n }\n } while (tokenType);\n }\n\n assertTokenType(tokenType, tt.RBracket);\n\n const lastToken = tokenizer.token;\n const range = createRange(firstToken.loc.start, lastToken.loc.end);\n\n return types.array(elements, {\n loc: {\n start: {\n ...firstToken.loc.start\n },\n end: {\n ...lastToken.loc.end\n }\n },\n ...range\n });\n\n }\n\n /**\n * Parses a JSON value.\n * @param {number} [tokenType] The token type to parse.\n * @returns {ValueNode|IdentifierNode} The node representing the value.\n */\n function parseValue(tokenType) {\n\n tokenType = tokenType ?? next();\n const token = tokenizer.token;\n \n switch (tokenType) {\n case tt.String:\n case tt.Boolean:\n return createLiteralNode(tokenType);\n\n case tt.Number:\n if (json5) {\n let tokenText = text.slice(token.loc.start.offset, token.loc.end.offset);\n if (tokenText[0] === \"+\" || tokenText[0] === \"-\") {\n tokenText = tokenText.slice(1);\n }\n\n if (tokenText === \"NaN\" || tokenText === \"Infinity\") {\n return createJSON5IdentifierNode(token);\n }\n }\n return createLiteralNode(tokenType);\n\n case tt.Null:\n return createNullNode(token);\n\n case tt.LBrace:\n return parseObject(tokenType);\n\n case tt.LBracket:\n return parseArray(tokenType);\n\n default:\n throw new UnexpectedToken(token);\n }\n\n }\n\n \n const docBody = parseValue();\n \n const unexpectedToken = next();\n if (unexpectedToken) {\n throw new UnexpectedToken(tokenizer.token);\n }\n \n \n const textEndLocation = getEndLocation(text);\n const docParts = {\n loc: {\n start: {\n line: 1,\n column: 1,\n offset: 0\n },\n end: {\n ...textEndLocation\n }\n }\n };\n \n if (options.tokens) {\n docParts.tokens = tokens;\n }\n\n if (options.ranges) {\n docParts.range = [\n docParts.loc.start.offset,\n docParts.loc.end.offset\n ];\n }\n\n return types.document(/** @type {ValueNode} */ (docBody), docParts);\n}\n\n/**\n * @fileoverview Traversal approaches for Momoa JSON AST.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").TraversalPhase} TraversalPhase */\n/**\n * @typedef {Object} TraversalVisitor\n * @property {(node: Node, parent?: Node) => void} [enter]\n * @property {(node: Node, parent?: Node) => void} [exit]\n */\n\n//-----------------------------------------------------------------------------\n// Data\n//-----------------------------------------------------------------------------\n\nconst childKeys = new Map([\n [\"Document\", [\"body\"]],\n [\"Object\", [\"members\"]],\n [\"Member\", [\"name\", \"value\"]],\n [\"Element\", [\"value\"]],\n [\"Array\", [\"elements\"]],\n [\"String\", []],\n [\"Number\", []],\n [\"Boolean\", []],\n [\"Null\", []],\n [\"NaN\", []],\n [\"Infinity\", []],\n [\"Identifier\", []],\n]);\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Determines if a given value is an object.\n * @param {*} value The value to check.\n * @returns {boolean} True if the value is an object, false if not. \n */\nfunction isObject(value) {\n return value && (typeof value === \"object\");\n}\n\n/**\n * Determines if a given value is an AST node.\n * @param {*} value The value to check.\n * @returns {boolean} True if the value is a node, false if not. \n */\nfunction isNode(value) {\n return isObject(value) && (typeof value.type === \"string\");\n}\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Traverses an AST from the given node.\n * @param {Node} root The node to traverse from \n * @param {TraversalVisitor} visitor An object with an `enter` and `exit` method. \n */\nfunction traverse(root, visitor) {\n\n /**\n * Recursively visits a node.\n * @param {Node} node The node to visit.\n * @param {Node} [parent] The parent of the node to visit.\n * @returns {void}\n */\n function visitNode(node, parent) {\n\n if (typeof visitor.enter === \"function\") {\n visitor.enter(node, parent);\n }\n\n for (const key of childKeys.get(node.type)) {\n const value = node[key];\n\n if (isObject(value)) {\n if (Array.isArray(value)) {\n value.forEach(child => visitNode(child, node));\n } else if (isNode(value)) {\n visitNode(value, node);\n }\n }\n }\n\n if (typeof visitor.exit === \"function\") {\n visitor.exit(node, parent);\n }\n }\n\n visitNode(root);\n}\n\n/**\n * @callback FilterPredicate\n * @param {{node: Node, parent?: Node, phase: TraversalPhase}} item\n * @param {number} index\n * @param {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} array\n * @returns {boolean}\n */\n\n/**\n * Creates an iterator over the given AST.\n * @param {Node} root The root AST node to traverse. \n * @param {FilterPredicate} [filter] A filter function to determine which steps to\n * return;\n * @returns {IterableIterator<{node: Node, parent?: Node, phase: TraversalPhase}>} An iterator over the AST. \n */\nfunction iterator(root, filter = () => true) {\n\n /** @type {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} */\n const traversal = [];\n\n traverse(root, {\n enter(node, parent) {\n traversal.push({ node, parent, phase: \"enter\" });\n },\n exit(node, parent) {\n traversal.push({ node, parent, phase: \"exit\" });\n }\n });\n\n return traversal.filter(filter).values();\n}\n\n/**\n * @fileoverview Evaluator for Momoa AST.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"./typedefs.js\").AnyNode} AnyNode */\n/** @typedef {import(\"./typedefs.js\").JSONValue} JSONValue */\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Evaluates a Momoa AST node into a JavaScript value.\n * @param {AnyNode} node The node to interpet.\n * @returns {JSONValue} The JavaScript value for the node. \n */\nfunction evaluate(node) {\n switch (node.type) {\n case \"String\":\n return node.value;\n\n case \"Number\":\n return node.value;\n\n case \"Boolean\":\n return node.value;\n\n case \"Null\":\n return null;\n\n case \"NaN\":\n return NaN;\n \n case \"Infinity\":\n return node.sign === \"-\" ? -Infinity : Infinity;\n\n case \"Identifier\":\n return node.name;\n\n case \"Array\": {\n // const arrayNode = /** @type {ArrayNode} */ (node);\n return node.elements.map(element => evaluate(element.value));\n }\n\n case \"Object\": {\n\n /** @type {{[property: string]: JSONValue}} */\n const object = {};\n\n node.members.forEach(member => {\n object[/** @type {string} */ (evaluate(member.name))] = evaluate(member.value);\n }); \n\n return object;\n } \n\n case \"Document\": {\n return evaluate(node.body);\n }\n\n case \"Element\":\n throw new Error(\"Cannot evaluate array element outside of an array.\");\n\n case \"Member\":\n throw new Error(\"Cannot evaluate object member outside of an object.\");\n\n default:\n // @ts-ignore tsc doesn't know about the type property here?\n throw new Error(`Unknown node type ${ node.type }.`);\n }\n}\n\n/**\n * @fileoverview Printer for Momoa AST.\n * @author Nicholas C. Zakas\n */\n\n\n//-----------------------------------------------------------------------------\n// Typedefs\n//-----------------------------------------------------------------------------\n\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Prints the string representation of a Boolean node.\n * @param {BooleanNode} node The node to print.\n * @returns {string} The boolean value.\n */\nfunction printBoolean(node) {\n return node.value ? \"true\" : \"false\";\n}\n\n/**\n * Prints the string representation of a null node.\n * @returns {string} The string \"null\".\n */\nfunction printNull() {\n return \"null\";\n}\n\n/**\n * Prints the string representation of a number node.\n * @param {NumberNode} node The node to print.\n * @returns {string} The number value.\n */\nfunction printNumber(node) {\n return node.value.toString();\n}\n\n/**\n * Prints the string representation of a NaN node.\n * @returns {string} The string \"NaN\".\n */\nfunction printNaN() {\n return \"NaN\";\n}\n\n/**\n * Prints the string representation of an Infinity node.\n * @param {InfinityNode} node The node to print.\n * @returns {string} The string \"Infinity\" or \"-Infinity\".\n */\nfunction printInfinity(node) {\n return node.sign + \"Infinity\";\n}\n\n/**\n * Prints the string representation of a string node.\n * @param {StringNode} node The node to print.\n * @returns {string} The string value.\n */\nfunction printString(node) {\n\n let result = \"\\\"\";\n\n // escape all characters that need escaping\n for (const c of node.value) {\n\n const newChar = json5CharToEscape.get(c);\n\n if (newChar) {\n result += \"\\\\\" + newChar;\n continue;\n }\n\n // if it's a double quote, escape it\n if (c === \"\\\"\") {\n result += \"\\\\\\\"\";\n continue;\n }\n\n // if it's a control character, escape it\n if (c < \" \" || c === \"\\u007F\") {\n const hex = c.codePointAt(0).toString(16).toUpperCase();\n result += `\\\\u${\"0000\".substring(hex.length)}${hex}`;\n continue;\n }\n\n // otherwise, just add the character\n result += c;\n\n }\n \n return result + \"\\\"\";\n}\n\n/**\n * Prints the string representation of an identifier node.\n * @param {IdentifierNode} node The node to print.\n * @returns {string} The identifier name.\n */\nfunction printIdentifier(node) {\n return node.name;\n}\n\n/**\n * Prints the string representation of an array node.\n * @param {ArrayNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The array value.\n */\nfunction printArray(node, indent, indentLevel) {\n const newLine = indent ? \"\\n\" : \"\";\n const indentString = indent.repeat(indentLevel);\n const elementIndentString = indent.repeat(indentLevel + 1);\n\n return `[${newLine}${\n node.elements.map(element =>\n `${elementIndentString}${printValue(element.value, indent, indentLevel + 1)}`\n ).join(`,${newLine}`)\n }${newLine}${indentString}]`;\n}\n\n/**\n * Prints the string representation of a member node.\n * @param {MemberNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The member value.\n */\nfunction printMember(node, indent, indentLevel) {\n const space = indent ? \" \" : \"\";\n return `${printValue(node.name, indent, indentLevel)}:${space}${printValue(node.value, indent, indentLevel + 1)}`;\n}\n\n/**\n * Prints the string representation of an object node.\n * @param {ObjectNode} node The node to print.\n * @param {string} indent The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The object value.\n */\nfunction printObject(node, indent, indentLevel) {\n const newLine = indent ? \"\\n\" : \"\";\n const indentString = indent.repeat(indentLevel);\n const memberIndentString = indent.repeat(indentLevel + 1);\n\n return `{${newLine}${\n node.members.map(member => \n `${memberIndentString}${printMember(member, indent, indentLevel)}`\n ).join(`,${newLine}`)\n }${newLine}${indentString}}`;\n}\n\n/**\n * Prints the string representation of a node.\n * @param {AnyNode} node The node to print.\n * @param {string} indentString The string to use for indentation.\n * @param {number} indentLevel The current level of indentation.\n * @returns {string} The string representation of the node.\n * @throws {TypeError} If the node type is unknown.\n\n */\nfunction printValue(node, indentString, indentLevel) {\n switch (node.type) {\n case \"String\":\n return printString(node);\n case \"Number\":\n return printNumber(node);\n case \"Boolean\":\n return printBoolean(node);\n case \"Null\":\n return printNull();\n case \"NaN\":\n return printNaN();\n case \"Infinity\":\n return printInfinity(node);\n case \"Identifier\":\n return printIdentifier(node);\n case \"Array\":\n return printArray(node, indentString, indentLevel);\n case \"Object\":\n return printObject(node, indentString, indentLevel);\n case \"Document\":\n return printValue(node.body, indentString, indentLevel);\n default:\n throw new TypeError(`Unknown node type: ${node.type}`);\n }\n}\n\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * Converts a Momoa AST back into a JSON string.\n * @param {AnyNode} node The node to print.\n * @param {Object} options Options for the print.\n * @param {number} [options.indent=0] The number of spaces to indent each line. If\n * greater than 0, then newlines and indents will be added to output. \n * @returns {string} The JSON representation of the AST.\n */\nfunction print(node, { indent = 0 } = {}) {\n\n const indentLevel = 0;\n const indentString = \" \".repeat(indent);\n\n return printValue(node, indentString, indentLevel);\n}\n\nexport { evaluate, iterator, parse, print, tokenize, traverse, types, childKeys as visitorKeys };\n", "import path from 'node:path';\nimport fs from 'node:fs';\nimport {locatePath, locatePathSync} from 'locate-path';\nimport {toPath} from 'unicorn-magic';\n\nexport const findUpStop = Symbol('findUpStop');\n\nexport async function findUpMultiple(name, options = {}) {\n\tlet directory = path.resolve(toPath(options.cwd) ?? '');\n\tconst {root} = path.parse(directory);\n\tconst stopAt = path.resolve(directory, toPath(options.stopAt) ?? root);\n\tconst limit = options.limit ?? Number.POSITIVE_INFINITY;\n\tconst paths = [name].flat();\n\n\tconst runMatcher = async locateOptions => {\n\t\tif (typeof name !== 'function') {\n\t\t\treturn locatePath(paths, locateOptions);\n\t\t}\n\n\t\tconst foundPath = await name(locateOptions.cwd);\n\t\tif (typeof foundPath === 'string') {\n\t\t\treturn locatePath([foundPath], locateOptions);\n\t\t}\n\n\t\treturn foundPath;\n\t};\n\n\tconst matches = [];\n\twhile (true) {\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tconst foundPath = await runMatcher({...options, cwd: directory});\n\n\t\tif (foundPath === findUpStop) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (foundPath) {\n\t\t\tmatches.push(path.resolve(directory, foundPath));\n\t\t}\n\n\t\tif (directory === stopAt || matches.length >= limit) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n\n\treturn matches;\n}\n\nexport function findUpMultipleSync(name, options = {}) {\n\tlet directory = path.resolve(toPath(options.cwd) ?? '');\n\tconst {root} = path.parse(directory);\n\tconst stopAt = path.resolve(directory, toPath(options.stopAt) ?? root);\n\tconst limit = options.limit ?? Number.POSITIVE_INFINITY;\n\tconst paths = [name].flat();\n\n\tconst runMatcher = locateOptions => {\n\t\tif (typeof name !== 'function') {\n\t\t\treturn locatePathSync(paths, locateOptions);\n\t\t}\n\n\t\tconst foundPath = name(locateOptions.cwd);\n\t\tif (typeof foundPath === 'string') {\n\t\t\treturn locatePathSync([foundPath], locateOptions);\n\t\t}\n\n\t\treturn foundPath;\n\t};\n\n\tconst matches = [];\n\twhile (true) {\n\t\tconst foundPath = runMatcher({...options, cwd: directory});\n\n\t\tif (foundPath === findUpStop) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (foundPath) {\n\t\t\tmatches.push(path.resolve(directory, foundPath));\n\t\t}\n\n\t\tif (directory === stopAt || matches.length >= limit) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n\n\treturn matches;\n}\n\nexport async function findUp(name, options = {}) {\n\tconst matches = await findUpMultiple(name, {...options, limit: 1});\n\treturn matches[0];\n}\n\nexport function findUpSync(name, options = {}) {\n\tconst matches = findUpMultipleSync(name, {...options, limit: 1});\n\treturn matches[0];\n}\n\nasync function findDownDepthFirst(directory, paths, maxDepth, locateOptions, currentDepth = 0) {\n\tconst found = await locatePath(paths, {cwd: directory, ...locateOptions});\n\tif (found) {\n\t\treturn path.resolve(directory, found);\n\t}\n\n\tif (currentDepth >= maxDepth) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst entries = await fs.promises.readdir(directory, {withFileTypes: true});\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\t\tconst result = await findDownDepthFirst(\n\t\t\t\t\tpath.join(directory, entry.name),\n\t\t\t\t\tpaths,\n\t\t\t\t\tmaxDepth,\n\t\t\t\t\tlocateOptions,\n\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {}\n\n\treturn undefined;\n}\n\nfunction findDownDepthFirstSync(directory, paths, maxDepth, locateOptions, currentDepth = 0) {\n\tconst found = locatePathSync(paths, {cwd: directory, ...locateOptions});\n\tif (found) {\n\t\treturn path.resolve(directory, found);\n\t}\n\n\tif (currentDepth >= maxDepth) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst entries = fs.readdirSync(directory, {withFileTypes: true});\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tconst result = findDownDepthFirstSync(\n\t\t\t\t\tpath.join(directory, entry.name),\n\t\t\t\t\tpaths,\n\t\t\t\t\tmaxDepth,\n\t\t\t\t\tlocateOptions,\n\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t);\n\t\t\t\tif (result) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {}\n\n\treturn undefined;\n}\n\nfunction prepareFindDownOptions(name, options) {\n\tconst startDirectory = path.resolve(toPath(options.cwd) ?? '');\n\tconst maxDepth = Math.max(0, options.depth ?? 1);\n\tconst paths = [name].flat();\n\tconst {type = 'file', allowSymlinks = true, strategy = 'breadth'} = options;\n\tconst locateOptions = {type, allowSymlinks};\n\treturn {\n\t\tstartDirectory,\n\t\tmaxDepth,\n\t\tpaths,\n\t\tlocateOptions,\n\t\tstrategy,\n\t};\n}\n\nasync function findDownBreadthFirst(startDirectory, paths, maxDepth, locateOptions) {\n\tconst queue = [{directory: startDirectory, depth: 0}];\n\n\twhile (queue.length > 0) {\n\t\tconst {directory, depth} = queue.shift();\n\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tconst found = await locatePath(paths, {cwd: directory, ...locateOptions});\n\t\tif (found) {\n\t\t\treturn path.resolve(directory, found);\n\t\t}\n\n\t\tif (depth >= maxDepth) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst entries = await fs.promises.readdir(directory, {withFileTypes: true});\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\tqueue.push({directory: path.join(directory, entry.name), depth: depth + 1});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\t}\n\n\treturn undefined;\n}\n\nfunction findDownBreadthFirstSync(startDirectory, paths, maxDepth, locateOptions) {\n\tconst queue = [{directory: startDirectory, depth: 0}];\n\n\twhile (queue.length > 0) {\n\t\tconst {directory, depth} = queue.shift();\n\n\t\tconst found = locatePathSync(paths, {cwd: directory, ...locateOptions});\n\t\tif (found) {\n\t\t\treturn path.resolve(directory, found);\n\t\t}\n\n\t\tif (depth >= maxDepth) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst entries = fs.readdirSync(directory, {withFileTypes: true});\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\tqueue.push({directory: path.join(directory, entry.name), depth: depth + 1});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\t}\n\n\treturn undefined;\n}\n\nexport async function findDown(name, options = {}) {\n\tconst {startDirectory, maxDepth, paths, locateOptions, strategy} = prepareFindDownOptions(name, options);\n\n\treturn strategy === 'depth'\n\t\t? findDownDepthFirst(startDirectory, paths, maxDepth, locateOptions)\n\t\t: findDownBreadthFirst(startDirectory, paths, maxDepth, locateOptions);\n}\n\nexport function findDownSync(name, options = {}) {\n\tconst {startDirectory, maxDepth, paths, locateOptions, strategy} = prepareFindDownOptions(name, options);\n\n\treturn strategy === 'depth'\n\t\t? findDownDepthFirstSync(startDirectory, paths, maxDepth, locateOptions)\n\t\t: findDownBreadthFirstSync(startDirectory, paths, maxDepth, locateOptions);\n}\n\n", "import process from 'node:process';\nimport path from 'node:path';\nimport fs, {promises as fsPromises} from 'node:fs';\nimport {fileURLToPath} from 'node:url';\nimport pLocate from 'p-locate';\n\nconst typeMappings = {\n\tdirectory: 'isDirectory',\n\tfile: 'isFile',\n};\n\nfunction checkType(type) {\n\tif (type === 'both' || Object.hasOwn(typeMappings, type)) {\n\t\treturn;\n\t}\n\n\tthrow new Error(`Invalid type specified: ${type}`);\n}\n\nconst matchType = (type, stat) => type === 'both' ? (stat.isFile() || stat.isDirectory()) : stat[typeMappings[type]]();\n\nconst toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;\n\nexport async function locatePath(\n\tpaths,\n\t{\n\t\tcwd = process.cwd(),\n\t\ttype = 'file',\n\t\tallowSymlinks = true,\n\t\tconcurrency,\n\t\tpreserveOrder,\n\t} = {},\n) {\n\tcheckType(type);\n\tcwd = toPath(cwd);\n\n\tconst statFunction = allowSymlinks ? fsPromises.stat : fsPromises.lstat;\n\n\treturn pLocate(paths, async path_ => {\n\t\ttry {\n\t\t\tconst stat = await statFunction(path.resolve(cwd, path_));\n\t\t\treturn matchType(type, stat);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}, {concurrency, preserveOrder});\n}\n\nexport function locatePathSync(\n\tpaths,\n\t{\n\t\tcwd = process.cwd(),\n\t\ttype = 'file',\n\t\tallowSymlinks = true,\n\t} = {},\n) {\n\tcheckType(type);\n\tcwd = toPath(cwd);\n\n\tconst statFunction = allowSymlinks ? fs.statSync : fs.lstatSync;\n\n\tfor (const path_ of paths) {\n\t\ttry {\n\t\t\tconst stat = statFunction(path.resolve(cwd, path_), {\n\t\t\t\tthrowIfNoEntry: false,\n\t\t\t});\n\n\t\t\tif (!stat) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (matchType(type, stat)) {\n\t\t\t\treturn path_;\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n", "/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\n\t\t// Clean up tail reference when queue becomes empty\n\t\tif (!this.#head) {\n\t\t\tthis.#tail = undefined;\n\t\t}\n\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n\n\t* drain() {\n\t\twhile (this.#head) {\n\t\t\tyield this.dequeue();\n\t\t}\n\t}\n}\n", "import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tif (queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t}\n\t};\n\n\tconst run = async (fn, resolve, args) => {\n\t\tactiveCount++;\n\n\t\tconst result = (async () => fn(...args))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (fn, resolve, args) => {\n\t\tqueue.enqueue(run.bind(undefined, fn, resolve, args));\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// when the run function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\t\tqueue.dequeue()();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (fn, ...args) => new Promise(resolve => {\n\t\tenqueue(fn, resolve, args);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue: () => {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n", "import pLimit from 'p-limit';\n\nclass EndError extends Error {\n\tconstructor(value) {\n\t\tsuper();\n\t\tthis.value = value;\n\t}\n}\n\n// The input can also be a promise, so we await it.\nconst testElement = async (element, tester) => tester(await element);\n\n// The input can also be a promise, so we `Promise.all()` them both.\nconst finder = async element => {\n\tconst values = await Promise.all(element);\n\tif (values[1] === true) {\n\t\tthrow new EndError(values[0]);\n\t}\n\n\treturn false;\n};\n\nexport default async function pLocate(\n\titerable,\n\ttester,\n\t{\n\t\tconcurrency = Number.POSITIVE_INFINITY,\n\t\tpreserveOrder = true,\n\t} = {},\n) {\n\tconst limit = pLimit(concurrency);\n\n\t// Start all the promises concurrently with optional limit.\n\tconst items = [...iterable].map(element => [element, limit(testElement, element, tester)]);\n\n\t// Check the promises either serially or concurrently.\n\tconst checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY);\n\n\ttry {\n\t\tawait Promise.all(items.map(element => checkLimit(finder, element)));\n\t} catch (error) {\n\t\tif (error instanceof EndError) {\n\t\t\treturn error.value;\n\t\t}\n\n\t\tthrow error;\n\t}\n}\n", "import {promisify} from 'node:util';\nimport {execFile as execFileCallback, execFileSync as execFileSyncOriginal} from 'node:child_process';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\n\nconst execFileOriginal = promisify(execFileCallback);\n\nexport function toPath(urlOrPath) {\n\treturn urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;\n}\n\nexport function rootDirectory(pathInput) {\n\treturn path.parse(toPath(pathInput)).root;\n}\n\nexport function traversePathUp(startPath) {\n\treturn {\n\t\t* [Symbol.iterator]() {\n\t\t\tlet currentPath = path.resolve(toPath(startPath));\n\t\t\tlet previousPath;\n\n\t\t\twhile (previousPath !== currentPath) {\n\t\t\t\tyield currentPath;\n\t\t\t\tpreviousPath = currentPath;\n\t\t\t\tcurrentPath = path.resolve(currentPath, '..');\n\t\t\t}\n\t\t},\n\t};\n}\n\nconst TEN_MEGABYTES_IN_BYTES = 10 * 1024 * 1024;\n\nexport async function execFile(file, arguments_, options = {}) {\n\treturn execFileOriginal(file, arguments_, {\n\t\tmaxBuffer: TEN_MEGABYTES_IN_BYTES,\n\t\t...options,\n\t});\n}\n\nexport function execFileSync(file, arguments_ = [], options = {}) {\n\treturn execFileSyncOriginal(file, arguments_, {\n\t\tmaxBuffer: TEN_MEGABYTES_IN_BYTES,\n\t\tencoding: 'utf8',\n\t\tstdio: 'pipe',\n\t\t...options,\n\t});\n}\n\nexport * from './default.js';\n", "/* eslint-disable security/detect-non-literal-regexp -- expected to be non-literal */\n\nexport function escape(text: string): string {\n\treturn text.replace(/\\./, \"\\\\.\");\n}\n\nexport function directory(path: string): RegExp {\n\treturn new RegExp(`(^|/)${path}/`);\n}\n\nexport function extension(ext: string): RegExp {\n\treturn new RegExp(`${escape(ext)}$`);\n}\n\nexport function filename(path: string): RegExp {\n\treturn new RegExp(`(^|/)${escape(path)}$`);\n}\n\nexport function rcfile(base: string): RegExp {\n\treturn new RegExp(`${escape(base)}(\\\\.(js|cjs|mjs|ts|yaml|yml|json))?$`);\n}\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tfilename(\"ava.config.js\"),\n\tfilename(\"ava.config.cjs\"),\n\tfilename(\"ava.config.mjs\"),\n];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [/#[^#]*#$/, /~$/, filename(\".dir-locals.el\")];\n\nexport default regexp;\n", "import { directory, filename, rcfile } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tdirectory(\".eslintcache\"),\n\tfilename(\".eslintignore\"),\n\trcfile(`.eslintrc`),\n\tfilename(\"eslint.config.js\"),\n\tfilename(\"eslint.config.cjs\"),\n\tfilename(\"eslint.config.mjs\"),\n\tfilename(\"eslint.config.ts\"),\n];\n\nexport default regexp;\n", "import { filename, rcfile } from \"./helpers\";\n\nconst regexp: RegExp[] = [filename(\".fimbullinter.yaml\"), rcfile(\".wotanrc\")];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tfilename(\".gitattributes\"),\n\tfilename(\".keep\"),\n\tfilename(\".gitkeep\"),\n\tfilename(\".gitmodules\"),\n];\n\nexport default regexp;\n", "import { directory, extension } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\tdirectory(\"__fixtures__\"),\n\tdirectory(\"__snapshots__\"),\n\tdirectory(\"__tests__\"),\n\textension(\".snap\"),\n\textension(\".spec.[jt]sx?\"),\n\textension(\".spec.js.map\"),\n\textension(\".spec.d.ts\"),\n\textension(\".spec.d.ts.map\"),\n\textension(\".test.[jt]sx?\"),\n\textension(\".test.js.map\"),\n\textension(\".test.d.ts\"),\n\textension(\".test.d.ts.map\"),\n];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [\n\t/(^|\\/)(npm|yarn|lerna)-(debug|error)\\.log.*$/,\n\tfilename(\"report.\\\\d+.\\\\d+.\\\\d+.\\\\d+.\\\\d+.json\"),\n\tfilename(\".npmignore\"),\n\tfilename(\".npmrc\"),\n\tfilename(\".nvmrc\"),\n\tfilename(\"lerna.json\"),\n\tfilename(\"yarn.lock\"),\n];\n\nexport default regexp;\n", "import { filename, rcfile } from \"./helpers\";\n\nconst regexp: RegExp[] = [filename(\".prettierignore\"), rcfile(`.prettierrc`)];\n\nexport default regexp;\n", "import { directory, filename } from \"./helpers\";\n\nconst regexp: RegExp[] = [directory(\".tsbuildinfo\"), filename(\"tsconfig.json\")];\n\nexport default regexp;\n", "import { filename } from \"./helpers\";\n\n/* reserved filenames on windows */\nconst regexp: RegExp[] = [\n\tfilename(\"CON\"),\n\tfilename(\"PRN\"),\n\tfilename(\"AUX\"),\n\tfilename(\"NUL\"),\n\t/(^|\\/)COM\\d/,\n\t/(^|\\/)LPT\\d/,\n];\n\nexport default regexp;\n", "import ava from \"./ava\";\nimport emacs from \"./emacs\";\nimport eslint from \"./eslint\";\nimport fimbullinter from \"./fimbullinter\";\nimport git from \"./git\";\nimport { directory, extension, filename, rcfile } from \"./helpers\";\nimport jest from \"./jest\";\nimport node from \"./node\";\nimport prettier from \"./prettier\";\nimport typescript from \"./typescript\";\nimport windows from \"./windows\";\n\nconst blacklist: RegExp[] = [\n\t/* tests in general */\n\tdirectory(\".nyc_output\"),\n\tdirectory(\"coverage\"),\n\textension(\".lcov\"),\n\textension(\"[.-]junit.xml\"),\n\tfilename(\".istanbul.yml\"),\n\tfilename(\"junit.xml\"),\n\tfilename(\"lcov.info\"),\n\tfilename(\".airtap.yml\"),\n\trcfile(\".c8rc\"),\n\trcfile(\".nycrc\"),\n\n\t/* tests */\n\tdirectory(\"examples?\"),\n\tdirectory(\"perf\"),\n\tdirectory(\"tests?\"),\n\tfilename(\"cypress.json\"),\n\tfilename(\"cypress.config.js\"),\n\tfilename(\"cypress.config.cjs\"),\n\tfilename(\"cypress.config.mjs\"),\n\tfilename(\"cypress.config.ts\"),\n\tfilename(\"karma.config.js\"),\n\tfilename(\"mocha.opts\"),\n\tfilename(\"playwright.config.js\"),\n\tfilename(\"playwright.config.cjs\"),\n\tfilename(\"playwright.config.mjs\"),\n\tfilename(\"playwright.config.ts\"),\n\tfilename(\"test.js\"),\n\tfilename(\"testem.json\"),\n\tfilename(\"testem.yml\"),\n\tfilename(\"wallaby.config.js\"),\n\tfilename(\"wallaby.js\"),\n\n\t/* linting */\n\tfilename(\".htmlvalidate.json\"),\n\tfilename(\".jshintignore\"),\n\tfilename(`tslint.json`),\n\tfilename(`tslint.yaml`),\n\tfilename(\".jscs.json\"),\n\trcfile(`.jscsrc`),\n\trcfile(`.jshintrc`),\n\n\t/* toolchains */\n\tfilename(\"rollup.config.js\"),\n\tfilename(\"webpack.config.js\"),\n\n\t/* task runners */\n\tfilename(\"[gG]runtfile.js\"),\n\tfilename(\"[gG]ulpfile.[jt]s\"),\n\tfilename(\"dangerfile.[jt]s\"),\n\tfilename(\"gulpfile.babel.js\"),\n\tfilename(\"gulpfile.esm.js\"),\n\tfilename(\"Herebyfile.js\"),\n\tfilename(\"Herebyfile.mjs\"),\n\n\t/* ci */\n\t/^\\.azure-.*$/,\n\tdirectory(\".circleci\"),\n\tdirectory(\".github\"),\n\tdirectory(\".gitlab\"),\n\tdirectory(\".?zuul.d\"),\n\tfilename(\".coveralls.yml\"),\n\tfilename(\".gitlab-ci.yml\"),\n\tfilename(\".travis.yml\"),\n\tfilename(\".?zuul.ya?ml\"),\n\tfilename(\"ISSUE_TEMPLATE.md\"),\n\tfilename(\"Jenkinsfile\"),\n\tfilename(\"PULL_REQUEST_TEMPLATE.md\"),\n\tfilename(\"appveyor.yml\"),\n\n\t/* editor specific files */\n\t/(^|\\/)\\.sw[a-p]/ /* vim */,\n\tdirectory(\".vscode\"),\n\textension(\".sublime-project\"),\n\textension(\".sublime-workspace\"),\n\tfilename(\".vscodeignore\"),\n\tfilename(\"Session.vim\"),\n\tfilename(\"Sessionx.vim\"),\n\tdirectory(\".idea\"),\n\tfilename(\".tm_properties\") /* textmate */,\n\n\t/* OS */\n\tdirectory(\".AppleDouble\"),\n\tdirectory(\".DS_Store\"),\n\tdirectory(\".LSOverride\"),\n\n\t/* logs */\n\tdirectory(\"logs\"),\n\textension(\".log\"),\n\n\t/* runtime */\n\tdirectory(\"pids\"),\n\textension(\".pid\"),\n\textension(\".pid.lock\"),\n\textension(\".seed\"),\n\n\t/* misc */\n\t/^[Jj]akefile(\\.js)?$/,\n\textension(\".bak\"),\n\textension(\".swp\"),\n\textension(\".tgz\"),\n\textension(\".tmp\"),\n\tfilename(\".env\"),\n\tfilename(\".svgo.yml\"),\n\tfilename(\".editorconfig\"),\n\tfilename(\".ext-prepush\"),\n\tfilename(\".tonic_example.js\"),\n\tfilename(\".flowconfig\"),\n\tfilename(\".cardinalrc\"),\n\tfilename(\"bower.json\"),\n\tfilename(\"commitlint.config.js\") /* commitlint */,\n\tfilename(\"composer.json\"),\n\tfilename(\"netlify.toml\"),\n\tfilename(\"release.config.js\") /* semantic release */,\n\n\t...ava,\n\t...emacs,\n\t...eslint,\n\t...fimbullinter,\n\t...git,\n\t...jest,\n\t...node,\n\t...prettier,\n\t...typescript,\n\t...windows,\n];\n\nexport default blacklist;\n", "import blacklist from \"./blacklist/index\";\n\nexport function setupBlacklist(name: string): void {\n\t/* eslint-disable-next-line security/detect-non-literal-regexp -- expected to be non-literal */\n\tblacklist.push(new RegExp(`^${name}-\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.tgz$`));\n}\n\nexport function isBlacklisted(filename: string): boolean {\n\treturn blacklist.some((entry) => filename.match(entry));\n}\n", "import fs from \"node:fs\";\nimport * as tar from \"tar\";\nimport { type ReadEntry, Parser } from \"tar\";\nimport { isBlacklisted } from \"./blacklist\";\nimport { type Message } from \"./message\";\nimport { type Result } from \"./result\";\nimport { type PackageJson, type PackageJsonExports } from \"./types\";\n\nexport interface TarballMeta {\n\t/** Path to tarball on disk */\n\tfilePath: string;\n\n\t/** Path to use in report (default filePath) */\n\treportPath?: string | undefined;\n}\n\ninterface RequiredFile {\n\tfield: string;\n\truleId: string;\n\tfilename: string;\n}\n\nconst ruleId = \"no-missing-main\";\n\nfunction normalize(filename: string): string {\n\treturn filename.replace(/^[^/]+\\//, \"\");\n}\n\nexport async function getFileList(filename: string): Promise<string[]> {\n\tconst entries: ReadEntry[] = [];\n\tawait tar.list({\n\t\tfile: filename,\n\t\tstrict: true,\n\t\tonentry: (entry: ReadEntry) => entries.push(entry),\n\t});\n\treturn entries.map((entry) => {\n\t\tconst filename = entry.path as unknown as string;\n\t\treturn normalize(filename);\n\t});\n}\n\nexport async function getFileContent(\n\ttarball: TarballMeta,\n\tfilenames: string[],\n): Promise<Record<string, Buffer>> {\n\tconst contents: Record<string, Buffer> = {};\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst t = new Parser({\n\t\t\tfilter(path): boolean {\n\t\t\t\treturn filenames.includes(normalize(path));\n\t\t\t},\n\t\t});\n\t\tt.on(\"entry\", (entry: tar.ReadEntry) => {\n\t\t\tconst p = normalize(entry.path);\n\t\t\tcontents[p] = Buffer.alloc(0);\n\t\t\tentry.on(\"data\", (data: Buffer) => {\n\t\t\t\tcontents[p] = Buffer.concat([contents[p], data]);\n\t\t\t});\n\t\t\tentry.on(\"error\", (error) => {\n\t\t\t\t/* eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- technical debt */\n\t\t\t\treject(error);\n\t\t\t});\n\t\t});\n\t\tt.on(\"end\", () => {\n\t\t\tresolve(contents);\n\t\t});\n\t\tconst rs = fs.createReadStream(tarball.filePath);\n\t\trs.pipe(t as unknown as NodeJS.WritableStream);\n\t});\n}\n\nexport function blacklistedFiles(filelist: string[]): string[] {\n\treturn filelist.filter(isBlacklisted);\n}\n\nfunction normalizeRequiredFiles(\n\tsrc: string | string[] | Record<string, string | boolean>,\n): string[] {\n\tif (typeof src === \"string\") {\n\t\treturn [src];\n\t} else if (Array.isArray(src)) {\n\t\treturn src;\n\t} else {\n\t\treturn Object.values(src).filter((it) => it !== false) as string[];\n\t}\n}\n\nfunction* yieldRequiredFiles(\n\tsrc: string | string[] | Record<string, string | boolean>,\n\ttemplate: Pick<RequiredFile, \"field\" | \"ruleId\">,\n): Generator<RequiredFile> {\n\tconst files = normalizeRequiredFiles(src);\n\tfor (const filename of files) {\n\t\tyield { ...template, filename };\n\t}\n}\n\nfunction* yieldExportedFiles(\n\texports: undefined | null | string | PackageJsonExports,\n): Generator<RequiredFile> {\n\tif (!exports) {\n\t\treturn;\n\t}\n\n\tif (typeof exports === \"string\") {\n\t\tyield {\n\t\t\tfield: \"exports\",\n\t\t\truleId: \"no-missing-exports\",\n\t\t\tfilename: exports,\n\t\t};\n\t\treturn;\n\t}\n\n\tfor (const [key, value] of Object.entries(exports)) {\n\t\t/* ignore wildcards for now */\n\t\tif (key.includes(\"*\")) {\n\t\t\tcontinue;\n\t\t}\n\t\tyield* yieldExportedFiles(value);\n\t}\n}\n\nfunction* requiredFiles(pkg: PackageJson): Generator<RequiredFile> {\n\tyield* yieldExportedFiles(pkg.exports);\n\tif (pkg.main) {\n\t\tyield* yieldRequiredFiles(pkg.main, { field: \"main\", ruleId });\n\t}\n\tif (pkg.browser) {\n\t\tyield* yieldRequiredFiles(pkg.browser, { field: \"browser\", ruleId });\n\t}\n\tif (pkg.module) {\n\t\tyield* yieldRequiredFiles(pkg.module, { field: \"module\", ruleId });\n\t}\n\tif (pkg[\"jsnext:main\"]) {\n\t\tyield* yieldRequiredFiles(pkg[\"jsnext:main\"], {\n\t\t\tfield: \"jsnext:main\",\n\t\t\truleId,\n\t\t});\n\t}\n\tif (pkg.types) {\n\t\tyield* yieldRequiredFiles(pkg.types, { field: \"types\", ruleId: \"no-missing-types\" });\n\t}\n\tif (pkg.typings) {\n\t\tyield* yieldRequiredFiles(pkg.typings, { field: \"typings\", ruleId: \"no-missing-typings\" });\n\t}\n\tif (pkg.bin) {\n\t\tyield* yieldRequiredFiles(pkg.bin, { field: \"bin\", ruleId: \"no-missing-binary\" });\n\t}\n\tif (pkg.man) {\n\t\tyield* yieldRequiredFiles(pkg.man, { field: \"man\", ruleId: \"no-missing-man\" });\n\t}\n}\n\nfunction fileExists(filelist: string[], filename: string): boolean {\n\t/* strip leading ./ */\n\tfilename = filename.replace(/^\\.\\//, \"\");\n\n\t/* exact match for filename */\n\tif (filelist.includes(filename)) {\n\t\treturn true;\n\t}\n\n\t/* try to append \".js\" */\n\tif (filelist.includes(`${filename}.js`)) {\n\t\treturn true;\n\t}\n\n\t/* test if it is actually a directory with index.js */\n\tif (filelist.includes(`${filename.replace(/\\/$/, \"\")}/index.js`)) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n/**\n * @param pkg - Parsed `package.json` data\n * @param tarball - Tarball paths\n */\nexport async function verifyTarball(pkg: PackageJson, tarball: TarballMeta): Promise<Result[]> {\n\tconst messages: Message[] = [];\n\tconst filelist = await getFileList(tarball.filePath);\n\n\tfor (const filename of blacklistedFiles(filelist)) {\n\t\tmessages.push({\n\t\t\truleId: \"no-disallowed-files\",\n\t\t\tseverity: 2,\n\t\t\tmessage: `${filename} is not allowed in tarball`,\n\t\t\tline: 1,\n\t\t\tcolumn: 1,\n\t\t});\n\t}\n\n\tfor (const requiredFile of requiredFiles(pkg)) {\n\t\tif (!fileExists(filelist, requiredFile.filename)) {\n\t\t\tmessages.push({\n\t\t\t\truleId: requiredFile.ruleId,\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `${requiredFile.filename} (pkg.${requiredFile.field}) is not present in tarball`,\n\t\t\t\tline: 1,\n\t\t\t\tcolumn: 1,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (messages.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [\n\t\t{\n\t\t\tmessages,\n\t\t\tfilePath: tarball.reportPath ?? tarball.filePath,\n\t\t\terrorCount: messages.filter((it) => it.severity === 2).length,\n\t\t\twarningCount: messages.filter((it) => it.severity === 1).length,\n\t\t\tfixableErrorCount: 0,\n\t\t\tfixableWarningCount: 0,\n\t\t},\n\t];\n}\n", "import EE from 'events'\nimport fs from 'fs'\nimport { Minipass } from 'minipass'\n\nconst writev = fs.writev\n\nconst _autoClose = Symbol('_autoClose')\nconst _close = Symbol('_close')\nconst _ended = Symbol('_ended')\nconst _fd = Symbol('_fd')\nconst _finished = Symbol('_finished')\nconst _flags = Symbol('_flags')\nconst _flush = Symbol('_flush')\nconst _handleChunk = Symbol('_handleChunk')\nconst _makeBuf = Symbol('_makeBuf')\nconst _mode = Symbol('_mode')\nconst _needDrain = Symbol('_needDrain')\nconst _onerror = Symbol('_onerror')\nconst _onopen = Symbol('_onopen')\nconst _onread = Symbol('_onread')\nconst _onwrite = Symbol('_onwrite')\nconst _open = Symbol('_open')\nconst _path = Symbol('_path')\nconst _pos = Symbol('_pos')\nconst _queue = Symbol('_queue')\nconst _read = Symbol('_read')\nconst _readSize = Symbol('_readSize')\nconst _reading = Symbol('_reading')\nconst _remain = Symbol('_remain')\nconst _size = Symbol('_size')\nconst _write = Symbol('_write')\nconst _writing = Symbol('_writing')\nconst _defaultFlag = Symbol('_defaultFlag')\nconst _errored = Symbol('_errored')\n\nexport type ReadStreamOptions =\n Minipass.Options<Minipass.ContiguousData> & {\n fd?: number\n readSize?: number\n size?: number\n autoClose?: boolean\n }\n\nexport type ReadStreamEvents = Minipass.Events<Minipass.ContiguousData> & {\n open: [fd: number]\n}\n\nexport class ReadStream extends Minipass<\n Minipass.ContiguousData,\n Buffer,\n ReadStreamEvents\n> {\n [_errored]: boolean = false;\n [_fd]?: number;\n [_path]: string;\n [_readSize]: number;\n [_reading]: boolean = false;\n [_size]: number;\n [_remain]: number;\n [_autoClose]: boolean\n\n constructor(path: string, opt: ReadStreamOptions) {\n opt = opt || {}\n super(opt)\n\n this.readable = true\n this.writable = false\n\n if (typeof path !== 'string') {\n throw new TypeError('path must be a string')\n }\n\n this[_errored] = false\n this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined\n this[_path] = path\n this[_readSize] = opt.readSize || 16 * 1024 * 1024\n this[_reading] = false\n this[_size] = typeof opt.size === 'number' ? opt.size : Infinity\n this[_remain] = this[_size]\n this[_autoClose] =\n typeof opt.autoClose === 'boolean' ? opt.autoClose : true\n\n if (typeof this[_fd] === 'number') {\n this[_read]()\n } else {\n this[_open]()\n }\n }\n\n get fd() {\n return this[_fd]\n }\n\n get path() {\n return this[_path]\n }\n\n //@ts-ignore\n write() {\n throw new TypeError('this is a readable stream')\n }\n\n //@ts-ignore\n end() {\n throw new TypeError('this is a readable stream')\n }\n\n [_open]() {\n fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd))\n }\n\n [_onopen](er?: NodeJS.ErrnoException | null, fd?: number) {\n if (er) {\n this[_onerror](er)\n } else {\n this[_fd] = fd\n this.emit('open', fd as number)\n this[_read]()\n }\n }\n\n [_makeBuf]() {\n return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]))\n }\n\n [_read]() {\n if (!this[_reading]) {\n this[_reading] = true\n const buf = this[_makeBuf]()\n /* c8 ignore start */\n if (buf.length === 0) {\n return process.nextTick(() => this[_onread](null, 0, buf))\n }\n /* c8 ignore stop */\n fs.read(this[_fd] as number, buf, 0, buf.length, null, (er, br, b) =>\n this[_onread](er, br, b),\n )\n }\n }\n\n [_onread](er?: NodeJS.ErrnoException | null, br?: number, buf?: Buffer) {\n this[_reading] = false\n if (er) {\n this[_onerror](er)\n } else if (this[_handleChunk](br as number, buf as Buffer)) {\n this[_read]()\n }\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.close(fd, er =>\n er ? this.emit('error', er) : this.emit('close'),\n )\n }\n }\n\n [_onerror](er: NodeJS.ErrnoException) {\n this[_reading] = true\n this[_close]()\n this.emit('error', er)\n }\n\n [_handleChunk](br: number, buf: Buffer) {\n let ret = false\n // no effect if infinite\n this[_remain] -= br\n if (br > 0) {\n ret = super.write(br < buf.length ? buf.subarray(0, br) : buf)\n }\n\n if (br === 0 || this[_remain] <= 0) {\n ret = false\n this[_close]()\n super.end()\n }\n\n return ret\n }\n\n emit<Event extends keyof ReadStreamEvents>(\n ev: Event,\n ...args: ReadStreamEvents[Event]\n ): boolean {\n switch (ev) {\n case 'prefinish':\n case 'finish':\n return false\n\n case 'drain':\n if (typeof this[_fd] === 'number') {\n this[_read]()\n }\n return false\n\n case 'error':\n if (this[_errored]) {\n return false\n }\n this[_errored] = true\n return super.emit(ev, ...args)\n\n default:\n return super.emit(ev, ...args)\n }\n }\n}\n\nexport class ReadStreamSync extends ReadStream {\n [_open]() {\n let threw = true\n try {\n this[_onopen](null, fs.openSync(this[_path], 'r'))\n threw = false\n } finally {\n if (threw) {\n this[_close]()\n }\n }\n }\n\n [_read]() {\n let threw = true\n try {\n if (!this[_reading]) {\n this[_reading] = true\n do {\n const buf = this[_makeBuf]()\n /* c8 ignore start */\n const br =\n buf.length === 0\n ? 0\n : fs.readSync(this[_fd] as number, buf, 0, buf.length, null)\n /* c8 ignore stop */\n if (!this[_handleChunk](br, buf)) {\n break\n }\n } while (true)\n this[_reading] = false\n }\n threw = false\n } finally {\n if (threw) {\n this[_close]()\n }\n }\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.closeSync(fd)\n this.emit('close')\n }\n }\n}\n\nexport type WriteStreamOptions = {\n fd?: number\n autoClose?: boolean\n mode?: number\n captureRejections?: boolean\n start?: number\n flags?: string\n}\n\nexport class WriteStream extends EE {\n readable: false = false\n writable: boolean = true;\n [_errored]: boolean = false;\n [_writing]: boolean = false;\n [_ended]: boolean = false;\n [_queue]: Buffer[] = [];\n [_needDrain]: boolean = false;\n [_path]: string;\n [_mode]: number;\n [_autoClose]: boolean;\n [_fd]?: number;\n [_defaultFlag]: boolean;\n [_flags]: string;\n [_finished]: boolean = false;\n [_pos]?: number\n\n constructor(path: string, opt: WriteStreamOptions) {\n opt = opt || {}\n super(opt)\n this[_path] = path\n this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined\n this[_mode] = opt.mode === undefined ? 0o666 : opt.mode\n this[_pos] = typeof opt.start === 'number' ? opt.start : undefined\n this[_autoClose] =\n typeof opt.autoClose === 'boolean' ? opt.autoClose : true\n\n // truncating makes no sense when writing into the middle\n const defaultFlag = this[_pos] !== undefined ? 'r+' : 'w'\n this[_defaultFlag] = opt.flags === undefined\n this[_flags] = opt.flags === undefined ? defaultFlag : opt.flags\n\n if (this[_fd] === undefined) {\n this[_open]()\n }\n }\n\n emit(ev: string, ...args: any[]) {\n if (ev === 'error') {\n if (this[_errored]) {\n return false\n }\n this[_errored] = true\n }\n return super.emit(ev, ...args)\n }\n\n get fd() {\n return this[_fd]\n }\n\n get path() {\n return this[_path]\n }\n\n [_onerror](er: NodeJS.ErrnoException) {\n this[_close]()\n this[_writing] = true\n this.emit('error', er)\n }\n\n [_open]() {\n fs.open(this[_path], this[_flags], this[_mode], (er, fd) =>\n this[_onopen](er, fd),\n )\n }\n\n [_onopen](er?: null | NodeJS.ErrnoException, fd?: number) {\n if (\n this[_defaultFlag] &&\n this[_flags] === 'r+' &&\n er &&\n er.code === 'ENOENT'\n ) {\n this[_flags] = 'w'\n this[_open]()\n } else if (er) {\n this[_onerror](er)\n } else {\n this[_fd] = fd\n this.emit('open', fd)\n if (!this[_writing]) {\n this[_flush]()\n }\n }\n }\n\n end(buf: string, enc?: BufferEncoding): this\n end(buf?: Buffer, enc?: undefined): this\n end(buf?: Buffer | string, enc?: BufferEncoding): this {\n if (buf) {\n //@ts-ignore\n this.write(buf, enc)\n }\n\n this[_ended] = true\n\n // synthetic after-write logic, where drain/finish live\n if (\n !this[_writing] &&\n !this[_queue].length &&\n typeof this[_fd] === 'number'\n ) {\n this[_onwrite](null, 0)\n }\n return this\n }\n\n write(buf: string, enc?: BufferEncoding): boolean\n write(buf: Buffer, enc?: undefined): boolean\n write(buf: Buffer | string, enc?: BufferEncoding): boolean {\n if (typeof buf === 'string') {\n buf = Buffer.from(buf, enc)\n }\n\n if (this[_ended]) {\n this.emit('error', new Error('write() after end()'))\n return false\n }\n\n if (this[_fd] === undefined || this[_writing] || this[_queue].length) {\n this[_queue].push(buf)\n this[_needDrain] = true\n return false\n }\n\n this[_writing] = true\n this[_write](buf)\n return true\n }\n\n [_write](buf: Buffer) {\n fs.write(\n this[_fd] as number,\n buf,\n 0,\n buf.length,\n this[_pos],\n (er, bw) => this[_onwrite](er, bw),\n )\n }\n\n [_onwrite](er?: null | NodeJS.ErrnoException, bw?: number) {\n if (er) {\n this[_onerror](er)\n } else {\n if (this[_pos] !== undefined && typeof bw === 'number') {\n this[_pos] += bw\n }\n if (this[_queue].length) {\n this[_flush]()\n } else {\n this[_writing] = false\n\n if (this[_ended] && !this[_finished]) {\n this[_finished] = true\n this[_close]()\n this.emit('finish')\n } else if (this[_needDrain]) {\n this[_needDrain] = false\n this.emit('drain')\n }\n }\n }\n }\n\n [_flush]() {\n if (this[_queue].length === 0) {\n if (this[_ended]) {\n this[_onwrite](null, 0)\n }\n } else if (this[_queue].length === 1) {\n this[_write](this[_queue].pop() as Buffer)\n } else {\n const iovec = this[_queue]\n this[_queue] = []\n writev(this[_fd] as number, iovec, this[_pos] as number, (er, bw) =>\n this[_onwrite](er, bw),\n )\n }\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.close(fd, er =>\n er ? this.emit('error', er) : this.emit('close'),\n )\n }\n }\n}\n\nexport class WriteStreamSync extends WriteStream {\n [_open](): void {\n let fd\n // only wrap in a try{} block if we know we'll retry, to avoid\n // the rethrow obscuring the error's source frame in most cases.\n if (this[_defaultFlag] && this[_flags] === 'r+') {\n try {\n fd = fs.openSync(this[_path], this[_flags], this[_mode])\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') {\n this[_flags] = 'w'\n return this[_open]()\n } else {\n throw er\n }\n }\n } else {\n fd = fs.openSync(this[_path], this[_flags], this[_mode])\n }\n\n this[_onopen](null, fd)\n }\n\n [_close]() {\n if (this[_autoClose] && typeof this[_fd] === 'number') {\n const fd = this[_fd]\n this[_fd] = undefined\n fs.closeSync(fd)\n this.emit('close')\n }\n }\n\n [_write](buf: Buffer) {\n // throw the original, but try to close if it fails\n let threw = true\n try {\n this[_onwrite](\n null,\n fs.writeSync(this[_fd] as number, buf, 0, buf.length, this[_pos]),\n )\n threw = false\n } finally {\n if (threw) {\n try {\n this[_close]()\n } catch {\n // ok error\n }\n }\n }\n }\n}\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "import { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass'\nimport { Minipass } from 'minipass'\nimport path from 'node:path'\nimport { list } from './list.js'\nimport { makeCommand } from './make-command.js'\nimport {\n TarOptions,\n TarOptionsFile,\n TarOptionsSync,\n TarOptionsSyncFile,\n} from './options.js'\nimport { Pack, PackSync } from './pack.js'\n\nconst createFileSync = (opt: TarOptionsSyncFile, files: string[]) => {\n const p = new PackSync(opt)\n const stream = new WriteStreamSync(opt.file, {\n mode: opt.mode || 0o666,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n addFilesSync(p, files)\n}\n\nconst createFile = (opt: TarOptionsFile, files: string[]) => {\n const p = new Pack(opt)\n const stream = new WriteStream(opt.file, {\n mode: opt.mode || 0o666,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n\n const promise = new Promise<void>((res, rej) => {\n stream.on('error', rej)\n stream.on('close', res)\n p.on('error', rej)\n })\n\n addFilesAsync(p, files)\n\n return promise\n}\n\nconst addFilesSync = (p: PackSync, files: string[]) => {\n files.forEach(file => {\n if (file.charAt(0) === '@') {\n list({\n file: path.resolve(p.cwd, file.slice(1)),\n sync: true,\n noResume: true,\n onReadEntry: entry => p.add(entry),\n })\n } else {\n p.add(file)\n }\n })\n p.end()\n}\n\nconst addFilesAsync = async (\n p: Pack,\n files: string[],\n): Promise<void> => {\n for (let i = 0; i < files.length; i++) {\n const file = String(files[i])\n if (file.charAt(0) === '@') {\n await list({\n file: path.resolve(String(p.cwd), file.slice(1)),\n noResume: true,\n onReadEntry: entry => {\n p.add(entry)\n },\n })\n } else {\n p.add(file)\n }\n }\n p.end()\n}\n\nconst createSync = (opt: TarOptionsSync, files: string[]) => {\n const p = new PackSync(opt)\n addFilesSync(p, files)\n return p\n}\n\nconst createAsync = (opt: TarOptions, files: string[]) => {\n const p = new Pack(opt)\n addFilesAsync(p, files)\n return p\n}\n\nexport const create = makeCommand(\n createFileSync,\n createFile,\n createSync,\n createAsync,\n (_opt, files) => {\n if (!files?.length) {\n throw new TypeError('no paths specified to add to archive')\n }\n },\n)\n", "// tar -t\nimport * as fsm from '@isaacs/fs-minipass'\nimport fs from 'node:fs'\nimport { dirname, parse } from 'path'\nimport { makeCommand } from './make-command.js'\nimport {\n TarOptions,\n TarOptionsFile,\n TarOptionsSyncFile,\n} from './options.js'\nimport { Parser } from './parse.js'\nimport { stripTrailingSlashes } from './strip-trailing-slashes.js'\n\nconst onReadEntryFunction = (opt: TarOptions) => {\n const onReadEntry = opt.onReadEntry\n opt.onReadEntry =\n onReadEntry ?\n e => {\n onReadEntry(e)\n e.resume()\n }\n : e => e.resume()\n}\n\n// construct a filter that limits the file entries listed\n// include child entries if a dir is included\nexport const filesFilter = (opt: TarOptions, files: string[]) => {\n const map = new Map<string, boolean>(\n files.map(f => [stripTrailingSlashes(f), true]),\n )\n const filter = opt.filter\n\n const mapHas = (file: string, r: string = ''): boolean => {\n const root = r || parse(file).root || '.'\n let ret: boolean\n if (file === root) ret = false\n else {\n const m = map.get(file)\n if (m !== undefined) {\n ret = m\n } else {\n ret = mapHas(dirname(file), root)\n }\n }\n\n map.set(file, ret)\n return ret\n }\n\n opt.filter =\n filter ?\n (file, entry) =>\n filter(file, entry) && mapHas(stripTrailingSlashes(file))\n : file => mapHas(stripTrailingSlashes(file))\n}\n\nconst listFileSync = (opt: TarOptionsSyncFile) => {\n const p = new Parser(opt)\n const file = opt.file\n let fd: number | undefined\n try {\n fd = fs.openSync(file, 'r')\n const stat: fs.Stats = fs.fstatSync(fd)\n const readSize: number = opt.maxReadSize || 16 * 1024 * 1024\n if (stat.size < readSize) {\n const buf = Buffer.allocUnsafe(stat.size)\n const read = fs.readSync(fd, buf, 0, stat.size, 0)\n p.end(read === buf.byteLength ? buf : buf.subarray(0, read))\n } else {\n let pos = 0\n const buf = Buffer.allocUnsafe(readSize)\n while (pos < stat.size) {\n const bytesRead = fs.readSync(fd, buf, 0, readSize, pos)\n if (bytesRead === 0) break\n pos += bytesRead\n p.write(buf.subarray(0, bytesRead))\n }\n p.end()\n }\n } finally {\n if (typeof fd === 'number') {\n try {\n fs.closeSync(fd)\n /* c8 ignore next */\n } catch (er) {}\n }\n }\n}\n\nconst listFile = (\n opt: TarOptionsFile,\n _files: string[],\n): Promise<void> => {\n const parse = new Parser(opt)\n const readSize = opt.maxReadSize || 16 * 1024 * 1024\n\n const file = opt.file\n const p = new Promise<void>((resolve, reject) => {\n parse.on('error', reject)\n parse.on('end', resolve)\n\n fs.stat(file, (er, stat) => {\n if (er) {\n reject(er)\n } else {\n const stream = new fsm.ReadStream(file, {\n readSize: readSize,\n size: stat.size,\n })\n stream.on('error', reject)\n stream.pipe(parse)\n }\n })\n })\n return p\n}\n\nexport const list = makeCommand(\n listFileSync,\n listFile,\n opt => new Parser(opt) as Parser & { sync: true },\n opt => new Parser(opt),\n (opt, files) => {\n if (files?.length) filesFilter(opt, files)\n if (!opt.noResume) onReadEntryFunction(opt)\n },\n)\n", "// turn tar(1) style args like `C` into the more verbose things like `cwd`\n\nimport { type GzipOptions, type ZlibOptions } from 'minizlib'\nimport { type Stats } from 'node:fs'\nimport { type ReadEntry } from './read-entry.js'\nimport { type WarnData } from './warn-method.js'\nimport { WriteEntry } from './write-entry.js'\n\nconst argmap = new Map<keyof TarOptionsWithAliases, keyof TarOptions>(\n [\n ['C', 'cwd'],\n ['f', 'file'],\n ['z', 'gzip'],\n ['P', 'preservePaths'],\n ['U', 'unlink'],\n ['strip-components', 'strip'],\n ['stripComponents', 'strip'],\n ['keep-newer', 'newer'],\n ['keepNewer', 'newer'],\n ['keep-newer-files', 'newer'],\n ['keepNewerFiles', 'newer'],\n ['k', 'keep'],\n ['keep-existing', 'keep'],\n ['keepExisting', 'keep'],\n ['m', 'noMtime'],\n ['no-mtime', 'noMtime'],\n ['p', 'preserveOwner'],\n ['L', 'follow'],\n ['h', 'follow'],\n ['onentry', 'onReadEntry'],\n ],\n)\n\n/**\n * The options that can be provided to tar commands.\n *\n * Note that some of these are only relevant for certain commands, since\n * they are specific to reading or writing.\n *\n * Aliases are provided in the {@link TarOptionsWithAliases} type.\n */\nexport interface TarOptions {\n //////////////////////////\n // shared options\n\n /**\n * Perform all I/O operations synchronously. If the stream is ended\n * immediately, then it will be processed entirely synchronously.\n */\n sync?: boolean\n\n /**\n * The tar file to be read and/or written. When this is set, a stream\n * is not returned. Asynchronous commands will return a promise indicating\n * when the operation is completed, and synchronous commands will return\n * immediately.\n */\n file?: string\n\n /**\n * Treat warnings as crash-worthy errors. Defaults false.\n */\n strict?: boolean\n\n /**\n * The effective current working directory for this tar command\n */\n cwd?: string\n\n /**\n * When creating a tar archive, this can be used to compress it as well.\n * Set to `true` to use the default gzip options, or customize them as\n * needed.\n *\n * When reading, if this is unset, then the compression status will be\n * inferred from the archive data. This is generally best, unless you are\n * sure of the compression settings in use to create the archive, and want to\n * fail if the archive doesn't match expectations.\n */\n gzip?: boolean | GzipOptions\n\n /**\n * When creating archives, preserve absolute and `..` paths in the archive,\n * rather than sanitizing them under the cwd.\n *\n * When extracting, allow absolute paths, paths containing `..`, and\n * extracting through symbolic links. By default, the root `/` is stripped\n * from absolute paths (eg, turning `/x/y/z` into `x/y/z`), paths containing\n * `..` are not extracted, and any file whose location would be modified by a\n * symbolic link is not extracted.\n *\n * **WARNING** This is almost always unsafe, and must NEVER be used on\n * archives from untrusted sources, such as user input, and every entry must\n * be validated to ensure it is safe to write. Even if the input is not\n * malicious, mistakes can cause a lot of damage!\n */\n preservePaths?: boolean\n\n /**\n * When extracting, do not set the `mtime` value for extracted entries to\n * match the `mtime` in the archive.\n *\n * When creating archives, do not store the `mtime` value in the entry. Note\n * that this prevents properly using other mtime-based features (such as\n * `tar.update` or the `newer` option) with the resulting archive.\n */\n noMtime?: boolean\n\n /**\n * Set to `true` or an object with settings for `zlib.BrotliCompress()` to\n * create a brotli-compressed archive\n *\n * When extracting, this will cause the archive to be treated as a\n * brotli-compressed file if set to `true` or a ZlibOptions object.\n *\n * If set `false`, then brotli options will not be used.\n *\n * If this, the `gzip`, and `zstd` options are left `undefined`, then tar\n * will attempt to infer the brotli compression status, but can only do so\n * based on the filename. If the filename ends in `.tbr` or `.tar.br`, and\n * the first 512 bytes are not a valid tar header, then brotli decompression\n * will be attempted.\n */\n brotli?: boolean | ZlibOptions\n\n /**\n * Set to `true` or an object with settings for `zstd.compress()` to\n * create a zstd-compressed archive\n *\n * When extracting, this will cause the archive to be treated as a\n * zstd-compressed file if set to `true` or a ZlibOptions object.\n *\n * If set `false`, then zstd options will not be used.\n *\n * If this, the `gzip`, and `brotli` options are left `undefined`, then tar\n * will attempt to infer the zstd compression status, but can only do so\n * based on the filename. If the filename ends in `.tzst` or `.tar.zst`, and\n * the first 512 bytes are not a valid tar header, then zstd decompression\n * will be attempted.\n */\n zstd?: boolean | ZlibOptions\n\n /**\n * A function that is called with `(path, stat)` when creating an archive, or\n * `(path, entry)` when extracting. Return true to process the file/entry, or\n * false to exclude it.\n */\n filter?: (path: string, entry: Stats | ReadEntry) => boolean\n\n /**\n * A function that gets called for any warning encountered.\n *\n * Note: if `strict` is set, then the warning will throw, and this method\n * will not be called.\n */\n onwarn?: (code: string, message: string, data: WarnData) => any\n\n //////////////////////////\n // extraction options\n\n /**\n * When extracting, unlink files before creating them. Without this option,\n * tar overwrites existing files, which preserves existing hardlinks. With\n * this option, existing hardlinks will be broken, as will any symlink that\n * would affect the location of an extracted file.\n */\n unlink?: boolean\n\n /**\n * When extracting, strip the specified number of path portions from the\n * entry path. For example, with `{strip: 2}`, the entry `a/b/c/d` would be\n * extracted to `{cwd}/c/d`.\n *\n * Any entry whose entire path is stripped will be excluded.\n */\n strip?: number\n\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n newer?: boolean\n\n /**\n * When extracting, do not overwrite existing files at all.\n */\n keep?: boolean\n\n /**\n * When extracting, set the `uid` and `gid` of extracted entries to the `uid`\n * and `gid` fields in the archive. Defaults to true when run as root, and\n * false otherwise.\n *\n * If false, then files and directories will be set with the owner and group\n * of the user running the process. This is similar to `-p` in `tar(1)`, but\n * ACLs and other system-specific data is never unpacked in this\n * implementation, and modes are set by default already.\n */\n preserveOwner?: boolean\n\n /**\n * The maximum depth of subfolders to extract into. This defaults to 1024.\n * Anything deeper than the limit will raise a warning and skip the entry.\n * Set to `Infinity` to remove the limitation.\n */\n maxDepth?: number\n\n /**\n * When extracting, force all created files and directories, and all\n * implicitly created directories, to be owned by the specified user id,\n * regardless of the `uid` field in the archive.\n *\n * Cannot be used along with `preserveOwner`. Requires also setting the `gid`\n * option.\n */\n uid?: number\n\n /**\n * When extracting, force all created files and directories, and all\n * implicitly created directories, to be owned by the specified group id,\n * regardless of the `gid` field in the archive.\n *\n * Cannot be used along with `preserveOwner`. Requires also setting the `uid`\n * option.\n */\n gid?: number\n\n /**\n * When extracting, provide a function that takes an `entry` object, and\n * returns a stream, or any falsey value. If a stream is provided, then that\n * stream's data will be written instead of the contents of the archive\n * entry. If a falsey value is provided, then the entry is written to disk as\n * normal.\n *\n * To exclude items from extraction, use the `filter` option.\n *\n * Note that using an asynchronous stream type with the `transform` option\n * will cause undefined behavior in synchronous extractions.\n * [MiniPass](http://npm.im/minipass)-based streams are designed for this use\n * case.\n */\n transform?: (entry: ReadEntry) => any\n\n /**\n * Call `chmod()` to ensure that extracted files match the entry's mode\n * field. Without this field set, all mode fields in archive entries are a\n * best effort attempt only.\n *\n * Setting this necessitates a call to the deprecated `process.umask()`\n * method to determine the default umask value, unless a `processUmask`\n * config is provided as well.\n *\n * If not set, tar will attempt to create file system entries with whatever\n * mode is provided, and let the implicit process `umask` apply normally, but\n * if a file already exists to be written to, then its existing mode will not\n * be modified.\n *\n * When setting `chmod: true`, it is highly recommend to set the\n * {@link TarOptions#processUmask} option as well, to avoid the call to the\n * deprecated (and thread-unsafe) `process.umask()` method.\n */\n chmod?: boolean\n\n /**\n * When setting the {@link TarOptions#chmod} option to `true`, you may\n * provide a value here to avoid having to call the deprecated and\n * thread-unsafe `process.umask()` method.\n *\n * This has no effect with `chmod` is not set to true, as mode values are not\n * set explicitly anyway. If `chmod` is set to `true`, and a value is not\n * provided here, then `process.umask()` must be called, which will result in\n * deprecation warnings.\n *\n * The most common values for this are `0o22` (resulting in directories\n * created with mode `0o755` and files with `0o644` by default) and `0o2`\n * (resulting in directores created with mode `0o775` and files `0o664`, so\n * they are group-writable).\n */\n processUmask?: number\n\n //////////////////////////\n // archive creation options\n\n /**\n * When parsing/listing archives, `entry` streams are by default resumed\n * (set into \"flowing\" mode) immediately after the call to `onReadEntry()`.\n * Set `noResume: true` to suppress this behavior.\n *\n * Note that when this is set, the stream will never complete until the\n * data is consumed somehow.\n *\n * Set automatically in extract operations, since the entry is piped to\n * a file system entry right away. Only relevant when parsing.\n */\n noResume?: boolean\n\n /**\n * When creating, updating, or replacing within archives, this method will\n * be called with each WriteEntry that is created.\n */\n onWriteEntry?: (entry: WriteEntry) => any\n\n /**\n * When extracting or listing archives, this method will be called with\n * each entry that is not excluded by a `filter`.\n *\n * Important when listing archives synchronously from a file, because there\n * is otherwise no way to interact with the data!\n */\n onReadEntry?: (entry: ReadEntry) => any\n\n /**\n * Pack the targets of symbolic links rather than the link itself.\n */\n follow?: boolean\n\n /**\n * When creating archives, omit any metadata that is system-specific:\n * `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and\n * `nlink`. Note that `mtime` is still included, because this is necessary\n * for other time-based operations such as `tar.update`. Additionally, `mode`\n * is set to a \"reasonable default\" for mose unix systems, based on an\n * effective `umask` of `0o22`.\n *\n * This also defaults the `portable` option in the gzip configs when creating\n * a compressed archive, in order to produce deterministic archives that are\n * not operating-system specific.\n */\n portable?: boolean\n\n /**\n * When creating archives, do not recursively archive the contents of\n * directories. By default, archiving a directory archives all of its\n * contents as well.\n */\n noDirRecurse?: boolean\n\n /**\n * Suppress Pax extended headers when creating archives. Note that this means\n * long paths and linkpaths will be truncated, and large or negative numeric\n * values may be interpreted incorrectly.\n */\n noPax?: boolean\n\n /**\n * Set to a `Date` object to force a specific `mtime` value for everything\n * written to an archive.\n *\n * This is useful when creating archives that are intended to be\n * deterministic based on their contents, irrespective of the file's last\n * modification time.\n *\n * Overridden by `noMtime`.\n */\n mtime?: Date\n\n /**\n * A path portion to prefix onto the entries added to an archive.\n */\n prefix?: string\n\n /**\n * The mode to set on any created file archive, defaults to 0o666\n * masked by the process umask, often resulting in 0o644.\n *\n * This does *not* affect the mode fields of individual entries, or the\n * mode status of extracted entries on the filesystem.\n */\n mode?: number\n\n //////////////////////////\n // internal options\n\n /**\n * A cache of mtime values, to avoid having to stat the same file repeatedly.\n *\n * @internal\n */\n mtimeCache?: Map<string, Date>\n\n /**\n * maximum buffer size for `fs.read()` operations.\n *\n * @internal\n */\n maxReadSize?: number\n\n /**\n * Filter modes of entries being unpacked, like `process.umask()`\n *\n * @internal\n */\n umask?: number\n\n /**\n * Default mode for directories. Used for all implicitly created directories,\n * and any directories in the archive that do not have a mode field.\n *\n * @internal\n */\n dmode?: number\n\n /**\n * default mode for files\n *\n * @internal\n */\n fmode?: number\n\n /**\n * Map that tracks which directories already exist, for extraction\n *\n * @internal\n */\n dirCache?: Map<string, boolean>\n /**\n * maximum supported size of meta entries. Defaults to 1MB\n *\n * @internal\n */\n maxMetaEntrySize?: number\n\n /**\n * A Map object containing the device and inode value for any file whose\n * `nlink` value is greater than 1, to identify hard links when creating\n * archives.\n *\n * @internal\n */\n linkCache?: Map<LinkCacheKey, string>\n\n /**\n * A map object containing the results of `fs.readdir()` calls.\n *\n * @internal\n */\n readdirCache?: Map<string, string[]>\n\n /**\n * A cache of all `lstat` results, for use in creating archives.\n *\n * @internal\n */\n statCache?: Map<string, Stats>\n\n /**\n * Number of concurrent jobs to run when creating archives.\n *\n * Defaults to 4.\n *\n * @internal\n */\n jobs?: number\n\n /**\n * Automatically set to true on Windows systems.\n *\n * When extracting, causes behavior where filenames containing `<|>?:`\n * characters are converted to windows-compatible escape sequences in the\n * created filesystem entries.\n *\n * When packing, causes behavior where paths replace `\\` with `/`, and\n * filenames containing the windows-compatible escaped forms of `<|>?:` are\n * converted to actual `<|>?:` characters in the archive.\n *\n * @internal\n */\n win32?: boolean\n\n /**\n * For `WriteEntry` objects, the absolute path to the entry on the\n * filesystem. By default, this is `resolve(cwd, entry.path)`, but it can be\n * overridden explicitly.\n *\n * @internal\n */\n absolute?: string\n\n /**\n * Used with Parser stream interface, to attach and take over when the\n * stream is completely parsed. If this is set, then the prefinish,\n * finish, and end events will not fire, and are the responsibility of\n * the ondone method to emit properly.\n *\n * @internal\n */\n ondone?: () => void\n\n /**\n * Mostly for testing, but potentially useful in some cases.\n * Forcibly trigger a chown on every entry, no matter what.\n */\n forceChown?: boolean\n\n /**\n * ambiguous deprecated name for {@link onReadEntry}\n *\n * @deprecated\n */\n onentry?: (entry: ReadEntry) => any\n}\n\nexport type TarOptionsSync = TarOptions & { sync: true }\nexport type TarOptionsAsync = TarOptions & { sync?: false }\nexport type TarOptionsFile = TarOptions & { file: string }\nexport type TarOptionsNoFile = TarOptions & { file?: undefined }\nexport type TarOptionsSyncFile = TarOptionsSync & TarOptionsFile\nexport type TarOptionsAsyncFile = TarOptionsAsync & TarOptionsFile\nexport type TarOptionsSyncNoFile = TarOptionsSync & TarOptionsNoFile\nexport type TarOptionsAsyncNoFile = TarOptionsAsync & TarOptionsNoFile\n\nexport type LinkCacheKey = `${number}:${number}`\n\nexport interface TarOptionsWithAliases extends TarOptions {\n /**\n * The effective current working directory for this tar command\n */\n C?: TarOptions['cwd']\n /**\n * The tar file to be read and/or written. When this is set, a stream\n * is not returned. Asynchronous commands will return a promise indicating\n * when the operation is completed, and synchronous commands will return\n * immediately.\n */\n f?: TarOptions['file']\n /**\n * When creating a tar archive, this can be used to compress it as well.\n * Set to `true` to use the default gzip options, or customize them as\n * needed.\n *\n * When reading, if this is unset, then the compression status will be\n * inferred from the archive data. This is generally best, unless you are\n * sure of the compression settings in use to create the archive, and want to\n * fail if the archive doesn't match expectations.\n */\n z?: TarOptions['gzip']\n /**\n * When creating archives, preserve absolute and `..` paths in the archive,\n * rather than sanitizing them under the cwd.\n *\n * When extracting, allow absolute paths, paths containing `..`, and\n * extracting through symbolic links. By default, the root `/` is stripped\n * from absolute paths (eg, turning `/x/y/z` into `x/y/z`), paths containing\n * `..` are not extracted, and any file whose location would be modified by a\n * symbolic link is not extracted.\n *\n * **WARNING** This is almost always unsafe, and must NEVER be used on\n * archives from untrusted sources, such as user input, and every entry must\n * be validated to ensure it is safe to write. Even if the input is not\n * malicious, mistakes can cause a lot of damage!\n */\n P?: TarOptions['preservePaths']\n /**\n * When extracting, unlink files before creating them. Without this option,\n * tar overwrites existing files, which preserves existing hardlinks. With\n * this option, existing hardlinks will be broken, as will any symlink that\n * would affect the location of an extracted file.\n */\n U?: TarOptions['unlink']\n /**\n * When extracting, strip the specified number of path portions from the\n * entry path. For example, with `{strip: 2}`, the entry `a/b/c/d` would be\n * extracted to `{cwd}/c/d`.\n */\n 'strip-components'?: TarOptions['strip']\n /**\n * When extracting, strip the specified number of path portions from the\n * entry path. For example, with `{strip: 2}`, the entry `a/b/c/d` would be\n * extracted to `{cwd}/c/d`.\n */\n stripComponents?: TarOptions['strip']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n 'keep-newer'?: TarOptions['newer']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n keepNewer?: TarOptions['newer']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n 'keep-newer-files'?: TarOptions['newer']\n /**\n * When extracting, keep the existing file on disk if it's newer than the\n * file in the archive.\n */\n keepNewerFiles?: TarOptions['newer']\n /**\n * When extracting, do not overwrite existing files at all.\n */\n k?: TarOptions['keep']\n /**\n * When extracting, do not overwrite existing files at all.\n */\n 'keep-existing'?: TarOptions['keep']\n /**\n * When extracting, do not overwrite existing files at all.\n */\n keepExisting?: TarOptions['keep']\n /**\n * When extracting, do not set the `mtime` value for extracted entries to\n * match the `mtime` in the archive.\n *\n * When creating archives, do not store the `mtime` value in the entry. Note\n * that this prevents properly using other mtime-based features (such as\n * `tar.update` or the `newer` option) with the resulting archive.\n */\n m?: TarOptions['noMtime']\n /**\n * When extracting, do not set the `mtime` value for extracted entries to\n * match the `mtime` in the archive.\n *\n * When creating archives, do not store the `mtime` value in the entry. Note\n * that this prevents properly using other mtime-based features (such as\n * `tar.update` or the `newer` option) with the resulting archive.\n */\n 'no-mtime'?: TarOptions['noMtime']\n /**\n * When extracting, set the `uid` and `gid` of extracted entries to the `uid`\n * and `gid` fields in the archive. Defaults to true when run as root, and\n * false otherwise.\n *\n * If false, then files and directories will be set with the owner and group\n * of the user running the process. This is similar to `-p` in `tar(1)`, but\n * ACLs and other system-specific data is never unpacked in this\n * implementation, and modes are set by default already.\n */\n p?: TarOptions['preserveOwner']\n /**\n * Pack the targets of symbolic links rather than the link itself.\n */\n L?: TarOptions['follow']\n /**\n * Pack the targets of symbolic links rather than the link itself.\n */\n h?: TarOptions['follow']\n\n /**\n * Deprecated option. Set explicitly false to set `chmod: true`. Ignored\n * if {@link TarOptions#chmod} is set to any boolean value.\n *\n * @deprecated\n */\n noChmod?: boolean\n}\n\nexport type TarOptionsWithAliasesSync = TarOptionsWithAliases & {\n sync: true\n}\nexport type TarOptionsWithAliasesAsync = TarOptionsWithAliases & {\n sync?: false\n}\nexport type TarOptionsWithAliasesFile =\n | (TarOptionsWithAliases & {\n file: string\n })\n | (TarOptionsWithAliases & { f: string })\nexport type TarOptionsWithAliasesSyncFile =\n TarOptionsWithAliasesSync & TarOptionsWithAliasesFile\nexport type TarOptionsWithAliasesAsyncFile =\n TarOptionsWithAliasesAsync & TarOptionsWithAliasesFile\n\nexport type TarOptionsWithAliasesNoFile = TarOptionsWithAliases & {\n f?: undefined\n file?: undefined\n}\n\nexport type TarOptionsWithAliasesSyncNoFile =\n TarOptionsWithAliasesSync & TarOptionsWithAliasesNoFile\nexport type TarOptionsWithAliasesAsyncNoFile =\n TarOptionsWithAliasesAsync & TarOptionsWithAliasesNoFile\n\nexport const isSyncFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsSyncFile => !!o.sync && !!o.file\nexport const isAsyncFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsAsyncFile => !o.sync && !!o.file\nexport const isSyncNoFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsSyncNoFile => !!o.sync && !o.file\nexport const isAsyncNoFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsAsyncNoFile => !o.sync && !o.file\nexport const isSync = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsSync => !!o.sync\nexport const isAsync = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsAsync => !o.sync\nexport const isFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsFile => !!o.file\nexport const isNoFile = <O extends TarOptions>(\n o: O,\n): o is O & TarOptionsNoFile => !o.file\n\nconst dealiasKey = (\n k: keyof TarOptionsWithAliases,\n): keyof TarOptions => {\n const d = argmap.get(k)\n if (d) return d\n return k as keyof TarOptions\n}\n\nexport const dealias = (\n opt: TarOptionsWithAliases = {},\n): TarOptions => {\n if (!opt) return {}\n const result: Record<string, any> = {}\n for (const [key, v] of Object.entries(opt) as [\n keyof TarOptionsWithAliases,\n any,\n ][]) {\n // TS doesn't know that aliases are going to always be the same type\n const k = dealiasKey(key)\n result[k] = v\n }\n // affordance for deprecated noChmod -> chmod\n if (result.chmod === undefined && result.noChmod === false) {\n result.chmod = true\n }\n delete result.noChmod\n return result as TarOptions\n}\n", "import {\n dealias,\n isAsyncFile,\n isAsyncNoFile,\n isSyncFile,\n isSyncNoFile,\n TarOptions,\n TarOptionsAsyncFile,\n TarOptionsAsyncNoFile,\n TarOptionsSyncFile,\n TarOptionsSyncNoFile,\n TarOptionsWithAliases,\n TarOptionsWithAliasesAsync,\n TarOptionsWithAliasesAsyncFile,\n TarOptionsWithAliasesAsyncNoFile,\n TarOptionsWithAliasesFile,\n TarOptionsWithAliasesNoFile,\n TarOptionsWithAliasesSync,\n TarOptionsWithAliasesSyncFile,\n TarOptionsWithAliasesSyncNoFile,\n} from './options.js'\n\nexport type CB = (er?: Error) => any\n\nexport type TarCommand<\n AsyncClass,\n SyncClass extends { sync: true },\n> = {\n // async and no file specified\n (): AsyncClass\n (opt: TarOptionsWithAliasesAsyncNoFile): AsyncClass\n (entries: string[]): AsyncClass\n (\n opt: TarOptionsWithAliasesAsyncNoFile,\n entries: string[],\n ): AsyncClass\n} & {\n // sync and no file\n (opt: TarOptionsWithAliasesSyncNoFile): SyncClass\n (opt: TarOptionsWithAliasesSyncNoFile, entries: string[]): SyncClass\n} & {\n // async and file\n (opt: TarOptionsWithAliasesAsyncFile): Promise<void>\n (\n opt: TarOptionsWithAliasesAsyncFile,\n entries: string[],\n ): Promise<void>\n (opt: TarOptionsWithAliasesAsyncFile, cb: CB): Promise<void>\n (\n opt: TarOptionsWithAliasesAsyncFile,\n entries: string[],\n cb: CB,\n ): Promise<void>\n} & {\n // sync and file\n (opt: TarOptionsWithAliasesSyncFile): void\n (opt: TarOptionsWithAliasesSyncFile, entries: string[]): void\n} & {\n // sync, maybe file\n (opt: TarOptionsWithAliasesSync): typeof opt extends (\n TarOptionsWithAliasesFile\n ) ?\n void\n : typeof opt extends TarOptionsWithAliasesNoFile ? SyncClass\n : void | SyncClass\n (\n opt: TarOptionsWithAliasesSync,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesFile ? void\n : typeof opt extends TarOptionsWithAliasesNoFile ? SyncClass\n : void | SyncClass\n} & {\n // async, maybe file\n (opt: TarOptionsWithAliasesAsync): typeof opt extends (\n TarOptionsWithAliasesFile\n ) ?\n Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ? AsyncClass\n : Promise<void> | AsyncClass\n (\n opt: TarOptionsWithAliasesAsync,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesFile ? Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ? AsyncClass\n : Promise<void> | AsyncClass\n (opt: TarOptionsWithAliasesAsync, cb: CB): Promise<void>\n (\n opt: TarOptionsWithAliasesAsync,\n entries: string[],\n cb: CB,\n ): typeof opt extends TarOptionsWithAliasesFile ? Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ? never\n : Promise<void>\n} & {\n // maybe sync, file\n (opt: TarOptionsWithAliasesFile): Promise<void> | void\n (\n opt: TarOptionsWithAliasesFile,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesSync ? void\n : typeof opt extends TarOptionsWithAliasesAsync ? Promise<void>\n : Promise<void> | void\n (opt: TarOptionsWithAliasesFile, cb: CB): Promise<void>\n (\n opt: TarOptionsWithAliasesFile,\n entries: string[],\n cb: CB,\n ): typeof opt extends TarOptionsWithAliasesSync ? never\n : typeof opt extends TarOptionsWithAliasesAsync ? Promise<void>\n : Promise<void>\n} & {\n // maybe sync, no file\n (opt: TarOptionsWithAliasesNoFile): typeof opt extends (\n TarOptionsWithAliasesSync\n ) ?\n SyncClass\n : typeof opt extends TarOptionsWithAliasesAsync ? AsyncClass\n : SyncClass | AsyncClass\n (\n opt: TarOptionsWithAliasesNoFile,\n entries: string[],\n ): typeof opt extends TarOptionsWithAliasesSync ? SyncClass\n : typeof opt extends TarOptionsWithAliasesAsync ? AsyncClass\n : SyncClass | AsyncClass\n} & {\n // maybe sync, maybe file\n (opt: TarOptionsWithAliases): typeof opt extends (\n TarOptionsWithAliasesFile\n ) ?\n typeof opt extends TarOptionsWithAliasesSync ? void\n : typeof opt extends TarOptionsWithAliasesAsync ? Promise<void>\n : void | Promise<void>\n : typeof opt extends TarOptionsWithAliasesNoFile ?\n typeof opt extends TarOptionsWithAliasesSync ? SyncClass\n : typeof opt extends TarOptionsWithAliasesAsync ? AsyncClass\n : SyncClass | AsyncClass\n : typeof opt extends TarOptionsWithAliasesSync ? SyncClass | void\n : typeof opt extends TarOptionsWithAliasesAsync ?\n AsyncClass | Promise<void>\n : SyncClass | void | AsyncClass | Promise<void>\n} & {\n // extras\n syncFile: (opt: TarOptionsSyncFile, entries: string[]) => void\n asyncFile: (\n opt: TarOptionsAsyncFile,\n entries: string[],\n cb?: CB,\n ) => Promise<void>\n syncNoFile: (\n opt: TarOptionsSyncNoFile,\n entries: string[],\n ) => SyncClass\n asyncNoFile: (\n opt: TarOptionsAsyncNoFile,\n entries: string[],\n ) => AsyncClass\n validate?: (opt: TarOptions, entries?: string[]) => void\n}\n\nexport const makeCommand = <\n AsyncClass,\n SyncClass extends { sync: true },\n>(\n syncFile: (opt: TarOptionsSyncFile, entries: string[]) => void,\n asyncFile: (\n opt: TarOptionsAsyncFile,\n entries: string[],\n cb?: CB,\n ) => Promise<void>,\n syncNoFile: (\n opt: TarOptionsSyncNoFile,\n entries: string[],\n ) => SyncClass,\n asyncNoFile: (\n opt: TarOptionsAsyncNoFile,\n entries: string[],\n ) => AsyncClass,\n validate?: (opt: TarOptions, entries?: string[]) => void,\n): TarCommand<AsyncClass, SyncClass> => {\n return Object.assign(\n (\n opt_: TarOptionsWithAliases | string[] = [],\n entries?: string[] | CB,\n cb?: CB,\n ) => {\n if (Array.isArray(opt_)) {\n entries = opt_\n opt_ = {}\n }\n\n if (typeof entries === 'function') {\n cb = entries\n entries = undefined\n }\n\n if (!entries) {\n entries = []\n } else {\n entries = Array.from(entries)\n }\n\n const opt = dealias(opt_)\n\n validate?.(opt, entries)\n\n if (isSyncFile(opt)) {\n if (typeof cb === 'function') {\n throw new TypeError(\n 'callback not supported for sync tar functions',\n )\n }\n return syncFile(opt, entries)\n } else if (isAsyncFile(opt)) {\n const p = asyncFile(opt, entries)\n // weirdness to make TS happy\n const c = cb ? cb : undefined\n return c ? p.then(() => c(), c) : p\n } else if (isSyncNoFile(opt)) {\n if (typeof cb === 'function') {\n throw new TypeError(\n 'callback not supported for sync tar functions',\n )\n }\n return syncNoFile(opt, entries)\n } else if (isAsyncNoFile(opt)) {\n if (typeof cb === 'function') {\n throw new TypeError(\n 'callback only supported with file option',\n )\n }\n return asyncNoFile(opt, entries)\n /* c8 ignore start */\n } else {\n throw new Error('impossible options??')\n }\n /* c8 ignore stop */\n },\n {\n syncFile,\n asyncFile,\n syncNoFile,\n asyncNoFile,\n validate,\n },\n ) as TarCommand<AsyncClass, SyncClass>\n}\n", "// this[BUFFER] is the remainder of a chunk if we're waiting for\n// the full 512 bytes of a header to come in. We will Buffer.concat()\n// it to the next write(), which is a mem copy, but a small one.\n//\n// this[QUEUE] is a list of entries that haven't been emitted\n// yet this can only get filled up if the user keeps write()ing after\n// a write() returns false, or does a write() with more than one entry\n//\n// We don't buffer chunks, we always parse them and either create an\n// entry, or push it into the active entry. The ReadEntry class knows\n// to throw data away if .ignore=true\n//\n// Shift entry off the buffer when it emits 'end', and emit 'entry' for\n// the next one in the list.\n//\n// At any time, we're pushing body chunks into the entry at WRITEENTRY,\n// and waiting for 'end' on the entry at READENTRY\n//\n// ignored entries get .resume() called on them straight away\n\nimport { EventEmitter as EE } from 'events'\nimport { BrotliDecompress, Unzip, ZstdDecompress } from 'minizlib'\nimport { Header } from './header.js'\nimport { TarOptions } from './options.js'\nimport { Pax } from './pax.js'\nimport { ReadEntry } from './read-entry.js'\nimport {\n warnMethod,\n type WarnData,\n type Warner,\n} from './warn-method.js'\n\nconst maxMetaEntrySize = 1024 * 1024\nconst gzipHeader = Buffer.from([0x1f, 0x8b])\nconst zstdHeader = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])\nconst ZIP_HEADER_LEN = Math.max(gzipHeader.length, zstdHeader.length)\n\nconst STATE = Symbol('state')\nconst WRITEENTRY = Symbol('writeEntry')\nconst READENTRY = Symbol('readEntry')\nconst NEXTENTRY = Symbol('nextEntry')\nconst PROCESSENTRY = Symbol('processEntry')\nconst EX = Symbol('extendedHeader')\nconst GEX = Symbol('globalExtendedHeader')\nconst META = Symbol('meta')\nconst EMITMETA = Symbol('emitMeta')\nconst BUFFER = Symbol('buffer')\nconst QUEUE = Symbol('queue')\nconst ENDED = Symbol('ended')\nconst EMITTEDEND = Symbol('emittedEnd')\nconst EMIT = Symbol('emit')\nconst UNZIP = Symbol('unzip')\nconst CONSUMECHUNK = Symbol('consumeChunk')\nconst CONSUMECHUNKSUB = Symbol('consumeChunkSub')\nconst CONSUMEBODY = Symbol('consumeBody')\nconst CONSUMEMETA = Symbol('consumeMeta')\nconst CONSUMEHEADER = Symbol('consumeHeader')\nconst CONSUMING = Symbol('consuming')\nconst BUFFERCONCAT = Symbol('bufferConcat')\nconst MAYBEEND = Symbol('maybeEnd')\nconst WRITING = Symbol('writing')\nconst ABORTED = Symbol('aborted')\nconst DONE = Symbol('onDone')\nconst SAW_VALID_ENTRY = Symbol('sawValidEntry')\nconst SAW_NULL_BLOCK = Symbol('sawNullBlock')\nconst SAW_EOF = Symbol('sawEOF')\nconst CLOSESTREAM = Symbol('closeStream')\n\nconst noop = () => true\n\nexport type State = 'begin' | 'header' | 'ignore' | 'meta' | 'body'\n\nexport class Parser extends EE implements Warner {\n file: string\n strict: boolean\n maxMetaEntrySize: number\n filter: Exclude<TarOptions['filter'], undefined>\n brotli?: TarOptions['brotli']\n zstd?: TarOptions['zstd']\n\n writable: true = true\n readable: false = false;\n\n [QUEUE]: (ReadEntry | [string | symbol, any, any])[] = [];\n [BUFFER]?: Buffer;\n [READENTRY]?: ReadEntry;\n [WRITEENTRY]?: ReadEntry;\n [STATE]: State = 'begin';\n [META]: string = '';\n [EX]?: Pax;\n [GEX]?: Pax;\n [ENDED]: boolean = false;\n [UNZIP]?: false | Unzip | BrotliDecompress | ZstdDecompress;\n [ABORTED]: boolean = false;\n [SAW_VALID_ENTRY]?: boolean;\n [SAW_NULL_BLOCK]: boolean = false;\n [SAW_EOF]: boolean = false;\n [WRITING]: boolean = false;\n [CONSUMING]: boolean = false;\n [EMITTEDEND]: boolean = false\n\n constructor(opt: TarOptions = {}) {\n super()\n\n this.file = opt.file || ''\n\n // these BADARCHIVE errors can't be detected early. listen on DONE.\n this.on(DONE, () => {\n if (\n this[STATE] === 'begin' ||\n this[SAW_VALID_ENTRY] === false\n ) {\n // either less than 1 block of data, or all entries were invalid.\n // Either way, probably not even a tarball.\n this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format')\n }\n })\n\n if (opt.ondone) {\n this.on(DONE, opt.ondone)\n } else {\n this.on(DONE, () => {\n this.emit('prefinish')\n this.emit('finish')\n this.emit('end')\n })\n }\n\n this.strict = !!opt.strict\n this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize\n this.filter = typeof opt.filter === 'function' ? opt.filter : noop\n // Unlike gzip, brotli doesn't have any magic bytes to identify it\n // Users need to explicitly tell us they're extracting a brotli file\n // Or we infer from the file extension\n const isTBR =\n opt.file &&\n (opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr'))\n // if it's a tbr file it MIGHT be brotli, but we don't know until\n // we look at it and verify it's not a valid tar file.\n this.brotli =\n !(opt.gzip || opt.zstd) && opt.brotli !== undefined ? opt.brotli\n : isTBR ? undefined\n : false\n\n // zstd has magic bytes to identify it, but we also support explicit options\n // and file extension detection\n const isTZST =\n opt.file &&\n (opt.file.endsWith('.tar.zst') || opt.file.endsWith('.tzst'))\n this.zstd =\n !(opt.gzip || opt.brotli) && opt.zstd !== undefined ? opt.zstd\n : isTZST ? true\n : undefined\n\n // have to set this so that streams are ok piping into it\n this.on('end', () => this[CLOSESTREAM]())\n\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n if (typeof opt.onReadEntry === 'function') {\n this.on('entry', opt.onReadEntry)\n }\n }\n\n warn(\n code: string,\n message: string | Error,\n data: WarnData = {},\n ): void {\n warnMethod(this, code, message, data)\n }\n\n [CONSUMEHEADER](chunk: Buffer, position: number) {\n if (this[SAW_VALID_ENTRY] === undefined) {\n this[SAW_VALID_ENTRY] = false\n }\n let header\n try {\n header = new Header(chunk, position, this[EX], this[GEX])\n } catch (er) {\n return this.warn('TAR_ENTRY_INVALID', er as Error)\n }\n\n if (header.nullBlock) {\n if (this[SAW_NULL_BLOCK]) {\n this[SAW_EOF] = true\n // ending an archive with no entries. pointless, but legal.\n if (this[STATE] === 'begin') {\n this[STATE] = 'header'\n }\n this[EMIT]('eof')\n } else {\n this[SAW_NULL_BLOCK] = true\n this[EMIT]('nullBlock')\n }\n } else {\n this[SAW_NULL_BLOCK] = false\n if (!header.cksumValid) {\n this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header })\n } else if (!header.path) {\n this.warn('TAR_ENTRY_INVALID', 'path is required', { header })\n } else {\n const type = header.type\n if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) {\n this.warn('TAR_ENTRY_INVALID', 'linkpath required', {\n header,\n })\n } else if (\n !/^(Symbolic)?Link$/.test(type) &&\n !/^(Global)?ExtendedHeader$/.test(type) &&\n header.linkpath\n ) {\n this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {\n header,\n })\n } else {\n const entry = (this[WRITEENTRY] = new ReadEntry(\n header,\n this[EX],\n this[GEX],\n ))\n\n // we do this for meta & ignored entries as well, because they\n // are still valid tar, or else we wouldn't know to ignore them\n if (!this[SAW_VALID_ENTRY]) {\n if (entry.remain) {\n // this might be the one!\n const onend = () => {\n if (!entry.invalid) {\n this[SAW_VALID_ENTRY] = true\n }\n }\n entry.on('end', onend)\n } else {\n this[SAW_VALID_ENTRY] = true\n }\n }\n\n if (entry.meta) {\n if (entry.size > this.maxMetaEntrySize) {\n entry.ignore = true\n this[EMIT]('ignoredEntry', entry)\n this[STATE] = 'ignore'\n entry.resume()\n } else if (entry.size > 0) {\n this[META] = ''\n entry.on('data', c => (this[META] += c))\n this[STATE] = 'meta'\n }\n } else {\n this[EX] = undefined\n entry.ignore =\n entry.ignore || !this.filter(entry.path, entry)\n\n if (entry.ignore) {\n // probably valid, just not something we care about\n this[EMIT]('ignoredEntry', entry)\n this[STATE] = entry.remain ? 'ignore' : 'header'\n entry.resume()\n } else {\n if (entry.remain) {\n this[STATE] = 'body'\n } else {\n this[STATE] = 'header'\n entry.end()\n }\n\n if (!this[READENTRY]) {\n this[QUEUE].push(entry)\n this[NEXTENTRY]()\n } else {\n this[QUEUE].push(entry)\n }\n }\n }\n }\n }\n }\n }\n\n [CLOSESTREAM]() {\n queueMicrotask(() => this.emit('close'))\n }\n\n [PROCESSENTRY](entry?: ReadEntry | [string | symbol, any, any]) {\n let go = true\n\n if (!entry) {\n this[READENTRY] = undefined\n go = false\n } else if (Array.isArray(entry)) {\n const [ev, ...args]: [string | symbol, any, any] = entry\n this.emit(ev, ...args)\n } else {\n this[READENTRY] = entry\n this.emit('entry', entry)\n if (!entry.emittedEnd) {\n entry.on('end', () => this[NEXTENTRY]())\n go = false\n }\n }\n\n return go\n }\n\n [NEXTENTRY]() {\n do {} while (this[PROCESSENTRY](this[QUEUE].shift()))\n\n if (!this[QUEUE].length) {\n // At this point, there's nothing in the queue, but we may have an\n // entry which is being consumed (readEntry).\n // If we don't, then we definitely can handle more data.\n // If we do, and either it's flowing, or it has never had any data\n // written to it, then it needs more.\n // The only other possibility is that it has returned false from a\n // write() call, so we wait for the next drain to continue.\n const re = this[READENTRY]\n const drainNow = !re || re.flowing || re.size === re.remain\n if (drainNow) {\n if (!this[WRITING]) {\n this.emit('drain')\n }\n } else {\n re.once('drain', () => this.emit('drain'))\n }\n }\n }\n\n [CONSUMEBODY](chunk: Buffer, position: number) {\n // write up to but no more than writeEntry.blockRemain\n const entry = this[WRITEENTRY]\n /* c8 ignore start */\n if (!entry) {\n throw new Error('attempt to consume body without entry??')\n }\n const br = entry.blockRemain ?? 0\n /* c8 ignore stop */\n const c =\n br >= chunk.length && position === 0 ?\n chunk\n : chunk.subarray(position, position + br)\n\n entry.write(c)\n\n if (!entry.blockRemain) {\n this[STATE] = 'header'\n this[WRITEENTRY] = undefined\n entry.end()\n }\n\n return c.length\n }\n\n [CONSUMEMETA](chunk: Buffer, position: number) {\n const entry = this[WRITEENTRY]\n const ret = this[CONSUMEBODY](chunk, position)\n\n // if we finished, then the entry is reset\n if (!this[WRITEENTRY] && entry) {\n this[EMITMETA](entry)\n }\n\n return ret\n }\n\n [EMIT](ev: string | symbol, data?: any, extra?: any) {\n if (!this[QUEUE].length && !this[READENTRY]) {\n this.emit(ev, data, extra)\n } else {\n this[QUEUE].push([ev, data, extra])\n }\n }\n\n [EMITMETA](entry: ReadEntry) {\n this[EMIT]('meta', this[META])\n switch (entry.type) {\n case 'ExtendedHeader':\n case 'OldExtendedHeader':\n this[EX] = Pax.parse(this[META], this[EX], false)\n break\n\n case 'GlobalExtendedHeader':\n this[GEX] = Pax.parse(this[META], this[GEX], true)\n break\n\n case 'NextFileHasLongPath':\n case 'OldGnuLongPath': {\n const ex = this[EX] ?? Object.create(null)\n this[EX] = ex\n ex.path = this[META].replace(/\\0.*/, '')\n break\n }\n\n case 'NextFileHasLongLinkpath': {\n const ex = this[EX] || Object.create(null)\n this[EX] = ex\n ex.linkpath = this[META].replace(/\\0.*/, '')\n break\n }\n\n /* c8 ignore start */\n default:\n throw new Error('unknown meta: ' + entry.type)\n /* c8 ignore stop */\n }\n }\n\n abort(error: Error) {\n this[ABORTED] = true\n this.emit('abort', error)\n // always throws, even in non-strict mode\n this.warn('TAR_ABORT', error, { recoverable: false })\n }\n\n write(\n buffer: Uint8Array | string,\n cb?: (err?: Error | null) => void,\n ): boolean\n write(\n str: string,\n encoding?: BufferEncoding,\n cb?: (err?: Error | null) => void,\n ): boolean\n write(\n chunk: Buffer | string,\n encoding?: BufferEncoding | (() => any),\n cb?: () => any,\n ): boolean {\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(\n chunk,\n /* c8 ignore next */\n typeof encoding === 'string' ? encoding : 'utf8',\n )\n }\n if (this[ABORTED]) {\n /* c8 ignore next */\n cb?.()\n return false\n }\n\n // first write, might be gzipped, zstd, or brotli compressed\n const needSniff =\n this[UNZIP] === undefined ||\n (this.brotli === undefined && this[UNZIP] === false)\n if (needSniff && chunk) {\n if (this[BUFFER]) {\n chunk = Buffer.concat([this[BUFFER], chunk])\n this[BUFFER] = undefined\n }\n if (chunk.length < ZIP_HEADER_LEN) {\n this[BUFFER] = chunk\n /* c8 ignore next */\n cb?.()\n return true\n }\n\n // look for gzip header\n for (\n let i = 0;\n this[UNZIP] === undefined && i < gzipHeader.length;\n i++\n ) {\n if (chunk[i] !== gzipHeader[i]) {\n this[UNZIP] = false\n }\n }\n\n // look for zstd header if gzip header not found\n let isZstd = false\n if (this[UNZIP] === false && this.zstd !== false) {\n isZstd = true\n for (let i = 0; i < zstdHeader.length; i++) {\n if (chunk[i] !== zstdHeader[i]) {\n isZstd = false\n break\n }\n }\n }\n\n const maybeBrotli = this.brotli === undefined && !isZstd\n if (this[UNZIP] === false && maybeBrotli) {\n // read the first header to see if it's a valid tar file. If so,\n // we can safely assume that it's not actually brotli, despite the\n // .tbr or .tar.br file extension.\n // if we ended before getting a full chunk, yes, def brotli\n if (chunk.length < 512) {\n if (this[ENDED]) {\n this.brotli = true\n } else {\n this[BUFFER] = chunk\n /* c8 ignore next */\n cb?.()\n return true\n }\n } else {\n // if it's tar, it's pretty reliably not brotli, chances of\n // that happening are astronomical.\n try {\n new Header(chunk.subarray(0, 512))\n this.brotli = false\n } catch (_) {\n this.brotli = true\n }\n }\n }\n\n if (\n this[UNZIP] === undefined ||\n (this[UNZIP] === false && (this.brotli || isZstd))\n ) {\n const ended = this[ENDED]\n this[ENDED] = false\n this[UNZIP] =\n this[UNZIP] === undefined ? new Unzip({})\n : isZstd ? new ZstdDecompress({})\n : new BrotliDecompress({})\n this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk))\n this[UNZIP].on('error', er => this.abort(er as Error))\n this[UNZIP].on('end', () => {\n this[ENDED] = true\n this[CONSUMECHUNK]()\n })\n this[WRITING] = true\n const ret = !!this[UNZIP][ended ? 'end' : 'write'](chunk)\n this[WRITING] = false\n cb?.()\n return ret\n }\n }\n\n this[WRITING] = true\n if (this[UNZIP]) {\n this[UNZIP].write(chunk)\n } else {\n this[CONSUMECHUNK](chunk)\n }\n this[WRITING] = false\n\n // return false if there's a queue, or if the current entry isn't flowing\n const ret =\n this[QUEUE].length ? false\n : this[READENTRY] ? this[READENTRY].flowing\n : true\n\n // if we have no queue, then that means a clogged READENTRY\n if (!ret && !this[QUEUE].length) {\n this[READENTRY]?.once('drain', () => this.emit('drain'))\n }\n\n /* c8 ignore next */\n cb?.()\n return ret\n }\n\n [BUFFERCONCAT](c: Buffer) {\n if (c && !this[ABORTED]) {\n this[BUFFER] =\n this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c\n }\n }\n\n [MAYBEEND]() {\n if (\n this[ENDED] &&\n !this[EMITTEDEND] &&\n !this[ABORTED] &&\n !this[CONSUMING]\n ) {\n this[EMITTEDEND] = true\n const entry = this[WRITEENTRY]\n if (entry && entry.blockRemain) {\n // truncated, likely a damaged file\n const have = this[BUFFER] ? this[BUFFER].length : 0\n this.warn(\n 'TAR_BAD_ARCHIVE',\n `Truncated input (needed ${entry.blockRemain} more bytes, only ${have} available)`,\n { entry },\n )\n if (this[BUFFER]) {\n entry.write(this[BUFFER])\n }\n entry.end()\n }\n this[EMIT](DONE)\n }\n }\n\n [CONSUMECHUNK](chunk?: Buffer) {\n if (this[CONSUMING] && chunk) {\n this[BUFFERCONCAT](chunk)\n } else if (!chunk && !this[BUFFER]) {\n this[MAYBEEND]()\n } else if (chunk) {\n this[CONSUMING] = true\n if (this[BUFFER]) {\n this[BUFFERCONCAT](chunk)\n const c = this[BUFFER]\n this[BUFFER] = undefined\n this[CONSUMECHUNKSUB](c)\n } else {\n this[CONSUMECHUNKSUB](chunk)\n }\n\n while (\n this[BUFFER] &&\n (this[BUFFER] as Buffer)?.length >= 512 &&\n !this[ABORTED] &&\n !this[SAW_EOF]\n ) {\n const c = this[BUFFER]\n this[BUFFER] = undefined\n this[CONSUMECHUNKSUB](c)\n }\n this[CONSUMING] = false\n }\n\n if (!this[BUFFER] || this[ENDED]) {\n this[MAYBEEND]()\n }\n }\n\n [CONSUMECHUNKSUB](chunk: Buffer) {\n // we know that we are in CONSUMING mode, so anything written goes into\n // the buffer. Advance the position and put any remainder in the buffer.\n let position = 0\n const length = chunk.length\n while (\n position + 512 <= length &&\n !this[ABORTED] &&\n !this[SAW_EOF]\n ) {\n switch (this[STATE]) {\n case 'begin':\n case 'header':\n this[CONSUMEHEADER](chunk, position)\n position += 512\n break\n\n case 'ignore':\n case 'body':\n position += this[CONSUMEBODY](chunk, position)\n break\n\n case 'meta':\n position += this[CONSUMEMETA](chunk, position)\n break\n\n /* c8 ignore start */\n default:\n throw new Error('invalid state: ' + this[STATE])\n /* c8 ignore stop */\n }\n }\n\n if (position < length) {\n if (this[BUFFER]) {\n this[BUFFER] = Buffer.concat([\n chunk.subarray(position),\n this[BUFFER],\n ])\n } else {\n this[BUFFER] = chunk.subarray(position)\n }\n }\n }\n\n end(cb?: () => void): this\n end(data: string | Buffer, cb?: () => void): this\n end(str: string, encoding?: BufferEncoding, cb?: () => void): this\n end(\n chunk?: string | Buffer | (() => void),\n encoding?: BufferEncoding | (() => void),\n cb?: () => void,\n ) {\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding)\n }\n if (cb) this.once('finish', cb)\n if (!this[ABORTED]) {\n if (this[UNZIP]) {\n /* c8 ignore start */\n if (chunk) this[UNZIP].write(chunk)\n /* c8 ignore stop */\n this[UNZIP].end()\n } else {\n this[ENDED] = true\n if (this.brotli === undefined || this.zstd === undefined)\n chunk = chunk || Buffer.alloc(0)\n if (chunk) this.write(chunk)\n this[MAYBEEND]()\n }\n }\n return this\n }\n}\n", "import assert from 'assert'\nimport { Buffer } from 'buffer'\nimport { Minipass } from 'minipass'\nimport * as realZlib from 'zlib'\nimport { constants } from './constants.js'\nexport { constants } from './constants.js'\n\nconst OriginalBufferConcat = Buffer.concat\nconst desc = Object.getOwnPropertyDescriptor(Buffer, 'concat')\nconst noop = (args: Buffer[]) => args as unknown as Buffer\nconst passthroughBufferConcat =\n desc?.writable === true || desc?.set !== undefined\n ? (makeNoOp: boolean) => {\n Buffer.concat = makeNoOp ? noop : OriginalBufferConcat\n }\n : (_: boolean) => {}\n\nconst _superWrite = Symbol('_superWrite')\n\nexport class ZlibError extends Error {\n code?: string\n errno?: number\n constructor(err: NodeJS.ErrnoException | Error, origin?: Function) {\n super('zlib: ' + err.message, { cause: err })\n this.code = (err as NodeJS.ErrnoException).code\n this.errno = (err as NodeJS.ErrnoException).errno\n /* c8 ignore next */\n if (!this.code) this.code = 'ZLIB_ERROR'\n\n this.message = 'zlib: ' + err.message\n Error.captureStackTrace(this, origin ?? this.constructor)\n }\n\n get name() {\n return 'ZlibError'\n }\n}\n\n// the Zlib class they all inherit from\n// This thing manages the queue of requests, and returns\n// true or false if there is anything in the queue when\n// you call the .write() method.\nconst _flushFlag = Symbol('flushFlag')\n\nexport type ChunkWithFlushFlag = Minipass.ContiguousData & {\n [_flushFlag]?: number\n}\n\nexport type ZlibBaseOptions = Minipass.Options<Minipass.ContiguousData> & {\n flush?: number\n finishFlush?: number\n fullFlushFlag?: number\n}\n\nexport type ZlibHandle =\n | realZlib.Gzip\n | realZlib.Gunzip\n | realZlib.Deflate\n | realZlib.Inflate\n | realZlib.DeflateRaw\n | realZlib.InflateRaw\n | realZlib.BrotliCompress\n | realZlib.BrotliDecompress\n | realZlib.ZstdCompress\n | realZlib.ZstdDecompress\nexport type ZlibMode =\n | 'Gzip'\n | 'Gunzip'\n | 'Deflate'\n | 'Inflate'\n | 'DeflateRaw'\n | 'InflateRaw'\n | 'Unzip'\nexport type BrotliMode = 'BrotliCompress' | 'BrotliDecompress'\nexport type ZstdMode = 'ZstdCompress' | 'ZstdDecompress'\n\nabstract class ZlibBase extends Minipass<Buffer, ChunkWithFlushFlag> {\n #sawError: boolean = false\n #ended: boolean = false\n #flushFlag: number\n #finishFlushFlag: number\n #fullFlushFlag: number\n #handle?: ZlibHandle\n #onError: (err: ZlibError) => any\n\n get sawError() {\n return this.#sawError\n }\n get handle() {\n return this.#handle\n }\n /* c8 ignore start */\n get flushFlag() {\n return this.#flushFlag\n }\n /* c8 ignore stop */\n\n constructor(opts: ZlibBaseOptions, mode: ZlibMode | BrotliMode | ZstdMode) {\n if (!opts || typeof opts !== 'object')\n throw new TypeError('invalid options for ZlibBase constructor')\n\n //@ts-ignore\n super(opts)\n\n /* c8 ignore start */\n this.#flushFlag = opts.flush ?? 0\n this.#finishFlushFlag = opts.finishFlush ?? 0\n this.#fullFlushFlag = opts.fullFlushFlag ?? 0\n /* c8 ignore stop */\n\n //@ts-ignore\n if (typeof realZlib[mode] !== 'function') {\n throw new TypeError('Compression method not supported: ' + mode)\n }\n\n // this will throw if any options are invalid for the class selected\n try {\n // @types/node doesn't know that it exports the classes, but they're there\n //@ts-ignore\n this.#handle = new realZlib[mode](opts)\n } catch (er) {\n // make sure that all errors get decorated properly\n throw new ZlibError(er as NodeJS.ErrnoException, this.constructor)\n }\n\n this.#onError = err => {\n // no sense raising multiple errors, since we abort on the first one.\n if (this.#sawError) return\n\n this.#sawError = true\n\n // there is no way to cleanly recover.\n // continuing only obscures problems.\n this.close()\n this.emit('error', err)\n }\n\n this.#handle?.on('error', er => this.#onError(new ZlibError(er)))\n this.once('end', () => this.close)\n }\n\n close() {\n if (this.#handle) {\n this.#handle.close()\n this.#handle = undefined\n this.emit('close')\n }\n }\n\n reset() {\n if (!this.#sawError) {\n assert(this.#handle, 'zlib binding closed')\n //@ts-ignore\n return this.#handle.reset?.()\n }\n }\n\n flush(flushFlag?: number) {\n if (this.ended) return\n\n if (typeof flushFlag !== 'number') flushFlag = this.#fullFlushFlag\n\n this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }))\n }\n\n end(cb?: () => void): this\n end(chunk: ChunkWithFlushFlag, cb?: () => void): this\n end(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): this\n end(\n chunk?: ChunkWithFlushFlag | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n /* c8 ignore start */\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n /* c8 ignore stop */\n if (chunk) {\n if (encoding) this.write(chunk, encoding)\n else this.write(chunk)\n }\n this.flush(this.#finishFlushFlag)\n this.#ended = true\n return super.end(cb)\n }\n\n get ended() {\n return this.#ended\n }\n\n // overridden in the gzip classes to do portable writes\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n return super.write(data)\n }\n\n write(chunk: ChunkWithFlushFlag, cb?: () => void): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n // process the chunk using the sync process\n // then super.write() all the outputted chunks\n if (typeof encoding === 'function')\n (cb = encoding), (encoding = 'utf8')\n\n if (typeof chunk === 'string')\n chunk = Buffer.from(chunk as string, encoding as BufferEncoding)\n\n if (this.#sawError) return\n assert(this.#handle, 'zlib binding closed')\n\n // _processChunk tries to .close() the native handle after it's done, so we\n // intercept that by temporarily making it a no-op.\n // diving into the node:zlib internals a bit here\n const nativeHandle = (this.#handle as unknown as { _handle: any })\n ._handle\n const originalNativeClose = nativeHandle.close\n nativeHandle.close = () => {}\n const originalClose = this.#handle.close\n this.#handle.close = () => {}\n // It also calls `Buffer.concat()` at the end, which may be convenient\n // for some, but which we are not interested in as it slows us down.\n passthroughBufferConcat(true)\n let result: undefined | Buffer | Buffer[] = undefined\n try {\n const flushFlag =\n typeof chunk[_flushFlag] === 'number'\n ? chunk[_flushFlag]\n : this.#flushFlag\n result = (\n this.#handle as unknown as {\n _processChunk: (chunk: Buffer, flushFlag: number) => Buffer[]\n }\n )._processChunk(chunk as Buffer, flushFlag)\n // if we don't throw, reset it back how it was\n passthroughBufferConcat(false)\n } catch (err) {\n // or if we do, put Buffer.concat() back before we emit error\n // Error events call into user code, which may call Buffer.concat()\n passthroughBufferConcat(false)\n this.#onError(new ZlibError(err as NodeJS.ErrnoException, this.write))\n } finally {\n if (this.#handle) {\n // Core zlib resets `_handle` to null after attempting to close the\n // native handle. Our no-op handler prevented actual closure, but we\n // need to restore the `._handle` property.\n ;(this.#handle as unknown as { _handle: any })._handle =\n nativeHandle\n nativeHandle.close = originalNativeClose\n this.#handle.close = originalClose\n // `_processChunk()` adds an 'error' listener. If we don't remove it\n // after each call, these handlers start piling up.\n this.#handle.removeAllListeners('error')\n // make sure OUR error listener is still attached tho\n }\n }\n\n if (this.#handle)\n this.#handle.on('error', er => this.#onError(new ZlibError(er, this.write)))\n\n let writeReturn\n if (result) {\n if (Array.isArray(result) && result.length > 0) {\n const r = result[0]\n // The first buffer is always `handle._outBuffer`, which would be\n // re-used for later invocations; so, we always have to copy that one.\n writeReturn = this[_superWrite](Buffer.from(r as Buffer))\n for (let i = 1; i < result.length; i++) {\n writeReturn = this[_superWrite](result[i] as Buffer)\n }\n } else {\n // either a single Buffer or an empty array\n writeReturn = this[_superWrite](Buffer.from(result as Buffer | []))\n }\n }\n\n if (cb) cb()\n return writeReturn\n }\n}\n\nexport type ZlibOptions = ZlibBaseOptions & {\n level?: number\n strategy?: number\n}\n\nexport class Zlib extends ZlibBase {\n #level?: number\n #strategy?: number\n\n constructor(opts: ZlibOptions, mode: ZlibMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.Z_NO_FLUSH\n opts.finishFlush = opts.finishFlush || constants.Z_FINISH\n opts.fullFlushFlag = constants.Z_FULL_FLUSH\n super(opts, mode)\n\n this.#level = opts.level\n this.#strategy = opts.strategy\n }\n\n params(level: number, strategy: number) {\n if (this.sawError) return\n\n if (!this.handle)\n throw new Error('cannot switch params when binding is closed')\n\n // no way to test this without also not supporting params at all\n /* c8 ignore start */\n if (!(this.handle as { params?: any }).params)\n throw new Error('not supported in this implementation')\n /* c8 ignore stop */\n\n if (this.#level !== level || this.#strategy !== strategy) {\n this.flush(constants.Z_SYNC_FLUSH)\n assert(this.handle, 'zlib binding closed')\n // .params() calls .flush(), but the latter is always async in the\n // core zlib. We override .flush() temporarily to intercept that and\n // flush synchronously.\n const origFlush = this.handle.flush\n this.handle.flush = (\n flushFlag?: (() => void) | number,\n cb?: () => void,\n ) => {\n /* c8 ignore start */\n if (typeof flushFlag === 'function') {\n cb = flushFlag\n flushFlag = this.flushFlag\n }\n /* c8 ignore stop */\n this.flush(flushFlag)\n cb?.()\n }\n try {\n ;(\n this.handle as unknown as {\n params: (level?: number, strategy?: number) => void\n }\n ).params(level, strategy)\n } finally {\n this.handle.flush = origFlush\n }\n /* c8 ignore start */\n if (this.handle) {\n this.#level = level\n this.#strategy = strategy\n }\n /* c8 ignore stop */\n }\n }\n}\n\n// minimal 2-byte header\nexport class Deflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Deflate')\n }\n}\n\nexport class Inflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Inflate')\n }\n}\n\n// gzip - bigger header, same deflate compression\nexport type GzipOptions = ZlibOptions & { portable?: boolean }\nexport class Gzip extends Zlib {\n #portable: boolean\n constructor(opts: GzipOptions) {\n super(opts, 'Gzip')\n this.#portable = opts && !!opts.portable\n }\n\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n if (!this.#portable) return super[_superWrite](data)\n\n // we'll always get the header emitted in one first chunk\n // overwrite the OS indicator byte with 0xFF\n this.#portable = false\n data[9] = 255\n return super[_superWrite](data)\n }\n}\n\nexport class Gunzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Gunzip')\n }\n}\n\n// raw - no header\nexport class DeflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'DeflateRaw')\n }\n}\n\nexport class InflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'InflateRaw')\n }\n}\n\n// auto-detect header.\nexport class Unzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Unzip')\n }\n}\n\nclass Brotli extends ZlibBase {\n constructor(opts: ZlibOptions, mode: BrotliMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS\n opts.finishFlush =\n opts.finishFlush || constants.BROTLI_OPERATION_FINISH\n opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH\n super(opts, mode)\n }\n}\n\nexport class BrotliCompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliCompress')\n }\n}\n\nexport class BrotliDecompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliDecompress')\n }\n}\n\nclass Zstd extends ZlibBase {\n constructor(opts: ZlibOptions, mode: ZstdMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.ZSTD_e_continue\n opts.finishFlush = opts.finishFlush || constants.ZSTD_e_end\n opts.fullFlushFlag = constants.ZSTD_e_flush\n super(opts, mode)\n }\n}\n\nexport class ZstdCompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdCompress')\n }\n}\n\nexport class ZstdDecompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdDecompress')\n }\n}\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "// Update with any zlib constants that are added or changed in the future.\n// Node v6 didn't export this, so we just hard code the version and rely\n// on all the other hard-coded values from zlib v4736. When node v6\n// support drops, we can just export the realZlibConstants object.\nimport realZlib from 'zlib'\n/* c8 ignore start */\nconst realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 }\n/* c8 ignore stop */\n\nexport const constants = Object.freeze(\n Object.assign(\n Object.create(null),\n {\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n Z_VERSION_ERROR: -6,\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n DEFLATE: 1,\n INFLATE: 2,\n GZIP: 3,\n GUNZIP: 4,\n DEFLATERAW: 5,\n INFLATERAW: 6,\n UNZIP: 7,\n BROTLI_DECODE: 8,\n BROTLI_ENCODE: 9,\n Z_MIN_WINDOWBITS: 8,\n Z_MAX_WINDOWBITS: 15,\n Z_DEFAULT_WINDOWBITS: 15,\n Z_MIN_CHUNK: 64,\n Z_MAX_CHUNK: Infinity,\n Z_DEFAULT_CHUNK: 16384,\n Z_MIN_MEMLEVEL: 1,\n Z_MAX_MEMLEVEL: 9,\n Z_DEFAULT_MEMLEVEL: 8,\n Z_MIN_LEVEL: -1,\n Z_MAX_LEVEL: 9,\n Z_DEFAULT_LEVEL: -1,\n BROTLI_OPERATION_PROCESS: 0,\n BROTLI_OPERATION_FLUSH: 1,\n BROTLI_OPERATION_FINISH: 2,\n BROTLI_OPERATION_EMIT_METADATA: 3,\n BROTLI_MODE_GENERIC: 0,\n BROTLI_MODE_TEXT: 1,\n BROTLI_MODE_FONT: 2,\n BROTLI_DEFAULT_MODE: 0,\n BROTLI_MIN_QUALITY: 0,\n BROTLI_MAX_QUALITY: 11,\n BROTLI_DEFAULT_QUALITY: 11,\n BROTLI_MIN_WINDOW_BITS: 10,\n BROTLI_MAX_WINDOW_BITS: 24,\n BROTLI_LARGE_MAX_WINDOW_BITS: 30,\n BROTLI_DEFAULT_WINDOW: 22,\n BROTLI_MIN_INPUT_BLOCK_BITS: 16,\n BROTLI_MAX_INPUT_BLOCK_BITS: 24,\n BROTLI_PARAM_MODE: 0,\n BROTLI_PARAM_QUALITY: 1,\n BROTLI_PARAM_LGWIN: 2,\n BROTLI_PARAM_LGBLOCK: 3,\n BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,\n BROTLI_PARAM_SIZE_HINT: 5,\n BROTLI_PARAM_LARGE_WINDOW: 6,\n BROTLI_PARAM_NPOSTFIX: 7,\n BROTLI_PARAM_NDIRECT: 8,\n BROTLI_DECODER_RESULT_ERROR: 0,\n BROTLI_DECODER_RESULT_SUCCESS: 1,\n BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,\n BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,\n BROTLI_DECODER_NO_ERROR: 0,\n BROTLI_DECODER_SUCCESS: 1,\n BROTLI_DECODER_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,\n BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,\n BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,\n BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,\n BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,\n BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,\n BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,\n BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,\n BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,\n BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,\n BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,\n BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,\n BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,\n BROTLI_DECODER_ERROR_UNREACHABLE: -31,\n },\n realZlibConstants,\n ),\n)\n", "// parse a 512-byte header block to a data object, or vice-versa\n// encode returns `true` if a pax extended header is needed, because\n// the data could not be faithfully encoded in a simple header.\n// (Also, check header.needPax to see if it needs a pax header.)\n\nimport { posix as pathModule } from 'node:path'\nimport * as large from './large-numbers.js'\nimport type { EntryTypeCode, EntryTypeName } from './types.js'\nimport * as types from './types.js'\n\nexport type HeaderData = {\n path?: string\n mode?: number\n uid?: number\n gid?: number\n size?: number\n cksum?: number\n type?: EntryTypeName | 'Unsupported'\n linkpath?: string\n uname?: string\n gname?: string\n devmaj?: number\n devmin?: number\n atime?: Date\n ctime?: Date\n mtime?: Date\n\n // fields that are common in extended PAX headers, but not in the\n // \"standard\" tar header block\n charset?: string\n comment?: string\n dev?: number\n ino?: number\n nlink?: number\n}\n\nexport class Header implements HeaderData {\n cksumValid: boolean = false\n needPax: boolean = false\n nullBlock: boolean = false\n\n block?: Buffer\n path?: string\n mode?: number\n uid?: number\n gid?: number\n size?: number\n cksum?: number\n #type: EntryTypeCode | 'Unsupported' = 'Unsupported'\n linkpath?: string\n uname?: string\n gname?: string\n devmaj: number = 0\n devmin: number = 0\n atime?: Date\n ctime?: Date\n mtime?: Date\n\n charset?: string\n comment?: string\n\n constructor(\n data?: Buffer | HeaderData,\n off: number = 0,\n ex?: HeaderData,\n gex?: HeaderData,\n ) {\n if (Buffer.isBuffer(data)) {\n this.decode(data, off || 0, ex, gex)\n } else if (data) {\n this.#slurp(data)\n }\n }\n\n decode(\n buf: Buffer,\n off: number,\n ex?: HeaderData,\n gex?: HeaderData,\n ) {\n if (!off) {\n off = 0\n }\n\n if (!buf || !(buf.length >= off + 512)) {\n throw new Error('need 512 bytes for header')\n }\n\n this.path = ex?.path ?? decString(buf, off, 100)\n this.mode = ex?.mode ?? gex?.mode ?? decNumber(buf, off + 100, 8)\n this.uid = ex?.uid ?? gex?.uid ?? decNumber(buf, off + 108, 8)\n this.gid = ex?.gid ?? gex?.gid ?? decNumber(buf, off + 116, 8)\n this.size = ex?.size ?? gex?.size ?? decNumber(buf, off + 124, 12)\n this.mtime =\n ex?.mtime ?? gex?.mtime ?? decDate(buf, off + 136, 12)\n this.cksum = decNumber(buf, off + 148, 12)\n\n // if we have extended or global extended headers, apply them now\n // See https://github.com/npm/node-tar/pull/187\n // Apply global before local, so it overrides\n if (gex) this.#slurp(gex, true)\n if (ex) this.#slurp(ex)\n\n // old tar versions marked dirs as a file with a trailing /\n const t = decString(buf, off + 156, 1)\n if (types.isCode(t)) {\n this.#type = t || '0'\n }\n if (this.#type === '0' && this.path.slice(-1) === '/') {\n this.#type = '5'\n }\n\n // tar implementations sometimes incorrectly put the stat(dir).size\n // as the size in the tarball, even though Directory entries are\n // not able to have any body at all. In the very rare chance that\n // it actually DOES have a body, we weren't going to do anything with\n // it anyway, and it'll just be a warning about an invalid header.\n if (this.#type === '5') {\n this.size = 0\n }\n\n this.linkpath = decString(buf, off + 157, 100)\n if (\n buf.subarray(off + 257, off + 265).toString() ===\n 'ustar\\u000000'\n ) {\n /* c8 ignore start */\n this.uname =\n ex?.uname ?? gex?.uname ?? decString(buf, off + 265, 32)\n this.gname =\n ex?.gname ?? gex?.gname ?? decString(buf, off + 297, 32)\n this.devmaj =\n ex?.devmaj ?? gex?.devmaj ?? decNumber(buf, off + 329, 8) ?? 0\n this.devmin =\n ex?.devmin ?? gex?.devmin ?? decNumber(buf, off + 337, 8) ?? 0\n /* c8 ignore stop */\n if (buf[off + 475] !== 0) {\n // definitely a prefix, definitely >130 chars.\n const prefix = decString(buf, off + 345, 155)\n this.path = prefix + '/' + this.path\n } else {\n const prefix = decString(buf, off + 345, 130)\n if (prefix) {\n this.path = prefix + '/' + this.path\n }\n /* c8 ignore start */\n this.atime =\n ex?.atime ?? gex?.atime ?? decDate(buf, off + 476, 12)\n this.ctime =\n ex?.ctime ?? gex?.ctime ?? decDate(buf, off + 488, 12)\n /* c8 ignore stop */\n }\n }\n\n let sum = 8 * 0x20\n for (let i = off; i < off + 148; i++) {\n sum += buf[i] as number\n }\n\n for (let i = off + 156; i < off + 512; i++) {\n sum += buf[i] as number\n }\n\n this.cksumValid = sum === this.cksum\n if (this.cksum === undefined && sum === 8 * 0x20) {\n this.nullBlock = true\n }\n }\n\n #slurp(ex: HeaderData, gex: boolean = false) {\n Object.assign(\n this,\n Object.fromEntries(\n Object.entries(ex).filter(([k, v]) => {\n // we slurp in everything except for the path attribute in\n // a global extended header, because that's weird. Also, any\n // null/undefined values are ignored.\n return !(\n v === null ||\n v === undefined ||\n (k === 'path' && gex) ||\n (k === 'linkpath' && gex) ||\n k === 'global'\n )\n }),\n ),\n )\n }\n\n encode(buf?: Buffer, off: number = 0) {\n if (!buf) {\n buf = this.block = Buffer.alloc(512)\n }\n\n if (this.#type === 'Unsupported') {\n this.#type = '0'\n }\n\n if (!(buf.length >= off + 512)) {\n throw new Error('need 512 bytes for header')\n }\n\n const prefixSize = this.ctime || this.atime ? 130 : 155\n const split = splitPrefix(this.path || '', prefixSize)\n const path = split[0]\n const prefix = split[1]\n this.needPax = !!split[2]\n\n this.needPax = encString(buf, off, 100, path) || this.needPax\n this.needPax =\n encNumber(buf, off + 100, 8, this.mode) || this.needPax\n this.needPax =\n encNumber(buf, off + 108, 8, this.uid) || this.needPax\n this.needPax =\n encNumber(buf, off + 116, 8, this.gid) || this.needPax\n this.needPax =\n encNumber(buf, off + 124, 12, this.size) || this.needPax\n this.needPax =\n encDate(buf, off + 136, 12, this.mtime) || this.needPax\n buf[off + 156] = this.#type.charCodeAt(0)\n this.needPax =\n encString(buf, off + 157, 100, this.linkpath) || this.needPax\n buf.write('ustar\\u000000', off + 257, 8)\n this.needPax =\n encString(buf, off + 265, 32, this.uname) || this.needPax\n this.needPax =\n encString(buf, off + 297, 32, this.gname) || this.needPax\n this.needPax =\n encNumber(buf, off + 329, 8, this.devmaj) || this.needPax\n this.needPax =\n encNumber(buf, off + 337, 8, this.devmin) || this.needPax\n this.needPax =\n encString(buf, off + 345, prefixSize, prefix) || this.needPax\n if (buf[off + 475] !== 0) {\n this.needPax =\n encString(buf, off + 345, 155, prefix) || this.needPax\n } else {\n this.needPax =\n encString(buf, off + 345, 130, prefix) || this.needPax\n this.needPax =\n encDate(buf, off + 476, 12, this.atime) || this.needPax\n this.needPax =\n encDate(buf, off + 488, 12, this.ctime) || this.needPax\n }\n\n let sum = 8 * 0x20\n for (let i = off; i < off + 148; i++) {\n sum += buf[i] as number\n }\n\n for (let i = off + 156; i < off + 512; i++) {\n sum += buf[i] as number\n }\n\n this.cksum = sum\n encNumber(buf, off + 148, 8, this.cksum)\n this.cksumValid = true\n\n return this.needPax\n }\n\n get type(): EntryTypeName {\n return (\n this.#type === 'Unsupported' ?\n this.#type\n : types.name.get(this.#type)) as EntryTypeName\n }\n\n get typeKey(): EntryTypeCode | 'Unsupported' {\n return this.#type\n }\n\n set type(type: EntryTypeCode | EntryTypeName | 'Unsupported') {\n const c = String(types.code.get(type as EntryTypeName))\n if (types.isCode(c) || c === 'Unsupported') {\n this.#type = c\n } else if (types.isCode(type)) {\n this.#type = type\n } else {\n throw new TypeError('invalid entry type: ' + type)\n }\n }\n}\n\nconst splitPrefix = (\n p: string,\n prefixSize: number,\n): [string, string, boolean] => {\n const pathSize = 100\n let pp = p\n let prefix = ''\n let ret: undefined | [string, string, boolean] = undefined\n const root = pathModule.parse(p).root || '.'\n\n if (Buffer.byteLength(pp) < pathSize) {\n ret = [pp, prefix, false]\n } else {\n // first set prefix to the dir, and path to the base\n prefix = pathModule.dirname(pp)\n pp = pathModule.basename(pp)\n\n do {\n if (\n Buffer.byteLength(pp) <= pathSize &&\n Buffer.byteLength(prefix) <= prefixSize\n ) {\n // both fit!\n ret = [pp, prefix, false]\n } else if (\n Buffer.byteLength(pp) > pathSize &&\n Buffer.byteLength(prefix) <= prefixSize\n ) {\n // prefix fits in prefix, but path doesn't fit in path\n ret = [pp.slice(0, pathSize - 1), prefix, true]\n } else {\n // make path take a bit from prefix\n pp = pathModule.join(pathModule.basename(prefix), pp)\n prefix = pathModule.dirname(prefix)\n }\n } while (prefix !== root && ret === undefined)\n\n // at this point, found no resolution, just truncate\n if (!ret) {\n ret = [p.slice(0, pathSize - 1), '', true]\n }\n }\n return ret\n}\n\nconst decString = (buf: Buffer, off: number, size: number) =>\n buf\n .subarray(off, off + size)\n .toString('utf8')\n .replace(/\\0.*/, '')\n\nconst decDate = (buf: Buffer, off: number, size: number) =>\n numToDate(decNumber(buf, off, size))\n\nconst numToDate = (num?: number) =>\n num === undefined ? undefined : new Date(num * 1000)\n\nconst decNumber = (buf: Buffer, off: number, size: number) =>\n Number(buf[off]) & 0x80 ?\n large.parse(buf.subarray(off, off + size))\n : decSmallNumber(buf, off, size)\n\nconst nanUndef = (value: number) => (isNaN(value) ? undefined : value)\n\nconst decSmallNumber = (buf: Buffer, off: number, size: number) =>\n nanUndef(\n parseInt(\n buf\n .subarray(off, off + size)\n .toString('utf8')\n .replace(/\\0.*$/, '')\n .trim(),\n 8,\n ),\n )\n\n// the maximum encodable as a null-terminated octal, by field size\nconst MAXNUM = {\n 12: 0o77777777777,\n 8: 0o7777777,\n}\n\nconst encNumber = (\n buf: Buffer,\n off: number,\n size: 12 | 8,\n num?: number,\n) =>\n num === undefined ? false\n : num > MAXNUM[size] || num < 0 ?\n (large.encode(num, buf.subarray(off, off + size)), true)\n : (encSmallNumber(buf, off, size, num), false)\n\nconst encSmallNumber = (\n buf: Buffer,\n off: number,\n size: number,\n num: number,\n) => buf.write(octalString(num, size), off, size, 'ascii')\n\nconst octalString = (num: number, size: number) =>\n padOctal(Math.floor(num).toString(8), size)\n\nconst padOctal = (str: string, size: number) =>\n (str.length === size - 1 ?\n str\n : new Array(size - str.length - 1).join('0') + str + ' ') + '\\0'\n\nconst encDate = (\n buf: Buffer,\n off: number,\n size: 8 | 12,\n date?: Date,\n) =>\n date === undefined ? false : (\n encNumber(buf, off, size, date.getTime() / 1000)\n )\n\n// enough to fill the longest string we've got\nconst NULLS = new Array(156).join('\\0')\n// pad with nulls, return true if it's longer or non-ascii\nconst encString = (\n buf: Buffer,\n off: number,\n size: number,\n str?: string,\n) =>\n str === undefined ? false : (\n (buf.write(str + NULLS, off, size, 'utf8'),\n str.length !== Buffer.byteLength(str) || str.length > size)\n )\n", "// Tar can encode large and negative numbers using a leading byte of\n// 0xff for negative, and 0x80 for positive.\n\nexport const encode = (num: number, buf: Buffer) => {\n if (!Number.isSafeInteger(num)) {\n // The number is so large that javascript cannot represent it with integer\n // precision.\n throw Error(\n 'cannot encode number outside of javascript safe integer range',\n )\n } else if (num < 0) {\n encodeNegative(num, buf)\n } else {\n encodePositive(num, buf)\n }\n return buf\n}\n\nconst encodePositive = (num: number, buf: Buffer) => {\n buf[0] = 0x80\n\n for (var i = buf.length; i > 1; i--) {\n buf[i - 1] = num & 0xff\n num = Math.floor(num / 0x100)\n }\n}\n\nconst encodeNegative = (num: number, buf: Buffer) => {\n buf[0] = 0xff\n var flipped = false\n num = num * -1\n for (var i = buf.length; i > 1; i--) {\n var byte = num & 0xff\n num = Math.floor(num / 0x100)\n if (flipped) {\n buf[i - 1] = onesComp(byte)\n } else if (byte === 0) {\n buf[i - 1] = 0\n } else {\n flipped = true\n buf[i - 1] = twosComp(byte)\n }\n }\n}\n\nexport const parse = (buf: Buffer) => {\n const pre = buf[0]\n const value =\n pre === 0x80 ? pos(buf.subarray(1, buf.length))\n : pre === 0xff ? twos(buf)\n : null\n if (value === null) {\n throw Error('invalid base256 encoding')\n }\n\n if (!Number.isSafeInteger(value)) {\n // The number is so large that javascript cannot represent it with integer\n // precision.\n throw Error(\n 'parsed number outside of javascript safe integer range',\n )\n }\n\n return value\n}\n\nconst twos = (buf: Buffer) => {\n var len = buf.length\n var sum = 0\n var flipped = false\n for (var i = len - 1; i > -1; i--) {\n var byte = Number(buf[i])\n var f\n if (flipped) {\n f = onesComp(byte)\n } else if (byte === 0) {\n f = byte\n } else {\n flipped = true\n f = twosComp(byte)\n }\n if (f !== 0) {\n sum -= f * Math.pow(256, len - i - 1)\n }\n }\n return sum\n}\n\nconst pos = (buf: Buffer) => {\n var len = buf.length\n var sum = 0\n for (var i = len - 1; i > -1; i--) {\n var byte = Number(buf[i])\n if (byte !== 0) {\n sum += byte * Math.pow(256, len - i - 1)\n }\n }\n return sum\n}\n\nconst onesComp = (byte: number) => (0xff ^ byte) & 0xff\n\nconst twosComp = (byte: number) => ((0xff ^ byte) + 1) & 0xff\n", "export const isCode = (c: string): c is EntryTypeCode =>\n name.has(c as EntryTypeCode)\n\nexport const isName = (c: string): c is EntryTypeName =>\n code.has(c as EntryTypeName)\n\nexport type EntryTypeCode =\n | '0'\n | ''\n | '1'\n | '2'\n | '3'\n | '4'\n | '5'\n | '6'\n | '7'\n | 'g'\n | 'x'\n | 'A'\n | 'D'\n | 'I'\n | 'K'\n | 'L'\n | 'M'\n | 'N'\n | 'S'\n | 'V'\n | 'X'\n\nexport type EntryTypeName =\n | 'File'\n | 'OldFile'\n | 'Link'\n | 'SymbolicLink'\n | 'CharacterDevice'\n | 'BlockDevice'\n | 'Directory'\n | 'FIFO'\n | 'ContiguousFile'\n | 'GlobalExtendedHeader'\n | 'ExtendedHeader'\n | 'SolarisACL'\n | 'GNUDumpDir'\n | 'Inode'\n | 'NextFileHasLongLinkpath'\n | 'NextFileHasLongPath'\n | 'ContinuationFile'\n | 'OldGnuLongPath'\n | 'SparseFile'\n | 'TapeVolumeHeader'\n | 'OldExtendedHeader'\n | 'Unsupported'\n\n// map types from key to human-friendly name\nexport const name = new Map<EntryTypeCode, EntryTypeName>([\n ['0', 'File'],\n // same as File\n ['', 'OldFile'],\n ['1', 'Link'],\n ['2', 'SymbolicLink'],\n // Devices and FIFOs aren't fully supported\n // they are parsed, but skipped when unpacking\n ['3', 'CharacterDevice'],\n ['4', 'BlockDevice'],\n ['5', 'Directory'],\n ['6', 'FIFO'],\n // same as File\n ['7', 'ContiguousFile'],\n // pax headers\n ['g', 'GlobalExtendedHeader'],\n ['x', 'ExtendedHeader'],\n // vendor-specific stuff\n // skip\n ['A', 'SolarisACL'],\n // like 5, but with data, which should be skipped\n ['D', 'GNUDumpDir'],\n // metadata only, skip\n ['I', 'Inode'],\n // data = link path of next file\n ['K', 'NextFileHasLongLinkpath'],\n // data = path of next file\n ['L', 'NextFileHasLongPath'],\n // skip\n ['M', 'ContinuationFile'],\n // like L\n ['N', 'OldGnuLongPath'],\n // skip\n ['S', 'SparseFile'],\n // skip\n ['V', 'TapeVolumeHeader'],\n // like x\n ['X', 'OldExtendedHeader'],\n])\n\n// map the other direction\nexport const code = new Map<EntryTypeName, EntryTypeCode>(\n Array.from(name).map(kv => [kv[1], kv[0]]),\n)\n", "import { basename } from 'node:path'\nimport { Header, HeaderData } from './header.js'\n\nexport class Pax implements HeaderData {\n atime?: Date\n mtime?: Date\n ctime?: Date\n\n charset?: string\n comment?: string\n\n gid?: number\n uid?: number\n\n gname?: string\n uname?: string\n linkpath?: string\n dev?: number\n ino?: number\n nlink?: number\n path?: string\n size?: number\n mode?: number\n\n global: boolean\n\n constructor(obj: HeaderData, global: boolean = false) {\n this.atime = obj.atime\n this.charset = obj.charset\n this.comment = obj.comment\n this.ctime = obj.ctime\n this.dev = obj.dev\n this.gid = obj.gid\n this.global = global\n this.gname = obj.gname\n this.ino = obj.ino\n this.linkpath = obj.linkpath\n this.mtime = obj.mtime\n this.nlink = obj.nlink\n this.path = obj.path\n this.size = obj.size\n this.uid = obj.uid\n this.uname = obj.uname\n }\n\n encode() {\n const body = this.encodeBody()\n if (body === '') {\n return Buffer.allocUnsafe(0)\n }\n\n const bodyLen = Buffer.byteLength(body)\n // round up to 512 bytes\n // add 512 for header\n const bufLen = 512 * Math.ceil(1 + bodyLen / 512)\n const buf = Buffer.allocUnsafe(bufLen)\n\n // 0-fill the header section, it might not hit every field\n for (let i = 0; i < 512; i++) {\n buf[i] = 0\n }\n\n new Header({\n // XXX split the path\n // then the path should be PaxHeader + basename, but less than 99,\n // prepend with the dirname\n /* c8 ignore start */\n path: ('PaxHeader/' + basename(this.path ?? '')).slice(0, 99),\n /* c8 ignore stop */\n mode: this.mode || 0o644,\n uid: this.uid,\n gid: this.gid,\n size: bodyLen,\n mtime: this.mtime,\n type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader',\n linkpath: '',\n uname: this.uname || '',\n gname: this.gname || '',\n devmaj: 0,\n devmin: 0,\n atime: this.atime,\n ctime: this.ctime,\n }).encode(buf)\n\n buf.write(body, 512, bodyLen, 'utf8')\n\n // null pad after the body\n for (let i = bodyLen + 512; i < buf.length; i++) {\n buf[i] = 0\n }\n\n return buf\n }\n\n encodeBody() {\n return (\n this.encodeField('path') +\n this.encodeField('ctime') +\n this.encodeField('atime') +\n this.encodeField('dev') +\n this.encodeField('ino') +\n this.encodeField('nlink') +\n this.encodeField('charset') +\n this.encodeField('comment') +\n this.encodeField('gid') +\n this.encodeField('gname') +\n this.encodeField('linkpath') +\n this.encodeField('mtime') +\n this.encodeField('size') +\n this.encodeField('uid') +\n this.encodeField('uname')\n )\n }\n\n encodeField(field: keyof Pax): string {\n if (this[field] === undefined) {\n return ''\n }\n const r = this[field]\n const v = r instanceof Date ? r.getTime() / 1000 : r\n const s =\n ' ' +\n (field === 'dev' || field === 'ino' || field === 'nlink' ?\n 'SCHILY.'\n : '') +\n field +\n '=' +\n v +\n '\\n'\n const byteLen = Buffer.byteLength(s)\n // the digits includes the length of the digits in ascii base-10\n // so if it's 9 characters, then adding 1 for the 9 makes it 10\n // which makes it 11 chars.\n let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1\n if (byteLen + digits >= Math.pow(10, digits)) {\n digits += 1\n }\n const len = digits + byteLen\n return len + s\n }\n\n static parse(str: string, ex?: HeaderData, g: boolean = false) {\n return new Pax(merge(parseKV(str), ex), g)\n }\n}\n\nconst merge = (a: HeaderData, b?: HeaderData) =>\n b ? Object.assign({}, b, a) : a\n\nconst parseKV = (str: string) =>\n str\n .replace(/\\n$/, '')\n .split('\\n')\n .reduce(parseKVLine, Object.create(null))\n\nconst parseKVLine = (set: Record<string, any>, line: string) => {\n const n = parseInt(line, 10)\n\n // XXX Values with \\n in them will fail this.\n // Refactor to not be a naive line-by-line parse.\n if (n !== Buffer.byteLength(line) + 1) {\n return set\n }\n\n line = line.slice((n + ' ').length)\n const kv = line.split('=')\n const r = kv.shift()\n\n if (!r) {\n return set\n }\n\n const k = r.replace(/^SCHILY\\.(dev|ino|nlink)/, '$1')\n\n const v = kv.join('=')\n set[k] =\n /^([A-Z]+\\.)?([mac]|birth|creation)time$/.test(k) ?\n new Date(Number(v) * 1000)\n : /^[0-9]+$/.test(v) ? +v\n : v\n return set\n}\n", "const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n", "// on windows, either \\ or / are valid directory separators.\n// on unix, \\ is a valid character in filenames.\n// so, on windows, and only on windows, we replace all \\ chars with /,\n// so that we can use / as our one and only directory separator char.\n\nconst platform =\n process.env.TESTING_TAR_FAKE_PLATFORM || process.platform\n\nexport const normalizeWindowsPath =\n platform !== 'win32' ?\n (p: string) => p\n : (p: string) => p && p.replace(/\\\\/g, '/')\n", "import { Minipass } from 'minipass'\nimport { Header } from './header.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { Pax } from './pax.js'\nimport { EntryTypeName } from './types.js'\n\nexport class ReadEntry extends Minipass<Buffer, Buffer> {\n extended?: Pax\n globalExtended?: Pax\n header: Header\n startBlockSize: number\n blockRemain: number\n remain: number\n type: EntryTypeName\n meta: boolean = false\n ignore: boolean = false\n path: string\n mode?: number\n uid?: number\n gid?: number\n uname?: string\n gname?: string\n size: number = 0\n mtime?: Date\n atime?: Date\n ctime?: Date\n linkpath?: string\n\n dev?: number\n ino?: number\n nlink?: number\n invalid: boolean = false\n absolute?: string\n unsupported: boolean = false\n\n constructor(header: Header, ex?: Pax, gex?: Pax) {\n super({})\n // read entries always start life paused. this is to avoid the\n // situation where Minipass's auto-ending empty streams results\n // in an entry ending before we're ready for it.\n this.pause()\n this.extended = ex\n this.globalExtended = gex\n this.header = header\n /* c8 ignore start */\n this.remain = header.size ?? 0\n /* c8 ignore stop */\n this.startBlockSize = 512 * Math.ceil(this.remain / 512)\n this.blockRemain = this.startBlockSize\n this.type = header.type\n switch (this.type) {\n case 'File':\n case 'OldFile':\n case 'Link':\n case 'SymbolicLink':\n case 'CharacterDevice':\n case 'BlockDevice':\n case 'Directory':\n case 'FIFO':\n case 'ContiguousFile':\n case 'GNUDumpDir':\n break\n\n case 'NextFileHasLongLinkpath':\n case 'NextFileHasLongPath':\n case 'OldGnuLongPath':\n case 'GlobalExtendedHeader':\n case 'ExtendedHeader':\n case 'OldExtendedHeader':\n this.meta = true\n break\n\n // NOTE: gnutar and bsdtar treat unrecognized types as 'File'\n // it may be worth doing the same, but with a warning.\n default:\n this.ignore = true\n }\n\n /* c8 ignore start */\n if (!header.path) {\n throw new Error('no path provided for tar.ReadEntry')\n }\n /* c8 ignore stop */\n\n this.path = normalizeWindowsPath(header.path) as string\n this.mode = header.mode\n if (this.mode) {\n this.mode = this.mode & 0o7777\n }\n this.uid = header.uid\n this.gid = header.gid\n this.uname = header.uname\n this.gname = header.gname\n this.size = this.remain\n this.mtime = header.mtime\n this.atime = header.atime\n this.ctime = header.ctime\n /* c8 ignore start */\n this.linkpath =\n header.linkpath ?\n normalizeWindowsPath(header.linkpath)\n : undefined\n /* c8 ignore stop */\n this.uname = header.uname\n this.gname = header.gname\n\n if (ex) {\n this.#slurp(ex)\n }\n if (gex) {\n this.#slurp(gex, true)\n }\n }\n\n write(data: Buffer) {\n const writeLen = data.length\n if (writeLen > this.blockRemain) {\n throw new Error('writing more to entry than is appropriate')\n }\n\n const r = this.remain\n const br = this.blockRemain\n this.remain = Math.max(0, r - writeLen)\n this.blockRemain = Math.max(0, br - writeLen)\n if (this.ignore) {\n return true\n }\n\n if (r >= writeLen) {\n return super.write(data)\n }\n\n // r < writeLen\n return super.write(data.subarray(0, r))\n }\n\n #slurp(ex: Pax, gex: boolean = false) {\n if (ex.path) ex.path = normalizeWindowsPath(ex.path)\n if (ex.linkpath) ex.linkpath = normalizeWindowsPath(ex.linkpath)\n Object.assign(\n this,\n Object.fromEntries(\n Object.entries(ex).filter(([k, v]) => {\n // we slurp in everything except for the path attribute in\n // a global extended header, because that's weird. Also, any\n // null/undefined values are ignored.\n return !(\n v === null ||\n v === undefined ||\n (k === 'path' && gex)\n )\n }),\n ),\n )\n }\n}\n", "import { type Minipass } from 'minipass'\n\n/** has a warn method */\nexport type Warner = {\n warn(code: string, message: string | Error, data: any): void\n file?: string\n cwd?: string\n strict?: boolean\n\n emit(\n event: 'warn',\n code: string,\n message: string,\n data?: WarnData,\n ): void\n emit(event: 'error', error: TarError): void\n}\n\nexport type WarnEvent<T = Buffer> = Minipass.Events<T> & {\n warn: [code: string, message: string, data: WarnData]\n}\n\nexport type WarnData = {\n file?: string\n cwd?: string\n code?: string\n tarCode?: string\n recoverable?: boolean\n [k: string]: any\n}\n\nexport type TarError = Error & WarnData\n\nexport const warnMethod = (\n self: Warner,\n code: string,\n message: string | Error,\n data: WarnData = {},\n) => {\n if (self.file) {\n data.file = self.file\n }\n if (self.cwd) {\n data.cwd = self.cwd\n }\n data.code =\n (message instanceof Error &&\n (message as NodeJS.ErrnoException).code) ||\n code\n data.tarCode = code\n if (!self.strict && data.recoverable !== false) {\n if (message instanceof Error) {\n data = Object.assign(message, data)\n message = message.message\n }\n self.emit('warn', code, message, data)\n } else if (message instanceof Error) {\n self.emit('error', Object.assign(message, data))\n } else {\n self.emit(\n 'error',\n Object.assign(new Error(`${code}: ${message}`), data),\n )\n }\n}\n", "// warning: extremely hot code path.\n// This has been meticulously optimized for use\n// within npm install on large package trees.\n// Do not edit without careful benchmarking.\nexport const stripTrailingSlashes = (str: string) => {\n let i = str.length - 1\n let slashesStart = -1\n while (i > -1 && str.charAt(i) === '/') {\n slashesStart = i\n i--\n }\n return slashesStart === -1 ? str : str.slice(0, slashesStart)\n}\n", "// A readable tar stream creator\n// Technically, this is a transform stream that you write paths into,\n// and tar format comes out of.\n// The `add()` method is like `write()` but returns this,\n// and end() return `this` as well, so you can\n// do `new Pack(opt).add('files').add('dir').end().pipe(output)\n// You could also do something like:\n// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))\n\nimport fs, { type Stats } from 'fs'\nimport {\n WriteEntry,\n WriteEntrySync,\n WriteEntryTar,\n} from './write-entry.js'\n\nexport class PackJob {\n path: string\n absolute: string\n entry?: WriteEntry | WriteEntryTar\n stat?: Stats\n readdir?: string[]\n pending: boolean = false\n ignore: boolean = false\n piped: boolean = false\n constructor(path: string, absolute: string) {\n this.path = path || './'\n this.absolute = absolute\n }\n}\n\nimport { Minipass } from 'minipass'\nimport * as zlib from 'minizlib'\nimport { Yallist } from 'yallist'\nimport { ReadEntry } from './read-entry.js'\nimport {\n WarnEvent,\n warnMethod,\n type WarnData,\n type Warner,\n} from './warn-method.js'\n\nconst EOF = Buffer.alloc(1024)\nconst ONSTAT = Symbol('onStat')\nconst ENDED = Symbol('ended')\nconst QUEUE = Symbol('queue')\nconst CURRENT = Symbol('current')\nconst PROCESS = Symbol('process')\nconst PROCESSING = Symbol('processing')\nconst PROCESSJOB = Symbol('processJob')\nconst JOBS = Symbol('jobs')\nconst JOBDONE = Symbol('jobDone')\nconst ADDFSENTRY = Symbol('addFSEntry')\nconst ADDTARENTRY = Symbol('addTarEntry')\nconst STAT = Symbol('stat')\nconst READDIR = Symbol('readdir')\nconst ONREADDIR = Symbol('onreaddir')\nconst PIPE = Symbol('pipe')\nconst ENTRY = Symbol('entry')\nconst ENTRYOPT = Symbol('entryOpt')\nconst WRITEENTRYCLASS = Symbol('writeEntryClass')\nconst WRITE = Symbol('write')\nconst ONDRAIN = Symbol('ondrain')\n\nimport path from 'path'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { TarOptions } from './options.js'\n\nexport class Pack\n extends Minipass<Buffer, ReadEntry | string, WarnEvent<Buffer>>\n implements Warner\n{\n sync: boolean = false\n opt: TarOptions\n cwd: string\n maxReadSize?: number\n preservePaths: boolean\n strict: boolean\n noPax: boolean\n prefix: string\n linkCache: Exclude<TarOptions['linkCache'], undefined>\n statCache: Exclude<TarOptions['statCache'], undefined>\n file: string\n portable: boolean\n zip?: zlib.BrotliCompress | zlib.Gzip | zlib.ZstdCompress\n readdirCache: Exclude<TarOptions['readdirCache'], undefined>\n noDirRecurse: boolean\n follow: boolean\n noMtime: boolean\n mtime?: Date\n filter: Exclude<TarOptions['filter'], undefined>\n jobs: number;\n\n [WRITEENTRYCLASS]: typeof WriteEntry | typeof WriteEntrySync\n onWriteEntry?: (entry: WriteEntry) => void;\n // Note: we actually DO need a linked list here, because we\n // shift() to update the head of the list where we start, but still\n // while that happens, need to know what the next item in the queue\n // will be. Since we do multiple jobs in parallel, it's not as simple\n // as just an Array.shift(), since that would lose the information about\n // the next job in the list. We could add a .next field on the PackJob\n // class, but then we'd have to be tracking the tail of the queue the\n // whole time, and Yallist just does that for us anyway.\n [QUEUE]: Yallist<PackJob>;\n [JOBS]: number = 0;\n [PROCESSING]: boolean = false;\n [ENDED]: boolean = false\n\n constructor(opt: TarOptions = {}) {\n //@ts-ignore\n super()\n this.opt = opt\n this.file = opt.file || ''\n this.cwd = opt.cwd || process.cwd()\n this.maxReadSize = opt.maxReadSize\n this.preservePaths = !!opt.preservePaths\n this.strict = !!opt.strict\n this.noPax = !!opt.noPax\n this.prefix = normalizeWindowsPath(opt.prefix || '')\n this.linkCache = opt.linkCache || new Map()\n this.statCache = opt.statCache || new Map()\n this.readdirCache = opt.readdirCache || new Map()\n this.onWriteEntry = opt.onWriteEntry\n\n this[WRITEENTRYCLASS] = WriteEntry\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n\n this.portable = !!opt.portable\n\n if (opt.gzip || opt.brotli || opt.zstd) {\n if (\n (opt.gzip ? 1 : 0) +\n (opt.brotli ? 1 : 0) +\n (opt.zstd ? 1 : 0) >\n 1\n ) {\n throw new TypeError(\n 'gzip, brotli, zstd are mutually exclusive',\n )\n }\n if (opt.gzip) {\n if (typeof opt.gzip !== 'object') {\n opt.gzip = {}\n }\n if (this.portable) {\n opt.gzip.portable = true\n }\n this.zip = new zlib.Gzip(opt.gzip)\n }\n if (opt.brotli) {\n if (typeof opt.brotli !== 'object') {\n opt.brotli = {}\n }\n this.zip = new zlib.BrotliCompress(opt.brotli)\n }\n if (opt.zstd) {\n if (typeof opt.zstd !== 'object') {\n opt.zstd = {}\n }\n this.zip = new zlib.ZstdCompress(opt.zstd)\n }\n /* c8 ignore next */\n if (!this.zip) throw new Error('impossible')\n const zip = this.zip\n zip.on('data', chunk => super.write(chunk as unknown as string))\n zip.on('end', () => super.end())\n zip.on('drain', () => this[ONDRAIN]())\n this.on('resume', () => zip.resume())\n } else {\n this.on('drain', this[ONDRAIN])\n }\n\n this.noDirRecurse = !!opt.noDirRecurse\n this.follow = !!opt.follow\n this.noMtime = !!opt.noMtime\n if (opt.mtime) this.mtime = opt.mtime\n\n this.filter =\n typeof opt.filter === 'function' ? opt.filter : () => true\n\n this[QUEUE] = new Yallist<PackJob>()\n this[JOBS] = 0\n this.jobs = Number(opt.jobs) || 4\n this[PROCESSING] = false\n this[ENDED] = false\n }\n\n [WRITE](chunk: Buffer) {\n return super.write(chunk as unknown as string)\n }\n\n add(path: string | ReadEntry) {\n this.write(path)\n return this\n }\n\n end(cb?: () => void): this\n end(path: string | ReadEntry, cb?: () => void): this\n end(\n path: string | ReadEntry,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): this\n end(\n path?: string | ReadEntry | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n /* c8 ignore start */\n if (typeof path === 'function') {\n cb = path\n path = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n /* c8 ignore stop */\n if (path) {\n this.add(path)\n }\n this[ENDED] = true\n this[PROCESS]()\n /* c8 ignore next */\n if (cb) cb()\n return this\n }\n\n write(path: string | ReadEntry) {\n if (this[ENDED]) {\n throw new Error('write after end')\n }\n\n if (path instanceof ReadEntry) {\n this[ADDTARENTRY](path)\n } else {\n this[ADDFSENTRY](path)\n }\n return this.flowing\n }\n\n [ADDTARENTRY](p: ReadEntry) {\n const absolute = normalizeWindowsPath(\n path.resolve(this.cwd, p.path),\n )\n // in this case, we don't have to wait for the stat\n if (!this.filter(p.path, p)) {\n p.resume()\n } else {\n const job = new PackJob(p.path, absolute)\n job.entry = new WriteEntryTar(p, this[ENTRYOPT](job))\n job.entry.on('end', () => this[JOBDONE](job))\n this[JOBS] += 1\n this[QUEUE].push(job)\n }\n\n this[PROCESS]()\n }\n\n [ADDFSENTRY](p: string) {\n const absolute = normalizeWindowsPath(path.resolve(this.cwd, p))\n this[QUEUE].push(new PackJob(p, absolute))\n this[PROCESS]()\n }\n\n [STAT](job: PackJob) {\n job.pending = true\n this[JOBS] += 1\n const stat = this.follow ? 'stat' : 'lstat'\n fs[stat](job.absolute, (er, stat) => {\n job.pending = false\n this[JOBS] -= 1\n if (er) {\n this.emit('error', er)\n } else {\n this[ONSTAT](job, stat)\n }\n })\n }\n\n [ONSTAT](job: PackJob, stat: Stats) {\n this.statCache.set(job.absolute, stat)\n job.stat = stat\n\n // now we have the stat, we can filter it.\n if (!this.filter(job.path, stat)) {\n job.ignore = true\n } else if (\n stat.isFile() &&\n stat.nlink > 1 &&\n job === this[CURRENT] &&\n !this.linkCache.get(`${stat.dev}:${stat.ino}`) &&\n !this.sync\n ) {\n // if it's not filtered, and it's a new File entry,\n // jump the queue in case any pending Link entries are about\n // to try to link to it. This prevents a hardlink from coming ahead\n // of its target in the archive.\n this[PROCESSJOB](job)\n }\n\n this[PROCESS]()\n }\n\n [READDIR](job: PackJob) {\n job.pending = true\n this[JOBS] += 1\n fs.readdir(job.absolute, (er, entries) => {\n job.pending = false\n this[JOBS] -= 1\n if (er) {\n return this.emit('error', er)\n }\n this[ONREADDIR](job, entries)\n })\n }\n\n [ONREADDIR](job: PackJob, entries: string[]) {\n this.readdirCache.set(job.absolute, entries)\n job.readdir = entries\n this[PROCESS]()\n }\n\n [PROCESS]() {\n if (this[PROCESSING]) {\n return\n }\n\n this[PROCESSING] = true\n for (\n let w = this[QUEUE].head;\n !!w && this[JOBS] < this.jobs;\n w = w.next\n ) {\n this[PROCESSJOB](w.value)\n if (w.value.ignore) {\n const p = w.next\n this[QUEUE].removeNode(w)\n w.next = p\n }\n }\n\n this[PROCESSING] = false\n\n if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) {\n if (this.zip) {\n this.zip.end(EOF)\n } else {\n super.write(EOF as unknown as string)\n super.end()\n }\n }\n }\n\n get [CURRENT]() {\n return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value\n }\n\n [JOBDONE](_job: PackJob) {\n this[QUEUE].shift()\n this[JOBS] -= 1\n this[PROCESS]()\n }\n\n [PROCESSJOB](job: PackJob) {\n if (job.pending) {\n return\n }\n\n if (job.entry) {\n if (job === this[CURRENT] && !job.piped) {\n this[PIPE](job)\n }\n return\n }\n\n if (!job.stat) {\n const sc = this.statCache.get(job.absolute)\n if (sc) {\n this[ONSTAT](job, sc)\n } else {\n this[STAT](job)\n }\n }\n if (!job.stat) {\n return\n }\n\n // filtered out!\n if (job.ignore) {\n return\n }\n\n if (\n !this.noDirRecurse &&\n job.stat.isDirectory() &&\n !job.readdir\n ) {\n const rc = this.readdirCache.get(job.absolute)\n if (rc) {\n this[ONREADDIR](job, rc)\n } else {\n this[READDIR](job)\n }\n if (!job.readdir) {\n return\n }\n }\n\n // we know it doesn't have an entry, because that got checked above\n job.entry = this[ENTRY](job)\n if (!job.entry) {\n job.ignore = true\n return\n }\n\n if (job === this[CURRENT] && !job.piped) {\n this[PIPE](job)\n }\n }\n\n [ENTRYOPT](job: PackJob): TarOptions {\n return {\n onwarn: (code, msg, data) => this.warn(code, msg, data),\n noPax: this.noPax,\n cwd: this.cwd,\n absolute: job.absolute,\n preservePaths: this.preservePaths,\n maxReadSize: this.maxReadSize,\n strict: this.strict,\n portable: this.portable,\n linkCache: this.linkCache,\n statCache: this.statCache,\n noMtime: this.noMtime,\n mtime: this.mtime,\n prefix: this.prefix,\n onWriteEntry: this.onWriteEntry,\n }\n }\n\n [ENTRY](job: PackJob) {\n this[JOBS] += 1\n try {\n const e = new this[WRITEENTRYCLASS](\n job.path,\n this[ENTRYOPT](job),\n )\n return e\n .on('end', () => this[JOBDONE](job))\n .on('error', er => this.emit('error', er))\n } catch (er) {\n this.emit('error', er)\n }\n }\n\n [ONDRAIN]() {\n if (this[CURRENT] && this[CURRENT].entry) {\n this[CURRENT].entry.resume()\n }\n }\n\n // like .pipe() but using super, because our write() is special\n [PIPE](job: PackJob) {\n job.piped = true\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = job.path\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n const source = job.entry\n const zip = this.zip\n /* c8 ignore start */\n if (!source) throw new Error('cannot pipe without source')\n /* c8 ignore stop */\n\n if (zip) {\n source.on('data', chunk => {\n if (!zip.write(chunk)) {\n source.pause()\n }\n })\n } else {\n source.on('data', chunk => {\n if (!super.write(chunk as unknown as string)) {\n source.pause()\n }\n })\n }\n }\n\n pause() {\n if (this.zip) {\n this.zip.pause()\n }\n return super.pause()\n }\n warn(\n code: string,\n message: string | Error,\n data: WarnData = {},\n ): void {\n warnMethod(this, code, message, data)\n }\n}\n\nexport class PackSync extends Pack {\n sync: true = true\n constructor(opt: TarOptions) {\n super(opt)\n this[WRITEENTRYCLASS] = WriteEntrySync\n }\n\n // pause/resume are no-ops in sync streams.\n pause() {}\n resume() {}\n\n [STAT](job: PackJob) {\n const stat = this.follow ? 'statSync' : 'lstatSync'\n this[ONSTAT](job, fs[stat](job.absolute))\n }\n\n [READDIR](job: PackJob) {\n this[ONREADDIR](job, fs.readdirSync(job.absolute))\n }\n\n // gotta get it all in this tick\n [PIPE](job: PackJob) {\n const source = job.entry\n const zip = this.zip\n\n if (job.readdir) {\n job.readdir.forEach(entry => {\n const p = job.path\n const base = p === './' ? '' : p.replace(/\\/*$/, '/')\n this[ADDFSENTRY](base + entry)\n })\n }\n\n /* c8 ignore start */\n if (!source) throw new Error('Cannot pipe without source')\n /* c8 ignore stop */\n\n if (zip) {\n source.on('data', chunk => {\n zip.write(chunk)\n })\n } else {\n source.on('data', chunk => {\n super[WRITE](chunk)\n })\n }\n }\n}\n", "import fs, { type Stats } from 'fs'\nimport { Minipass } from 'minipass'\nimport path from 'path'\nimport { Header } from './header.js'\nimport { modeFix } from './mode-fix.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport {\n dealias,\n LinkCacheKey,\n TarOptions,\n TarOptionsWithAliases,\n} from './options.js'\nimport { Pax } from './pax.js'\nimport { ReadEntry } from './read-entry.js'\nimport { stripAbsolutePath } from './strip-absolute-path.js'\nimport { stripTrailingSlashes } from './strip-trailing-slashes.js'\nimport { EntryTypeName } from './types.js'\nimport {\n WarnData,\n Warner,\n WarnEvent,\n warnMethod,\n} from './warn-method.js'\nimport * as winchars from './winchars.js'\n\nconst prefixPath = (path: string, prefix?: string) => {\n if (!prefix) {\n return normalizeWindowsPath(path)\n }\n path = normalizeWindowsPath(path).replace(/^\\.(\\/|$)/, '')\n return stripTrailingSlashes(prefix) + '/' + path\n}\n\nconst maxReadSize = 16 * 1024 * 1024\n\nconst PROCESS = Symbol('process')\nconst FILE = Symbol('file')\nconst DIRECTORY = Symbol('directory')\nconst SYMLINK = Symbol('symlink')\nconst HARDLINK = Symbol('hardlink')\nconst HEADER = Symbol('header')\nconst READ = Symbol('read')\nconst LSTAT = Symbol('lstat')\nconst ONLSTAT = Symbol('onlstat')\nconst ONREAD = Symbol('onread')\nconst ONREADLINK = Symbol('onreadlink')\nconst OPENFILE = Symbol('openfile')\nconst ONOPENFILE = Symbol('onopenfile')\nconst CLOSE = Symbol('close')\nconst MODE = Symbol('mode')\nconst AWAITDRAIN = Symbol('awaitDrain')\nconst ONDRAIN = Symbol('ondrain')\nconst PREFIX = Symbol('prefix')\n\nexport class WriteEntry\n extends Minipass<Buffer, Minipass.ContiguousData, WarnEvent>\n implements Warner\n{\n path: string\n portable: boolean\n myuid: number = (process.getuid && process.getuid()) || 0\n // until node has builtin pwnam functions, this'll have to do\n myuser: string = process.env.USER || ''\n maxReadSize: number\n linkCache: Exclude<TarOptions['linkCache'], undefined>\n statCache: Exclude<TarOptions['statCache'], undefined>\n preservePaths: boolean\n cwd: string\n strict: boolean\n mtime?: Date\n noPax: boolean\n noMtime: boolean\n prefix?: string\n fd?: number\n\n blockLen: number = 0\n blockRemain: number = 0\n buf?: Buffer\n pos: number = 0\n remain: number = 0\n length: number = 0\n offset: number = 0\n\n win32: boolean\n absolute: string\n\n header?: Header\n type?: EntryTypeName | 'Unsupported'\n linkpath?: string\n stat?: Stats\n onWriteEntry?: (entry: WriteEntry) => any\n\n #hadError: boolean = false\n\n constructor(p: string, opt_: TarOptionsWithAliases = {}) {\n const opt = dealias(opt_)\n super()\n this.path = normalizeWindowsPath(p)\n // suppress atime, ctime, uid, gid, uname, gname\n this.portable = !!opt.portable\n this.maxReadSize = opt.maxReadSize || maxReadSize\n this.linkCache = opt.linkCache || new Map()\n this.statCache = opt.statCache || new Map()\n this.preservePaths = !!opt.preservePaths\n this.cwd = normalizeWindowsPath(opt.cwd || process.cwd())\n this.strict = !!opt.strict\n this.noPax = !!opt.noPax\n this.noMtime = !!opt.noMtime\n this.mtime = opt.mtime\n this.prefix =\n opt.prefix ? normalizeWindowsPath(opt.prefix) : undefined\n this.onWriteEntry = opt.onWriteEntry\n\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n\n let pathWarn: string | boolean = false\n if (!this.preservePaths) {\n const [root, stripped] = stripAbsolutePath(this.path)\n if (root && typeof stripped === 'string') {\n this.path = stripped\n pathWarn = root\n }\n }\n\n this.win32 = !!opt.win32 || process.platform === 'win32'\n if (this.win32) {\n // force the \\ to / normalization, since we might not *actually*\n // be on windows, but want \\ to be considered a path separator.\n this.path = winchars.decode(this.path.replace(/\\\\/g, '/'))\n p = p.replace(/\\\\/g, '/')\n }\n\n this.absolute = normalizeWindowsPath(\n opt.absolute || path.resolve(this.cwd, p),\n )\n\n if (this.path === '') {\n this.path = './'\n }\n\n if (pathWarn) {\n this.warn(\n 'TAR_ENTRY_INFO',\n `stripping ${pathWarn} from absolute path`,\n {\n entry: this,\n path: pathWarn + this.path,\n },\n )\n }\n\n const cs = this.statCache.get(this.absolute)\n if (cs) {\n this[ONLSTAT](cs)\n } else {\n this[LSTAT]()\n }\n }\n\n warn(code: string, message: string | Error, data: WarnData = {}) {\n return warnMethod(this, code, message, data)\n }\n\n emit(ev: keyof WarnEvent, ...data: any[]) {\n if (ev === 'error') {\n this.#hadError = true\n }\n return super.emit(ev, ...data)\n }\n\n [LSTAT]() {\n fs.lstat(this.absolute, (er, stat) => {\n if (er) {\n return this.emit('error', er)\n }\n this[ONLSTAT](stat)\n })\n }\n\n [ONLSTAT](stat: Stats) {\n this.statCache.set(this.absolute, stat)\n this.stat = stat\n if (!stat.isFile()) {\n stat.size = 0\n }\n this.type = getType(stat)\n this.emit('stat', stat)\n this[PROCESS]()\n }\n\n [PROCESS]() {\n switch (this.type) {\n case 'File':\n return this[FILE]()\n case 'Directory':\n return this[DIRECTORY]()\n case 'SymbolicLink':\n return this[SYMLINK]()\n // unsupported types are ignored.\n default:\n return this.end()\n }\n }\n\n [MODE](mode: number) {\n return modeFix(mode, this.type === 'Directory', this.portable)\n }\n\n [PREFIX](path: string) {\n return prefixPath(path, this.prefix)\n }\n\n [HEADER]() {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot write header before stat')\n }\n /* c8 ignore stop */\n\n if (this.type === 'Directory' && this.portable) {\n this.noMtime = true\n }\n\n this.onWriteEntry?.(this)\n this.header = new Header({\n path: this[PREFIX](this.path),\n // only apply the prefix to hard links.\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n // only the permissions and setuid/setgid/sticky bitflags\n // not the higher-order bits that specify file type\n mode: this[MODE](this.stat.mode),\n uid: this.portable ? undefined : this.stat.uid,\n gid: this.portable ? undefined : this.stat.gid,\n size: this.stat.size,\n mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime,\n /* c8 ignore next */\n type: this.type === 'Unsupported' ? undefined : this.type,\n uname:\n this.portable ? undefined\n : this.stat.uid === this.myuid ? this.myuser\n : '',\n atime: this.portable ? undefined : this.stat.atime,\n ctime: this.portable ? undefined : this.stat.ctime,\n })\n\n if (this.header.encode() && !this.noPax) {\n super.write(\n new Pax({\n atime: this.portable ? undefined : this.header.atime,\n ctime: this.portable ? undefined : this.header.ctime,\n gid: this.portable ? undefined : this.header.gid,\n mtime:\n this.noMtime ? undefined : (\n this.mtime || this.header.mtime\n ),\n path: this[PREFIX](this.path),\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n size: this.header.size,\n uid: this.portable ? undefined : this.header.uid,\n uname: this.portable ? undefined : this.header.uname,\n dev: this.portable ? undefined : this.stat.dev,\n ino: this.portable ? undefined : this.stat.ino,\n nlink: this.portable ? undefined : this.stat.nlink,\n }).encode(),\n )\n }\n const block = this.header?.block\n /* c8 ignore start */\n if (!block) {\n throw new Error('failed to encode header')\n }\n /* c8 ignore stop */\n super.write(block)\n }\n\n [DIRECTORY]() {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot create directory entry without stat')\n }\n /* c8 ignore stop */\n if (this.path.slice(-1) !== '/') {\n this.path += '/'\n }\n this.stat.size = 0\n this[HEADER]()\n this.end()\n }\n\n [SYMLINK]() {\n fs.readlink(this.absolute, (er, linkpath) => {\n if (er) {\n return this.emit('error', er)\n }\n this[ONREADLINK](linkpath)\n })\n }\n\n [ONREADLINK](linkpath: string) {\n this.linkpath = normalizeWindowsPath(linkpath)\n this[HEADER]()\n this.end()\n }\n\n [HARDLINK](linkpath: string) {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot create link entry without stat')\n }\n /* c8 ignore stop */\n this.type = 'Link'\n this.linkpath = normalizeWindowsPath(\n path.relative(this.cwd, linkpath),\n )\n this.stat.size = 0\n this[HEADER]()\n this.end()\n }\n\n [FILE]() {\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('cannot create file entry without stat')\n }\n /* c8 ignore stop */\n if (this.stat.nlink > 1) {\n const linkKey =\n `${this.stat.dev}:${this.stat.ino}` as LinkCacheKey\n const linkpath = this.linkCache.get(linkKey)\n if (linkpath?.indexOf(this.cwd) === 0) {\n return this[HARDLINK](linkpath)\n }\n this.linkCache.set(linkKey, this.absolute)\n }\n\n this[HEADER]()\n if (this.stat.size === 0) {\n return this.end()\n }\n\n this[OPENFILE]()\n }\n\n [OPENFILE]() {\n fs.open(this.absolute, 'r', (er, fd) => {\n if (er) {\n return this.emit('error', er)\n }\n this[ONOPENFILE](fd)\n })\n }\n\n [ONOPENFILE](fd: number) {\n this.fd = fd\n if (this.#hadError) {\n return this[CLOSE]()\n }\n /* c8 ignore start */\n if (!this.stat) {\n throw new Error('should stat before calling onopenfile')\n }\n /* c8 ignore start */\n\n this.blockLen = 512 * Math.ceil(this.stat.size / 512)\n this.blockRemain = this.blockLen\n const bufLen = Math.min(this.blockLen, this.maxReadSize)\n this.buf = Buffer.allocUnsafe(bufLen)\n this.offset = 0\n this.pos = 0\n this.remain = this.stat.size\n this.length = this.buf.length\n this[READ]()\n }\n\n [READ]() {\n const { fd, buf, offset, length, pos } = this\n if (fd === undefined || buf === undefined) {\n throw new Error('cannot read file without first opening')\n }\n fs.read(fd, buf, offset, length, pos, (er, bytesRead) => {\n if (er) {\n // ignoring the error from close(2) is a bad practice, but at\n // this point we already have an error, don't need another one\n return this[CLOSE](() => this.emit('error', er))\n }\n this[ONREAD](bytesRead)\n })\n }\n\n /* c8 ignore start */\n [CLOSE](\n cb: (er?: null | Error | NodeJS.ErrnoException) => any = () => {},\n ) {\n /* c8 ignore stop */\n if (this.fd !== undefined) fs.close(this.fd, cb)\n }\n\n [ONREAD](bytesRead: number) {\n if (bytesRead <= 0 && this.remain > 0) {\n const er = Object.assign(\n new Error('encountered unexpected EOF'),\n {\n path: this.absolute,\n syscall: 'read',\n code: 'EOF',\n },\n )\n return this[CLOSE](() => this.emit('error', er))\n }\n\n if (bytesRead > this.remain) {\n const er = Object.assign(\n new Error('did not encounter expected EOF'),\n {\n path: this.absolute,\n syscall: 'read',\n code: 'EOF',\n },\n )\n return this[CLOSE](() => this.emit('error', er))\n }\n\n /* c8 ignore start */\n if (!this.buf) {\n throw new Error('should have created buffer prior to reading')\n }\n /* c8 ignore stop */\n\n // null out the rest of the buffer, if we could fit the block padding\n // at the end of this loop, we've incremented bytesRead and this.remain\n // to be incremented up to the blockRemain level, as if we had expected\n // to get a null-padded file, and read it until the end. then we will\n // decrement both remain and blockRemain by bytesRead, and know that we\n // reached the expected EOF, without any null buffer to append.\n if (bytesRead === this.remain) {\n for (\n let i = bytesRead;\n i < this.length && bytesRead < this.blockRemain;\n i++\n ) {\n this.buf[i + this.offset] = 0\n bytesRead++\n this.remain++\n }\n }\n\n const chunk =\n this.offset === 0 && bytesRead === this.buf.length ?\n this.buf\n : this.buf.subarray(this.offset, this.offset + bytesRead)\n\n const flushed = this.write(chunk)\n if (!flushed) {\n this[AWAITDRAIN](() => this[ONDRAIN]())\n } else {\n this[ONDRAIN]()\n }\n }\n\n [AWAITDRAIN](cb: () => any) {\n this.once('drain', cb)\n }\n\n write(buffer: Buffer | string, cb?: () => void): boolean\n write(\n str: Buffer | string,\n encoding?: BufferEncoding | null,\n cb?: () => void,\n ): boolean\n write(\n chunk: Buffer | string,\n encoding?: BufferEncoding | (() => any) | null,\n cb?: () => any,\n ): boolean {\n /* c8 ignore start - just junk to comply with NodeJS.WritableStream */\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(\n chunk,\n typeof encoding === 'string' ? encoding : 'utf8',\n )\n }\n /* c8 ignore stop */\n\n if (this.blockRemain < chunk.length) {\n const er = Object.assign(\n new Error('writing more data than expected'),\n {\n path: this.absolute,\n },\n )\n return this.emit('error', er)\n }\n this.remain -= chunk.length\n this.blockRemain -= chunk.length\n this.pos += chunk.length\n this.offset += chunk.length\n return super.write(chunk, null, cb)\n }\n\n [ONDRAIN]() {\n if (!this.remain) {\n if (this.blockRemain) {\n super.write(Buffer.alloc(this.blockRemain))\n }\n return this[CLOSE](er =>\n er ? this.emit('error', er) : this.end(),\n )\n }\n\n /* c8 ignore start */\n if (!this.buf) {\n throw new Error('buffer lost somehow in ONDRAIN')\n }\n /* c8 ignore stop */\n\n if (this.offset >= this.length) {\n // if we only have a smaller bit left to read, alloc a smaller buffer\n // otherwise, keep it the same length it was before.\n this.buf = Buffer.allocUnsafe(\n Math.min(this.blockRemain, this.buf.length),\n )\n this.offset = 0\n }\n this.length = this.buf.length - this.offset\n this[READ]()\n }\n}\n\nexport class WriteEntrySync extends WriteEntry implements Warner {\n sync: true = true;\n\n [LSTAT]() {\n this[ONLSTAT](fs.lstatSync(this.absolute))\n }\n\n [SYMLINK]() {\n this[ONREADLINK](fs.readlinkSync(this.absolute))\n }\n\n [OPENFILE]() {\n this[ONOPENFILE](fs.openSync(this.absolute, 'r'))\n }\n\n [READ]() {\n let threw = true\n try {\n const { fd, buf, offset, length, pos } = this\n /* c8 ignore start */\n if (fd === undefined || buf === undefined) {\n throw new Error('fd and buf must be set in READ method')\n }\n /* c8 ignore stop */\n const bytesRead = fs.readSync(fd, buf, offset, length, pos)\n this[ONREAD](bytesRead)\n threw = false\n } finally {\n // ignoring the error from close(2) is a bad practice, but at\n // this point we already have an error, don't need another one\n if (threw) {\n try {\n this[CLOSE](() => {})\n } catch (er) {}\n }\n }\n }\n\n [AWAITDRAIN](cb: () => any) {\n cb()\n }\n\n /* c8 ignore start */\n [CLOSE](\n cb: (er?: null | Error | NodeJS.ErrnoException) => any = () => {},\n ) {\n /* c8 ignore stop */\n if (this.fd !== undefined) fs.closeSync(this.fd)\n cb()\n }\n}\n\nexport class WriteEntryTar\n extends Minipass<Buffer, Buffer | string, WarnEvent>\n implements Warner\n{\n blockLen: number = 0\n blockRemain: number = 0\n buf: number = 0\n pos: number = 0\n remain: number = 0\n length: number = 0\n preservePaths: boolean\n portable: boolean\n strict: boolean\n noPax: boolean\n noMtime: boolean\n readEntry: ReadEntry\n type: EntryTypeName\n prefix?: string\n path: string\n mode?: number\n uid?: number\n gid?: number\n uname?: string\n gname?: string\n header?: Header\n mtime?: Date\n atime?: Date\n ctime?: Date\n linkpath?: string\n size: number\n onWriteEntry?: (entry: WriteEntry) => any\n\n warn(code: string, message: string | Error, data: WarnData = {}) {\n return warnMethod(this, code, message, data)\n }\n\n constructor(\n readEntry: ReadEntry,\n opt_: TarOptionsWithAliases = {},\n ) {\n const opt = dealias(opt_)\n super()\n this.preservePaths = !!opt.preservePaths\n this.portable = !!opt.portable\n this.strict = !!opt.strict\n this.noPax = !!opt.noPax\n this.noMtime = !!opt.noMtime\n this.onWriteEntry = opt.onWriteEntry\n\n this.readEntry = readEntry\n const { type } = readEntry\n /* c8 ignore start */\n if (type === 'Unsupported') {\n throw new Error('writing entry that should be ignored')\n }\n /* c8 ignore stop */\n this.type = type\n if (this.type === 'Directory' && this.portable) {\n this.noMtime = true\n }\n\n this.prefix = opt.prefix\n\n this.path = normalizeWindowsPath(readEntry.path)\n this.mode =\n readEntry.mode !== undefined ?\n this[MODE](readEntry.mode)\n : undefined\n this.uid = this.portable ? undefined : readEntry.uid\n this.gid = this.portable ? undefined : readEntry.gid\n this.uname = this.portable ? undefined : readEntry.uname\n this.gname = this.portable ? undefined : readEntry.gname\n this.size = readEntry.size\n this.mtime =\n this.noMtime ? undefined : opt.mtime || readEntry.mtime\n this.atime = this.portable ? undefined : readEntry.atime\n this.ctime = this.portable ? undefined : readEntry.ctime\n this.linkpath =\n readEntry.linkpath !== undefined ?\n normalizeWindowsPath(readEntry.linkpath)\n : undefined\n\n if (typeof opt.onwarn === 'function') {\n this.on('warn', opt.onwarn)\n }\n\n let pathWarn: false | string = false\n if (!this.preservePaths) {\n const [root, stripped] = stripAbsolutePath(this.path)\n if (root && typeof stripped === 'string') {\n this.path = stripped\n pathWarn = root\n }\n }\n\n this.remain = readEntry.size\n this.blockRemain = readEntry.startBlockSize\n\n this.onWriteEntry?.(this as unknown as WriteEntry)\n this.header = new Header({\n path: this[PREFIX](this.path),\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n // only the permissions and setuid/setgid/sticky bitflags\n // not the higher-order bits that specify file type\n mode: this.mode,\n uid: this.portable ? undefined : this.uid,\n gid: this.portable ? undefined : this.gid,\n size: this.size,\n mtime: this.noMtime ? undefined : this.mtime,\n type: this.type,\n uname: this.portable ? undefined : this.uname,\n atime: this.portable ? undefined : this.atime,\n ctime: this.portable ? undefined : this.ctime,\n })\n\n if (pathWarn) {\n this.warn(\n 'TAR_ENTRY_INFO',\n `stripping ${pathWarn} from absolute path`,\n {\n entry: this,\n path: pathWarn + this.path,\n },\n )\n }\n\n if (this.header.encode() && !this.noPax) {\n super.write(\n new Pax({\n atime: this.portable ? undefined : this.atime,\n ctime: this.portable ? undefined : this.ctime,\n gid: this.portable ? undefined : this.gid,\n mtime: this.noMtime ? undefined : this.mtime,\n path: this[PREFIX](this.path),\n linkpath:\n this.type === 'Link' && this.linkpath !== undefined ?\n this[PREFIX](this.linkpath)\n : this.linkpath,\n size: this.size,\n uid: this.portable ? undefined : this.uid,\n uname: this.portable ? undefined : this.uname,\n dev: this.portable ? undefined : this.readEntry.dev,\n ino: this.portable ? undefined : this.readEntry.ino,\n nlink: this.portable ? undefined : this.readEntry.nlink,\n }).encode(),\n )\n }\n\n const b = this.header?.block\n /* c8 ignore start */\n if (!b) throw new Error('failed to encode header')\n /* c8 ignore stop */\n super.write(b)\n readEntry.pipe(this)\n }\n\n [PREFIX](path: string) {\n return prefixPath(path, this.prefix)\n }\n\n [MODE](mode: number) {\n return modeFix(mode, this.type === 'Directory', this.portable)\n }\n\n write(buffer: Buffer | string, cb?: () => void): boolean\n write(\n str: Buffer | string,\n encoding?: BufferEncoding | null,\n cb?: () => void,\n ): boolean\n write(\n chunk: Buffer | string,\n encoding?: BufferEncoding | (() => any) | null,\n cb?: () => any,\n ): boolean {\n /* c8 ignore start - just junk to comply with NodeJS.WritableStream */\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(\n chunk,\n typeof encoding === 'string' ? encoding : 'utf8',\n )\n }\n /* c8 ignore stop */\n const writeLen = chunk.length\n if (writeLen > this.blockRemain) {\n throw new Error('writing more to entry than is appropriate')\n }\n this.blockRemain -= writeLen\n return super.write(chunk, cb)\n }\n\n end(cb?: () => void): this\n end(chunk: Buffer | string, cb?: () => void): this\n end(\n chunk: Buffer | string,\n encoding?: BufferEncoding,\n cb?: () => void,\n ): this\n end(\n chunk?: Buffer | string | (() => void),\n encoding?: BufferEncoding | (() => void),\n cb?: () => void,\n ): this {\n if (this.blockRemain) {\n super.write(Buffer.alloc(this.blockRemain))\n }\n /* c8 ignore start - just junk to comply with NodeJS.WritableStream */\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n if (typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding ?? 'utf8')\n }\n if (cb) this.once('finish', cb)\n chunk ? super.end(chunk, cb) : super.end(cb)\n /* c8 ignore stop */\n return this\n }\n}\n\nconst getType = (stat: Stats): EntryTypeName | 'Unsupported' =>\n stat.isFile() ? 'File'\n : stat.isDirectory() ? 'Directory'\n : stat.isSymbolicLink() ? 'SymbolicLink'\n : 'Unsupported'\n", "export const modeFix = (\n mode: number,\n isDir: boolean,\n portable: boolean,\n) => {\n mode &= 0o7777\n\n // in portable mode, use the minimum reasonable umask\n // if this system creates files with 0o664 by default\n // (as some linux distros do), then we'll write the\n // archive with 0o644 instead. Also, don't ever create\n // a file that is not readable/writable by the owner.\n if (portable) {\n mode = (mode | 0o600) & ~0o22\n }\n\n // if dirs are readable, then they should be listable\n if (isDir) {\n if (mode & 0o400) {\n mode |= 0o100\n }\n if (mode & 0o40) {\n mode |= 0o10\n }\n if (mode & 0o4) {\n mode |= 0o1\n }\n }\n return mode\n}\n", "// unix absolute paths are also absolute on win32, so we use this for both\nimport { win32 } from 'node:path'\nconst { isAbsolute, parse } = win32\n\n// returns [root, stripped]\n// Note that windows will think that //x/y/z/a has a \"root\" of //x/y, and in\n// those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip /\n// explicitly if it's the first character.\n// drive-specific relative paths on Windows get their root stripped off even\n// though they are not absolute, so `c:../foo` becomes ['c:', '../foo']\nexport const stripAbsolutePath = (path: string) => {\n let r = ''\n\n let parsed = parse(path)\n while (isAbsolute(path) || parsed.root) {\n // windows will think that //x/y/z has a \"root\" of //x/y/\n // but strip the //?/C:/ off of //?/C:/path\n const root =\n path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ?\n '/'\n : parsed.root\n path = path.slice(root.length)\n r += root\n parsed = parse(path)\n }\n return [r, path]\n}\n", "// When writing files on Windows, translate the characters to their\n// 0xf000 higher-encoded versions.\n\nconst raw = ['|', '<', '>', '?', ':']\n\nconst win = raw.map(char =>\n String.fromCharCode(0xf000 + char.charCodeAt(0)),\n)\n\nconst toWin = new Map(raw.map((char, i) => [char, win[i]]))\nconst toRaw = new Map(win.map((char, i) => [char, raw[i]]))\n\nexport const encode = (s: string) =>\n raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s)\nexport const decode = (s: string) =>\n win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s)\n", "export class Yallist<T = unknown> {\n tail?: Node<T>\n head?: Node<T>\n length: number = 0\n\n static create<T = unknown>(list: Iterable<T> = []) {\n return new Yallist(list)\n }\n\n constructor(list: Iterable<T> = []) {\n for (const item of list) {\n this.push(item)\n }\n }\n\n *[Symbol.iterator]() {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n\n removeNode(node: Node<T>) {\n if (node.list !== this) {\n throw new Error(\n 'removing node which does not belong to this list',\n )\n }\n\n const next = node.next\n const prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n this.length--\n node.next = undefined\n node.prev = undefined\n node.list = undefined\n\n return next\n }\n\n unshiftNode(node: Node<T>) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n const head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n }\n\n pushNode(node: Node<T>) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n const tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n }\n\n push(...args: T[]) {\n for (let i = 0, l = args.length; i < l; i++) {\n push(this, args[i])\n }\n return this.length\n }\n\n unshift(...args: T[]) {\n for (var i = 0, l = args.length; i < l; i++) {\n unshift(this, args[i])\n }\n return this.length\n }\n\n pop() {\n if (!this.tail) {\n return undefined\n }\n\n const res = this.tail.value\n const t = this.tail\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = undefined\n } else {\n this.head = undefined\n }\n t.list = undefined\n this.length--\n return res\n }\n\n shift() {\n if (!this.head) {\n return undefined\n }\n\n const res = this.head.value\n const h = this.head\n this.head = this.head.next\n if (this.head) {\n this.head.prev = undefined\n } else {\n this.tail = undefined\n }\n h.list = undefined\n this.length--\n return res\n }\n\n forEach(\n fn: (value: T, i: number, list: Yallist<T>) => any,\n thisp?: any,\n ) {\n thisp = thisp || this\n for (let walker = this.head, i = 0; !!walker; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n }\n\n forEachReverse(\n fn: (value: T, i: number, list: Yallist<T>) => any,\n thisp?: any,\n ) {\n thisp = thisp || this\n for (let walker = this.tail, i = this.length - 1; !!walker; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n }\n\n get(n: number) {\n let i = 0\n let walker = this.head\n for (; !!walker && i < n; i++) {\n walker = walker.next\n }\n if (i === n && !!walker) {\n return walker.value\n }\n }\n\n getReverse(n: number) {\n let i = 0\n let walker = this.tail\n for (; !!walker && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && !!walker) {\n return walker.value\n }\n }\n\n map<R = any>(\n fn: (value: T, list: Yallist<T>) => R,\n thisp?: any,\n ): Yallist<R> {\n thisp = thisp || this\n const res = new Yallist<R>()\n for (let walker = this.head; !!walker; ) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n }\n\n mapReverse<R = any>(\n fn: (value: T, list: Yallist<T>) => R,\n thisp?: any,\n ): Yallist<R> {\n thisp = thisp || this\n var res = new Yallist<R>()\n for (let walker = this.tail; !!walker; ) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n }\n\n reduce(fn: (left: T, right: T, i: number) => T): T\n reduce<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial: R,\n ): R\n reduce<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial?: R,\n ): R {\n let acc: R | T\n let walker = this.head\n if (arguments.length > 1) {\n acc = initial as R\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError(\n 'Reduce of empty list with no initial value',\n )\n }\n\n for (var i = 0; !!walker; i++) {\n acc = fn(acc as R, walker.value, i)\n walker = walker.next\n }\n\n return acc as R\n }\n\n reduceReverse(fn: (left: T, right: T, i: number) => T): T\n reduceReverse<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial: R,\n ): R\n reduceReverse<R = any>(\n fn: (acc: R, next: T, i: number) => R,\n initial?: R,\n ): R {\n let acc: R | T\n let walker = this.tail\n if (arguments.length > 1) {\n acc = initial as R\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError(\n 'Reduce of empty list with no initial value',\n )\n }\n\n for (let i = this.length - 1; !!walker; i--) {\n acc = fn(acc as R, walker.value, i)\n walker = walker.prev\n }\n\n return acc as R\n }\n\n toArray() {\n const arr = new Array(this.length)\n for (let i = 0, walker = this.head; !!walker; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n }\n\n toArrayReverse() {\n const arr = new Array(this.length)\n for (let i = 0, walker = this.tail; !!walker; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n }\n\n slice(from: number = 0, to: number = this.length) {\n if (to < 0) {\n to += this.length\n }\n if (from < 0) {\n from += this.length\n }\n const ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n let walker = this.head\n let i = 0\n for (i = 0; !!walker && i < from; i++) {\n walker = walker.next\n }\n for (; !!walker && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n }\n\n sliceReverse(from: number = 0, to: number = this.length) {\n if (to < 0) {\n to += this.length\n }\n if (from < 0) {\n from += this.length\n }\n const ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n let i = this.length\n let walker = this.tail\n for (; !!walker && i > to; i--) {\n walker = walker.prev\n }\n for (; !!walker && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n }\n\n splice(start: number, deleteCount: number = 0, ...nodes: T[]) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start\n }\n\n let walker = this.head\n\n for (let i = 0; !!walker && i < start; i++) {\n walker = walker.next\n }\n\n const ret: T[] = []\n for (let i = 0; !!walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (!walker) {\n walker = this.tail\n } else if (walker !== this.tail) {\n walker = walker.prev\n }\n\n for (const v of nodes) {\n walker = insertAfter<T>(this, walker, v)\n }\n\n return ret\n }\n\n reverse() {\n const head = this.head\n const tail = this.tail\n for (let walker = head; !!walker; walker = walker.prev) {\n const p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n }\n}\n\n// insertAfter undefined means \"make the node the new head of list\"\nfunction insertAfter<T>(\n self: Yallist<T>,\n node: Node<T> | undefined,\n value: T,\n) {\n const prev = node\n const next = node ? node.next : self.head\n const inserted = new Node<T>(value, prev, next, self)\n\n if (inserted.next === undefined) {\n self.tail = inserted\n }\n if (inserted.prev === undefined) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push<T>(self: Yallist<T>, item: T) {\n self.tail = new Node<T>(item, self.tail, undefined, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift<T>(self: Yallist<T>, item: T) {\n self.head = new Node<T>(item, undefined, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nexport class Node<T = unknown> {\n list?: Yallist<T>\n next?: Node<T>\n prev?: Node<T>\n value: T\n\n constructor(\n value: T,\n prev?: Node<T> | undefined,\n next?: Node<T> | undefined,\n list?: Yallist<T> | undefined,\n ) {\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = undefined\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = undefined\n }\n }\n}\n", "// tar -x\nimport * as fsm from '@isaacs/fs-minipass'\nimport fs from 'node:fs'\nimport { filesFilter } from './list.js'\nimport { makeCommand } from './make-command.js'\nimport { TarOptionsFile, TarOptionsSyncFile } from './options.js'\nimport { Unpack, UnpackSync } from './unpack.js'\n\nconst extractFileSync = (opt: TarOptionsSyncFile) => {\n const u = new UnpackSync(opt)\n const file = opt.file\n const stat = fs.statSync(file)\n // This trades a zero-byte read() syscall for a stat\n // However, it will usually result in less memory allocation\n const readSize = opt.maxReadSize || 16 * 1024 * 1024\n const stream = new fsm.ReadStreamSync(file, {\n readSize: readSize,\n size: stat.size,\n })\n stream.pipe(u)\n}\n\nconst extractFile = (opt: TarOptionsFile, _?: string[]) => {\n const u = new Unpack(opt)\n const readSize = opt.maxReadSize || 16 * 1024 * 1024\n\n const file = opt.file\n const p = new Promise<void>((resolve, reject) => {\n u.on('error', reject)\n u.on('close', resolve)\n\n // This trades a zero-byte read() syscall for a stat\n // However, it will usually result in less memory allocation\n fs.stat(file, (er, stat) => {\n if (er) {\n reject(er)\n } else {\n const stream = new fsm.ReadStream(file, {\n readSize: readSize,\n size: stat.size,\n })\n stream.on('error', reject)\n stream.pipe(u)\n }\n })\n })\n return p\n}\n\nexport const extract = makeCommand<Unpack, UnpackSync>(\n extractFileSync,\n extractFile,\n opt => new UnpackSync(opt),\n opt => new Unpack(opt),\n (opt, files) => {\n if (files?.length) filesFilter(opt, files)\n },\n)\n", "// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.\n// but the path reservations are required to avoid race conditions where\n// parallelized unpack ops may mess with one another, due to dependencies\n// (like a Link depending on its target) or destructive operations (like\n// clobbering an fs object to create one of a different type.)\n\nimport * as fsm from '@isaacs/fs-minipass'\nimport assert from 'node:assert'\nimport { randomBytes } from 'node:crypto'\nimport fs, { type Stats } from 'node:fs'\nimport path from 'node:path'\nimport { getWriteFlag } from './get-write-flag.js'\nimport { mkdir, MkdirError, mkdirSync } from './mkdir.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { Parser } from './parse.js'\nimport { stripAbsolutePath } from './strip-absolute-path.js'\nimport * as wc from './winchars.js'\n\nimport { TarOptions } from './options.js'\nimport { PathReservations } from './path-reservations.js'\nimport { ReadEntry } from './read-entry.js'\nimport { WarnData } from './warn-method.js'\n\nconst ONENTRY = Symbol('onEntry')\nconst CHECKFS = Symbol('checkFs')\nconst CHECKFS2 = Symbol('checkFs2')\nconst ISREUSABLE = Symbol('isReusable')\nconst MAKEFS = Symbol('makeFs')\nconst FILE = Symbol('file')\nconst DIRECTORY = Symbol('directory')\nconst LINK = Symbol('link')\nconst SYMLINK = Symbol('symlink')\nconst HARDLINK = Symbol('hardlink')\nconst UNSUPPORTED = Symbol('unsupported')\nconst CHECKPATH = Symbol('checkPath')\nconst STRIPABSOLUTEPATH = Symbol('stripAbsolutePath')\nconst MKDIR = Symbol('mkdir')\nconst ONERROR = Symbol('onError')\nconst PENDING = Symbol('pending')\nconst PEND = Symbol('pend')\nconst UNPEND = Symbol('unpend')\nconst ENDED = Symbol('ended')\nconst MAYBECLOSE = Symbol('maybeClose')\nconst SKIP = Symbol('skip')\nconst DOCHOWN = Symbol('doChown')\nconst UID = Symbol('uid')\nconst GID = Symbol('gid')\nconst CHECKED_CWD = Symbol('checkedCwd')\nconst platform =\n process.env.TESTING_TAR_FAKE_PLATFORM || process.platform\nconst isWindows = platform === 'win32'\nconst DEFAULT_MAX_DEPTH = 1024\n\n// Unlinks on Windows are not atomic.\n//\n// This means that if you have a file entry, followed by another\n// file entry with an identical name, and you cannot re-use the file\n// (because it's a hardlink, or because unlink:true is set, or it's\n// Windows, which does not have useful nlink values), then the unlink\n// will be committed to the disk AFTER the new file has been written\n// over the old one, deleting the new file.\n//\n// To work around this, on Windows systems, we rename the file and then\n// delete the renamed file. It's a sloppy kludge, but frankly, I do not\n// know of a better way to do this, given windows' non-atomic unlink\n// semantics.\n//\n// See: https://github.com/npm/node-tar/issues/183\n/* c8 ignore start */\nconst unlinkFile = (\n path: string,\n cb: (er?: Error | null) => void,\n) => {\n if (!isWindows) {\n return fs.unlink(path, cb)\n }\n\n const name = path + '.DELETE.' + randomBytes(16).toString('hex')\n fs.rename(path, name, er => {\n if (er) {\n return cb(er)\n }\n fs.unlink(name, cb)\n })\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */\nconst unlinkFileSync = (path: string) => {\n if (!isWindows) {\n return fs.unlinkSync(path)\n }\n\n const name = path + '.DELETE.' + randomBytes(16).toString('hex')\n fs.renameSync(path, name)\n fs.unlinkSync(name)\n}\n/* c8 ignore stop */\n\n// this.gid, entry.gid, this.processUid\nconst uint32 = (\n a: number | undefined,\n b: number | undefined,\n c: number | undefined,\n) =>\n a !== undefined && a === a >>> 0 ? a\n : b !== undefined && b === b >>> 0 ? b\n : c\n\nexport class Unpack extends Parser {\n [ENDED]: boolean = false;\n [CHECKED_CWD]: boolean = false;\n [PENDING]: number = 0\n\n reservations: PathReservations = new PathReservations()\n transform?: TarOptions['transform']\n writable: true = true\n readable: false = false\n uid?: number\n gid?: number\n setOwner: boolean\n preserveOwner: boolean\n processGid?: number\n processUid?: number\n maxDepth: number\n forceChown: boolean\n win32: boolean\n newer: boolean\n keep: boolean\n noMtime: boolean\n preservePaths: boolean\n unlink: boolean\n cwd: string\n strip: number\n processUmask: number\n umask: number\n dmode: number\n fmode: number\n chmod: boolean\n\n constructor(opt: TarOptions = {}) {\n opt.ondone = () => {\n this[ENDED] = true\n this[MAYBECLOSE]()\n }\n\n super(opt)\n\n this.transform = opt.transform\n\n this.chmod = !!opt.chmod\n\n if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {\n // need both or neither\n if (\n typeof opt.uid !== 'number' ||\n typeof opt.gid !== 'number'\n ) {\n throw new TypeError(\n 'cannot set owner without number uid and gid',\n )\n }\n if (opt.preserveOwner) {\n throw new TypeError(\n 'cannot preserve owner in archive and also set owner explicitly',\n )\n }\n this.uid = opt.uid\n this.gid = opt.gid\n this.setOwner = true\n } else {\n this.uid = undefined\n this.gid = undefined\n this.setOwner = false\n }\n\n // default true for root\n if (\n opt.preserveOwner === undefined &&\n typeof opt.uid !== 'number'\n ) {\n this.preserveOwner = !!(\n process.getuid && process.getuid() === 0\n )\n } else {\n this.preserveOwner = !!opt.preserveOwner\n }\n\n this.processUid =\n (this.preserveOwner || this.setOwner) && process.getuid ?\n process.getuid()\n : undefined\n this.processGid =\n (this.preserveOwner || this.setOwner) && process.getgid ?\n process.getgid()\n : undefined\n\n // prevent excessively deep nesting of subfolders\n // set to `Infinity` to remove this restriction\n this.maxDepth =\n typeof opt.maxDepth === 'number' ?\n opt.maxDepth\n : DEFAULT_MAX_DEPTH\n\n // mostly just for testing, but useful in some cases.\n // Forcibly trigger a chown on every entry, no matter what\n this.forceChown = opt.forceChown === true\n\n // turn ><?| in filenames into 0xf000-higher encoded forms\n this.win32 = !!opt.win32 || isWindows\n\n // do not unpack over files that are newer than what's in the archive\n this.newer = !!opt.newer\n\n // do not unpack over ANY files\n this.keep = !!opt.keep\n\n // do not set mtime/atime of extracted entries\n this.noMtime = !!opt.noMtime\n\n // allow .., absolute path entries, and unpacking through symlinks\n // without this, warn and skip .., relativize absolutes, and error\n // on symlinks in extraction path\n this.preservePaths = !!opt.preservePaths\n\n // unlink files and links before writing. This breaks existing hard\n // links, and removes symlink directories rather than erroring\n this.unlink = !!opt.unlink\n\n this.cwd = normalizeWindowsPath(\n path.resolve(opt.cwd || process.cwd()),\n )\n this.strip = Number(opt.strip) || 0\n // if we're not chmodding, then we don't need the process umask\n this.processUmask =\n !this.chmod ? 0\n : typeof opt.processUmask === 'number' ? opt.processUmask\n : process.umask()\n this.umask =\n typeof opt.umask === 'number' ? opt.umask : this.processUmask\n\n // default mode for dirs created as parents\n this.dmode = opt.dmode || 0o0777 & ~this.umask\n this.fmode = opt.fmode || 0o0666 & ~this.umask\n\n this.on('entry', entry => this[ONENTRY](entry))\n }\n\n // a bad or damaged archive is a warning for Parser, but an error\n // when extracting. Mark those errors as unrecoverable, because\n // the Unpack contract cannot be met.\n warn(code: string, msg: string | Error, data: WarnData = {}) {\n if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') {\n data.recoverable = false\n }\n return super.warn(code, msg, data)\n }\n\n [MAYBECLOSE]() {\n if (this[ENDED] && this[PENDING] === 0) {\n this.emit('prefinish')\n this.emit('finish')\n this.emit('end')\n }\n }\n\n // return false if we need to skip this file\n // return true if the field was successfully sanitized\n [STRIPABSOLUTEPATH](\n entry: ReadEntry,\n field: 'path' | 'linkpath',\n ): boolean {\n const p = entry[field]\n const { type } = entry\n if (!p || this.preservePaths) return true\n\n const parts = p.split('/')\n\n if (\n parts.includes('..') ||\n /* c8 ignore next */\n (isWindows && /^[a-z]:\\.\\.$/i.test(parts[0] ?? ''))\n ) {\n // For linkpath, check if the resolved path escapes cwd rather than\n // just rejecting any path with '..' - relative symlinks like\n // '../sibling/file' are valid if they resolve within the cwd.\n // For paths, they just simply may not ever use .. at all.\n if (field === 'path' || type === 'Link') {\n this.warn('TAR_ENTRY_ERROR', `${field} contains '..'`, {\n entry,\n [field]: p,\n })\n // not ok!\n return false\n } else {\n // Resolve linkpath relative to the entry's directory.\n // `path.posix` is safe to use because we're operating on\n // tar paths, not a filesystem.\n const entryDir = path.posix.dirname(entry.path)\n const resolved = path.posix.normalize(\n path.posix.join(entryDir, p),\n )\n // If the resolved path escapes (starts with ..), reject it\n if (resolved.startsWith('../') || resolved === '..') {\n this.warn(\n 'TAR_ENTRY_ERROR',\n `${field} escapes extraction directory`,\n {\n entry,\n [field]: p,\n },\n )\n return false\n }\n }\n }\n\n // strip off the root\n const [root, stripped] = stripAbsolutePath(p)\n if (root) {\n // ok, but triggers warning about stripping root\n entry[field] = String(stripped)\n this.warn(\n 'TAR_ENTRY_INFO',\n `stripping ${root} from absolute ${field}`,\n {\n entry,\n [field]: p,\n },\n )\n }\n return true\n }\n\n [CHECKPATH](entry: ReadEntry) {\n const p = normalizeWindowsPath(entry.path)\n const parts = p.split('/')\n\n if (this.strip) {\n if (parts.length < this.strip) {\n return false\n }\n if (entry.type === 'Link') {\n const linkparts = normalizeWindowsPath(\n String(entry.linkpath),\n ).split('/')\n if (linkparts.length >= this.strip) {\n entry.linkpath = linkparts.slice(this.strip).join('/')\n } else {\n return false\n }\n }\n parts.splice(0, this.strip)\n entry.path = parts.join('/')\n }\n\n if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {\n this.warn('TAR_ENTRY_ERROR', 'path excessively deep', {\n entry,\n path: p,\n depth: parts.length,\n maxDepth: this.maxDepth,\n })\n return false\n }\n\n if (\n !this[STRIPABSOLUTEPATH](entry, 'path') ||\n !this[STRIPABSOLUTEPATH](entry, 'linkpath')\n ) {\n return false\n }\n\n if (path.isAbsolute(entry.path)) {\n entry.absolute = normalizeWindowsPath(path.resolve(entry.path))\n } else {\n entry.absolute = normalizeWindowsPath(\n path.resolve(this.cwd, entry.path),\n )\n }\n\n // if we somehow ended up with a path that escapes the cwd, and we are\n // not in preservePaths mode, then something is fishy! This should have\n // been prevented above, so ignore this for coverage.\n /* c8 ignore start - defense in depth */\n if (\n !this.preservePaths &&\n typeof entry.absolute === 'string' &&\n entry.absolute.indexOf(this.cwd + '/') !== 0 &&\n entry.absolute !== this.cwd\n ) {\n this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', {\n entry,\n path: normalizeWindowsPath(entry.path),\n resolvedPath: entry.absolute,\n cwd: this.cwd,\n })\n return false\n }\n /* c8 ignore stop */\n\n // an archive can set properties on the extraction directory, but it\n // may not replace the cwd with a different kind of thing entirely.\n if (\n entry.absolute === this.cwd &&\n entry.type !== 'Directory' &&\n entry.type !== 'GNUDumpDir'\n ) {\n return false\n }\n\n // only encode : chars that aren't drive letter indicators\n if (this.win32) {\n const { root: aRoot } = path.win32.parse(String(entry.absolute))\n entry.absolute =\n aRoot + wc.encode(String(entry.absolute).slice(aRoot.length))\n const { root: pRoot } = path.win32.parse(entry.path)\n entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length))\n }\n\n return true\n }\n\n [ONENTRY](entry: ReadEntry) {\n if (!this[CHECKPATH](entry)) {\n return entry.resume()\n }\n\n assert.equal(typeof entry.absolute, 'string')\n\n switch (entry.type) {\n case 'Directory':\n case 'GNUDumpDir':\n if (entry.mode) {\n entry.mode = entry.mode | 0o700\n }\n\n // eslint-disable-next-line no-fallthrough\n case 'File':\n case 'OldFile':\n case 'ContiguousFile':\n case 'Link':\n case 'SymbolicLink':\n return this[CHECKFS](entry)\n\n case 'CharacterDevice':\n case 'BlockDevice':\n case 'FIFO':\n default:\n return this[UNSUPPORTED](entry)\n }\n }\n\n [ONERROR](er: Error, entry: ReadEntry) {\n // Cwd has to exist, or else nothing works. That's serious.\n // Other errors are warnings, which raise the error in strict\n // mode, but otherwise continue on.\n if (er.name === 'CwdError') {\n this.emit('error', er)\n } else {\n this.warn('TAR_ENTRY_ERROR', er, { entry })\n this[UNPEND]()\n entry.resume()\n }\n }\n\n [MKDIR](\n dir: string,\n mode: number,\n cb: (er?: null | MkdirError, made?: string) => void,\n ) {\n mkdir(\n normalizeWindowsPath(dir),\n {\n uid: this.uid,\n gid: this.gid,\n processUid: this.processUid,\n processGid: this.processGid,\n umask: this.processUmask,\n preserve: this.preservePaths,\n unlink: this.unlink,\n cwd: this.cwd,\n mode: mode,\n },\n cb,\n )\n }\n\n [DOCHOWN](entry: ReadEntry) {\n // in preserve owner mode, chown if the entry doesn't match process\n // in set owner mode, chown if setting doesn't match process\n return (\n this.forceChown ||\n (this.preserveOwner &&\n ((typeof entry.uid === 'number' &&\n entry.uid !== this.processUid) ||\n (typeof entry.gid === 'number' &&\n entry.gid !== this.processGid))) ||\n (typeof this.uid === 'number' &&\n this.uid !== this.processUid) ||\n (typeof this.gid === 'number' && this.gid !== this.processGid)\n )\n }\n\n [UID](entry: ReadEntry) {\n return uint32(this.uid, entry.uid, this.processUid)\n }\n\n [GID](entry: ReadEntry) {\n return uint32(this.gid, entry.gid, this.processGid)\n }\n\n [FILE](entry: ReadEntry, fullyDone: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.fmode\n const stream = new fsm.WriteStream(String(entry.absolute), {\n // slight lie, but it can be numeric flags\n flags: getWriteFlag(entry.size) as string,\n mode: mode,\n autoClose: false,\n })\n stream.on('error', (er: Error) => {\n if (stream.fd) {\n fs.close(stream.fd, () => {})\n }\n\n // flush all the data out so that we aren't left hanging\n // if the error wasn't actually fatal. otherwise the parse\n // is blocked, and we never proceed.\n stream.write = () => true\n this[ONERROR](er, entry)\n fullyDone()\n })\n\n let actions = 1\n const done = (er?: null | Error) => {\n if (er) {\n /* c8 ignore start - we should always have a fd by now */\n if (stream.fd) {\n fs.close(stream.fd, () => {})\n }\n /* c8 ignore stop */\n\n this[ONERROR](er, entry)\n fullyDone()\n return\n }\n\n if (--actions === 0) {\n if (stream.fd !== undefined) {\n fs.close(stream.fd, er => {\n if (er) {\n this[ONERROR](er, entry)\n } else {\n this[UNPEND]()\n }\n fullyDone()\n })\n }\n }\n }\n\n stream.on('finish', () => {\n // if futimes fails, try utimes\n // if utimes fails, fail with the original error\n // same for fchown/chown\n const abs = String(entry.absolute)\n const fd = stream.fd\n\n if (typeof fd === 'number' && entry.mtime && !this.noMtime) {\n actions++\n const atime = entry.atime || new Date()\n const mtime = entry.mtime\n fs.futimes(fd, atime, mtime, er =>\n er ?\n fs.utimes(abs, atime, mtime, er2 => done(er2 && er))\n : done(),\n )\n }\n\n if (typeof fd === 'number' && this[DOCHOWN](entry)) {\n actions++\n const uid = this[UID](entry)\n const gid = this[GID](entry)\n if (typeof uid === 'number' && typeof gid === 'number') {\n fs.fchown(fd, uid, gid, er =>\n er ?\n fs.chown(abs, uid, gid, er2 => done(er2 && er))\n : done(),\n )\n }\n }\n\n done()\n })\n\n const tx = this.transform ? this.transform(entry) || entry : entry\n if (tx !== entry) {\n tx.on('error', (er: Error) => {\n this[ONERROR](er, entry)\n fullyDone()\n })\n entry.pipe(tx)\n }\n tx.pipe(stream)\n }\n\n [DIRECTORY](entry: ReadEntry, fullyDone: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.dmode\n this[MKDIR](String(entry.absolute), mode, er => {\n if (er) {\n this[ONERROR](er, entry)\n fullyDone()\n return\n }\n\n let actions = 1\n const done = () => {\n if (--actions === 0) {\n fullyDone()\n this[UNPEND]()\n entry.resume()\n }\n }\n\n if (entry.mtime && !this.noMtime) {\n actions++\n fs.utimes(\n String(entry.absolute),\n entry.atime || new Date(),\n entry.mtime,\n done,\n )\n }\n\n if (this[DOCHOWN](entry)) {\n actions++\n fs.chown(\n String(entry.absolute),\n Number(this[UID](entry)),\n Number(this[GID](entry)),\n done,\n )\n }\n\n done()\n })\n }\n\n [UNSUPPORTED](entry: ReadEntry) {\n entry.unsupported = true\n this.warn(\n 'TAR_ENTRY_UNSUPPORTED',\n `unsupported entry type: ${entry.type}`,\n { entry },\n )\n entry.resume()\n }\n\n [SYMLINK](entry: ReadEntry, done: () => void) {\n this[LINK](entry, String(entry.linkpath), 'symlink', done)\n }\n\n [HARDLINK](entry: ReadEntry, done: () => void) {\n const linkpath = normalizeWindowsPath(\n path.resolve(this.cwd, String(entry.linkpath)),\n )\n this[LINK](entry, linkpath, 'link', done)\n }\n\n [PEND]() {\n this[PENDING]++\n }\n\n [UNPEND]() {\n this[PENDING]--\n this[MAYBECLOSE]()\n }\n\n [SKIP](entry: ReadEntry) {\n this[UNPEND]()\n entry.resume()\n }\n\n // Check if we can reuse an existing filesystem entry safely and\n // overwrite it, rather than unlinking and recreating\n // Windows doesn't report a useful nlink, so we just never reuse entries\n [ISREUSABLE](entry: ReadEntry, st: Stats) {\n return (\n entry.type === 'File' &&\n !this.unlink &&\n st.isFile() &&\n st.nlink <= 1 &&\n !isWindows\n )\n }\n\n // check if a thing is there, and if so, try to clobber it\n [CHECKFS](entry: ReadEntry) {\n this[PEND]()\n const paths = [entry.path]\n if (entry.linkpath) {\n paths.push(entry.linkpath)\n }\n this.reservations.reserve(paths, done =>\n this[CHECKFS2](entry, done),\n )\n }\n\n [CHECKFS2](entry: ReadEntry, fullyDone: (er?: Error) => void) {\n const done = (er?: Error) => {\n fullyDone(er)\n }\n\n const checkCwd = () => {\n this[MKDIR](this.cwd, this.dmode, er => {\n if (er) {\n this[ONERROR](er, entry)\n done()\n return\n }\n this[CHECKED_CWD] = true\n start()\n })\n }\n\n const start = () => {\n if (entry.absolute !== this.cwd) {\n const parent = normalizeWindowsPath(\n path.dirname(String(entry.absolute)),\n )\n if (parent !== this.cwd) {\n return this[MKDIR](parent, this.dmode, er => {\n if (er) {\n this[ONERROR](er, entry)\n done()\n return\n }\n afterMakeParent()\n })\n }\n }\n afterMakeParent()\n }\n\n const afterMakeParent = () => {\n fs.lstat(String(entry.absolute), (lstatEr, st) => {\n if (\n st &&\n (this.keep ||\n /* c8 ignore next */\n (this.newer && st.mtime > (entry.mtime ?? st.mtime)))\n ) {\n this[SKIP](entry)\n done()\n return\n }\n if (lstatEr || this[ISREUSABLE](entry, st)) {\n return this[MAKEFS](null, entry, done)\n }\n\n if (st.isDirectory()) {\n if (entry.type === 'Directory') {\n const needChmod =\n this.chmod &&\n entry.mode &&\n (st.mode & 0o7777) !== entry.mode\n const afterChmod = (er?: Error | null | undefined) =>\n this[MAKEFS](er ?? null, entry, done)\n if (!needChmod) {\n return afterChmod()\n }\n return fs.chmod(\n String(entry.absolute),\n Number(entry.mode),\n afterChmod,\n )\n }\n // Not a dir entry, have to remove it.\n // NB: the only way to end up with an entry that is the cwd\n // itself, in such a way that == does not detect, is a\n // tricky windows absolute path with UNC or 8.3 parts (and\n // preservePaths:true, or else it will have been stripped).\n // In that case, the user has opted out of path protections\n // explicitly, so if they blow away the cwd, c'est la vie.\n if (entry.absolute !== this.cwd) {\n return fs.rmdir(\n String(entry.absolute),\n (er?: null | Error) =>\n this[MAKEFS](er ?? null, entry, done),\n )\n }\n }\n\n // not a dir, and not reusable\n // don't remove if the cwd, we want that error\n if (entry.absolute === this.cwd) {\n return this[MAKEFS](null, entry, done)\n }\n\n unlinkFile(String(entry.absolute), er =>\n this[MAKEFS](er ?? null, entry, done),\n )\n })\n }\n\n if (this[CHECKED_CWD]) {\n start()\n } else {\n checkCwd()\n }\n }\n\n [MAKEFS](\n er: null | undefined | Error,\n entry: ReadEntry,\n done: () => void,\n ) {\n if (er) {\n this[ONERROR](er, entry)\n done()\n return\n }\n\n switch (entry.type) {\n case 'File':\n case 'OldFile':\n case 'ContiguousFile':\n return this[FILE](entry, done)\n\n case 'Link':\n return this[HARDLINK](entry, done)\n\n case 'SymbolicLink':\n return this[SYMLINK](entry, done)\n\n case 'Directory':\n case 'GNUDumpDir':\n return this[DIRECTORY](entry, done)\n }\n }\n\n [LINK](\n entry: ReadEntry,\n linkpath: string,\n link: 'link' | 'symlink',\n done: () => void,\n ) {\n // XXX: get the type ('symlink' or 'junction') for windows\n fs[link](linkpath, String(entry.absolute), er => {\n if (er) {\n this[ONERROR](er, entry)\n } else {\n this[UNPEND]()\n entry.resume()\n }\n done()\n })\n }\n}\n\nconst callSync = (fn: () => any) => {\n try {\n return [null, fn()]\n } catch (er) {\n return [er, null]\n }\n}\n\nexport class UnpackSync extends Unpack {\n sync: true = true;\n\n [MAKEFS](er: null | Error | undefined, entry: ReadEntry) {\n return super[MAKEFS](er, entry, () => {})\n }\n\n [CHECKFS](entry: ReadEntry) {\n if (!this[CHECKED_CWD]) {\n const er = this[MKDIR](this.cwd, this.dmode)\n if (er) {\n return this[ONERROR](er as Error, entry)\n }\n this[CHECKED_CWD] = true\n }\n\n // don't bother to make the parent if the current entry is the cwd,\n // we've already checked it.\n if (entry.absolute !== this.cwd) {\n const parent = normalizeWindowsPath(\n path.dirname(String(entry.absolute)),\n )\n if (parent !== this.cwd) {\n const mkParent = this[MKDIR](parent, this.dmode)\n if (mkParent) {\n return this[ONERROR](mkParent as Error, entry)\n }\n }\n }\n\n const [lstatEr, st] = callSync(() =>\n fs.lstatSync(String(entry.absolute)),\n )\n if (\n st &&\n (this.keep ||\n /* c8 ignore next */\n (this.newer && st.mtime > (entry.mtime ?? st.mtime)))\n ) {\n return this[SKIP](entry)\n }\n\n if (lstatEr || this[ISREUSABLE](entry, st)) {\n return this[MAKEFS](null, entry)\n }\n\n if (st.isDirectory()) {\n if (entry.type === 'Directory') {\n const needChmod =\n this.chmod &&\n entry.mode &&\n (st.mode & 0o7777) !== entry.mode\n const [er] =\n needChmod ?\n callSync(() => {\n fs.chmodSync(String(entry.absolute), Number(entry.mode))\n })\n : []\n return this[MAKEFS](er, entry)\n }\n // not a dir entry, have to remove it\n const [er] = callSync(() =>\n fs.rmdirSync(String(entry.absolute)),\n )\n this[MAKEFS](er, entry)\n }\n\n // not a dir, and not reusable.\n // don't remove if it's the cwd, since we want that error.\n const [er] =\n entry.absolute === this.cwd ?\n []\n : callSync(() => unlinkFileSync(String(entry.absolute)))\n this[MAKEFS](er, entry)\n }\n\n [FILE](entry: ReadEntry, done: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.fmode\n\n const oner = (er?: null | Error | undefined) => {\n let closeError\n try {\n fs.closeSync(fd)\n } catch (e) {\n closeError = e\n }\n if (er || closeError) {\n this[ONERROR]((er as Error) || closeError, entry)\n }\n done()\n }\n\n let fd: number\n try {\n fd = fs.openSync(\n String(entry.absolute),\n getWriteFlag(entry.size),\n mode,\n )\n /* c8 ignore start - This is only a problem if the file was successfully\n * statted, BUT failed to open. Testing this is annoying, and we\n * already have ample testint for other uses of oner() methods.\n */\n } catch (er) {\n return oner(er as Error)\n }\n /* c8 ignore stop */\n const tx = this.transform ? this.transform(entry) || entry : entry\n if (tx !== entry) {\n tx.on('error', (er: Error) => this[ONERROR](er, entry))\n entry.pipe(tx)\n }\n\n tx.on('data', (chunk: Buffer) => {\n try {\n fs.writeSync(fd, chunk, 0, chunk.length)\n } catch (er) {\n oner(er as Error)\n }\n })\n\n tx.on('end', () => {\n let er = null\n // try both, falling futimes back to utimes\n // if either fails, handle the first error\n if (entry.mtime && !this.noMtime) {\n const atime = entry.atime || new Date()\n const mtime = entry.mtime\n try {\n fs.futimesSync(fd, atime, mtime)\n } catch (futimeser) {\n try {\n fs.utimesSync(String(entry.absolute), atime, mtime)\n } catch (utimeser) {\n er = futimeser\n }\n }\n }\n\n if (this[DOCHOWN](entry)) {\n const uid = this[UID](entry)\n const gid = this[GID](entry)\n\n try {\n fs.fchownSync(fd, Number(uid), Number(gid))\n } catch (fchowner) {\n try {\n fs.chownSync(\n String(entry.absolute),\n Number(uid),\n Number(gid),\n )\n } catch (chowner) {\n er = er || fchowner\n }\n }\n }\n\n oner(er as Error)\n })\n }\n\n [DIRECTORY](entry: ReadEntry, done: () => void) {\n const mode =\n typeof entry.mode === 'number' ?\n entry.mode & 0o7777\n : this.dmode\n const er = this[MKDIR](String(entry.absolute), mode)\n if (er) {\n this[ONERROR](er as Error, entry)\n done()\n return\n }\n if (entry.mtime && !this.noMtime) {\n try {\n fs.utimesSync(\n String(entry.absolute),\n entry.atime || new Date(),\n entry.mtime,\n )\n /* c8 ignore next */\n } catch (er) {}\n }\n if (this[DOCHOWN](entry)) {\n try {\n fs.chownSync(\n String(entry.absolute),\n Number(this[UID](entry)),\n Number(this[GID](entry)),\n )\n } catch (er) {}\n }\n done()\n entry.resume()\n }\n\n [MKDIR](dir: string, mode: number) {\n try {\n return mkdirSync(normalizeWindowsPath(dir), {\n uid: this.uid,\n gid: this.gid,\n processUid: this.processUid,\n processGid: this.processGid,\n umask: this.processUmask,\n preserve: this.preservePaths,\n unlink: this.unlink,\n cwd: this.cwd,\n mode: mode,\n })\n } catch (er) {\n return er\n }\n }\n\n [LINK](\n entry: ReadEntry,\n linkpath: string,\n link: 'link' | 'symlink',\n done: () => void,\n ) {\n const ls: `${typeof link}Sync` = `${link}Sync`\n try {\n fs[ls](linkpath, String(entry.absolute))\n done()\n entry.resume()\n } catch (er) {\n return this[ONERROR](er as Error, entry)\n }\n }\n}\n", "// Get the appropriate flag to use for creating files\n// We use fmap on Windows platforms for files less than\n// 512kb. This is a fairly low limit, but avoids making\n// things slower in some cases. Since most of what this\n// library is used for is extracting tarballs of many\n// relatively small files in npm packages and the like,\n// it can be a big boost on Windows platforms.\n\nimport fs from 'fs'\n\nconst platform = process.env.__FAKE_PLATFORM__ || process.platform\nconst isWindows = platform === 'win32'\n\n/* c8 ignore start */\nconst { O_CREAT, O_TRUNC, O_WRONLY } = fs.constants\nconst UV_FS_O_FILEMAP =\n Number(process.env.__FAKE_FS_O_FILENAME__) ||\n fs.constants.UV_FS_O_FILEMAP ||\n 0\n/* c8 ignore stop */\n\nconst fMapEnabled = isWindows && !!UV_FS_O_FILEMAP\nconst fMapLimit = 512 * 1024\nconst fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY\nexport const getWriteFlag =\n !fMapEnabled ?\n () => 'w'\n : (size: number) => (size < fMapLimit ? fMapFlag : 'w')\n", "import fs, { type Dirent } from 'node:fs'\nimport path from 'node:path'\n\nconst lchownSync = (path: string, uid: number, gid: number) => {\n try {\n return fs.lchownSync(path, uid, gid)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code !== 'ENOENT') throw er\n }\n}\n\nconst chown = (\n cpath: string,\n uid: number,\n gid: number,\n cb: (er?: unknown) => any,\n) => {\n fs.lchown(cpath, uid, gid, er => {\n // Skip ENOENT error\n cb(er && (er as NodeJS.ErrnoException)?.code !== 'ENOENT' ? er : null)\n })\n}\n\nconst chownrKid = (\n p: string,\n child: Dirent,\n uid: number,\n gid: number,\n cb: (er?: unknown) => any,\n) => {\n if (child.isDirectory()) {\n chownr(path.resolve(p, child.name), uid, gid, (er: unknown) => {\n if (er) return cb(er)\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n })\n } else {\n const cpath = path.resolve(p, child.name)\n chown(cpath, uid, gid, cb)\n }\n}\n\nexport const chownr = (\n p: string,\n uid: number,\n gid: number,\n cb: (er?: unknown) => any,\n) => {\n fs.readdir(p, { withFileTypes: true }, (er, children) => {\n // any error other than ENOTDIR or ENOTSUP means it's not readable,\n // or doesn't exist. give up.\n if (er) {\n if (er.code === 'ENOENT') return cb()\n else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')\n return cb(er)\n }\n if (er || !children.length) return chown(p, uid, gid, cb)\n\n let len = children.length\n let errState: null | NodeJS.ErrnoException = null\n const then = (er?: unknown) => {\n /* c8 ignore start */\n if (errState) return\n /* c8 ignore stop */\n if (er) return cb((errState = er as NodeJS.ErrnoException))\n if (--len === 0) return chown(p, uid, gid, cb)\n }\n\n for (const child of children) {\n chownrKid(p, child, uid, gid, then)\n }\n })\n}\n\nconst chownrKidSync = (\n p: string,\n child: Dirent,\n uid: number,\n gid: number,\n) => {\n if (child.isDirectory())\n chownrSync(path.resolve(p, child.name), uid, gid)\n\n lchownSync(path.resolve(p, child.name), uid, gid)\n}\n\nexport const chownrSync = (p: string, uid: number, gid: number) => {\n let children: Dirent[]\n try {\n children = fs.readdirSync(p, { withFileTypes: true })\n } catch (er) {\n const e = er as NodeJS.ErrnoException\n if (e?.code === 'ENOENT') return\n else if (e?.code === 'ENOTDIR' || e?.code === 'ENOTSUP')\n return lchownSync(p, uid, gid)\n else throw e\n }\n\n for (const child of children) {\n chownrKidSync(p, child, uid, gid)\n }\n\n return lchownSync(p, uid, gid)\n}\n", "import { chownr, chownrSync } from 'chownr'\nimport fs from 'node:fs'\nimport fsp from 'node:fs/promises'\nimport path from 'node:path'\nimport { CwdError } from './cwd-error.js'\nimport { normalizeWindowsPath } from './normalize-windows-path.js'\nimport { SymlinkError } from './symlink-error.js'\n\nexport type MkdirOptions = {\n uid?: number\n gid?: number\n processUid?: number\n processGid?: number\n umask?: number\n preserve: boolean\n unlink: boolean\n cwd: string\n mode: number\n}\n\nexport type MkdirError =\n | NodeJS.ErrnoException\n | CwdError\n | SymlinkError\n\nconst checkCwd = (\n dir: string,\n cb: (er?: null | MkdirError) => any,\n) => {\n fs.stat(dir, (er, st) => {\n if (er || !st.isDirectory()) {\n er = new CwdError(\n dir,\n (er as NodeJS.ErrnoException)?.code || 'ENOTDIR',\n )\n }\n cb(er)\n })\n}\n\n/**\n * Wrapper around fs/promises.mkdir for tar's needs.\n *\n * The main purpose is to avoid creating directories if we know that\n * they already exist (and track which ones exist for this purpose),\n * and prevent entries from being extracted into symlinked folders,\n * if `preservePaths` is not set.\n */\nexport const mkdir = (\n dir: string,\n opt: MkdirOptions,\n cb: (er?: null | MkdirError, made?: string) => void,\n) => {\n dir = normalizeWindowsPath(dir)\n\n // if there's any overlap between mask and mode,\n // then we'll need an explicit chmod\n /* c8 ignore next */\n const umask = opt.umask ?? 0o22\n const mode = opt.mode | 0o0700\n const needChmod = (mode & umask) !== 0\n\n const uid = opt.uid\n const gid = opt.gid\n const doChown =\n typeof uid === 'number' &&\n typeof gid === 'number' &&\n (uid !== opt.processUid || gid !== opt.processGid)\n\n const preserve = opt.preserve\n const unlink = opt.unlink\n const cwd = normalizeWindowsPath(opt.cwd)\n\n const done = (er?: null | MkdirError, created?: string) => {\n if (er) {\n cb(er)\n } else {\n if (created && doChown) {\n chownr(created, uid, gid, er =>\n done(er as NodeJS.ErrnoException),\n )\n } else if (needChmod) {\n fs.chmod(dir, mode, cb)\n } else {\n cb()\n }\n }\n }\n\n if (dir === cwd) {\n return checkCwd(dir, done)\n }\n\n if (preserve) {\n return fsp.mkdir(dir, { mode, recursive: true }).then(\n made => done(null, made ?? undefined), // oh, ts\n done,\n )\n }\n\n const sub = normalizeWindowsPath(path.relative(cwd, dir))\n const parts = sub.split('/')\n mkdir_(cwd, parts, mode, unlink, cwd, undefined, done)\n}\n\nconst mkdir_ = (\n base: string,\n parts: string[],\n mode: number,\n unlink: boolean,\n cwd: string,\n created: string | undefined,\n cb: (er?: null | MkdirError, made?: string) => void,\n): void => {\n if (!parts.length) {\n return cb(null, created)\n }\n const p = parts.shift()\n const part = normalizeWindowsPath(path.resolve(base + '/' + p))\n fs.mkdir(\n part,\n mode,\n onmkdir(part, parts, mode, unlink, cwd, created, cb),\n )\n}\n\nconst onmkdir =\n (\n part: string,\n parts: string[],\n mode: number,\n unlink: boolean,\n cwd: string,\n created: string | undefined,\n cb: (er?: null | MkdirError, made?: string) => void,\n ) =>\n (er?: null | NodeJS.ErrnoException) => {\n if (er) {\n fs.lstat(part, (statEr, st) => {\n if (statEr) {\n statEr.path =\n statEr.path && normalizeWindowsPath(statEr.path)\n cb(statEr)\n } else if (st.isDirectory()) {\n mkdir_(part, parts, mode, unlink, cwd, created, cb)\n } else if (unlink) {\n fs.unlink(part, er => {\n if (er) {\n return cb(er)\n }\n fs.mkdir(\n part,\n mode,\n onmkdir(part, parts, mode, unlink, cwd, created, cb),\n )\n })\n } else if (st.isSymbolicLink()) {\n return cb(\n new SymlinkError(part, part + '/' + parts.join('/')),\n )\n } else {\n cb(er)\n }\n })\n } else {\n created = created || part\n mkdir_(part, parts, mode, unlink, cwd, created, cb)\n }\n }\n\nconst checkCwdSync = (dir: string) => {\n let ok = false\n let code: string | undefined = undefined\n try {\n ok = fs.statSync(dir).isDirectory()\n } catch (er) {\n code = (er as NodeJS.ErrnoException)?.code\n } finally {\n if (!ok) {\n throw new CwdError(dir, code ?? 'ENOTDIR')\n }\n }\n}\n\nexport const mkdirSync = (dir: string, opt: MkdirOptions) => {\n dir = normalizeWindowsPath(dir)\n // if there's any overlap between mask and mode,\n // then we'll need an explicit chmod\n /* c8 ignore next */\n const umask = opt.umask ?? 0o22\n const mode = opt.mode | 0o700\n const needChmod = (mode & umask) !== 0\n\n const uid = opt.uid\n const gid = opt.gid\n const doChown =\n typeof uid === 'number' &&\n typeof gid === 'number' &&\n (uid !== opt.processUid || gid !== opt.processGid)\n\n const preserve = opt.preserve\n const unlink = opt.unlink\n const cwd = normalizeWindowsPath(opt.cwd)\n\n const done = (created?: string | undefined) => {\n if (created && doChown) {\n chownrSync(created, uid, gid)\n }\n if (needChmod) {\n fs.chmodSync(dir, mode)\n }\n }\n\n if (dir === cwd) {\n checkCwdSync(cwd)\n return done()\n }\n\n if (preserve) {\n return done(\n fs.mkdirSync(dir, { mode, recursive: true }) ?? undefined,\n )\n }\n\n const sub = normalizeWindowsPath(path.relative(cwd, dir))\n const parts = sub.split('/')\n let created: string | undefined = undefined\n for (\n let p = parts.shift(), part = cwd;\n p && (part += '/' + p);\n p = parts.shift()\n ) {\n part = normalizeWindowsPath(path.resolve(part))\n\n try {\n fs.mkdirSync(part, mode)\n created = created || part\n } catch (er) {\n const st = fs.lstatSync(part)\n if (st.isDirectory()) {\n continue\n } else if (unlink) {\n fs.unlinkSync(part)\n fs.mkdirSync(part, mode)\n created = created || part\n continue\n } else if (st.isSymbolicLink()) {\n return new SymlinkError(part, part + '/' + parts.join('/'))\n }\n }\n }\n\n return done(created)\n}\n", "export class CwdError extends Error {\n path: string\n code: string\n syscall: 'chdir' = 'chdir'\n\n constructor(path: string, code: string) {\n super(`${code}: Cannot cd into '${path}'`)\n this.path = path\n this.code = code\n }\n\n get name() {\n return 'CwdError'\n }\n}\n", "export class SymlinkError extends Error {\n path: string\n symlink: string\n syscall: 'symlink' = 'symlink'\n code: 'TAR_SYMLINK_ERROR' = 'TAR_SYMLINK_ERROR'\n constructor(symlink: string, path: string) {\n super('TAR_SYMLINK_ERROR: Cannot extract through symbolic link')\n this.symlink = symlink\n this.path = path\n }\n get name() {\n return 'SymlinkError'\n }\n}\n", "// A path exclusive reservation system\n// reserve([list, of, paths], fn)\n// When the fn is first in line for all its paths, it\n// is called with a cb that clears the reservation.\n//\n// Used by async unpack to avoid clobbering paths in use,\n// while still allowing maximal safe parallelization.\n\nimport { join } from 'node:path'\nimport { normalizeUnicode } from './normalize-unicode.js'\nimport { stripTrailingSlashes } from './strip-trailing-slashes.js'\n\nconst platform =\n process.env.TESTING_TAR_FAKE_PLATFORM || process.platform\nconst isWindows = platform === 'win32'\n\nexport type Reservation = {\n paths: string[]\n dirs: Set<string>\n}\n\nexport type Handler = (clear: () => void) => void\n\n// return a set of parent dirs for a given path\n// '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d']\nconst getDirs = (path: string) => {\n const dirs = path\n .split('/')\n .slice(0, -1)\n .reduce((set: string[], path) => {\n const s = set[set.length - 1]\n if (s !== undefined) {\n path = join(s, path)\n }\n set.push(path || '/')\n return set\n }, [])\n return dirs\n}\n\nexport class PathReservations {\n // path => [function or Set]\n // A Set object means a directory reservation\n // A fn is a direct reservation on that path\n #queues = new Map<string, (Handler | Set<Handler>)[]>()\n\n // fn => {paths:[path,...], dirs:[path, ...]}\n #reservations = new Map<Handler, Reservation>()\n\n // functions currently running\n #running = new Set<Handler>()\n\n reserve(paths: string[], fn: Handler) {\n paths =\n isWindows ?\n ['win32 parallelization disabled']\n : paths.map(p => {\n // don't need normPath, because we skip this entirely for windows\n return stripTrailingSlashes(join(normalizeUnicode(p)))\n })\n\n const dirs = new Set<string>(\n paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)),\n )\n this.#reservations.set(fn, { dirs, paths })\n for (const p of paths) {\n const q = this.#queues.get(p)\n if (!q) {\n this.#queues.set(p, [fn])\n } else {\n q.push(fn)\n }\n }\n for (const dir of dirs) {\n const q = this.#queues.get(dir)\n if (!q) {\n this.#queues.set(dir, [new Set([fn])])\n } else {\n const l = q[q.length - 1]\n if (l instanceof Set) {\n l.add(fn)\n } else {\n q.push(new Set([fn]))\n }\n }\n }\n return this.#run(fn)\n }\n\n // return the queues for each path the function cares about\n // fn => {paths, dirs}\n #getQueues(fn: Handler): {\n paths: Handler[][]\n dirs: (Handler | Set<Handler>)[][]\n } {\n const res = this.#reservations.get(fn)\n /* c8 ignore start */\n if (!res) {\n throw new Error('function does not have any path reservations')\n }\n /* c8 ignore stop */\n return {\n paths: res.paths.map((path: string) =>\n this.#queues.get(path),\n ) as Handler[][],\n dirs: [...res.dirs].map(path => this.#queues.get(path)) as (\n | Handler\n | Set<Handler>\n )[][],\n }\n }\n\n // check if fn is first in line for all its paths, and is\n // included in the first set for all its dir queues\n check(fn: Handler) {\n const { paths, dirs } = this.#getQueues(fn)\n return (\n paths.every(q => q && q[0] === fn) &&\n dirs.every(q => q && q[0] instanceof Set && q[0].has(fn))\n )\n }\n\n // run the function if it's first in line and not already running\n #run(fn: Handler) {\n if (this.#running.has(fn) || !this.check(fn)) {\n return false\n }\n this.#running.add(fn)\n fn(() => this.#clear(fn))\n return true\n }\n\n #clear(fn: Handler) {\n if (!this.#running.has(fn)) {\n return false\n }\n const res = this.#reservations.get(fn)\n /* c8 ignore start */\n if (!res) {\n throw new Error('invalid reservation')\n }\n /* c8 ignore stop */\n const { paths, dirs } = res\n\n const next = new Set<Handler>()\n for (const path of paths) {\n const q = this.#queues.get(path)\n /* c8 ignore start */\n if (!q || q?.[0] !== fn) {\n continue\n }\n /* c8 ignore stop */\n const q0 = q[1]\n if (!q0) {\n this.#queues.delete(path)\n continue\n }\n q.shift()\n if (typeof q0 === 'function') {\n next.add(q0)\n } else {\n for (const f of q0) {\n next.add(f)\n }\n }\n }\n\n for (const dir of dirs) {\n const q = this.#queues.get(dir)\n const q0 = q?.[0]\n /* c8 ignore next - type safety only */\n if (!q || !(q0 instanceof Set)) continue\n if (q0.size === 1 && q.length === 1) {\n this.#queues.delete(dir)\n continue\n } else if (q0.size === 1) {\n q.shift()\n // next one must be a function,\n // or else the Set would've been reused\n const n = q[0]\n if (typeof n === 'function') {\n next.add(n)\n }\n } else {\n q0.delete(fn)\n }\n }\n\n this.#running.delete(fn)\n next.forEach(fn => this.#run(fn))\n return true\n }\n}\n", "// warning: extremely hot code path.\n// This has been meticulously optimized for use\n// within npm install on large package trees.\n// Do not edit without careful benchmarking.\nconst normalizeCache: Record<string, string> = Object.create(null)\n\n// Limit the size of this. Very low-sophistication LRU cache\nconst MAX = 10000\nconst cache = new Set<string>()\nexport const normalizeUnicode = (s: string): string => {\n if (!cache.has(s)) {\n // shake out identical accents and ligatures\n normalizeCache[s] = s\n .normalize('NFD')\n .toLocaleLowerCase('en')\n .toLocaleUpperCase('en')\n } else {\n cache.delete(s)\n }\n cache.add(s)\n\n const ret = normalizeCache[s] as string\n\n let i = cache.size - MAX\n // only prune when we're 10% over the max\n if (i > MAX / 10) {\n for (const s of cache) {\n cache.delete(s)\n delete normalizeCache[s]\n if (--i <= 0) break\n }\n }\n\n return ret\n}\n", "// tar -r\nimport { WriteStream, WriteStreamSync } from '@isaacs/fs-minipass'\nimport { Minipass } from 'minipass'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { Header } from './header.js'\nimport { list } from './list.js'\nimport { makeCommand } from './make-command.js'\nimport {\n isFile,\n TarOptionsFile,\n TarOptionsSyncFile,\n} from './options.js'\nimport { Pack, PackSync } from './pack.js'\n\n// starting at the head of the file, read a Header\n// If the checksum is invalid, that's our position to start writing\n// If it is, jump forward by the specified size (round up to 512)\n// and try again.\n// Write the new Pack stream starting there.\n\nconst replaceSync = (opt: TarOptionsSyncFile, files: string[]) => {\n const p = new PackSync(opt)\n\n let threw = true\n let fd\n let position\n\n try {\n try {\n fd = fs.openSync(opt.file, 'r+')\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') {\n fd = fs.openSync(opt.file, 'w+')\n } else {\n throw er\n }\n }\n\n const st = fs.fstatSync(fd)\n const headBuf = Buffer.alloc(512)\n\n POSITION: for (\n position = 0;\n position < st.size;\n position += 512\n ) {\n for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) {\n bytes = fs.readSync(\n fd,\n headBuf,\n bufPos,\n headBuf.length - bufPos,\n position + bufPos,\n )\n\n if (\n position === 0 &&\n headBuf[0] === 0x1f &&\n headBuf[1] === 0x8b\n ) {\n throw new Error('cannot append to compressed archives')\n }\n\n if (!bytes) {\n break POSITION\n }\n }\n\n const h = new Header(headBuf)\n if (!h.cksumValid) {\n break\n }\n const entryBlockSize = 512 * Math.ceil((h.size || 0) / 512)\n if (position + entryBlockSize + 512 > st.size) {\n break\n }\n // the 512 for the header we just parsed will be added as well\n // also jump ahead all the blocks for the body\n position += entryBlockSize\n if (opt.mtimeCache && h.mtime) {\n opt.mtimeCache.set(String(h.path), h.mtime)\n }\n }\n threw = false\n\n streamSync(opt, p, position, fd, files)\n } finally {\n if (threw) {\n try {\n fs.closeSync(fd as number)\n } catch (er) {}\n }\n }\n}\n\nconst streamSync = (\n opt: TarOptionsSyncFile,\n p: Pack,\n position: number,\n fd: number,\n files: string[],\n) => {\n const stream = new WriteStreamSync(opt.file, {\n fd: fd,\n start: position,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n addFilesSync(p, files)\n}\n\nconst replaceAsync = (\n opt: TarOptionsFile,\n files: string[],\n): Promise<void> => {\n files = Array.from(files)\n const p = new Pack(opt)\n\n const getPos = (\n fd: number,\n size: number,\n cb_: (er?: null | Error, pos?: number) => void,\n ) => {\n const cb = (er?: Error | null, pos?: number) => {\n if (er) {\n fs.close(fd, _ => cb_(er))\n } else {\n cb_(null, pos)\n }\n }\n\n let position = 0\n if (size === 0) {\n return cb(null, 0)\n }\n\n let bufPos = 0\n const headBuf = Buffer.alloc(512)\n const onread = (er?: null | Error, bytes?: number): void => {\n if (er || typeof bytes === 'undefined') {\n return cb(er)\n }\n bufPos += bytes\n if (bufPos < 512 && bytes) {\n return fs.read(\n fd,\n headBuf,\n bufPos,\n headBuf.length - bufPos,\n position + bufPos,\n onread,\n )\n }\n\n if (\n position === 0 &&\n headBuf[0] === 0x1f &&\n headBuf[1] === 0x8b\n ) {\n return cb(new Error('cannot append to compressed archives'))\n }\n\n // truncated header\n if (bufPos < 512) {\n return cb(null, position)\n }\n\n const h = new Header(headBuf)\n if (!h.cksumValid) {\n return cb(null, position)\n }\n\n /* c8 ignore next */\n const entryBlockSize = 512 * Math.ceil((h.size ?? 0) / 512)\n if (position + entryBlockSize + 512 > size) {\n return cb(null, position)\n }\n\n position += entryBlockSize + 512\n if (position >= size) {\n return cb(null, position)\n }\n\n if (opt.mtimeCache && h.mtime) {\n opt.mtimeCache.set(String(h.path), h.mtime)\n }\n bufPos = 0\n fs.read(fd, headBuf, 0, 512, position, onread)\n }\n fs.read(fd, headBuf, 0, 512, position, onread)\n }\n\n const promise = new Promise<void>((resolve, reject) => {\n p.on('error', reject)\n let flag = 'r+'\n const onopen = (\n er?: NodeJS.ErrnoException | null,\n fd?: number,\n ) => {\n if (er && er.code === 'ENOENT' && flag === 'r+') {\n flag = 'w+'\n return fs.open(opt.file, flag, onopen)\n }\n\n if (er || !fd) {\n return reject(er)\n }\n\n fs.fstat(fd, (er, st) => {\n if (er) {\n return fs.close(fd, () => reject(er))\n }\n\n getPos(fd, st.size, (er, position) => {\n if (er) {\n return reject(er)\n }\n const stream = new WriteStream(opt.file, {\n fd: fd,\n start: position,\n })\n p.pipe(stream as unknown as Minipass.Writable)\n stream.on('error', reject)\n stream.on('close', resolve)\n addFilesAsync(p, files)\n })\n })\n }\n fs.open(opt.file, flag, onopen)\n })\n\n return promise\n}\n\nconst addFilesSync = (p: Pack, files: string[]) => {\n files.forEach(file => {\n if (file.charAt(0) === '@') {\n list({\n file: path.resolve(p.cwd, file.slice(1)),\n sync: true,\n noResume: true,\n onReadEntry: entry => p.add(entry),\n })\n } else {\n p.add(file)\n }\n })\n p.end()\n}\n\nconst addFilesAsync = async (\n p: Pack,\n files: string[],\n): Promise<void> => {\n for (let i = 0; i < files.length; i++) {\n const file = String(files[i])\n if (file.charAt(0) === '@') {\n await list({\n file: path.resolve(String(p.cwd), file.slice(1)),\n noResume: true,\n onReadEntry: entry => p.add(entry),\n })\n } else {\n p.add(file)\n }\n }\n p.end()\n}\n\nexport const replace = makeCommand(\n replaceSync,\n replaceAsync,\n /* c8 ignore start */\n (): never => {\n throw new TypeError('file is required')\n },\n (): never => {\n throw new TypeError('file is required')\n },\n /* c8 ignore stop */\n (opt, entries) => {\n if (!isFile(opt)) {\n throw new TypeError('file is required')\n }\n\n if (\n opt.gzip ||\n opt.brotli ||\n opt.zstd ||\n opt.file.endsWith('.br') ||\n opt.file.endsWith('.tbr')\n ) {\n throw new TypeError('cannot append to compressed archives')\n }\n\n if (!entries?.length) {\n throw new TypeError('no paths specified to add/replace')\n }\n },\n)\n", "// tar -u\n\nimport { makeCommand } from './make-command.js'\nimport { type TarOptionsWithAliases } from './options.js'\n\nimport { replace as r } from './replace.js'\n\n// just call tar.r with the filter and mtimeCache\nexport const update = makeCommand(\n r.syncFile,\n r.asyncFile,\n r.syncNoFile,\n r.asyncNoFile,\n (opt, entries = []) => {\n r.validate?.(opt, entries)\n mtimeFilter(opt)\n },\n)\n\nconst mtimeFilter = (opt: TarOptionsWithAliases) => {\n const filter = opt.filter\n\n if (!opt.mtimeCache) {\n opt.mtimeCache = new Map()\n }\n\n opt.filter =\n filter ?\n (path, stat) =>\n filter(path, stat) &&\n !(\n /* c8 ignore start */\n (\n (opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >\n (stat.mtime ?? 0)\n )\n /* c8 ignore stop */\n )\n : (path, stat) =>\n !(\n /* c8 ignore start */\n (\n (opt.mtimeCache?.get(path) ?? stat.mtime ?? 0) >\n (stat.mtime ?? 0)\n )\n /* c8 ignore stop */\n )\n}\n", "import path from \"node:path\";\nimport { type PackageJson } from \"./types\";\n\nfunction normalize(name: string): string {\n\treturn name.replace(\"/\", \"-\").replace(/^@/, \"\");\n}\n\nexport function tarballLocation(pkg: PackageJson, pkgPath: string): string {\n\tconst name = normalize(pkg.name);\n\treturn path.join(path.dirname(pkgPath), `${name}-${pkg.version}.tgz`);\n}\n", "import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nconst enabled = os.platform() === \"linux\";\nconst cacheRoot = process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), \".cache\");\nlet cacheDir = path.join(cacheRoot, \"npm-pkg-lint\");\n\n/* istanbul ignore next */\nfunction getFilePath(key: string): string {\n\t/* eslint-disable-next-line sonarjs/hashing -- technical debt, should use a different algo but should not cause any issues as is either */\n\tconst hash = crypto.createHash(\"md5\").update(key).digest(\"hex\");\n\tconst filename = `${hash.slice(0, 2)}/${hash.slice(2)}.json`;\n\treturn path.join(cacheDir, filename);\n}\n\n/* istanbul ignore next */\nexport async function setCacheDirecory(directory: string): Promise<void> {\n\tawait fs.mkdir(directory, { recursive: true });\n\tcacheDir = directory;\n}\n\n/* istanbul ignore next */\nexport async function persistentCacheGet(key: string): Promise<unknown> {\n\tif (!enabled) {\n\t\treturn null;\n\t}\n\n\tconst filePath = getFilePath(key);\n\ttry {\n\t\tconst content = await fs.readFile(filePath, \"utf-8\");\n\t\treturn JSON.parse(content) as unknown;\n\t} catch (err: unknown) {\n\t\tif (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n\t\t\treturn null;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\n/* istanbul ignore next */\nexport async function persistentCacheSet(key: string, data: unknown): Promise<void> {\n\tif (!enabled) {\n\t\treturn;\n\t}\n\n\tconst filePath = getFilePath(key);\n\tconst content = JSON.stringify(data, null, 2);\n\tawait fs.mkdir(path.dirname(filePath), { recursive: true });\n\tawait fs.writeFile(filePath, content, \"utf-8\");\n}\n", "import { type DocumentNode, type MemberNode, type ValueNode } from \"@humanwhocodes/momoa\";\n\ninterface Result {\n\tvalue: ValueNode;\n\tmember?: MemberNode;\n}\n\nfunction findNextNode(current: Result, segment: string, datapath: string[]): Result {\n\tconst { value } = current;\n\tswitch (value.type) {\n\t\tcase \"Object\": {\n\t\t\tconst found = value.members.find((it) => {\n\t\t\t\treturn it.name.type === \"String\" && it.name.value === segment;\n\t\t\t});\n\t\t\tif (!found) {\n\t\t\t\tthrow new Error(`Failed to find \"${datapath.join(\".\")}\" in JSON structure`);\n\t\t\t}\n\t\t\treturn { value: found.value, member: found };\n\t\t}\n\t\tdefault: {\n\t\t\tthrow new Error(\n\t\t\t\t`Dont know how to handle node type \"${value.type}\" when searching for \"${datapath.join(\n\t\t\t\t\t\".\",\n\t\t\t\t)}\" in JSON structure`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport function jsonLocation(\n\tast: DocumentNode,\n\tpick: \"member\" | \"value\",\n\t...datapath: string[]\n): { line: number; column: number } {\n\tconst result = datapath.reduce<Result>(\n\t\t(state, segment) => findNextNode(state, segment, datapath),\n\t\t{ value: ast.body },\n\t);\n\n\tswitch (pick) {\n\t\tcase \"member\":\n\t\t\treturn result.member?.loc.start ?? { line: 1, column: 1 };\n\t\tcase \"value\":\n\t\t\treturn result.value.loc.start;\n\t}\n}\n", "import process from 'node:process';\nimport {stripVTControlCharacters} from 'node:util';\n\nexport const getContext = raw => ({\n\tstart: process.hrtime.bigint(),\n\tcommand: raw.map(part => getCommandPart(stripVTControlCharacters(part))).join(' '),\n\tstate: {\n\t\tstdout: '', stderr: '', output: '', isIterating: {}, nonIterable: [false, false],\n\t},\n});\n\nconst getCommandPart = part => /[^\\w./-]/.test(part)\n\t? `'${part.replaceAll('\\'', '\\'\\\\\\'\\'')}'`\n\t: part;\n", "import path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport process from 'node:process';\n\nexport const getOptions = ({\n\tstdin,\n\tstdout,\n\tstderr,\n\tstdio = [stdin, stdout, stderr],\n\tenv: envOption,\n\tpreferLocal,\n\tcwd: cwdOption = '.',\n\t...options\n}) => {\n\tconst cwd = cwdOption instanceof URL ? fileURLToPath(cwdOption) : path.resolve(cwdOption);\n\tconst env = envOption ? {...process.env, ...envOption} : undefined;\n\tconst input = stdio[0]?.string;\n\treturn {\n\t\t...options,\n\t\tinput,\n\t\tstdio: input === undefined ? stdio : ['pipe', ...stdio.slice(1)],\n\t\tenv: preferLocal ? addLocalPath(env ?? process.env, cwd) : env,\n\t\tcwd,\n\t};\n};\n\nconst addLocalPath = ({Path = '', PATH = Path, ...env}, cwd) => {\n\tconst pathParts = PATH.split(path.delimiter);\n\tconst localPaths = getLocalPaths([], path.resolve(cwd))\n\t\t.map(localPath => path.join(localPath, 'node_modules/.bin'))\n\t\t.filter(localPath => !pathParts.includes(localPath));\n\treturn {...env, PATH: [...localPaths, PATH].filter(Boolean).join(path.delimiter)};\n};\n\nconst getLocalPaths = (localPaths, localPath) => localPaths.at(-1) === localPath\n\t? localPaths\n\t: getLocalPaths([...localPaths, localPath], path.resolve(localPath, '..'));\n", "import {spawn} from 'node:child_process';\nimport {once} from 'node:events';\nimport process from 'node:process';\nimport {applyForceShell} from './windows.js';\nimport {getResultError} from './result.js';\n\nexport const spawnSubprocess = async (file, commandArguments, options, context) => {\n\ttry {\n\t\t// When running `node`, keep the current Node version and CLI flags.\n\t\t// Not applied with file paths to `.../node` since those indicate a clear intent to use a specific Node version.\n\t\t// This also provides a way to opting out, e.g. using `process.execPath` instead of `node` to discard current CLI flags.\n\t\t// Does not work with shebangs, but those don't work cross-platform anyway.\n\t\tif (['node', 'node.exe'].includes(file.toLowerCase())) {\n\t\t\tfile = process.execPath;\n\t\t\tcommandArguments = [...process.execArgv.filter(flag => !flag.startsWith('--inspect')), ...commandArguments];\n\t\t}\n\n\t\t[file, commandArguments, options] = await applyForceShell(file, commandArguments, options);\n\t\t[file, commandArguments, options] = concatenateShell(file, commandArguments, options);\n\t\tconst instance = spawn(file, commandArguments, options);\n\t\tbufferOutput(instance.stdout, context, 'stdout');\n\t\tbufferOutput(instance.stderr, context, 'stderr');\n\n\t\t// The `error` event is caught by `once(instance, 'spawn')` and `once(instance, 'close')`.\n\t\t// But it creates an uncaught exception if it happens exactly one tick after 'spawn'.\n\t\t// This prevents that.\n\t\tinstance.once('error', () => {});\n\n\t\tawait once(instance, 'spawn');\n\t\treturn instance;\n\t} catch (error) {\n\t\tthrow getResultError(error, {}, context);\n\t}\n};\n\n// When the `shell` option is set, any command argument is concatenated as a single string by Node.js:\n// https://github.com/nodejs/node/blob/e38ce27f3ca0a65f68a31cedd984cddb927d4002/lib/child_process.js#L614-L624\n// However, since Node 24, it also prints a deprecation warning.\n// To avoid this warning, we perform that same operation before calling `node:child_process`.\n// Shells only understand strings, which is why Node.js performs that concatenation.\n// However, we rely on users splitting command arguments as an array.\n// For example, this allows us to easily detect whether the binary file is `node` or `node.exe`.\n// So we do want users to pass array of arguments even with `shell: true`, but we also want to avoid any warning.\nconst concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0\n\t? [[file, ...commandArguments].join(' '), [], options]\n\t: [file, commandArguments, options];\n\nconst bufferOutput = (stream, {state}, streamName) => {\n\tif (stream) {\n\t\tstream.setEncoding('utf8');\n\t\tif (!state.isIterating[streamName]) {\n\t\t\tstate.isIterating[streamName] = false;\n\t\t\tstream.on('data', chunk => {\n\t\t\t\tstate[streamName] += chunk;\n\t\t\t\tstate.output += chunk;\n\t\t\t});\n\t\t}\n\t}\n};\n", "import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\n// When setting `shell: true` under-the-hood, we must manually escape the file and arguments.\n// This ensures arguments are properly split, and prevents command injection.\nexport const applyForceShell = async (file, commandArguments, options) => await shouldForceShell(file, options)\n\t? [escapeFile(file), commandArguments.map(argument => escapeArgument(argument)), {...options, shell: true}]\n\t: [file, commandArguments, options];\n\n// On Windows, running most executable files (except *.exe and *.com) requires using a shell.\n// This includes *.cmd and *.bat, which itself includes Node modules binaries.\n// We detect this situation and automatically:\n// - Set the `shell: true` option\n// - Escape shell-specific characters\nconst shouldForceShell = async (file, {shell, cwd, env = process.env}) => process.platform === 'win32'\n\t&& !shell\n\t&& !(await isExe(file, cwd, env));\n\n// Detect whether the executable file is a *.exe or *.com file.\n// Windows allows omitting file extensions (present in the `PATHEXT` environment variable).\n// Therefore we must use the `PATH` environment variable and make `access` calls to check this.\n// Environment variables are case-insensitive on Windows, so we check both `PATH` and `Path`.\nconst isExe = (file, cwd, {Path = '', PATH = Path}) =>\n\t// If the *.exe or *.com file extension was not omitted.\n\t// Windows common file systems are case-insensitive.\n\texeExtensions.some(extension => file.toLowerCase().endsWith(extension))\n\t|| mIsExe(file, cwd, PATH);\n\n// Memoize the `mIsExe` and `fs.access`, for performance\nconst EXE_MEMO = {};\n// eslint-disable-next-line no-return-assign\nconst memoize = function_ => (...arguments_) =>\n\t// Use returned assignment to keep code small\n\tEXE_MEMO[arguments_.join('\\0')] ??= function_(...arguments_);\n\nconst access = memoize(fs.access);\nconst mIsExe = memoize(async (file, cwd, PATH) => {\n\tconst parts = PATH\n\t\t// `PATH` is ;-separated on Windows\n\t\t.split(path.delimiter)\n\t\t// `PATH` allows leading/trailing ; on Windows\n\t\t.filter(Boolean)\n\t\t// `PATH` parts can be double quoted on Windows\n\t\t.map(part => part.replace(/^\"(.*)\"$/, '$1'));\n\n\t// For performance, parallelize and stop iteration as soon as an *.exe or *.com file is found\n\ttry {\n\t\tawait Promise.any(\n\t\t\t[cwd, ...parts].flatMap(part => exeExtensions\n\t\t\t\t.map(extension => access(`${path.resolve(part, file)}${extension}`)),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n\n\treturn true;\n});\n\n// Other file extensions require using a shell\nconst exeExtensions = ['.exe', '.com'];\n\n// `cmd.exe` escaping for arguments.\n// Taken from https://github.com/moxystudio/node-cross-spawn\nconst escapeArgument = argument => escapeFile(escapeFile(`\"${argument\n\t.replaceAll(/(\\\\*)\"/g, '$1$1\\\\\"')\n\t.replace(/(\\\\*)$/, '$1$1')}\"`));\n\n// `cmd.exe` escaping for file and arguments.\nconst escapeFile = file => file.replaceAll(/([()\\][%!^\"`<>&|;, *?])/g, '^$1');\n", "import {once, on} from 'node:events';\nimport process from 'node:process';\n\nexport const getResult = async (nodeChildProcess, {input}, context) => {\n\tconst instance = await nodeChildProcess;\n\tif (input !== undefined) {\n\t\tinstance.stdin.end(input);\n\t}\n\n\tconst onClose = once(instance, 'close');\n\n\ttry {\n\t\tawait Promise.race([\n\t\t\tonClose,\n\t\t\t...instance.stdio.filter(Boolean).map(stream => onStreamError(stream)),\n\t\t]);\n\t\tcheckFailure(context, getErrorOutput(instance));\n\t\treturn getOutputs(context);\n\t} catch (error) {\n\t\tawait Promise.allSettled([onClose]);\n\t\tthrow getResultError(error, instance, context);\n\t}\n};\n\nconst onStreamError = async stream => {\n\tfor await (const [error] of on(stream, 'error')) {\n\t\t// Ignore errors that are due to closing errors when the subprocesses exit normally, or due to piping\n\t\tif (!['ERR_STREAM_PREMATURE_CLOSE', 'EPIPE'].includes(error?.code)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n};\n\nconst checkFailure = ({command}, {exitCode, signalName}) => {\n\tif (signalName !== undefined) {\n\t\tthrow new SubprocessError(`Command was terminated with ${signalName}: ${command}`);\n\t}\n\n\tif (exitCode !== undefined) {\n\t\tthrow new SubprocessError(`Command failed with exit code ${exitCode}: ${command}`);\n\t}\n};\n\nexport const getResultError = (error, instance, context) => Object.assign(\n\tgetErrorInstance(error, context),\n\tgetErrorOutput(instance),\n\tgetOutputs(context),\n);\n\nconst getErrorInstance = (error, {command}) => error instanceof SubprocessError\n\t? error\n\t: new SubprocessError(`Command failed: ${command}`, {cause: error});\n\nexport class SubprocessError extends Error {\n\tname = 'SubprocessError';\n}\n\nconst getErrorOutput = ({exitCode, signalCode}) => ({\n\t// `exitCode` can be a negative number (`errno`) when the `error` event is emitted on the `instance`\n\t...(exitCode < 1 ? {} : {exitCode}),\n\t...(signalCode === null ? {} : {signalName: signalCode}),\n});\n\nconst getOutputs = ({state: {stdout, stderr, output}, command, start}) => ({\n\tstdout: getOutput(stdout),\n\tstderr: getOutput(stderr),\n\toutput: getOutput(output),\n\tcommand,\n\tdurationMs: Number(process.hrtime.bigint() - start) / 1e6,\n});\n\nconst getOutput = output => output.at(-1) === '\\n'\n\t? output.slice(0, output.at(-2) === '\\r' ? -2 : -1)\n\t: output;\n", "import {pipeline} from 'node:stream/promises';\n\nexport const handlePipe = async subprocesses => {\n\t// Ensure both subprocesses have exited before resolving, and that we handle errors from both\n\tconst [[from, to]] = await Promise.all([Promise.allSettled(subprocesses), pipeStreams(subprocesses)]);\n\n\t// If both subprocesses fail, throw destination error to use a predictable order and avoid race conditions\n\tif (to.reason) {\n\t\tto.reason.pipedFrom = from.reason ?? from.value;\n\t\tthrow to.reason;\n\t}\n\n\tif (from.reason) {\n\t\tthrow from.reason;\n\t}\n\n\treturn {...to.value, pipedFrom: from.value};\n};\n\nconst pipeStreams = async subprocesses => {\n\ttry {\n\t\tconst [{stdout}, {stdin}] = await Promise.all(subprocesses.map(({nodeChildProcess}) => nodeChildProcess));\n\t\tif (stdin === null) {\n\t\t\tthrow new Error('The \"stdin\" option must be set on the first \"spawn()\" call in the pipeline.');\n\t\t}\n\n\t\tif (stdout === null) {\n\t\t\tthrow new Error('The \"stdout\" option must be set on the last \"spawn()\" call in the pipeline.');\n\t\t}\n\n\t\t// Do not `await` nor handle stream errors since this is already done by each subprocess\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\tpipeline(stdout, stdin).catch(() => {});\n\t} catch (error) {\n\t\tawait Promise.allSettled(subprocesses.map(({nodeChildProcess}) => closeStdin(nodeChildProcess)));\n\t\tthrow error;\n\t}\n};\n\nconst closeStdin = async nodeChildProcess => {\n\tconst {stdin} = await nodeChildProcess;\n\tstdin.end();\n};\n", "import * as readline from 'node:readline/promises';\n\nexport const lineIterator = async function * (subprocess, {state}, streamName, index) {\n\t// Prevent buffering when iterating.\n\t// This would defeat one of the main goals of iterating: low memory consumption.\n\tif (state.isIterating[streamName] === false) {\n\t\tthrow new Error(`The subprocess must be iterated right away, for example:\n\tfor await (const line of spawn(...)) { ... }`);\n\t}\n\n\tstate.isIterating[streamName] = true;\n\n\ttry {\n\t\tconst {[streamName]: stream} = await subprocess.nodeChildProcess;\n\t\tif (!stream) {\n\t\t\tstate.nonIterable[index] = true;\n\t\t\tconst message = state.nonIterable.every(Boolean)\n\t\t\t\t? 'either the option `stdout` or `stderr`'\n\t\t\t\t: `the option \\`${streamName}\\``;\n\t\t\tthrow new TypeError(\n\t\t\t\t`The subprocess cannot be iterated unless ${message} is 'pipe'.`,\n\t\t\t);\n\t\t}\n\n\t\thandleErrors(subprocess);\n\t\tyield * readline.createInterface({input: stream});\n\t} finally {\n\t\tawait subprocess;\n\t}\n};\n\n// When the `subprocess` promise is rejected, we await it in the `finally`\n// block. However, this might not happen right away, so an `unhandledRejection`\n// error is emitted first, crashing the process. This prevents it.\n// This is safe since we are guaranteed to propagate the `subprocess` error\n// with the `finally` block.\n// See https://github.com/sindresorhus/nano-spawn/issues/104\nconst handleErrors = async subprocess => {\n\ttry {\n\t\tawait subprocess;\n\t} catch {}\n};\n\n// Merge two async iterators into one\nexport const combineAsyncIterators = async function * ({state}, ...iterators) {\n\ttry {\n\t\tlet promises = [];\n\t\twhile (iterators.length > 0) {\n\t\t\tpromises = iterators.map((iterator, index) => promises[index] ?? getNext(iterator, index, state));\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst [{value, done}, index] = await Promise.race(promises\n\t\t\t\t.map((promise, index) => Promise.all([promise, index])));\n\n\t\t\tconst [iterator] = iterators.splice(index, 1);\n\t\t\tpromises.splice(index, 1);\n\n\t\t\tif (!done) {\n\t\t\t\titerators.push(iterator);\n\t\t\t\tyield value;\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait Promise.all(iterators.map(iterator => iterator.return()));\n\t}\n};\n\nconst getNext = async (iterator, index, {nonIterable}) => {\n\ttry {\n\t\treturn await iterator.next();\n\t} catch (error) {\n\t\treturn shouldIgnoreError(nonIterable, index)\n\t\t\t? iterator.return()\n\t\t\t: iterator.throw(error);\n\t}\n};\n\nconst shouldIgnoreError = (nonIterable, index) => nonIterable.every(Boolean)\n\t? index !== nonIterable.length - 1\n\t: nonIterable[index];\n", "import {getContext} from './context.js';\nimport {getOptions} from './options.js';\nimport {spawnSubprocess} from './spawn.js';\nimport {getResult} from './result.js';\nimport {handlePipe} from './pipe.js';\nimport {lineIterator, combineAsyncIterators} from './iterable.js';\n\nexport {SubprocessError} from './result.js';\n\nexport default function spawn(file, second, third, previous) {\n\tconst [commandArguments = [], options = {}] = Array.isArray(second) ? [second, third] : [[], second];\n\tconst context = getContext([file, ...commandArguments]);\n\tconst spawnOptions = getOptions(options);\n\tconst nodeChildProcess = spawnSubprocess(file, commandArguments, spawnOptions, context);\n\tlet subprocess = getResult(nodeChildProcess, spawnOptions, context);\n\tObject.assign(subprocess, {nodeChildProcess});\n\tsubprocess = previous ? handlePipe([previous, subprocess]) : subprocess;\n\n\tconst stdout = lineIterator(subprocess, context, 'stdout', 0);\n\tconst stderr = lineIterator(subprocess, context, 'stderr', 1);\n\treturn Object.assign(subprocess, {\n\t\tnodeChildProcess,\n\t\tstdout,\n\t\tstderr,\n\t\t[Symbol.asyncIterator]: () => combineAsyncIterators(context, stdout, stderr),\n\t\tpipe: (file, second, third) => spawn(file, second, third, subprocess),\n\t});\n}\n", "import spawn from \"nano-spawn\";\nimport { type PackageJson } from \"../types\";\nimport { persistentCacheGet, persistentCacheSet } from \"./persistent-cache\";\n\nexport interface NpmInfo {\n\tdeprecated?: string;\n}\n\nexport interface NpmInfoError {\n\tcode: string;\n\tsummary: string;\n\tdetail: string;\n}\n\nexport interface ExecaError extends Error {\n\tstdout: string;\n}\n\nconst cache = new Map<string, PackageJson | null>();\n\nfunction isExecaError(error: unknown): error is ExecaError {\n\treturn Boolean(error && error instanceof Error && \"stdout\" in error);\n}\n\nexport function isNpmInfoError(error: unknown): error is NpmInfoError {\n\treturn Boolean(error && error instanceof Error && \"summary\" in error);\n}\n\nfunction tryParse(maybeJson: string): { error: NpmInfoError } | null {\n\ttry {\n\t\treturn JSON.parse(maybeJson) as { error: NpmInfoError };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function npmInfo(pkg: string): Promise<PackageJson & NpmInfo>;\nexport async function npmInfo(\n\tpkg: string,\n\toptions: { ignoreUnpublished: true },\n): Promise<(PackageJson & NpmInfo) | null>;\n/* eslint-disable-next-line complexity -- technical debt */\nexport async function npmInfo(\n\tpkg: string,\n\toptions: { ignoreUnpublished: boolean } = { ignoreUnpublished: false },\n): Promise<(PackageJson & NpmInfo) | null> {\n\tconst { ignoreUnpublished } = options;\n\tconst cached = cache.get(pkg);\n\tif (cached === null) {\n\t\tif (ignoreUnpublished) {\n\t\t\treturn null;\n\t\t}\n\t} else if (cached) {\n\t\treturn cached;\n\t}\n\n\tconst persistent = await persistentCacheGet(pkg);\n\tif (persistent) {\n\t\treturn persistent as PackageJson;\n\t}\n\n\ttry {\n\t\tconst result = await spawn(\"npm\", [\"info\", \"--json\", pkg]);\n\t\tconst pkgData = JSON.parse(result.stdout) as PackageJson;\n\t\tcache.set(pkg, pkgData);\n\t\tawait persistentCacheSet(pkg, pkgData);\n\t\treturn pkgData;\n\t} catch (err: unknown) {\n\t\tif (!isExecaError(err)) {\n\t\t\tthrow err;\n\t\t}\n\t\tconst parsed = tryParse(err.stdout);\n\t\tif (!parsed) {\n\t\t\tthrow err;\n\t\t}\n\t\tconst { code, summary, detail } = parsed.error;\n\n\t\t/* cache for this session but don't store in persistent cache as this\n\t\t * error might be temporary */\n\t\tcache.set(pkg, null);\n\n\t\tif (ignoreUnpublished && code === \"E404\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst wrappedError = new Error(summary, { cause: err }) as Error & NpmInfoError;\n\t\twrappedError.code = code;\n\t\twrappedError.summary = summary;\n\t\twrappedError.detail = detail;\n\t\tthrow wrappedError;\n\t}\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"conflicting-types-typings\";\nconst severity = Severity.ERROR;\n\n/**\n * Yields an error if both the `types` and `typings` field are set.\n *\n * @param pkg - Parsed `package.json\"`.\n * @param pkgAst - JSON syntax tree for the `pkg` parameter.\n */\nexport function* conflictingTypesTypings(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n): Generator<Message> {\n\tif (!pkg.types || !pkg.typings) {\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"typings\");\n\tyield {\n\t\truleId,\n\t\tseverity,\n\t\tmessage: `Duplicate \"typings\" and \"types\" field`,\n\t\tline,\n\t\tcolumn,\n\t};\n}\n", "import { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport semver from \"semver\";\nimport { type Message } from \"../message\";\nimport { type VerifyPackageJsonOptions } from \"../package-json\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation, npmInfo } from \"../utils\";\nimport { isNpmInfoError } from \"../utils/npm-info\";\n\nconst ruleId = \"no-deprecated-dependency\";\n\ninterface Dependency {\n\tname: string;\n\tversion: string;\n\tspec: string;\n\tsource: \"dependencies\" | \"devDependencies\" | \"peerDependencies\";\n}\n\nfunction createEntry(\n\tkey: string,\n\tversion: string,\n\tsource: Dependency[\"source\"],\n): Dependency | null {\n\t/* ignore packages with file: prefix */\n\tif (version.startsWith(\"file:\")) {\n\t\treturn null;\n\t}\n\n\t/* handle npm: prefix */\n\tif (version.startsWith(\"npm:\")) {\n\t\tconst [newKey, newVersion] = version.slice(\"npm:\".length).split(\"@\", 2);\n\t\tkey = newKey;\n\t\tversion = newVersion;\n\t}\n\n\t/* ignore this as this package is sometimes is present as version \"*\" which\n\t * just yields way to many versions to handle causing MaxBuffer errors and\n\t * there is another rule to make sure the outermost @types/node package\n\t * matches the configured engines */\n\tif (key === \"@types/node\") {\n\t\treturn null;\n\t}\n\n\tconst minVersion = semver.minVersion(version);\n\treturn {\n\t\tname: key,\n\t\tversion,\n\t\tspec: `${key}@${minVersion ? minVersion.version : version}`,\n\t\tsource,\n\t};\n}\n\nfunction* getDependencies(pkg: PackageJson): Generator<Dependency> {\n\tconst { dependencies = {}, devDependencies = {}, peerDependencies = {} } = pkg;\n\tfor (const [key, version] of Object.entries(dependencies)) {\n\t\tconst entry = createEntry(key, version, \"dependencies\");\n\t\tif (entry) {\n\t\t\tyield entry;\n\t\t}\n\t}\n\tfor (const [key, version] of Object.entries(devDependencies)) {\n\t\tconst entry = createEntry(key, version, \"devDependencies\");\n\t\tif (entry) {\n\t\t\tyield entry;\n\t\t}\n\t}\n\tfor (const [key, version] of Object.entries(peerDependencies)) {\n\t\tconst entry = createEntry(key, version, \"peerDependencies\");\n\t\tif (entry) {\n\t\t\tyield entry;\n\t\t}\n\t}\n}\n\nexport async function deprecatedDependency(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\toptions: VerifyPackageJsonOptions,\n): Promise<Message[]> {\n\tconst { allowedDependencies } = options;\n\tconst messages: Message[] = [];\n\n\tfor (const dependency of getDependencies(pkg)) {\n\t\t/* allow explicitly allowed dependencies */\n\t\tif (allowedDependencies.has(dependency.name)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst { deprecated } = await npmInfo(dependency.spec);\n\t\t\tif (!deprecated) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", dependency.source, dependency.name);\n\t\t\tmessages.push({\n\t\t\t\truleId,\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `\"${dependency.spec}\" is deprecated and must not be used`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t});\n\t\t} catch (err: unknown) {\n\t\t\tif (isNpmInfoError(err) && err.code === \"E404\") {\n\t\t\t\tif (dependency.source === \"devDependencies\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", dependency.source, dependency.name);\n\t\t\t\tmessages.push({\n\t\t\t\t\truleId,\n\t\t\t\t\tseverity: 1,\n\t\t\t\t\tmessage: `\"${dependency.spec}\" is not published to the NPM registry`,\n\t\t\t\t\tline,\n\t\t\t\t\tcolumn,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\treturn messages;\n}\n", "/* eslint-disable security/detect-non-literal-regexp -- expected to be non-literal */\n\nimport { type PackageJson } from \"../types\";\n\nfunction exact(name: string): RegExp {\n\treturn new RegExp(`^${name}$`);\n}\nfunction scope(scope: string): RegExp {\n\treturn new RegExp(`^${scope}/`);\n}\n\nfunction prefix(prefix: string): RegExp {\n\treturn new RegExp(`^${prefix}(-.+)?`);\n}\n\nfunction scopedPrefix(prefix: string): RegExp {\n\treturn new RegExp(`^(.*)/${prefix}(-.+)?`);\n}\n\nconst disallowedDependencies: RegExp[] = [\n\texact(\"ava\"),\n\texact(\"jake\"),\n\texact(\"tsd\"),\n\texact(\"typescript\"),\n\texact(\"xo\"),\n\tprefix(\"babel-core\"),\n\tprefix(\"cypress\"),\n\tprefix(\"grunt\"),\n\tprefix(\"gulp\"),\n\tprefix(\"html-validate\"),\n\tprefix(\"jasmine\"),\n\tprefix(\"mocha\"),\n\tprefix(\"nyc\"),\n\tprefix(\"protractor\"),\n\tprefix(\"ts-node\"),\n\tprefix(\"webpack\"),\n\tscope(\"@babel\"),\n\tscope(\"@tsconfig\"),\n\tscope(\"@types\"),\n];\n\nconst disallowedEslint: RegExp[] = [\n\texact(\"eslint\"),\n\texact(\"typescript-eslint\"),\n\tprefix(\"eslint-config\"),\n\tprefix(\"eslint-formatter\"),\n\tprefix(\"eslint-plugin\"),\n\tscope(\"@typescript-eslint\"),\n\tscopedPrefix(\"eslint-config\"),\n\tscopedPrefix(\"eslint-formatter\"),\n\tscopedPrefix(\"eslint-plugin\"),\n];\n\nconst disallowedJest: RegExp[] = [\n\texact(\"jest\"),\n\texact(\"babel-jest\"),\n\texact(\"ts-jest\"),\n\tprefix(\"jest-\"),\n\tscope(\"@jest\"),\n];\n\nconst disallowedPrettier: RegExp[] = [\n\texact(\"prettier\"),\n\tprefix(\"prettier-\"),\n\tscopedPrefix(\"prettier-\"),\n];\n\nconst allowedDependencies: string[] = [\n\t\"@babel/code-frame\",\n\t\"@babel/polyfill\",\n\t\"@babel/runtime\",\n\t\"gulp-utils\",\n\t\"jest-diff\",\n\t\"webpack-sources\",\n];\n\nfunction match(list: RegExp[], dependency: string): boolean {\n\treturn list.some((it) => dependency.match(it));\n}\n\nexport function isDisallowedDependency(pkg: PackageJson, dependency: string): boolean {\n\t/* test if dependency is explicitly listed as allowed */\n\tif (allowedDependencies.includes(dependency)) {\n\t\treturn false;\n\t}\n\n\tconst keywords = pkg.keywords ?? [];\n\n\t/* eslint-* is allowed only if keywords includes \"eslint\" */\n\tif (!keywords.includes(\"eslint\") && match(disallowedEslint, dependency)) {\n\t\treturn true;\n\t}\n\n\t/* jest-* is allowed only if keywords includes \"jest\" */\n\tif (!keywords.includes(\"jest\") && match(disallowedJest, dependency)) {\n\t\treturn true;\n\t}\n\n\t/* prettier-* is allowed only if keywords includes \"prettier\" */\n\tif (!keywords.includes(\"prettier\") && match(disallowedPrettier, dependency)) {\n\t\treturn true;\n\t}\n\n\t/* test if dependency is explicitly listed as disallowed */\n\treturn match(disallowedDependencies, dependency);\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson, type PackageJsonExports } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"exports-types-order\";\nconst severity = Severity.ERROR;\n\nfunction* validateOrder(\n\tpkgAst: DocumentNode,\n\tvalue: string | PackageJsonExports | null,\n\tpath: string[],\n): Generator<Message> {\n\tif (!value || typeof value === \"string\") {\n\t\treturn;\n\t}\n\n\tconst keys = Object.keys(value);\n\tif (keys.length === 0) {\n\t\treturn;\n\t}\n\n\tif (keys.includes(\"types\") && keys[0] !== \"types\") {\n\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"exports\", ...path, \"types\");\n\t\tconst property = path.map((it) => `[\"${it}\"]`).join(\"\");\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage: `\"types\" must be the first condition in \"exports${property}\"`,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t}\n\n\tfor (const key of keys) {\n\t\tyield* validateOrder(pkgAst, value[key], [...path, key]);\n\t}\n}\n\nexport function* exportsTypesOrder(pkg: PackageJson, pkgAst: DocumentNode): Generator<Message> {\n\tif (pkg.exports) {\n\t\tyield* validateOrder(pkgAst, pkg.exports, []);\n\t}\n}\n", "export interface ObsoleteDependency {\n\tpackage: string;\n\tmessage: string;\n}\n\nconst obsolete: ObsoleteDependency[] = [\n\t{ package: \"make-dir\", message: `use native \"fs.mkdir(..., { recursive: true })\" instead` },\n\t{ package: \"mkdirp\", message: `use native \"fs.mkdir(..., { recursive: true })\" instead` },\n\t{ package: \"stable\", message: `Array#sort is stable in all current implementations` },\n\t{ package: \"querystring\", message: `use native \"URLSearchParams\" instead` },\n];\n\nexport function isObsoleteDependency(dependency: string): ObsoleteDependency | false {\n\treturn obsolete.find((it) => it.package === dependency) ?? false;\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport semver from \"semver\";\nimport { type Message } from \"../message\";\nimport { nodeVersions } from \"../node-versions\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"outdated-engines\";\nconst severity = Severity.ERROR;\n\n/* eslint-disable-next-line complexity -- technical debt */\nexport function* outdatedEngines(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\tignoreNodeVersion: boolean | number,\n): Generator<Message> {\n\tif (!pkg.engines?.node) {\n\t\tconst { line, column } = pkg.engines\n\t\t\t? jsonLocation(pkgAst, \"member\", \"engines\")\n\t\t\t: { line: 1, column: 1 };\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage: \"Missing engines.node field\",\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"value\", \"engines\", \"node\");\n\n\tconst range = pkg.engines.node;\n\tif (!semver.validRange(range)) {\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage: `engines.node \"${range}\" is not a valid semver range`,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t\treturn;\n\t}\n\n\tif (ignoreNodeVersion === true) {\n\t\treturn;\n\t}\n\n\tfor (const [version, descriptor] of nodeVersions) {\n\t\t/* assume the list of versions are sorted: when a version not EOL is found\n\t\t * we stop processing the list, e.g. `>= 18` is OK while Node 18 is not EOL\n\t\t * even if Node 19 is EOL. */\n\t\tif (!descriptor.eol) {\n\t\t\tbreak;\n\t\t}\n\n\t\tconst expanded = version.replace(/[xX*]/g, \"999\");\n\t\tif (!semver.satisfies(expanded, range)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- parsing hardcoded values and covered by unit tests */\n\t\tconst parsed = semver.parse(expanded)!;\n\n\t\tconst { major, minor } = parsed;\n\t\tif (ignoreNodeVersion === major) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst nodeRelease = major > 0 ? major : `0.${String(minor)}`;\n\t\tconst message = `engines.node is satisfied by Node ${String(nodeRelease)} (EOL since ${\n\t\t\tdescriptor.eol\n\t\t})`;\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t\treturn;\n\t}\n\n\t/* if we reached this far there was no error silenced by ignoreNodeVersion so\n\t * we yield a new error informing that the ignore is no longer needed */\n\tif (typeof ignoreNodeVersion === \"number\") {\n\t\tconst option = String(ignoreNodeVersion);\n\t\tconst version = `v${String(ignoreNodeVersion)}.x`;\n\t\tconst message = `--ignore-node-version=${option} used but engines.node=\"${range}\" does not match ${version} or the version is not EOL yet`;\n\t\tyield {\n\t\t\truleId,\n\t\t\tseverity,\n\t\t\tmessage,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t};\n\t}\n}\n", "interface NodeVersionDescriptor {\n\t/** If set this version is EOL since given date */\n\teol?: string;\n}\n\n/* https://github.com/nodejs/Release/blob/main/schedule.json */\nexport const nodeVersions: Array<[string, NodeVersionDescriptor]> = [\n\t[\"0.10.x\", { eol: \"2016-10-31\" }],\n\t[\"0.12.x\", { eol: \"2016-12-31\" }],\n\t[\"4.x.x\", { eol: \"2018-04-30\" }],\n\t[\"5.x.x\", { eol: \"2016-06-30\" }],\n\t[\"6.x.x\", { eol: \"2019-04-30\" }],\n\t[\"7.x.x\", { eol: \"2017-06-30\" }],\n\t[\"8.x.x\", { eol: \"2019-12-31\" }],\n\t[\"9.x.x\", { eol: \"2018-06-30\" }],\n\t[\"10.x.x\", { eol: \"2021-04-30\" }],\n\t[\"11.x.x\", { eol: \"2019-06-01\" }],\n\t[\"12.x.x\", { eol: \"2022-04-30\" }],\n\t[\"13.x.x\", { eol: \"2020-06-01\" }],\n\t[\"14.x.x\", { eol: \"2023-04-30\" }],\n\t[\"15.x.x\", { eol: \"2021-06-01\" }],\n\t[\"16.x.x\", { eol: \"2023-09-11\" }],\n\t[\"17.x.x\", { eol: \"2022-06-01\" }],\n\t[\"18.x.x\", { eol: \"2025-04-30\" }],\n\t[\"19.x.x\", { eol: \"2023-06-01\" }],\n\t[\"20.x.x\", {}],\n\t[\"21.x.x\", { eol: \"2024-06-01\" }],\n\t[\"22.x.x\", {}],\n];\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"prefer-types\";\nconst severity = Severity.ERROR;\n\n/**\n * Yields an error if the `typings` field is present instead of `types`.\n *\n * @param pkg - Parsed `package.json\"`.\n * @param pkgAst - JSON syntax tree for the `pkg` parameter.\n */\nexport function* preferTypes(pkg: PackageJson, pkgAst: DocumentNode): Generator<Message> {\n\tif (!pkg.typings || pkg.types) {\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"typings\");\n\tyield {\n\t\truleId,\n\t\tseverity,\n\t\tmessage: `Prefer \"types\" over \"typings\"`,\n\t\tline,\n\t\tcolumn,\n\t};\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"../message\";\nimport { type PackageJson, type PackageJsonExports } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"shadowed-types\";\nconst severity = Severity.ERROR;\n\nfunction walkConditions(conditions: PackageJsonExports | string | null): string[] {\n\tif (!conditions || typeof conditions === \"string\") {\n\t\treturn [];\n\t}\n\n\tconst types = conditions.types;\n\tif (typeof types === \"string\") {\n\t\treturn [types];\n\t}\n\n\treturn Object.values(conditions).reduce<string[]>((subpaths, it) => {\n\t\treturn [...subpaths, ...walkConditions(it)];\n\t}, []);\n}\n\n/**\n * Given the value of the \"exports\" field get all \"types\" conditions.\n *\n * @internal\n */\nexport function getTypesConditions(exports: PackageJsonExports | string | null): string[] {\n\tif (exports === null || typeof exports === \"string\") {\n\t\treturn [];\n\t}\n\n\tconst dot = exports[\".\"];\n\tif (dot) {\n\t\treturn walkConditions(dot);\n\t}\n\n\tconst types = exports.types;\n\tif (types && typeof types === \"string\") {\n\t\treturn [types];\n\t}\n\n\treturn [];\n}\n\n/**\n * Compare \"types\" from \"exports\" with the \"types\" or \"typings\" field and yields\n * an error if there is a mismatch.\n *\n * @param pkgAst - JSON syntax tree to get error location from.\n * @param subpaths - The resolved value from exports \".\".\n * @param field - Which field holds the value parameter.\n * @param value - The value of the \"types\" or \"typings\" field.\n */\nfunction* validateTypeSubpath(\n\tpkgAst: DocumentNode,\n\tsubpaths: string[],\n\tfield: \"types\" | \"typings\",\n\tvalue: string,\n): Generator<Message> {\n\t/* normalize types/typings value to always start with ./ as required by the exports field */\n\tconst normalizedValue = value.startsWith(\"./\") ? value : `./${value}`;\n\n\t/* test if the types value matches one or more subpath export */\n\tif (subpaths.some((it) => it === normalizedValue)) {\n\t\treturn;\n\t}\n\n\tconst { line, column } = jsonLocation(pkgAst, \"member\", field);\n\tyield {\n\t\truleId,\n\t\tseverity,\n\t\tmessage: `\"${field}\" cannot be resolved when respecting \"exports\" field`,\n\t\tline,\n\t\tcolumn,\n\t};\n}\n\n/**\n * Validates the `\"types\"` or `\"typings\"` field against the `\"exports\"` field to\n * ensure all versions of TypeScript can resolve the types.\n *\n * @param pkg - Parsed `package.json\"`.\n * @param pkgAst - JSON syntax tree for the `pkg` parameter.\n */\nexport function* shadowedTypes(pkg: PackageJson, pkgAst: DocumentNode): Generator<Message> {\n\tconst { exports } = pkg;\n\tif (!exports) {\n\t\treturn;\n\t}\n\n\tconst subpaths = getTypesConditions(exports);\n\n\tif (pkg.types) {\n\t\tyield* validateTypeSubpath(pkgAst, subpaths, \"types\", pkg.types);\n\t}\n\n\tif (pkg.typings) {\n\t\tyield* validateTypeSubpath(pkgAst, subpaths, \"typings\", pkg.typings);\n\t}\n}\n", "import { Severity } from \"@html-validate/stylish\";\nimport { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport semver from \"semver\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { jsonLocation } from \"../utils\";\n\nconst ruleId = \"types-node-matching-engine\";\nconst severity = Severity.ERROR;\n\nexport function* typesNodeMatchingEngine(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n): Generator<Message> {\n\tif (!pkg.engines?.node) {\n\t\treturn;\n\t}\n\n\tfor (const source of [\"dependencies\", \"devDependencies\", \"peerDependencies\"] as const) {\n\t\tconst dependencies = pkg[source] ?? {};\n\t\tif (!dependencies[\"@types/node\"]) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst declaredVersion = dependencies[\"@types/node\"];\n\t\tif (declaredVersion === \"latest\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst nodeVersion = semver.minVersion(pkg.engines.node);\n\t\tconst typesVersion = semver.minVersion(declaredVersion);\n\n\t\tif (!nodeVersion || !typesVersion) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typesVersion.major !== nodeVersion.major) {\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"value\", source, \"@types/node\");\n\t\t\tconst actualVersion = `v${String(typesVersion.major)}`;\n\t\t\tconst expectedVersion = `v${String(nodeVersion.major)}`;\n\t\t\tyield {\n\t\t\t\truleId,\n\t\t\t\tseverity,\n\t\t\t\tmessage: `@types/node ${actualVersion} does not equal engines.node ${expectedVersion}`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t};\n\t\t}\n\t}\n}\n", "import semver, { type SemVer } from \"semver\";\nimport { type Message } from \"../message\";\nimport { type PackageJson } from \"../types\";\nimport { isNpmInfoError, npmInfo } from \"../utils\";\n\nconst ruleId = \"invalid-engine-constraint\";\n\nasync function* getDeepDependencies(\n\tpkg: PackageJson,\n\tvisited: Set<string>,\n\tdependency?: string,\n): AsyncGenerator<string> {\n\tif (dependency) {\n\t\tif (visited.has(dependency)) {\n\t\t\treturn;\n\t\t}\n\t\tvisited.add(dependency);\n\t}\n\n\tconst pkgData = dependency ? await npmInfo(dependency, { ignoreUnpublished: true }) : pkg;\n\tif (!pkgData) {\n\t\treturn;\n\t}\n\tfor (let [key, version] of Object.entries(pkgData.dependencies ?? {})) {\n\t\t/* handle npm: prefix */\n\t\tif (version.startsWith(\"npm:\")) {\n\t\t\tconst [newKey, newVersion] = version.slice(\"npm:\".length).split(\"@\", 2);\n\t\t\tkey = newKey; // eslint-disable-line sonarjs/updated-loop-counter -- technical debt\n\t\t\tversion = newVersion; // eslint-disable-line sonarjs/updated-loop-counter -- technical debt\n\t\t}\n\n\t\t/* ignore this as this package is sometimes is present as version \"*\" which\n\t\t * just yields way to many versions to handle causing MaxBuffer errors and\n\t\t * there is another rule to make sure the outermost @types/node package\n\t\t * matches the configured engines */\n\t\tif (key === \"@types/node\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst minVersion = semver.minVersion(version);\n\t\tconst deep = `${key}@${minVersion ? minVersion.version : version}`;\n\n\t\tyield deep;\n\t\tyield* getDeepDependencies(pkg, visited, deep);\n\t}\n}\n\nasync function verifyDependency(\n\tdependency: string,\n\tminDeclared: SemVer,\n\tdeclaredConstraint: string,\n): Promise<Message | null> {\n\tconst pkgData = await npmInfo(dependency, { ignoreUnpublished: true });\n\tif (!pkgData) {\n\t\treturn null;\n\t}\n\tconst constraint = pkgData.engines?.node;\n\tif (!constraint) {\n\t\treturn null;\n\t}\n\n\tif (!semver.satisfies(minDeclared, constraint)) {\n\t\treturn {\n\t\t\truleId,\n\t\t\tseverity: 2,\n\t\t\tmessage: `the transitive dependency \"${dependency}\" (node ${constraint}) does not satisfy the declared node engine \"${declaredConstraint}\"`,\n\t\t\tline: 1,\n\t\t\tcolumn: 1,\n\t\t};\n\t}\n\n\treturn null;\n}\n\nexport async function verifyEngineConstraint(pkg: PackageJson): Promise<Message[]> {\n\tconst declaredConstraint = pkg.engines?.node;\n\tif (!declaredConstraint) {\n\t\treturn [];\n\t}\n\n\tconst minDeclared = semver.minVersion(declaredConstraint);\n\tif (!minDeclared) {\n\t\tthrow new Error(`Failed to parse engine constraint \"${declaredConstraint}\"`);\n\t}\n\n\tconst messages: Message[] = [];\n\tconst visited = new Set<string>();\n\n\tfor await (const dependency of getDeepDependencies(pkg, visited)) {\n\t\ttry {\n\t\t\tconst message = await verifyDependency(dependency, minDeclared, declaredConstraint);\n\t\t\tif (message) {\n\t\t\t\tmessages.push(message);\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tif (isNpmInfoError(err) && err.code === \"E404\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\truleId,\n\t\t\t\t\tseverity: 1,\n\t\t\t\t\tmessage: `the transitive dependency \"${dependency}\" is not published to the NPM registry`,\n\t\t\t\t\tline: 1,\n\t\t\t\t\tcolumn: 1,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\treturn messages;\n}\n", "export class ValidationError extends Error {\n\tpublic validator: string;\n\n\tpublic constructor(validator: string, message: string) {\n\t\tsuper(message);\n\t\tthis.validator = validator;\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nfunction isEmpty(value: unknown): boolean {\n\t/* undefined, null and empty string is considered empty */\n\treturn typeof value === \"undefined\" || value === null || value === \"\";\n}\n\nexport function nonempty(key: string, value: unknown): void {\n\tif (isEmpty(value)) {\n\t\tthrow new ValidationError(nonempty.name, `\"${key}\" must not be empty`);\n\t}\n\n\t/* any number is considered set, even 0 */\n\tif (typeof value === \"number\") {\n\t\treturn;\n\t}\n\n\t/* for arrays the array must be populated and each entry but be non-empty */\n\tif (Array.isArray(value)) {\n\t\tif (value.length === 0) {\n\t\t\tthrow new ValidationError(nonempty.name, `\"${key}\" must not be empty`);\n\t\t}\n\t\t/* eslint-disable-next-line @typescript-eslint/no-for-in-array -- technical debt */\n\t\tfor (const index in value) {\n\t\t\tnonempty(`${key}[${index}]`, value[index]);\n\t\t}\n\t\treturn;\n\t}\n\n\t/* object must have at least one one property set */\n\tif (value && typeof value === \"object\") {\n\t\tconst values = Object.values(value);\n\t\tif (values.length === 0) {\n\t\t\tthrow new ValidationError(nonempty.name, `\"${key}\" must not be empty`);\n\t\t}\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function present(key: string, value: unknown): void {\n\tif (typeof value === \"undefined\" || value === null) {\n\t\tthrow new ValidationError(present.name, `\"${key}\" must be set`);\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function typeArray(key: string, value: unknown): void {\n\tif (!Array.isArray(value)) {\n\t\tthrow new ValidationError(typeArray.name, `\"${key}\" must be array`);\n\t}\n\t/* eslint-disable-next-line @typescript-eslint/no-for-in-array -- technical debt */\n\tfor (const index in value) {\n\t\tif (typeof value[index] !== \"string\") {\n\t\t\tthrow new ValidationError(typeArray.name, `\"${key}[${index}]\" must be string`);\n\t\t}\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function typeString(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(typeString.name, `\"${key}\" must be string`);\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nfunction validateType(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.type\" must be a string`);\n\t}\n\tif (value !== \"git\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.type\" must be \"git\"`);\n\t}\n}\n\nfunction validateUrl(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" must be a string`);\n\t}\n\tif (value.trim() === \"\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" must not be empty`);\n\t}\n\tif (value !== value.trim()) {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}.url\" must not have leading or trailing whitespace`,\n\t\t);\n\t}\n\tconst url = new URL(value);\n\tif (url.protocol === \"git+http:\" || url.protocol === \"http:\") {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}.url\" must use \"git+https://\" instead of \"http://\"`,\n\t\t);\n\t}\n\tif (url.protocol !== \"git+https:\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" must use \"git+https://\" protocol`);\n\t}\n\tif (url.host === \"\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.url\" be a valid url`);\n\t}\n}\n\nfunction validateDirectory(key: string, value: unknown): void {\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}.directory\" must be a string`);\n\t}\n\tif (value.trim() === \"\") {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}.directory\" must be set to non-empty string or the property must be removed`,\n\t\t);\n\t}\n}\n\nexport function validRepoUrl(key: string, value: unknown): void {\n\tif (value === undefined) {\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new ValidationError(\n\t\t\tvalidRepoUrl.name,\n\t\t\t`\"${key}\" must be an object with \"type\" and \"url\"`,\n\t\t);\n\t}\n\tif (\"type\" in value) {\n\t\tvalidateType(key, value.type);\n\t} else {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}\" is missing required \"type\" property`);\n\t}\n\tif (\"url\" in value) {\n\t\tvalidateUrl(key, value.url);\n\t} else {\n\t\tthrow new ValidationError(validRepoUrl.name, `\"${key}\" is missing required \"url\" property`);\n\t}\n\tif (\"directory\" in value) {\n\t\tvalidateDirectory(key, value.directory);\n\t}\n}\n", "import { ValidationError } from \"./validation-error\";\n\nexport function validUrl(key: string, value: unknown): void {\n\tif (typeof value === \"string\" && /^https:\\/\\/.+$/.exec(value)) {\n\t\treturn;\n\t} else if (value && typeof value === \"object\" && \"url\" in value) {\n\t\tvalidUrl(`${key}.url`, value.url);\n\t} else {\n\t\tthrow new ValidationError(validUrl.name, `\"${key}\" must be a valid url (https only)`);\n\t}\n}\n", "import { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type Message } from \"./message\";\nimport { type Result } from \"./result\";\nimport { conflictingTypesTypings } from \"./rules/conflicting-types-typings\";\nimport { deprecatedDependency } from \"./rules/deprecated-dependency\";\nimport { isDisallowedDependency } from \"./rules/disallowed-dependency\";\nimport { exportsTypesOrder } from \"./rules/exports-types-order\";\nimport { isObsoleteDependency } from \"./rules/obsolete-dependency\";\nimport { outdatedEngines } from \"./rules/outdated-engines\";\nimport { preferTypes } from \"./rules/prefer-types\";\nimport { shadowedTypes } from \"./rules/shadowed-types\";\nimport { typesNodeMatchingEngine } from \"./rules/types-node-matching-engine\";\nimport { verifyEngineConstraint } from \"./rules/verify-engine-constraint\";\nimport { type PackageJson } from \"./types\";\nimport { jsonLocation } from \"./utils\";\nimport {\n\tValidationError,\n\tnonempty,\n\tpresent,\n\ttypeArray,\n\ttypeString,\n\tvalidRepoUrl,\n\tvalidUrl,\n} from \"./validators\";\n\nexport interface VerifyPackageJsonOptions {\n\tallowedDependencies: Set<string>;\n\tallowTypesDependencies?: boolean | undefined;\n\tignoreMissingFields?: boolean | undefined;\n\tignoreNodeVersion: boolean | number;\n}\n\ntype validator = (key: string, value: unknown) => void;\n\nconst fields: Record<string, validator[]> = {\n\tdescription: [present, typeString, nonempty],\n\tkeywords: [present, typeArray, nonempty],\n\thomepage: [present, typeString, validUrl],\n\tbugs: [present, validUrl],\n\tlicense: [present, typeString, nonempty],\n\tauthor: [present, nonempty],\n\trepository: [present, validRepoUrl],\n};\n\nfunction verifyFields(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\toptions: VerifyPackageJsonOptions,\n): Message[] {\n\tconst messages: Message[] = [];\n\n\tfor (const [field, validators] of Object.entries(fields)) {\n\t\ttry {\n\t\t\tfor (const validator of validators) {\n\t\t\t\tvalidator(field, pkg[field]);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// istanbul ignore next\n\t\t\tif (!(error instanceof ValidationError)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (error.validator === present.name && options.ignoreMissingFields) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst { line, column } =\n\t\t\t\terror.validator !== present.name\n\t\t\t\t\t? jsonLocation(pkgAst, \"value\", field)\n\t\t\t\t\t: { line: 1, column: 1 };\n\t\t\tif (error instanceof Error) {\n\t\t\t\tmessages.push({\n\t\t\t\t\truleId: \"package-json-fields\",\n\t\t\t\t\tseverity: 2,\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tline,\n\t\t\t\t\tcolumn,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn messages;\n}\n\nfunction getActualDependency(key: string, version: string): string {\n\t/* handle npm: prefix */\n\tif (version.startsWith(\"npm:\")) {\n\t\tconst [name] = version.slice(\"npm:\".length).split(\"@\", 2);\n\t\treturn name;\n\t}\n\n\treturn key;\n}\n\n/* eslint-disable-next-line complexity -- technical debt */\nfunction verifyDependencies(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\toptions: VerifyPackageJsonOptions,\n): Message[] {\n\tconst messages: Message[] = [];\n\tconst { dependencies = {}, devDependencies = {}, peerDependencies = {} } = pkg;\n\n\tfor (const [key, version] of Object.entries(dependencies)) {\n\t\tconst dependency = getActualDependency(key, version);\n\n\t\t/* skip dependencies explicitly allowed by the user */\n\t\tif (options.allowedDependencies.has(dependency)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* skip @types/* if explicitly allowed by user */\n\t\tif (options.allowTypesDependencies && /^@types\\//.exec(dependency)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isDisallowedDependency(pkg, dependency)) {\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", \"dependencies\", key);\n\t\t\tconst name = key === dependency ? `\"${dependency}\"` : `\"${key}\" (\"npm:${dependency}\")`;\n\t\t\tmessages.push({\n\t\t\t\truleId: \"disallowed-dependency\",\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `${name} should be a devDependency`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t});\n\t\t}\n\t}\n\n\tfunction verifyObsolete(\n\t\tdependency: string,\n\t\tsource: \"dependencies\" | \"devDependencies\" | \"peerDependencies\",\n\t): void {\n\t\tconst obsolete = isObsoleteDependency(dependency);\n\t\tif (obsolete) {\n\t\t\tconst { line, column } = jsonLocation(pkgAst, \"member\", source, dependency);\n\t\t\tmessages.push({\n\t\t\t\truleId: \"obsolete-dependency\",\n\t\t\t\tseverity: 2,\n\t\t\t\tmessage: `\"${dependency}\" is obsolete and should no longer be used: ${obsolete.message}`,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const dependency of Object.keys(dependencies)) {\n\t\tverifyObsolete(dependency, \"dependencies\");\n\t}\n\n\tfor (const dependency of Object.keys(devDependencies)) {\n\t\tverifyObsolete(dependency, \"devDependencies\");\n\t}\n\n\tfor (const dependency of Object.keys(peerDependencies)) {\n\t\tverifyObsolete(dependency, \"peerDependencies\");\n\t}\n\n\treturn messages;\n}\n\nexport async function verifyPackageJson(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\tfilePath: string,\n\toptions: VerifyPackageJsonOptions = { allowedDependencies: new Set(), ignoreNodeVersion: false },\n): Promise<Result[]> {\n\tconst { ignoreNodeVersion } = options;\n\n\tconst messages: Message[] = [\n\t\t...conflictingTypesTypings(pkg, pkgAst),\n\t\t...(await deprecatedDependency(pkg, pkgAst, options)),\n\t\t...(await verifyEngineConstraint(pkg)),\n\t\t...exportsTypesOrder(pkg, pkgAst),\n\t\t...verifyFields(pkg, pkgAst, options),\n\t\t...verifyDependencies(pkg, pkgAst, options),\n\t\t...outdatedEngines(pkg, pkgAst, ignoreNodeVersion),\n\t\t...preferTypes(pkg, pkgAst),\n\t\t...shadowedTypes(pkg, pkgAst),\n\t\t...typesNodeMatchingEngine(pkg, pkgAst),\n\t];\n\n\tif (messages.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [\n\t\t{\n\t\t\tmessages,\n\t\t\tfilePath,\n\t\t\terrorCount: messages.filter((it) => it.severity === 2).length,\n\t\t\twarningCount: messages.filter((it) => it.severity === 1).length,\n\t\t\tfixableErrorCount: 0,\n\t\t\tfixableWarningCount: 0,\n\t\t},\n\t];\n}\n", "import { type Result } from \"./result\";\nimport { type TarballMeta, getFileContent } from \"./tarball\";\nimport { type PackageJson } from \"./types\";\n\nfunction getBinaries(pkg: PackageJson): string[] {\n\tif (!pkg.bin) {\n\t\treturn [];\n\t}\n\treturn typeof pkg.bin === \"string\" ? [pkg.bin] : Object.values(pkg.bin);\n}\n\nexport async function verifyShebang(pkg: PackageJson, tarball: TarballMeta): Promise<Result[]> {\n\tconst results: Result[] = [];\n\tconst binaries = getBinaries(pkg);\n\tconst contents = await getFileContent(tarball, binaries);\n\n\tfor (const [filePath, content] of Object.entries(contents)) {\n\t\tconst text = content.toString(\"utf-8\");\n\t\tif (/^#!.+?\\r?\\n/.exec(text)) {\n\t\t\tcontinue;\n\t\t}\n\t\tresults.push({\n\t\t\tmessages: [\n\t\t\t\t{\n\t\t\t\t\truleId: \"no-missing-shebang\",\n\t\t\t\t\tseverity: 2,\n\t\t\t\t\tmessage: `first line must contain shebang to be executable`,\n\t\t\t\t\tline: 1,\n\t\t\t\t\tcolumn: 1,\n\t\t\t\t},\n\t\t\t],\n\t\t\tfilePath,\n\t\t\terrorCount: 1,\n\t\t\twarningCount: 0,\n\t\t\tfixableErrorCount: 0,\n\t\t\tfixableWarningCount: 0,\n\t\t});\n\t}\n\n\treturn results;\n}\n", "import { type DocumentNode } from \"@humanwhocodes/momoa\";\nimport { type VerifyPackageJsonOptions, verifyPackageJson } from \"./package-json\";\nimport { type Result } from \"./result\";\nimport { verifyShebang } from \"./shebang\";\nimport { type TarballMeta, verifyTarball } from \"./tarball\";\nimport { type PackageJson } from \"./types\";\n\nexport type VerifyOptions = VerifyPackageJsonOptions;\n\nexport async function verify(\n\tpkg: PackageJson,\n\tpkgAst: DocumentNode,\n\tpkgPath: string,\n\ttarball: TarballMeta,\n\toptions: VerifyOptions,\n): Promise<Result[]> {\n\treturn [\n\t\t...(await verifyTarball(pkg, tarball)),\n\t\t...(await verifyPackageJson(pkg, pkgAst, pkgPath, options)),\n\t\t...(await verifyShebang(pkg, tarball)),\n\t];\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A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,KAAK;AACT,YAAQ,MAAM,+EAA+E;AAC7F,YAAQ,WAAW;AACnB;AAAA,EACD;AAEA,QAAM,UAAuB;AAAA,IAC5B,UAAU,KAAK,WAAW,gBAAgB,KAAK,OAAO;AAAA,IACtD,YAAY,uBAAuB,GAAG,IAAI,IAAI,IAAI,IAAI,OAAO,SAAS;AAAA,EACvE;AACA,MAAI,CAAC,WAAW,QAAQ,QAAQ,GAAG;AAClC,YAAQ,MAAM,IAAI,QAAQ,QAAQ,sDAAsD;AACxF,YAAQ,WAAW;AACnB;AAAA,EACD;AAEA,iBAAe,IAAI,IAAI;AAEvB,QAAM,UAAyB;AAAA,IAC9B,qBAAAA;AAAA,IACA,wBAAwB,KAAK;AAAA,IAC7B,qBAAqB,KAAK;AAAA,IAC1B,mBAAmB,KAAK;AAAA,EACzB;AAEA,QAAM,UAAU,MAAM,OAAO,KAAK,QAAQ,SAAS,SAAS,OAAO;AAEnE,aAAW,UAAU,SAAS;AAC7B,WAAO,SAAS,KAAK,CAAC,GAAG,MAAM;AAC9B,UAAI,EAAE,SAAS,EAAE,MAAM;AACtB,eAAO,EAAE,OAAO,EAAE;AAAA,MACnB,OAAO;AACN,eAAO,EAAE,SAAS,EAAE;AAAA,MACrB;AAAA,IACD,CAAC;AAAA,EACF;AAEA,QAAM,SAAS,QAAQ,OAAO;AAC9B,UAAQ,OAAO,MAAM,MAAM;AAE3B,QAAM,cAAc,QAAQ,OAAO,CAAC,KAAK,WAAW;AACnD,WAAO,MAAM,OAAO;AAAA,EACrB,GAAG,CAAC;AAEJ,UAAQ,WAAW,cAAc,IAAI,IAAI;AAC1C;AAEA,IAAI,EAAE,MAAM,CAAC,QAAiB;AAC7B,UAAQ,MAAM,GAAG;AACjB,UAAQ,WAAW;AACpB,CAAC;",
6
6
  "names": ["name", "indent", "assert", "fs", "path", "name", "renames", "key", "prefix", "lines", "version", "args", "action", "ArgumentParser", "start_index", "option_string", "arg_strings", "match", "fs", "os", "path", "crypto", "name", "err", "basename", "dir", "code", "name", "version", "match", "parse", "version", "parse", "version", "parse", "version", "version", "parse", "prefix", "parse", "version", "list", "list", "parse", "version", "match", "cache", "version", "version", "version", "require_valid", "version", "version", "version", "version", "require_semver", "constants", "parse", "fs", "path", "fileURLToPath", "__commonJS", "init", "__toESM", "reset", "bold", "dim", "underline", "yellow", "red", "Severity", "table", "name", "types", "path", "process", "run", "process", "fileURLToPath", "toPath", "name", "directory", "path", "toPath", "name", "path", "regexp", "regexp", "regexp", "regexp", "regexp", "regexp", "regexp", "regexp", "regexp", "name", "filename", "fs", "fs", "p", "ret", "res", "fs", "path", "path", "fs", "parse", "EE", "Buffer", "EventEmitter", "Stream", "StringDecoder", "proc", "isStream", "Minipass", "isReadable", "isWritable", "EOF", "MAYBE_EMIT_END", "EMITTED_END", "EMITTING_END", "EMITTED_ERROR", "CLOSED", "READ", "FLUSH", "FLUSHCHUNK", "ENCODING", "DECODER", "FLOWING", "PAUSED", "RESUME", "BUFFER", "PIPES", "BUFFERLENGTH", "BUFFERPUSH", "BUFFERSHIFT", "OBJECTMODE", "DESTROYED", "ERROR", "EMITDATA", "EMITEND", "EMITEND2", "ASYNC", "ABORT", "ABORTED", "SIGNAL", "DATALISTENERS", "DISCARDED", "defer", "nodefer", "isEndish", "isArrayBufferLike", "isArrayBufferView", "Pipe", "PipeProxyErrors", "isObjectModeOptions", "isEncodingOptions", "p", "ret", "res", "realZlib", "Buffer", "Minipass", "realZlib", "parse", "prefix", "path", "parse", "EventEmitter", "Stream", "StringDecoder", "proc", "isStream", "Minipass", "isReadable", "isWritable", "EOF", "MAYBE_EMIT_END", "EMITTED_END", "EMITTING_END", "EMITTED_ERROR", "CLOSED", "READ", "FLUSH", "FLUSHCHUNK", "ENCODING", "DECODER", "FLOWING", "PAUSED", "RESUME", "BUFFER", "PIPES", "BUFFERLENGTH", "BUFFERPUSH", "BUFFERSHIFT", "OBJECTMODE", "DESTROYED", "ERROR", "EMITDATA", "EMITEND", "EMITEND2", "ASYNC", "ABORT", "ABORTED", "SIGNAL", "DATALISTENERS", "DISCARDED", "defer", "nodefer", "isEndish", "isArrayBufferLike", "isArrayBufferView", "Pipe", "PipeProxyErrors", "isObjectModeOptions", "isEncodingOptions", "p", "ret", "res", "Minipass", "code", "BUFFER", "ABORTED", "noop", "EE", "code", "chunk", "ret", "parse", "fs", "pos", "fs", "fs", "path", "parse", "path", "encode", "s", "path", "prefix", "READ", "Minipass", "code", "fs", "pos", "list", "Node", "path", "path", "EOF", "ENDED", "QUEUE", "PROCESS", "ONDRAIN", "Minipass", "fs", "stat", "code", "path", "fs", "assert", "fs", "path", "fs", "platform", "fs", "path", "er", "fs", "path", "path", "code", "path", "fs", "er", "path", "code", "created", "s", "platform", "isWindows", "path", "fn", "FILE", "DIRECTORY", "SYMLINK", "HARDLINK", "ENDED", "platform", "isWindows", "path", "fs", "name", "code", "encode", "assert", "er", "checkCwd", "fs", "fs", "path", "fs", "addFilesSync", "pos", "er", "addFilesAsync", "path", "path", "filename", "path", "fs", "path", "normalize", "name", "fs", "path", "filename", "directory", "process", "raw", "path", "fileURLToPath", "process", "once", "process", "fs", "path", "process", "extension", "process", "process", "once", "iterator", "index", "spawn", "file", "second", "third", "cache", "spawn", "code", "ruleId", "ruleId", "version", "semver", "allowedDependencies", "name", "scope", "prefix", "list", "ruleId", "severity", "path", "import_semver", "ruleId", "severity", "line", "column", "semver", "version", "ruleId", "severity", "ruleId", "severity", "types", "import_semver", "ruleId", "severity", "semver", "import_semver", "ruleId", "version", "semver", "version", "name", "obsolete", "fileURLToPath", "tmp", "path", "err", "fs", "allowedDependencies"]
7
7
  }