From 3b1499c9714c14a8f7b5282366f18774b53acaff Mon Sep 17 00:00:00 2001 From: Richard Lau Date: Tue, 26 Oct 2021 14:19:41 -0400 Subject: [PATCH 001/118] doc: update CHANGELOG.md for Node.js 16.13.0 Update missed changes for the main CHANGELOG.md for Node.js 16.13.0. PR-URL: https://github.com/nodejs/node/pull/40617 Refs: https://github.com/nodejs/node/pull/40536 Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb1e8497c1723a..c74234918300fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,13 +27,14 @@ release. - + '); - }, - - tableData() { - /** @type {number} */ - // @ts-expect-error Custom. - const column = this.getData('tableColumn'); // @ts-expect-error Custom. - - if (column in this.getData('tableAlign')) { - this.tag(''); - this.setData('tableColumn', column + 1); - } else { - // Stop capturing. - this.resume(); - } - }, - - tableHead() { - this.lineEndingIfNeeded(); - this.tag(''); - this.setData('slurpOneLineEnding', true); // Slurp the line ending from the delimiter row. - }, - - tableHeader() { - this.tag(''); // @ts-expect-error Custom. - - this.setData('tableColumn', this.getData('tableColumn') + 1); - }, - - tableRow() { - /** @type {Align[]} */ - // @ts-expect-error Custom. - const align = this.getData('tableAlign'); - /** @type {number} */ - // @ts-expect-error Custom. - - let column = this.getData('tableColumn'); - - while (column < align.length) { - this.lineEndingIfNeeded(); // @ts-expect-error `null` is fine as an index. - - this.tag(''); - column++; - } - - this.setData('tableColumn', column); - this.lineEndingIfNeeded(); - this.tag(''); - } - } -}; -/** - * @param {string} $0 - * @param {string} $1 - * @returns {string} - */ - -function replace$1($0, $1) { - // Pipes work, backslashes don’t (but can’t escape pipes). - return $1 === '|' ? $1 : $0 -} - /** * @typedef {import('micromark-util-types').Extension} Extension * @typedef {import('micromark-util-types').Resolver} Resolver @@ -15601,74 +15629,6 @@ function tokenizeNextPrefixedOrBlank(effects, ok, nok) { } } -/** - * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension - * @typedef {import('micromark-util-types').Token} Token - * @typedef {import('micromark-util-types').CompileContext} CompileContext - */ - -/** - * An opening or closing tag, followed by a case-insensitive specific tag name, - * followed by HTML whitespace, a greater than, or a slash. - */ -const reFlow = - /<(\/?)(iframe|noembed|noframes|plaintext|script|style|title|textarea|xmp)(?=[\t\n\f\r />])/gi; - -/** - * As HTML (text) parses tags separately (and v. strictly), we don’t need to be - * global. - */ -const reText = new RegExp('^' + reFlow.source, 'i'); - -/** @type {HtmlExtension} */ -const gfmTagfilterHtml = { - exit: { - htmlFlowData(token) { - exitHtmlData.call(this, token, reFlow); - }, - htmlTextData(token) { - exitHtmlData.call(this, token, reText); - } - } -}; - -/** - * @this {CompileContext} - * @param {Token} token - * @param {RegExp} filter - */ -function exitHtmlData(token, filter) { - let value = this.sliceSerialize(token); - - if (this.options.allowDangerousHtml) { - value = value.replace(filter, '<$1$2'); - } - - this.raw(this.encode(value)); -} - -/** - * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension - */ - -/** @type {HtmlExtension} */ -const gfmTaskListItemHtml = { - enter: { - taskListCheck() { - this.tag(''); - }, - - taskListCheckValueChecked() { - this.tag('checked="" '); - } - } -}; - /** * @typedef {import('micromark-util-types').Extension} Extension * @typedef {import('micromark-util-types').ConstructRecord} ConstructRecord @@ -15770,6 +15730,7 @@ function spaceThenNonSpace(effects, ok, nok) { * @typedef {import('micromark-util-types').Extension} Extension * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options + * @typedef {import('micromark-extension-gfm-footnote').HtmlOptions} HtmlOptions */ /** @@ -15781,21 +15742,13 @@ function spaceThenNonSpace(effects, ok, nok) { function gfm(options) { return combineExtensions([ gfmAutolinkLiteral, + gfmFootnote(), gfmStrikethrough(options), gfmTable, gfmTaskListItem ]) } -/** @type {HtmlExtension} */ -combineHtmlExtensions([ - gfmAutolinkLiteralHtml, - gfmStrikethroughHtml, - gfmTableHtml, - gfmTagfilterHtml, - gfmTaskListItemHtml -]); - /** * Get the total count of `character` in `value`. * @@ -16454,6 +16407,174 @@ function previous(match, email) { ) } +/** + * @typedef {import('mdast').FootnoteReference} FootnoteReference + * @typedef {import('mdast').FootnoteDefinition} FootnoteDefinition + * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension + * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle + * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension + * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle + * @typedef {import('mdast-util-to-markdown').Map} Map + */ + +let warningColonInFootnote = false; +let warningListInFootnote = false; + +/** + * @returns {FromMarkdownExtension} + */ +function gfmFootnoteFromMarkdown() { + return { + enter: { + gfmFootnoteDefinition: enterFootnoteDefinition, + gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString, + gfmFootnoteCall: enterFootnoteCall, + gfmFootnoteCallString: enterFootnoteCallString + }, + exit: { + gfmFootnoteDefinition: exitFootnoteDefinition, + gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString, + gfmFootnoteCall: exitFootnoteCall, + gfmFootnoteCallString: exitFootnoteCallString + } + } + + /** @type {FromMarkdownHandle} */ + function enterFootnoteDefinition(token) { + this.enter( + {type: 'footnoteDefinition', identifier: '', label: '', children: []}, + token + ); + } + + /** @type {FromMarkdownHandle} */ + function enterFootnoteDefinitionLabelString() { + this.buffer(); + } + + /** @type {FromMarkdownHandle} */ + function exitFootnoteDefinitionLabelString(token) { + const label = this.resume(); + const node = /** @type {FootnoteDefinition} */ ( + this.stack[this.stack.length - 1] + ); + node.label = label; + node.identifier = normalizeIdentifier( + this.sliceSerialize(token) + ).toLowerCase(); + } + + /** @type {FromMarkdownHandle} */ + function exitFootnoteDefinition(token) { + this.exit(token); + } + + /** @type {FromMarkdownHandle} */ + function enterFootnoteCall(token) { + this.enter({type: 'footnoteReference', identifier: '', label: ''}, token); + } + + /** @type {FromMarkdownHandle} */ + function enterFootnoteCallString() { + this.buffer(); + } + + /** @type {FromMarkdownHandle} */ + function exitFootnoteCallString(token) { + const label = this.resume(); + const node = /** @type {FootnoteDefinition} */ ( + this.stack[this.stack.length - 1] + ); + node.label = label; + node.identifier = normalizeIdentifier( + this.sliceSerialize(token) + ).toLowerCase(); + } + + /** @type {FromMarkdownHandle} */ + function exitFootnoteCall(token) { + this.exit(token); + } +} + +/** + * @returns {ToMarkdownExtension} + */ +function gfmFootnoteToMarkdown() { + footnoteReference.peek = footnoteReferencePeek; + + return { + // This is on by default already. + unsafe: [{character: '[', inConstruct: ['phrasing', 'label', 'reference']}], + handlers: {footnoteDefinition, footnoteReference} + } + + /** + * @type {ToMarkdownHandle} + * @param {FootnoteReference} node + */ + function footnoteReference(node, _, context) { + const exit = context.enter('footnoteReference'); + const subexit = context.enter('reference'); + const reference = safe(context, association(node), { + before: '^', + after: ']' + }); + subexit(); + exit(); + return '[^' + reference + ']' + } + + /** @type {ToMarkdownHandle} */ + function footnoteReferencePeek() { + return '[' + } + + /** + * @type {ToMarkdownHandle} + * @param {FootnoteDefinition} node + */ + function footnoteDefinition(node, _, context) { + const exit = context.enter('footnoteDefinition'); + const subexit = context.enter('label'); + const id = safe(context, association(node), {before: '^', after: ']'}); + const label = '[^' + id + ']:'; + subexit(); + const value = indentLines(containerFlow(node, context), map); + exit(); + + if (!warningColonInFootnote && id.includes(':')) { + console.warn( + '[mdast-util-gfm-footnote] Warning: Found a colon in footnote identifier `' + + id + + '`. GitHub currently crahes on colons in footnotes (see for more info)' + ); + warningColonInFootnote = true; + } + + if (!warningListInFootnote) { + visit$1(node, 'list', () => { + console.warn( + '[mdast-util-gfm-footnote] Warning: Found a list in a footnote definition. GitHub currently crahes on lists in footnotes (see for more info)' + ); + warningListInFootnote = true; + return EXIT$1 + }); + } + + return value + + /** @type {Map} */ + function map(line, index, blank) { + if (index) { + return (blank ? '' : ' ') + line + } + + return (blank ? label : label + ' ') + line + } + } +} + /** * @typedef {import('mdast').Delete} Delete * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension @@ -17110,14 +17231,17 @@ function listItemWithTaskListItem(node, parent, context) { */ /** - * @type {Array.} + * @returns {Array.} */ -const gfmFromMarkdown = [ - gfmAutolinkLiteralFromMarkdown, - gfmStrikethroughFromMarkdown, - gfmTableFromMarkdown, - gfmTaskListItemFromMarkdown -]; +function gfmFromMarkdown() { + return [ + gfmAutolinkLiteralFromMarkdown, + gfmFootnoteFromMarkdown(), + gfmStrikethroughFromMarkdown, + gfmTableFromMarkdown, + gfmTaskListItemFromMarkdown + ] +} /** * @param {Options} [options] @@ -17127,6 +17251,7 @@ function gfmToMarkdown(options) { return { extensions: [ gfmAutolinkLiteralToMarkdown, + gfmFootnoteToMarkdown(), gfmStrikethroughToMarkdown, gfmTableToMarkdown(options), gfmTaskListItemToMarkdown @@ -17148,7 +17273,7 @@ function remarkGfm(options = {}) { const data = this.data(); add('micromarkExtensions', gfm(options)); - add('fromMarkdownExtensions', gfmFromMarkdown); + add('fromMarkdownExtensions', gfmFromMarkdown()); add('toMarkdownExtensions', gfmToMarkdown(options)); /** @@ -27397,8 +27522,17 @@ function testProhibited (val, content) { } let regexpString = '(? escapeStringRegexp(a)).join('|'); + ignoreNextTo = `(?:${parts})`; + } else { + ignoreNextTo = escapeStringRegexp(val.ignoreNextTo); + } + } else { + ignoreNextTo = ''; + } const replaceCaptureGroups = !!val.replaceCaptureGroups; // If it starts with a letter, make sure it is a word break. @@ -28211,12 +28345,6 @@ var remarkLintUnorderedListMarkerStyle$1 = remarkLintUnorderedListMarkerStyle; // @see https://github.com/nodejs/node/blob/HEAD/doc/guides/doc-style-guide.md -// Remove remark-lint-no-auto-link-without-protocol -remarkPresetLintRecommended$1.plugins = - remarkPresetLintRecommended$1.plugins.filter( - (fn) => fn.name !== "remark-lint:no-auto-link-without-protocol" - ); - // Add in rules alphabetically after Gfm and PresetLintRecommended. const plugins = [ remarkGfm, diff --git a/tools/lint-md/package-lock.json b/tools/lint-md/package-lock.json index 4525157c8bf8af..75e4ea906e72b5 100644 --- a/tools/lint-md/package-lock.json +++ b/tools/lint-md/package-lock.json @@ -9,8 +9,8 @@ "version": "1.0.0", "dependencies": { "remark-parse": "^10.0.0", - "remark-preset-lint-node": "^3.0.1", - "remark-stringify": "^10.0.0", + "remark-preset-lint-node": "^3.3.0", + "remark-stringify": "^10.0.1", "to-vfile": "^7.2.2", "unified": "^10.1.0", "vfile-reporter": "^7.0.2" @@ -621,11 +621,12 @@ } }, "node_modules/mdast-util-gfm": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-1.0.0.tgz", - "integrity": "sha512-JY4qImsTqivQ0Gl3qvdaizCpomFaNrHnjEhNjNNKeNEA5jZHAJDYu1+yO4V9jn4/ti8GrKdAScaT4F71knoxsA==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-2.0.0.tgz", + "integrity": "sha512-wMwejlTN3EQADPFuvxe8lmGsay3+f6gSJKdAHR6KBJzpcxvsjJSILB9K6u6G7eQLC7iOTyVIHYGui9uBc9r1Tg==", "dependencies": { "mdast-util-gfm-autolink-literal": "^1.0.0", + "mdast-util-gfm-footnote": "^1.0.0", "mdast-util-gfm-strikethrough": "^1.0.0", "mdast-util-gfm-table": "^1.0.0", "mdast-util-gfm-task-list-item": "^1.0.0" @@ -650,6 +651,21 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/mdast-util-gfm-footnote": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-1.0.0.tgz", + "integrity": "sha512-qeg9YoS2YYP6OBmMyUFxKXb6BLwAsbGidIxgwDAXHIMYZQhIwe52L9BSJs+zP29Jp5nSERPkmG3tSwAN23/ZbQ==", + "dependencies": { + "@types/mdast": "^3.0.0", + "mdast-util-to-markdown": "^1.0.0", + "micromark-util-normalize-identifier": "^1.0.0", + "unist-util-visit": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/mdast-util-gfm-strikethrough": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-1.0.0.tgz", @@ -808,11 +824,12 @@ } }, "node_modules/micromark-extension-gfm": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-1.0.0.tgz", - "integrity": "sha512-OjqbQPL1Vec/4l5hnC8WnMNmWwgrT9JvzR2udqIGrGKecZsdwY9GAWZ5482CuD12SXuHNj8aS8epni6ip0Pwog==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-2.0.0.tgz", + "integrity": "sha512-yYPlZ48Ss8fRFSmlQP/QXt3/M6tEvawEVFO+jDPnFA3mGeVgzIyaeHgrIV/9AMFAjQhctKA47Bk8xBhcuaL74Q==", "dependencies": { "micromark-extension-gfm-autolink-literal": "^1.0.0", + "micromark-extension-gfm-footnote": "^1.0.0", "micromark-extension-gfm-strikethrough": "^1.0.0", "micromark-extension-gfm-table": "^1.0.0", "micromark-extension-gfm-tagfilter": "^1.0.0", @@ -841,6 +858,24 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/micromark-extension-gfm-footnote": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-1.0.2.tgz", + "integrity": "sha512-C6o+B7w1wDM4JjDJeHCTszFYF1q46imElNY6mfXsBfw4E91M9TvEEEt3sy0FbJmGVzdt1pqFVRYWT9ZZ0FjFuA==", + "dependencies": { + "micromark-core-commonmark": "^1.0.0", + "micromark-factory-space": "^1.0.0", + "micromark-util-character": "^1.0.0", + "micromark-util-normalize-identifier": "^1.0.0", + "micromark-util-sanitize-uri": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "uvu": "^0.5.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/micromark-extension-gfm-strikethrough": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-1.0.3.tgz", @@ -1344,13 +1379,13 @@ } }, "node_modules/remark-gfm": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-2.0.0.tgz", - "integrity": "sha512-waIv4Tjcd2CTUDxKRYzuPyIHw1FoX4H2GjXAzXV9PxQWb+dU4fJivd/FZ+nxyzPARrqTjMIkwIwPoWNbpBhjcQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-3.0.0.tgz", + "integrity": "sha512-CXJw5h1iwUW6czFwi4tveoOSlsEZU44hcdNzUxC5uiNi7r/OQySf46AoEihM8/NwBbW1LcsnyGIsHBnbURFw2g==", "dependencies": { "@types/mdast": "^3.0.0", - "mdast-util-gfm": "^1.0.0", - "micromark-extension-gfm": "^1.0.0", + "mdast-util-gfm": "^2.0.0", + "micromark-extension-gfm": "^2.0.0", "unified": "^10.0.0" }, "funding": { @@ -1975,9 +2010,9 @@ } }, "node_modules/remark-lint-prohibited-strings": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/remark-lint-prohibited-strings/-/remark-lint-prohibited-strings-3.0.0.tgz", - "integrity": "sha512-Aw21KVeoOiDte6dNfeTfTgjKV19yWXpPjLxfJ3ShC22/r97gkGdOo4dnuwyEEAfKhr3uimtSf3rRQyGSudY5tQ==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/remark-lint-prohibited-strings/-/remark-lint-prohibited-strings-3.1.0.tgz", + "integrity": "sha512-zwfDDdYl7ye0gEHcwhdkv1ZGXj1ibw4gnLLZkkvySnDdTz2tshY3fOJLY5NikbVseaIRVGOr5qa+8J9WNQT/fA==", "dependencies": { "escape-string-regexp": "^5.0.0", "unified-lint-rule": "^2.0.0", @@ -2099,12 +2134,12 @@ } }, "node_modules/remark-preset-lint-node": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/remark-preset-lint-node/-/remark-preset-lint-node-3.2.0.tgz", - "integrity": "sha512-FWKZOVYiiAd9eRMvcjlJihatuXnzfgD/PEO1Oc8+USZe/3MFH3HcUCsUvoymalJ0YM++ekKTQEYrhsFYtk4PIQ==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/remark-preset-lint-node/-/remark-preset-lint-node-3.3.0.tgz", + "integrity": "sha512-JPjXould+7VTpwj+YJHSoPiGwKLpmLAZJRveU/dT7mCDOdSSORe/SGo9fJDm6owUReg50b5AG2AY8nlReytHcA==", "dependencies": { "js-yaml": "^4.0.0", - "remark-gfm": "^2.0.0", + "remark-gfm": "^3.0.0", "remark-lint-blockquote-indentation": "^3.0.0", "remark-lint-checkbox-character-style": "^4.0.0", "remark-lint-checkbox-content-indent": "^4.0.0", @@ -2134,7 +2169,7 @@ "remark-lint-table-cell-padding": "^4.0.0", "remark-lint-table-pipes": "^4.0.0", "remark-lint-unordered-list-marker-style": "^3.0.0", - "remark-preset-lint-recommended": "^6.0.0", + "remark-preset-lint-recommended": "^6.1.1", "semver": "^7.3.2", "unified-lint-rule": "^2.0.0", "unist-util-visit": "^4.1.0" @@ -2172,9 +2207,9 @@ } }, "node_modules/remark-stringify": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-10.0.0.tgz", - "integrity": "sha512-3LAQqJ/qiUxkWc7fUcVuB7RtIT38rvmxfmJG8z1TiE/D8zi3JGQ2tTcTJu9Tptdpb7gFwU0whRi5q1FbFOb9yA==", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-10.0.1.tgz", + "integrity": "sha512-380vOu9EHqRTDhI9RlPU2EKY1abUDEmxw9fW7pJ/8Jr1izk0UcdnZB30qiDDRYi6pGn5FnVf9Wd2iUeCWTqM7Q==", "dependencies": { "@types/mdast": "^3.0.0", "mdast-util-to-markdown": "^1.0.0", @@ -3027,11 +3062,12 @@ } }, "mdast-util-gfm": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-1.0.0.tgz", - "integrity": "sha512-JY4qImsTqivQ0Gl3qvdaizCpomFaNrHnjEhNjNNKeNEA5jZHAJDYu1+yO4V9jn4/ti8GrKdAScaT4F71knoxsA==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-2.0.0.tgz", + "integrity": "sha512-wMwejlTN3EQADPFuvxe8lmGsay3+f6gSJKdAHR6KBJzpcxvsjJSILB9K6u6G7eQLC7iOTyVIHYGui9uBc9r1Tg==", "requires": { "mdast-util-gfm-autolink-literal": "^1.0.0", + "mdast-util-gfm-footnote": "^1.0.0", "mdast-util-gfm-strikethrough": "^1.0.0", "mdast-util-gfm-table": "^1.0.0", "mdast-util-gfm-task-list-item": "^1.0.0" @@ -3048,6 +3084,17 @@ "micromark-util-character": "^1.0.0" } }, + "mdast-util-gfm-footnote": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-1.0.0.tgz", + "integrity": "sha512-qeg9YoS2YYP6OBmMyUFxKXb6BLwAsbGidIxgwDAXHIMYZQhIwe52L9BSJs+zP29Jp5nSERPkmG3tSwAN23/ZbQ==", + "requires": { + "@types/mdast": "^3.0.0", + "mdast-util-to-markdown": "^1.0.0", + "micromark-util-normalize-identifier": "^1.0.0", + "unist-util-visit": "^4.0.0" + } + }, "mdast-util-gfm-strikethrough": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-1.0.0.tgz", @@ -3158,11 +3205,12 @@ } }, "micromark-extension-gfm": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-1.0.0.tgz", - "integrity": "sha512-OjqbQPL1Vec/4l5hnC8WnMNmWwgrT9JvzR2udqIGrGKecZsdwY9GAWZ5482CuD12SXuHNj8aS8epni6ip0Pwog==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-2.0.0.tgz", + "integrity": "sha512-yYPlZ48Ss8fRFSmlQP/QXt3/M6tEvawEVFO+jDPnFA3mGeVgzIyaeHgrIV/9AMFAjQhctKA47Bk8xBhcuaL74Q==", "requires": { "micromark-extension-gfm-autolink-literal": "^1.0.0", + "micromark-extension-gfm-footnote": "^1.0.0", "micromark-extension-gfm-strikethrough": "^1.0.0", "micromark-extension-gfm-table": "^1.0.0", "micromark-extension-gfm-tagfilter": "^1.0.0", @@ -3183,6 +3231,20 @@ "uvu": "^0.5.0" } }, + "micromark-extension-gfm-footnote": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-1.0.2.tgz", + "integrity": "sha512-C6o+B7w1wDM4JjDJeHCTszFYF1q46imElNY6mfXsBfw4E91M9TvEEEt3sy0FbJmGVzdt1pqFVRYWT9ZZ0FjFuA==", + "requires": { + "micromark-core-commonmark": "^1.0.0", + "micromark-factory-space": "^1.0.0", + "micromark-util-character": "^1.0.0", + "micromark-util-normalize-identifier": "^1.0.0", + "micromark-util-sanitize-uri": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "uvu": "^0.5.0" + } + }, "micromark-extension-gfm-strikethrough": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-1.0.3.tgz", @@ -3458,13 +3520,13 @@ "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==" }, "remark-gfm": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-2.0.0.tgz", - "integrity": "sha512-waIv4Tjcd2CTUDxKRYzuPyIHw1FoX4H2GjXAzXV9PxQWb+dU4fJivd/FZ+nxyzPARrqTjMIkwIwPoWNbpBhjcQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-3.0.0.tgz", + "integrity": "sha512-CXJw5h1iwUW6czFwi4tveoOSlsEZU44hcdNzUxC5uiNi7r/OQySf46AoEihM8/NwBbW1LcsnyGIsHBnbURFw2g==", "requires": { "@types/mdast": "^3.0.0", - "mdast-util-gfm": "^1.0.0", - "micromark-extension-gfm": "^1.0.0", + "mdast-util-gfm": "^2.0.0", + "micromark-extension-gfm": "^2.0.0", "unified": "^10.0.0" } }, @@ -3939,9 +4001,9 @@ } }, "remark-lint-prohibited-strings": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/remark-lint-prohibited-strings/-/remark-lint-prohibited-strings-3.0.0.tgz", - "integrity": "sha512-Aw21KVeoOiDte6dNfeTfTgjKV19yWXpPjLxfJ3ShC22/r97gkGdOo4dnuwyEEAfKhr3uimtSf3rRQyGSudY5tQ==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/remark-lint-prohibited-strings/-/remark-lint-prohibited-strings-3.1.0.tgz", + "integrity": "sha512-zwfDDdYl7ye0gEHcwhdkv1ZGXj1ibw4gnLLZkkvySnDdTz2tshY3fOJLY5NikbVseaIRVGOr5qa+8J9WNQT/fA==", "requires": { "escape-string-regexp": "^5.0.0", "unified-lint-rule": "^2.0.0", @@ -4035,12 +4097,12 @@ } }, "remark-preset-lint-node": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/remark-preset-lint-node/-/remark-preset-lint-node-3.2.0.tgz", - "integrity": "sha512-FWKZOVYiiAd9eRMvcjlJihatuXnzfgD/PEO1Oc8+USZe/3MFH3HcUCsUvoymalJ0YM++ekKTQEYrhsFYtk4PIQ==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/remark-preset-lint-node/-/remark-preset-lint-node-3.3.0.tgz", + "integrity": "sha512-JPjXould+7VTpwj+YJHSoPiGwKLpmLAZJRveU/dT7mCDOdSSORe/SGo9fJDm6owUReg50b5AG2AY8nlReytHcA==", "requires": { "js-yaml": "^4.0.0", - "remark-gfm": "^2.0.0", + "remark-gfm": "^3.0.0", "remark-lint-blockquote-indentation": "^3.0.0", "remark-lint-checkbox-character-style": "^4.0.0", "remark-lint-checkbox-content-indent": "^4.0.0", @@ -4070,7 +4132,7 @@ "remark-lint-table-cell-padding": "^4.0.0", "remark-lint-table-pipes": "^4.0.0", "remark-lint-unordered-list-marker-style": "^3.0.0", - "remark-preset-lint-recommended": "^6.0.0", + "remark-preset-lint-recommended": "^6.1.1", "semver": "^7.3.2", "unified-lint-rule": "^2.0.0", "unist-util-visit": "^4.1.0" @@ -4101,9 +4163,9 @@ } }, "remark-stringify": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-10.0.0.tgz", - "integrity": "sha512-3LAQqJ/qiUxkWc7fUcVuB7RtIT38rvmxfmJG8z1TiE/D8zi3JGQ2tTcTJu9Tptdpb7gFwU0whRi5q1FbFOb9yA==", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-10.0.1.tgz", + "integrity": "sha512-380vOu9EHqRTDhI9RlPU2EKY1abUDEmxw9fW7pJ/8Jr1izk0UcdnZB30qiDDRYi6pGn5FnVf9Wd2iUeCWTqM7Q==", "requires": { "@types/mdast": "^3.0.0", "mdast-util-to-markdown": "^1.0.0", diff --git a/tools/lint-md/package.json b/tools/lint-md/package.json index a6c883f9882c85..6b3e48c4671817 100644 --- a/tools/lint-md/package.json +++ b/tools/lint-md/package.json @@ -7,8 +7,8 @@ }, "dependencies": { "remark-parse": "^10.0.0", - "remark-preset-lint-node": "^3.0.1", - "remark-stringify": "^10.0.0", + "remark-preset-lint-node": "^3.3.0", + "remark-stringify": "^10.0.1", "to-vfile": "^7.2.2", "unified": "^10.1.0", "vfile-reporter": "^7.0.2" From 996bc6e840aac137772083808ccaa51e2fbfba21 Mon Sep 17 00:00:00 2001 From: Brian White Date: Mon, 11 Oct 2021 19:26:49 -0400 Subject: [PATCH 013/118] benchmark: increase crypto DSA keygen params MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenSSL 3.0 increased the minimum values for these parameters. PR-URL: https://github.com/nodejs/node/pull/40416 Fixes: https://github.com/nodejs/node/issues/40410 Reviewed-By: Luigi Pinca Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen Reviewed-By: Richard Lau Reviewed-By: Zijian Liu --- benchmark/crypto/keygen.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/benchmark/crypto/keygen.js b/benchmark/crypto/keygen.js index e055a02cd2b116..373be24c80e5ab 100644 --- a/benchmark/crypto/keygen.js +++ b/benchmark/crypto/keygen.js @@ -43,8 +43,8 @@ const methods = { bench.start(); for (let i = 0; i < n; ++i) { generateKeyPairSync('dsa', { - modulusLength: 512, - divisorLength: 256, + modulusLength: 1024, + divisorLength: 160, }); } bench.end(n); @@ -60,8 +60,8 @@ const methods = { bench.start(); for (let i = 0; i < n; ++i) generateKeyPair('dsa', { - modulusLength: 512, - divisorLength: 256, + modulusLength: 1024, + divisorLength: 160, }, done); }, }; From 2a2b549a2834d8032dcbe826cc7dce0b76eca84e Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 15 Oct 2021 06:17:24 -0700 Subject: [PATCH 014/118] meta: consolidate AUTHORS entries for emanuelbuholzer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40469 Reviewed-By: Luigi Pinca Reviewed-By: Tobias Nießen --- .mailmap | 1 + AUTHORS | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index 19c8811d513138..97d73f9a68660a 100644 --- a/.mailmap +++ b/.mailmap @@ -120,6 +120,7 @@ Doug Wade Eduard Burtescu Einar Otto Stangvik Elliott Cable +Emanuel Buholzer Eric Bickle Eric Phetteplace Ernesto Salazar diff --git a/AUTHORS b/AUTHORS index 693878d20788f3..4c80e974e8c582 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1306,7 +1306,6 @@ Neeraj Sharma Ashita Nagesh Jason Wohlgemuth Segu Riluvan -Emanuel Buholzer Avery, Frank Chase Starr sivaprasanna From b4f51276cb32e46190e172dc800fb89cc46e172d Mon Sep 17 00:00:00 2001 From: "Node.js GitHub Bot" Date: Sun, 17 Oct 2021 00:13:57 +0000 Subject: [PATCH 015/118] meta: update AUTHORS PR-URL: https://github.com/nodejs/node/pull/40485 Reviewed-By: Antoine du Hamel Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca --- AUTHORS | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/AUTHORS b/AUTHORS index 4c80e974e8c582..097cb3dd193369 100644 --- a/AUTHORS +++ b/AUTHORS @@ -3324,5 +3324,10 @@ gc <30398469+gc@users.noreply.github.com> ylemkimon Milan Burda gdccwxx <765553928@qq.com> +Ignacio Carbajo +Constantine Kim +OliverOdo +Mark Skelton +Isaac Brodsky # Generated by tools/update-authors.js From 17433060d44496d71d11d33afb23005a7bc19cb2 Mon Sep 17 00:00:00 2001 From: Mestery Date: Mon, 18 Oct 2021 06:30:28 +0200 Subject: [PATCH 016/118] build: fix actions pull request's branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40494 Reviewed-By: Michaël Zasso Reviewed-By: Qingyu Deng Reviewed-By: Tobias Nießen --- .github/workflows/find-inactive-collaborators.yml | 1 + .github/workflows/license-builder.yml | 2 ++ 2 files changed, 3 insertions(+) diff --git a/.github/workflows/find-inactive-collaborators.yml b/.github/workflows/find-inactive-collaborators.yml index 1d7d8304d1888a..4de6f34691f2cc 100644 --- a/.github/workflows/find-inactive-collaborators.yml +++ b/.github/workflows/find-inactive-collaborators.yml @@ -35,6 +35,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GH_USER_TOKEN }} with: author: Node.js GitHub Bot + branch: actions/inactive-collaborators body: This PR was generated by tools/find-inactive-collaborators.yml. commit-message: "meta: move one or more collaborators to emeritus" labels: meta diff --git a/.github/workflows/license-builder.yml b/.github/workflows/license-builder.yml index b6453d61ac5199..5f9af7bd7750ac 100644 --- a/.github/workflows/license-builder.yml +++ b/.github/workflows/license-builder.yml @@ -17,6 +17,8 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: + author: Node.js GitHub Bot + branch: actions/license-builder title: "doc: run license-builder" body: "License is likely out of date. This is an automatically generated PR by the `license-builder.yml` GitHub Action, which runs `license-builder.sh` and submits a new PR or updates an existing PR." commit-message: 'doc: run license-builder' From 36d3b123a06c4fc24a023c99152288f8f2cbec6a Mon Sep 17 00:00:00 2001 From: Mestery Date: Thu, 23 Sep 2021 19:26:25 +0200 Subject: [PATCH 017/118] stream: support array of streams in promises pipeline Fixes: https://github.com/nodejs/node/issues/40191 PR-URL: https://github.com/nodejs/node/pull/40193 Reviewed-By: Luigi Pinca Reviewed-By: Robert Nagy Reviewed-By: James M Snell --- lib/internal/streams/pipeline.js | 11 +++---- test/parallel/test-stream-pipeline.js | 41 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/lib/internal/streams/pipeline.js b/lib/internal/streams/pipeline.js index 012d99de0357f2..8dc4e5792c47d8 100644 --- a/lib/internal/streams/pipeline.js +++ b/lib/internal/streams/pipeline.js @@ -166,17 +166,14 @@ async function pump(iterable, writable, finish) { } function pipeline(...streams) { - const callback = once(popCallback(streams)); + return pipelineImpl(streams, once(popCallback(streams))); +} - // stream.pipeline(streams, callback) - if (ArrayIsArray(streams[0]) && streams.length === 1) { +function pipelineImpl(streams, callback, opts) { + if (streams.length === 1 && ArrayIsArray(streams[0])) { streams = streams[0]; } - return pipelineImpl(streams, callback); -} - -function pipelineImpl(streams, callback, opts) { if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams'); } diff --git a/test/parallel/test-stream-pipeline.js b/test/parallel/test-stream-pipeline.js index b21e1ce52b3cb3..067a7e65a4c67d 100644 --- a/test/parallel/test-stream-pipeline.js +++ b/test/parallel/test-stream-pipeline.js @@ -1406,3 +1406,44 @@ const tsp = require('timers/promises'); })); ac.abort(); } + +{ + async function run() { + let finished = false; + let text = ''; + const write = new Writable({ + write(data, enc, cb) { + text += data; + cb(); + } + }); + write.on('finish', () => { + finished = true; + }); + + await pipelinep([Readable.from('Hello World!'), write]); + assert(finished); + assert.strictEqual(text, 'Hello World!'); + } + + run(); +} + +{ + let finished = false; + let text = ''; + const write = new Writable({ + write(data, enc, cb) { + text += data; + cb(); + } + }); + write.on('finish', () => { + finished = true; + }); + + pipeline([Readable.from('Hello World!'), write], common.mustSucceed(() => { + assert(finished); + assert.strictEqual(text, 'Hello World!'); + })); +} From 143c881ccb3c58e5a8c3243e9ead22f6d281dc99 Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Fri, 8 Oct 2021 17:48:18 -0400 Subject: [PATCH 018/118] src: add missing inialization in agent.h This missing initialization was reported by the coverity scans we are in the process of re-enabling. Signed-off-by: Michael Dawson PR-URL: https://github.com/nodejs/node/pull/40379 Reviewed-By: James M Snell Reviewed-By: Minwoo Jung Reviewed-By: Darshan Sen --- src/tracing/agent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tracing/agent.h b/src/tracing/agent.h index 7ee1b417c6ffa0..b542a849fe8da7 100644 --- a/src/tracing/agent.h +++ b/src/tracing/agent.h @@ -76,7 +76,7 @@ class AgentWriterHandle { inline AgentWriterHandle(Agent* agent, int id) : agent_(agent), id_(id) {} Agent* agent_ = nullptr; - int id_; + int id_ = 0; friend class Agent; }; From 9227f2af7945679ac6dfcea64ddb6ab9b32add4e Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Thu, 14 Oct 2021 12:52:44 +0800 Subject: [PATCH 019/118] test: split test-crypto-dh.js Split test-crypto-dh.js so that it is less likely to timeout on less powerful bots. PR-URL: https://github.com/nodejs/node/pull/40451 Refs: https://github.com/nodejs/reliability/issues/86 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott --- test/common/crypto.js | 48 +++ test/parallel/test-crypto-dh-constructor.js | 34 +++ test/parallel/test-crypto-dh-curves.js | 191 ++++++++++++ test/parallel/test-crypto-dh-modp2-views.js | 24 ++ test/parallel/test-crypto-dh-modp2.js | 43 +++ test/parallel/test-crypto-dh-shared.js | 15 + test/parallel/test-crypto-dh.js | 313 +------------------- test/parallel/test-crypto-modp1-error.js | 26 ++ 8 files changed, 389 insertions(+), 305 deletions(-) create mode 100644 test/common/crypto.js create mode 100644 test/parallel/test-crypto-dh-constructor.js create mode 100644 test/parallel/test-crypto-dh-curves.js create mode 100644 test/parallel/test-crypto-dh-modp2-views.js create mode 100644 test/parallel/test-crypto-dh-modp2.js create mode 100644 test/parallel/test-crypto-dh-shared.js create mode 100644 test/parallel/test-crypto-modp1-error.js diff --git a/test/common/crypto.js b/test/common/crypto.js new file mode 100644 index 00000000000000..298badf5c2b8bc --- /dev/null +++ b/test/common/crypto.js @@ -0,0 +1,48 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); + +// The values below (modp2/modp2buf) are for a 1024 bits long prime from +// RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */ +const modp2buf = Buffer.from([ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, + 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, + 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, + 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, + 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, + 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, + 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, + 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, + 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, + 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +]); + +function testDH({ publicKey: alicePublicKey, privateKey: alicePrivateKey }, + { publicKey: bobPublicKey, privateKey: bobPrivateKey }, + expectedValue) { + const buf1 = crypto.diffieHellman({ + privateKey: alicePrivateKey, + publicKey: bobPublicKey + }); + const buf2 = crypto.diffieHellman({ + privateKey: bobPrivateKey, + publicKey: alicePublicKey + }); + assert.deepStrictEqual(buf1, buf2); + + if (expectedValue !== undefined) + assert.deepStrictEqual(buf1, expectedValue); +} + +module.exports = { + modp2buf, + testDH +}; diff --git a/test/parallel/test-crypto-dh-constructor.js b/test/parallel/test-crypto-dh-constructor.js new file mode 100644 index 00000000000000..c7eaca29347a2b --- /dev/null +++ b/test/parallel/test-crypto-dh-constructor.js @@ -0,0 +1,34 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); + +const size = common.hasFipsCrypto || common.hasOpenSSL3 ? 1024 : 256; +const dh1 = crypto.createDiffieHellman(size); +const p1 = dh1.getPrime('buffer'); + +{ + const DiffieHellman = crypto.DiffieHellman; + + const dh = DiffieHellman(p1, 'buffer'); + assert(dh instanceof DiffieHellman, 'DiffieHellman is expected to return a ' + + 'new instance when called without `new`'); +} + +{ + const DiffieHellmanGroup = crypto.DiffieHellmanGroup; + const dhg = DiffieHellmanGroup('modp5'); + assert(dhg instanceof DiffieHellmanGroup, 'DiffieHellmanGroup is expected ' + + 'to return a new instance when ' + + 'called without `new`'); +} + +{ + const ECDH = crypto.ECDH; + const ecdh = ECDH('prime256v1'); + assert(ecdh instanceof ECDH, 'ECDH is expected to return a new instance ' + + 'when called without `new`'); +} diff --git a/test/parallel/test-crypto-dh-curves.js b/test/parallel/test-crypto-dh-curves.js new file mode 100644 index 00000000000000..81a469c226c261 --- /dev/null +++ b/test/parallel/test-crypto-dh-curves.js @@ -0,0 +1,191 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); + +// Second OAKLEY group, see +// https://github.com/nodejs/node-v0.x-archive/issues/2338 and +// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc2412.html#anchor49 +const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; +crypto.createDiffieHellman(p, 'hex'); + +// Confirm DH_check() results are exposed for optional examination. +const bad_dh = crypto.createDiffieHellman('02', 'hex'); +assert.notStrictEqual(bad_dh.verifyError, 0); + +const availableCurves = new Set(crypto.getCurves()); +const availableHashes = new Set(crypto.getHashes()); + +// Oakley curves do not clean up ERR stack, it was causing unexpected failure +// when accessing other OpenSSL APIs afterwards. +if (availableCurves.has('Oakley-EC2N-3')) { + crypto.createECDH('Oakley-EC2N-3'); + crypto.createHash('sha256'); +} + +// Test ECDH +if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) { + const ecdh1 = crypto.createECDH('prime256v1'); + const ecdh2 = crypto.createECDH('prime256v1'); + const key1 = ecdh1.generateKeys(); + const key2 = ecdh2.generateKeys('hex'); + const secret1 = ecdh1.computeSecret(key2, 'hex', 'base64'); + const secret2 = ecdh2.computeSecret(key1, 'latin1', 'buffer'); + + assert.strictEqual(secret1, secret2.toString('base64')); + + // Point formats + assert.strictEqual(ecdh1.getPublicKey('buffer', 'uncompressed')[0], 4); + let firstByte = ecdh1.getPublicKey('buffer', 'compressed')[0]; + assert(firstByte === 2 || firstByte === 3); + firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0]; + assert(firstByte === 6 || firstByte === 7); + // Format value should be string + + assert.throws( + () => ecdh1.getPublicKey('buffer', 10), + { + code: 'ERR_CRYPTO_ECDH_INVALID_FORMAT', + name: 'TypeError', + message: 'Invalid ECDH format: 10' + }); + + // ECDH should check that point is on curve + const ecdh3 = crypto.createECDH('secp256k1'); + const key3 = ecdh3.generateKeys(); + + assert.throws( + () => ecdh2.computeSecret(key3, 'latin1', 'buffer'), + { + code: 'ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY', + name: 'Error', + message: 'Public key is not valid for specified curve' + }); + + // ECDH should allow .setPrivateKey()/.setPublicKey() + const ecdh4 = crypto.createECDH('prime256v1'); + + ecdh4.setPrivateKey(ecdh1.getPrivateKey()); + ecdh4.setPublicKey(ecdh1.getPublicKey()); + + assert.throws(() => { + ecdh4.setPublicKey(ecdh3.getPublicKey()); + }, { message: 'Failed to convert Buffer to EC_POINT' }); + + // Verify that we can use ECDH without having to use newly generated keys. + const ecdh5 = crypto.createECDH('secp256k1'); + + // Verify errors are thrown when retrieving keys from an uninitialized object. + assert.throws(() => { + ecdh5.getPublicKey(); + }, /^Error: Failed to get ECDH public key$/); + + assert.throws(() => { + ecdh5.getPrivateKey(); + }, /^Error: Failed to get ECDH private key$/); + + // A valid private key for the secp256k1 curve. + const cafebabeKey = 'cafebabe'.repeat(8); + // Associated compressed and uncompressed public keys (points). + const cafebabePubPtComp = + '03672a31bfc59d3f04548ec9b7daeeba2f61814e8ccc40448045007f5479f693a3'; + const cafebabePubPtUnComp = + '04672a31bfc59d3f04548ec9b7daeeba2f61814e8ccc40448045007f5479f693a3' + + '2e02c7f93d13dc2732b760ca377a5897b9dd41a1c1b29dc0442fdce6d0a04d1d'; + ecdh5.setPrivateKey(cafebabeKey, 'hex'); + assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); + // Show that the public point (key) is generated while setting the + // private key. + assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); + + // Compressed and uncompressed public points/keys for other party's + // private key. + // 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF + const peerPubPtComp = + '02c6b754b20826eb925e052ee2c25285b162b51fdca732bcf67e39d647fb6830ae'; + const peerPubPtUnComp = + '04c6b754b20826eb925e052ee2c25285b162b51fdca732bcf67e39d647fb6830ae' + + 'b651944a574a362082a77e3f2b5d9223eb54d7f2f76846522bf75f3bedb8178e'; + + const sharedSecret = + '1da220b5329bbe8bfd19ceef5a5898593f411a6f12ea40f2a8eead9a5cf59970'; + + assert.strictEqual(ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'), + sharedSecret); + assert.strictEqual(ecdh5.computeSecret(peerPubPtUnComp, 'hex', 'hex'), + sharedSecret); + + // Verify that we still have the same key pair as before the computation. + assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); + assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); + + // Verify setting and getting compressed and non-compressed serializations. + ecdh5.setPublicKey(cafebabePubPtComp, 'hex'); + assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); + assert.strictEqual( + ecdh5.getPublicKey('hex', 'compressed'), + cafebabePubPtComp + ); + ecdh5.setPublicKey(cafebabePubPtUnComp, 'hex'); + assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); + assert.strictEqual( + ecdh5.getPublicKey('hex', 'compressed'), + cafebabePubPtComp + ); + + // Show why allowing the public key to be set on this type + // does not make sense. + ecdh5.setPublicKey(peerPubPtComp, 'hex'); + assert.strictEqual(ecdh5.getPublicKey('hex'), peerPubPtUnComp); + assert.throws(() => { + // Error because the public key does not match the private key anymore. + ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'); + }, /Invalid key pair/); + + // Set to a valid key to show that later attempts to set an invalid key are + // rejected. + ecdh5.setPrivateKey(cafebabeKey, 'hex'); + + // Some invalid private keys for the secp256k1 curve. + const errMessage = /Private key is not valid for specified curve/; + ['0000000000000000000000000000000000000000000000000000000000000000', + 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', + 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', + ].forEach((element) => { + assert.throws(() => { + ecdh5.setPrivateKey(element, 'hex'); + }, errMessage); + // Verify object state did not change. + assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); + }); +} + +// Use of invalid keys was not cleaning up ERR stack, and was causing +// unexpected failure in subsequent signing operations. +if (availableCurves.has('prime256v1') && availableHashes.has('sha256')) { + const curve = crypto.createECDH('prime256v1'); + const invalidKey = Buffer.alloc(65); + invalidKey.fill('\0'); + curve.generateKeys(); + assert.throws( + () => curve.computeSecret(invalidKey), + { + code: 'ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY', + name: 'Error', + message: 'Public key is not valid for specified curve' + }); + // Check that signing operations are not impacted by the above error. + const ecPrivateKey = + '-----BEGIN EC PRIVATE KEY-----\n' + + 'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' + + 'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' + + 'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' + + '-----END EC PRIVATE KEY-----'; + crypto.createSign('SHA256').sign(ecPrivateKey); +} diff --git a/test/parallel/test-crypto-dh-modp2-views.js b/test/parallel/test-crypto-dh-modp2-views.js new file mode 100644 index 00000000000000..8d01731af79394 --- /dev/null +++ b/test/parallel/test-crypto-dh-modp2-views.js @@ -0,0 +1,24 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); +const { modp2buf } = require('../common/crypto'); + +const modp2 = crypto.createDiffieHellmanGroup('modp2'); + +const views = common.getArrayBufferViews(modp2buf); +for (const buf of [modp2buf, ...views]) { + // Ensure specific generator (string with encoding) works as expected with + // any ArrayBufferViews as the first argument to createDiffieHellman(). + const exmodp2 = crypto.createDiffieHellman(buf, '02', 'hex'); + modp2.generateKeys(); + exmodp2.generateKeys(); + const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) + .toString('hex'); + const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) + .toString('hex'); + assert.strictEqual(modp2Secret, exmodp2Secret); +} diff --git a/test/parallel/test-crypto-dh-modp2.js b/test/parallel/test-crypto-dh-modp2.js new file mode 100644 index 00000000000000..19767d26f4e5fb --- /dev/null +++ b/test/parallel/test-crypto-dh-modp2.js @@ -0,0 +1,43 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); +const { modp2buf } = require('../common/crypto'); +const modp2 = crypto.createDiffieHellmanGroup('modp2'); + +{ + // Ensure specific generator (buffer) works as expected. + const exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2])); + modp2.generateKeys(); + exmodp2.generateKeys(); + const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) + .toString('hex'); + const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) + .toString('hex'); + assert.strictEqual(modp2Secret, exmodp2Secret); +} + +{ + // Ensure specific generator (string without encoding) works as expected. + const exmodp2 = crypto.createDiffieHellman(modp2buf, '\x02'); + exmodp2.generateKeys(); + const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) + .toString('hex'); + const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) + .toString('hex'); + assert.strictEqual(modp2Secret, exmodp2Secret); +} + +{ + // Ensure specific generator (numeric) works as expected. + const exmodp2 = crypto.createDiffieHellman(modp2buf, 2); + exmodp2.generateKeys(); + const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) + .toString('hex'); + const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) + .toString('hex'); + assert.strictEqual(modp2Secret, exmodp2Secret); +} diff --git a/test/parallel/test-crypto-dh-shared.js b/test/parallel/test-crypto-dh-shared.js new file mode 100644 index 00000000000000..515405034d76b0 --- /dev/null +++ b/test/parallel/test-crypto-dh-shared.js @@ -0,0 +1,15 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); + +const alice = crypto.createDiffieHellmanGroup('modp5'); +const bob = crypto.createDiffieHellmanGroup('modp5'); +alice.generateKeys(); +bob.generateKeys(); +const aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); +const bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); +assert.strictEqual(aSecret, bSecret); diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index cae9301517c37c..18721fcf289e55 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -6,17 +6,17 @@ if (!common.hasCrypto) const assert = require('assert'); const crypto = require('crypto'); -// Test Diffie-Hellman with two parties sharing a secret, -// using various encodings as we go along const size = common.hasFipsCrypto || common.hasOpenSSL3 ? 1024 : 256; const dh1 = crypto.createDiffieHellman(size); const p1 = dh1.getPrime('buffer'); const dh2 = crypto.createDiffieHellman(p1, 'buffer'); -let key1 = dh1.generateKeys(); -let key2 = dh2.generateKeys('hex'); -let secret1 = dh1.computeSecret(key2, 'hex', 'base64'); -let secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); +const key1 = dh1.generateKeys(); +const key2 = dh2.generateKeys('hex'); +const secret1 = dh1.computeSecret(key2, 'hex', 'base64'); +const secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); +// Test Diffie-Hellman with two parties sharing a secret, +// using various encodings as we go along assert.strictEqual(secret2.toString('base64'), secret1); assert.strictEqual(dh1.verifyError, 0); assert.strictEqual(dh2.verifyError, 0); @@ -85,28 +85,6 @@ for (const g of [Buffer.from([]), assert.throws(() => crypto.createDiffieHellman('abcdef', 'hex', g), ex); } -{ - const DiffieHellman = crypto.DiffieHellman; - const dh = DiffieHellman(p1, 'buffer'); - assert(dh instanceof DiffieHellman, 'DiffieHellman is expected to return a ' + - 'new instance when called without `new`'); -} - -{ - const DiffieHellmanGroup = crypto.DiffieHellmanGroup; - const dhg = DiffieHellmanGroup('modp5'); - assert(dhg instanceof DiffieHellmanGroup, 'DiffieHellmanGroup is expected ' + - 'to return a new instance when ' + - 'called without `new`'); -} - -{ - const ECDH = crypto.ECDH; - const ecdh = ECDH('prime256v1'); - assert(ecdh instanceof ECDH, 'ECDH is expected to return a new instance ' + - 'when called without `new`'); -} - [ [0x1, 0x2], () => { }, @@ -191,264 +169,6 @@ assert.throws(() => { 'error:02800080:Diffie-Hellman routines::invalid secret' : 'Supplied key is too small' }); -// Create a shared using a DH group. -const alice = crypto.createDiffieHellmanGroup('modp5'); -const bob = crypto.createDiffieHellmanGroup('modp5'); -alice.generateKeys(); -bob.generateKeys(); -const aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); -const bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); -assert.strictEqual(aSecret, bSecret); - -// Ensure specific generator (buffer) works as expected. -// The values below (modp2/modp2buf) are for a 1024 bits long prime from -// RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */ -const modp2 = crypto.createDiffieHellmanGroup('modp2'); -const modp2buf = Buffer.from([ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, - 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, - 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, - 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, -]); - -{ - const exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2])); - modp2.generateKeys(); - exmodp2.generateKeys(); - const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) - .toString('hex'); - const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) - .toString('hex'); - assert.strictEqual(modp2Secret, exmodp2Secret); -} - -for (const buf of [modp2buf, ...common.getArrayBufferViews(modp2buf)]) { - // Ensure specific generator (string with encoding) works as expected with - // any ArrayBufferViews as the first argument to createDiffieHellman(). - const exmodp2 = crypto.createDiffieHellman(buf, '02', 'hex'); - exmodp2.generateKeys(); - const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) - .toString('hex'); - const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) - .toString('hex'); - assert.strictEqual(modp2Secret, exmodp2Secret); -} - -{ - // Ensure specific generator (string without encoding) works as expected. - const exmodp2 = crypto.createDiffieHellman(modp2buf, '\x02'); - exmodp2.generateKeys(); - const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) - .toString('hex'); - const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) - .toString('hex'); - assert.strictEqual(modp2Secret, exmodp2Secret); -} - -{ - // Ensure specific generator (numeric) works as expected. - const exmodp2 = crypto.createDiffieHellman(modp2buf, 2); - exmodp2.generateKeys(); - const modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()) - .toString('hex'); - const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) - .toString('hex'); - assert.strictEqual(modp2Secret, exmodp2Secret); -} - -// Second OAKLEY group, see -// https://github.com/nodejs/node-v0.x-archive/issues/2338 and -// https://xml2rfc.tools.ietf.org/public/rfc/html/rfc2412.html#anchor49 -const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + - '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + - '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + - 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; -crypto.createDiffieHellman(p, 'hex'); - -// Confirm DH_check() results are exposed for optional examination. -const bad_dh = crypto.createDiffieHellman('02', 'hex'); -assert.notStrictEqual(bad_dh.verifyError, 0); - -const availableCurves = new Set(crypto.getCurves()); -const availableHashes = new Set(crypto.getHashes()); - -// Oakley curves do not clean up ERR stack, it was causing unexpected failure -// when accessing other OpenSSL APIs afterwards. -if (availableCurves.has('Oakley-EC2N-3')) { - crypto.createECDH('Oakley-EC2N-3'); - crypto.createHash('sha256'); -} - -// Test ECDH -if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) { - const ecdh1 = crypto.createECDH('prime256v1'); - const ecdh2 = crypto.createECDH('prime256v1'); - key1 = ecdh1.generateKeys(); - key2 = ecdh2.generateKeys('hex'); - secret1 = ecdh1.computeSecret(key2, 'hex', 'base64'); - secret2 = ecdh2.computeSecret(key1, 'latin1', 'buffer'); - - assert.strictEqual(secret1, secret2.toString('base64')); - - // Point formats - assert.strictEqual(ecdh1.getPublicKey('buffer', 'uncompressed')[0], 4); - let firstByte = ecdh1.getPublicKey('buffer', 'compressed')[0]; - assert(firstByte === 2 || firstByte === 3); - firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0]; - assert(firstByte === 6 || firstByte === 7); - // Format value should be string - - assert.throws( - () => ecdh1.getPublicKey('buffer', 10), - { - code: 'ERR_CRYPTO_ECDH_INVALID_FORMAT', - name: 'TypeError', - message: 'Invalid ECDH format: 10' - }); - - // ECDH should check that point is on curve - const ecdh3 = crypto.createECDH('secp256k1'); - const key3 = ecdh3.generateKeys(); - - assert.throws( - () => ecdh2.computeSecret(key3, 'latin1', 'buffer'), - { - code: 'ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY', - name: 'Error', - message: 'Public key is not valid for specified curve' - }); - - // ECDH should allow .setPrivateKey()/.setPublicKey() - const ecdh4 = crypto.createECDH('prime256v1'); - - ecdh4.setPrivateKey(ecdh1.getPrivateKey()); - ecdh4.setPublicKey(ecdh1.getPublicKey()); - - assert.throws(() => { - ecdh4.setPublicKey(ecdh3.getPublicKey()); - }, { message: 'Failed to convert Buffer to EC_POINT' }); - - // Verify that we can use ECDH without having to use newly generated keys. - const ecdh5 = crypto.createECDH('secp256k1'); - - // Verify errors are thrown when retrieving keys from an uninitialized object. - assert.throws(() => { - ecdh5.getPublicKey(); - }, /^Error: Failed to get ECDH public key$/); - - assert.throws(() => { - ecdh5.getPrivateKey(); - }, /^Error: Failed to get ECDH private key$/); - - // A valid private key for the secp256k1 curve. - const cafebabeKey = 'cafebabe'.repeat(8); - // Associated compressed and uncompressed public keys (points). - const cafebabePubPtComp = - '03672a31bfc59d3f04548ec9b7daeeba2f61814e8ccc40448045007f5479f693a3'; - const cafebabePubPtUnComp = - '04672a31bfc59d3f04548ec9b7daeeba2f61814e8ccc40448045007f5479f693a3' + - '2e02c7f93d13dc2732b760ca377a5897b9dd41a1c1b29dc0442fdce6d0a04d1d'; - ecdh5.setPrivateKey(cafebabeKey, 'hex'); - assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); - // Show that the public point (key) is generated while setting the - // private key. - assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); - - // Compressed and uncompressed public points/keys for other party's - // private key. - // 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF - const peerPubPtComp = - '02c6b754b20826eb925e052ee2c25285b162b51fdca732bcf67e39d647fb6830ae'; - const peerPubPtUnComp = - '04c6b754b20826eb925e052ee2c25285b162b51fdca732bcf67e39d647fb6830ae' + - 'b651944a574a362082a77e3f2b5d9223eb54d7f2f76846522bf75f3bedb8178e'; - - const sharedSecret = - '1da220b5329bbe8bfd19ceef5a5898593f411a6f12ea40f2a8eead9a5cf59970'; - - assert.strictEqual(ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'), - sharedSecret); - assert.strictEqual(ecdh5.computeSecret(peerPubPtUnComp, 'hex', 'hex'), - sharedSecret); - - // Verify that we still have the same key pair as before the computation. - assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); - assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); - - // Verify setting and getting compressed and non-compressed serializations. - ecdh5.setPublicKey(cafebabePubPtComp, 'hex'); - assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); - assert.strictEqual( - ecdh5.getPublicKey('hex', 'compressed'), - cafebabePubPtComp - ); - ecdh5.setPublicKey(cafebabePubPtUnComp, 'hex'); - assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); - assert.strictEqual( - ecdh5.getPublicKey('hex', 'compressed'), - cafebabePubPtComp - ); - - // Show why allowing the public key to be set on this type - // does not make sense. - ecdh5.setPublicKey(peerPubPtComp, 'hex'); - assert.strictEqual(ecdh5.getPublicKey('hex'), peerPubPtUnComp); - assert.throws(() => { - // Error because the public key does not match the private key anymore. - ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'); - }, /Invalid key pair/); - - // Set to a valid key to show that later attempts to set an invalid key are - // rejected. - ecdh5.setPrivateKey(cafebabeKey, 'hex'); - - // Some invalid private keys for the secp256k1 curve. - const errMessage = /Private key is not valid for specified curve/; - ['0000000000000000000000000000000000000000000000000000000000000000', - 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', - 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', - ].forEach((element) => { - assert.throws(() => { - ecdh5.setPrivateKey(element, 'hex'); - }, errMessage); - // Verify object state did not change. - assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); - }); -} - -// Use of invalid keys was not cleaning up ERR stack, and was causing -// unexpected failure in subsequent signing operations. -if (availableCurves.has('prime256v1') && availableHashes.has('sha256')) { - const curve = crypto.createECDH('prime256v1'); - const invalidKey = Buffer.alloc(65); - invalidKey.fill('\0'); - curve.generateKeys(); - assert.throws( - () => curve.computeSecret(invalidKey), - { - code: 'ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY', - name: 'Error', - message: 'Public key is not valid for specified curve' - }); - // Check that signing operations are not impacted by the above error. - const ecPrivateKey = - '-----BEGIN EC PRIVATE KEY-----\n' + - 'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' + - 'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' + - 'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' + - '-----END EC PRIVATE KEY-----'; - crypto.createSign('SHA256').sign(ecPrivateKey); -} - // Invalid test: curve argument is undefined assert.throws( () => crypto.createECDH(), @@ -456,7 +176,7 @@ assert.throws( code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', message: 'The "curve" argument must be of type string. ' + - 'Received undefined' + 'Received undefined' }); assert.throws( @@ -471,24 +191,7 @@ assert.throws( 'crypto.getDiffieHellman(\'unknown-group\') ' + 'failed to throw the expected error.' ); -assert.throws( - function() { - crypto.getDiffieHellman('modp1').setPrivateKey(''); - }, - new RegExp('^TypeError: crypto\\.getDiffieHellman\\(\\.\\.\\.\\)\\.' + - 'setPrivateKey is not a function$'), - 'crypto.getDiffieHellman(\'modp1\').setPrivateKey(\'\') ' + - 'failed to throw the expected error.' -); -assert.throws( - function() { - crypto.getDiffieHellman('modp1').setPublicKey(''); - }, - new RegExp('^TypeError: crypto\\.getDiffieHellman\\(\\.\\.\\.\\)\\.' + - 'setPublicKey is not a function$'), - 'crypto.getDiffieHellman(\'modp1\').setPublicKey(\'\') ' + - 'failed to throw the expected error.' -); + assert.throws( () => crypto.createDiffieHellman('', true), { diff --git a/test/parallel/test-crypto-modp1-error.js b/test/parallel/test-crypto-modp1-error.js new file mode 100644 index 00000000000000..38f78c158704b2 --- /dev/null +++ b/test/parallel/test-crypto-modp1-error.js @@ -0,0 +1,26 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); + +assert.throws( + function() { + crypto.getDiffieHellman('modp1').setPrivateKey(''); + }, + new RegExp('^TypeError: crypto\\.getDiffieHellman\\(\\.\\.\\.\\)\\.' + + 'setPrivateKey is not a function$'), + 'crypto.getDiffieHellman(\'modp1\').setPrivateKey(\'\') ' + + 'failed to throw the expected error.' +); +assert.throws( + function() { + crypto.getDiffieHellman('modp1').setPublicKey(''); + }, + new RegExp('^TypeError: crypto\\.getDiffieHellman\\(\\.\\.\\.\\)\\.' + + 'setPublicKey is not a function$'), + 'crypto.getDiffieHellman(\'modp1\').setPublicKey(\'\') ' + + 'failed to throw the expected error.' +); From 7b746381cea06b2259b0aeaba0ea57936c9d22a3 Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Sat, 16 Oct 2021 19:55:31 +0200 Subject: [PATCH 020/118] doc: specify that maxFreeSockets is per host The `maxFreeSockets` option specifies the maximum number of free sockets per host. PR-URL: https://github.com/nodejs/node/pull/40483 Fixes: https://github.com/nodejs/node/issues/40446 Reviewed-By: Colin Ihrig Reviewed-By: Benjamin Gruenbaum --- doc/api/http.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/http.md b/doc/api/http.md index c32872f65843f1..74b0f9975fd5bb 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -156,7 +156,7 @@ changes: all hosts in total. Each request will use a new socket until the maximum is reached. **Default:** `Infinity`. - * `maxFreeSockets` {number} Maximum number of sockets to leave open + * `maxFreeSockets` {number} Maximum number of sockets per host to leave open in a free state. Only relevant if `keepAlive` is set to `true`. **Default:** `256`. * `scheduling` {string} Scheduling strategy to apply when picking From de125a556cd9b9a55035c4c7fe0f85552f6f7830 Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Fri, 8 Oct 2021 18:24:40 -0400 Subject: [PATCH 021/118] crypto: avoid double free Coverity scan reported a free after use and I think its right. Tweak to avoid double free. Signed-off-by: Michael Dawson PR-URL: https://github.com/nodejs/node/pull/40380 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Minwoo Jung Reviewed-By: Darshan Sen --- src/crypto/crypto_util.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index ac95612a0b1a85..9606c29097dfc0 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -550,9 +550,12 @@ struct EnginePointer { inline void reset(ENGINE* engine_ = nullptr, bool finish_on_exit_ = false) { if (engine != nullptr) { - if (finish_on_exit) - ENGINE_finish(engine); - ENGINE_free(engine); + if (finish_on_exit) { + // This also does the equivalent of ENGINE_free. + CHECK_EQ(ENGINE_finish(engine), 1); + } else { + CHECK_EQ(ENGINE_free(engine), 1); + } } engine = engine_; finish_on_exit = finish_on_exit_; From 50c6666b375b9fe0d633fcbf3295b696f37697ab Mon Sep 17 00:00:00 2001 From: Piotr Rybak Date: Sun, 31 Oct 2021 17:58:09 +0900 Subject: [PATCH 022/118] test: fix test-datetime-change-notify after daylight change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add standard timezone name for Dublin without daylight saving PR-URL: https://github.com/nodejs/node/pull/40684 Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen Reviewed-By: Voltrex --- test/parallel/test-datetime-change-notify.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-datetime-change-notify.js b/test/parallel/test-datetime-change-notify.js index 9cd6d7abfd898a..01843511907077 100644 --- a/test/parallel/test-datetime-change-notify.js +++ b/test/parallel/test-datetime-change-notify.js @@ -18,15 +18,15 @@ const cases = [ }, { timeZone: 'America/New_York', - expected: /Eastern (Standard|Daylight) Time/, + expected: /Eastern (?:Standard|Daylight) Time/, }, { timeZone: 'America/Los_Angeles', - expected: /Pacific (Standard|Daylight) Time/, + expected: /Pacific (?:Standard|Daylight) Time/, }, { timeZone: 'Europe/Dublin', - expected: /Irish/, + expected: /Irish Standard Time|Greenwich Mean Time/, }, ]; From 908f6447cd87dabc0d7cadeaada85700eecee8c1 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 31 Oct 2021 22:43:20 -0700 Subject: [PATCH 023/118] test,tools: increase timeout for benchmark tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test-benchmark-buffer is consistently timing out on a single Windows host in CI. Rather than try to figure out if we need to scale the timeout up for a certain memory limit or chip speed or something else, let's increase the timeout for benchmark tests in general. PR-URL: https://github.com/nodejs/node/pull/40684 Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen Reviewed-By: Voltrex --- tools/test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test.py b/tools/test.py index 5d4f48700c427b..3663e0f6098c53 100755 --- a/tools/test.py +++ b/tools/test.py @@ -944,7 +944,7 @@ def GetVm(self, arch, mode): def GetTimeout(self, mode, section=''): timeout = self.timeout * TIMEOUT_SCALEFACTOR[ARCH_GUESS or 'ia32'][mode] - if section == 'pummel': + if section == 'pummel' or section == 'benchmark': timeout = timeout * 4 return timeout From aef809f5c860aaedd27cd946f8774a128f929889 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 1 Nov 2021 00:13:23 -0700 Subject: [PATCH 024/118] test,tools: increase pummel/benchmark test timeout from 4x to 6x MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The win10-COMPILED_BY-vs2019 hosts in CI are very slow and timing out on certain tests in pummel and (previously) benchmark. Increase timeout from 4x to 6x. PR-URL: https://github.com/nodejs/node/pull/40684 Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen Reviewed-By: Voltrex --- tools/test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test.py b/tools/test.py index 3663e0f6098c53..8ca1f58e9a1223 100755 --- a/tools/test.py +++ b/tools/test.py @@ -945,7 +945,7 @@ def GetVm(self, arch, mode): def GetTimeout(self, mode, section=''): timeout = self.timeout * TIMEOUT_SCALEFACTOR[ARCH_GUESS or 'ia32'][mode] if section == 'pummel' or section == 'benchmark': - timeout = timeout * 4 + timeout = timeout * 6 return timeout def RunTestCases(cases_to_run, progress, tasks, flaky_tests_mode): From 82266900970f1b2421c82db25b3987176ce1cdee Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 1 Nov 2021 08:08:12 -0700 Subject: [PATCH 025/118] test: mark test-policy-integrity flaky on Windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ref: https://github.com/nodejs/node/issues/40694 PR-URL: https://github.com/nodejs/node/pull/40684 Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen Reviewed-By: Voltrex --- test/pummel/pummel.status | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/pummel/pummel.status b/test/pummel/pummel.status index 5ff3cdbe0e5a7a..a447b56498c123 100644 --- a/test/pummel/pummel.status +++ b/test/pummel/pummel.status @@ -7,6 +7,8 @@ prefix pummel [true] # This section applies to all platforms [$system==win32] +# https://github.com/nodejs/node/issues/40694 +test-policy-integrity: PASS,FLAKY [$system==linux] # https://github.com/nodejs/node/issues/38226 From 6de88bc5ed39f67ddfb0f2d23d12d84cf1907913 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 11 Oct 2021 06:58:38 -0700 Subject: [PATCH 026/118] test: adjust CLI flags test to ignore blank lines in doc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40403 Backport-PR-URL: https://github.com/nodejs/node/pull/40530 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Zijian Liu Reviewed-By: Michaël Zasso Reviewed-By: Antoine du Hamel --- .../test-process-env-allowed-flags-are-documented.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/parallel/test-process-env-allowed-flags-are-documented.js b/test/parallel/test-process-env-allowed-flags-are-documented.js index 64626b71f01902..a2738f08e2fd27 100644 --- a/test/parallel/test-process-env-allowed-flags-are-documented.js +++ b/test/parallel/test-process-env-allowed-flags-are-documented.js @@ -15,7 +15,9 @@ const parseSection = (text, startMarker, endMarker) => { const match = text.match(regExp); assert(match, `Unable to locate text between '${startMarker}' and '${endMarker}'.`); - return match[1].split(/\r?\n/); + return match[1] + .split(/\r?\n/) + .filter((val) => val.trim() !== ''); }; const nodeOptionsLines = parseSection(cliText, @@ -24,6 +26,7 @@ const nodeOptionsLines = parseSection(cliText, const v8OptionsLines = parseSection(cliText, '', ''); + // Check the options are documented in alphabetical order. assert.deepStrictEqual(nodeOptionsLines, [...nodeOptionsLines].sort()); assert.deepStrictEqual(v8OptionsLines, [...v8OptionsLines].sort()); From 621266afc7530854ab61012b7380b2408fa945a4 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 10 Oct 2021 21:55:04 -0700 Subject: [PATCH 027/118] doc: format doc/api/*.md with markdown formatter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40403 Backport-PR-URL: https://github.com/nodejs/node/pull/40530 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Zijian Liu Reviewed-By: Michaël Zasso Reviewed-By: Antoine du Hamel --- doc/api/addons.md | 1 + doc/api/assert.md | 26 ++ doc/api/async_context.md | 13 + doc/api/async_hooks.md | 14 +- doc/api/buffer.md | 172 ++++++++--- doc/api/child_process.md | 64 ++-- doc/api/cli.md | 146 ++++++++- doc/api/cluster.md | 39 ++- doc/api/console.md | 36 ++- doc/api/crypto.md | 186 +++++++++++- doc/api/debugger.md | 1 + doc/api/deprecations.md | 163 +++++++++- doc/api/dgram.md | 45 ++- doc/api/dns.md | 161 ++++++---- doc/api/documentation.md | 2 + doc/api/domain.md | 1 + doc/api/embedding.md | 1 + doc/api/errors.md | 445 ++++++++++++++++++++++++++-- doc/api/esm.md | 380 ++++++++++++------------ doc/api/events.md | 116 ++++++-- doc/api/fs.md | 281 +++++++++++++++--- doc/api/globals.md | 31 ++ doc/api/http.md | 196 ++++++++++-- doc/api/http2.md | 219 ++++++++++++-- doc/api/https.md | 16 + doc/api/index.md | 14 +- doc/api/inspector.md | 12 +- doc/api/intl.md | 4 +- doc/api/module.md | 15 +- doc/api/modules.md | 47 ++- doc/api/n-api.md | 606 ++++++++++++++++++++++++-------------- doc/api/net.md | 101 ++++++- doc/api/os.md | 29 +- doc/api/packages.md | 105 ++++--- doc/api/path.md | 15 + doc/api/perf_hooks.md | 69 ++++- doc/api/process.md | 162 +++++++--- doc/api/punycode.md | 11 +- doc/api/querystring.md | 11 +- doc/api/readline.md | 49 ++- doc/api/repl.md | 50 ++-- doc/api/report.md | 1 + doc/api/stream.md | 163 +++++++--- doc/api/string_decoder.md | 9 +- doc/api/synopsis.md | 3 +- doc/api/timers.md | 25 +- doc/api/tls.md | 202 +++++++++---- doc/api/tracing.md | 18 +- doc/api/tty.md | 26 +- doc/api/url.md | 58 ++-- doc/api/util.md | 170 ++++++++--- doc/api/v8.md | 24 +- doc/api/vm.md | 59 ++-- doc/api/wasi.md | 5 + doc/api/webcrypto.md | 322 ++++++++++++++------ doc/api/webstreams.md | 102 ++++++- doc/api/worker_threads.md | 73 ++++- doc/api/zlib.md | 55 +++- 58 files changed, 4225 insertions(+), 1145 deletions(-) diff --git a/doc/api/addons.md b/doc/api/addons.md index a906306b2cd1bc..3635d5bd54d8fb 100644 --- a/doc/api/addons.md +++ b/doc/api/addons.md @@ -235,6 +235,7 @@ NODE_MODULE_INIT(/* exports, module, context */) { ``` #### Worker support + @@ -216,6 +218,7 @@ try { ``` ## Class: `assert.CallTracker` + @@ -453,6 +461,7 @@ added: v0.5.9 An alias of [`assert.ok()`][]. ## `assert.deepEqual(actual, expected[, message])` + @@ -999,6 +1011,7 @@ assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) ``` ## `assert.doesNotThrow(fn[, error][, message])` + @@ -1223,6 +1238,7 @@ Using `assert.fail()` with more than two arguments is possible but deprecated. See below for further details. ## `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])` + @@ -1974,6 +1998,7 @@ example in [`assert.throws()`][] carefully if using a string as the second argument gets considered. ## `assert.strictEqual(actual, expected[, message])` + ## Introduction + These classes are used to associate state and propagate it throughout callbacks and promise chains. They allow storing data throughout the lifetime of a web request @@ -25,6 +26,7 @@ const async_hooks = require('async_hooks'); ``` ## Class: `AsyncLocalStorage` + @@ -507,6 +519,7 @@ never be called. `AsyncResource` constructor. + ### Using `AsyncResource` for a `Worker` thread pool The following example shows how to use the `AsyncResource` class to properly diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index 132f2a6bb2e910..c3170f8162f49b 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -190,7 +190,7 @@ const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); Because promises are asynchronous resources whose lifecycle is tracked via the async hooks mechanism, the `init()`, `before()`, `after()`, and -`destroy()` callbacks *must not* be async functions that return promises. +`destroy()` callbacks _must not_ be async functions that return promises. ### Error handling @@ -350,8 +350,8 @@ listening to the hooks. `triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered") the new resource to initialize and that caused `init` to call. This is different -from `async_hooks.executionAsyncId()` that only shows *when* a resource was -created, while `triggerAsyncId` shows *why* a resource was created. +from `async_hooks.executionAsyncId()` that only shows _when_ a resource was +created, while `triggerAsyncId` shows _why_ a resource was created. The following is a simple demonstration of `triggerAsyncId`: @@ -499,13 +499,13 @@ TickObject(6) The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for `console.log()` being called. This is because binding to a port without a host -name is a *synchronous* operation, but to maintain a completely asynchronous +name is a _synchronous_ operation, but to maintain a completely asynchronous API the user's callback is placed in a `process.nextTick()`. Which is why `TickObject` is present in the output and is a 'parent' for `.listen()` callback. -The graph only shows *when* a resource was created, not *why*, so to track -the *why* use `triggerAsyncId`. Which can be represented with the following +The graph only shows _when_ a resource was created, not _why_, so to track +the _why_ use `triggerAsyncId`. Which can be represented with the following graph: ```console @@ -545,7 +545,7 @@ it only once. Called immediately after the callback specified in `before` is completed. If an uncaught exception occurs during execution of the callback, then `after` -will run *after* the `'uncaughtException'` event is emitted or a `domain`'s +will run _after_ the `'uncaughtException'` event is emitted or a `domain`'s handler runs. #### `destroy(asyncId)` diff --git a/doc/api/buffer.md b/doc/api/buffer.md index c6f403a60b78a4..af34991256cf01 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -83,6 +83,7 @@ const buf7 = Buffer.from('tést', 'latin1'); ``` ## Buffers and character encodings + @@ -457,6 +460,7 @@ A [`Blob`][] encapsulates immutable, raw data that can be safely shared across multiple worker threads. ### `new buffer.Blob([sources[, options]])` + -* `sources` {string[]|ArrayBuffer[]|TypedArray[]|DataView[]|Blob[]} An array - of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects, or - any mix of such objects, that will be stored within the `Blob`. +* `sources` {string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]} An + array of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects, + or any mix of such objects, that will be stored within the `Blob`. * `options` {Object} * `endings` {string} One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be converted to @@ -487,6 +491,7 @@ Unmatched surrogate pairs within each string part will be replaced by Unicode U+FFFD replacement characters. ### `blob.arrayBuffer()` + @@ -497,6 +502,7 @@ Returns a promise that fulfills with an {ArrayBuffer} containing a copy of the `Blob` data. ### `blob.size` + @@ -504,6 +510,7 @@ added: v15.7.0 The total size of the `Blob` in bytes. ### `blob.slice([start, [end, [type]]])` + @@ -516,6 +523,7 @@ Creates and returns a new `Blob` containing a subset of this `Blob` objects data. The original `Blob` is not altered. ### `blob.stream()` + @@ -525,6 +533,7 @@ added: v16.7.0 Returns a new `ReadableStream` that allows the content of the `Blob` to be read. ### `blob.text()` + @@ -535,6 +544,7 @@ Returns a promise that fulfills with the contents of the `Blob` decoded as a UTF-8 string. ### `blob.type` + @@ -610,6 +620,7 @@ The `Buffer` class is a global type for dealing with binary data directly. It can be constructed in a variety of ways. ### Static method: `Buffer.alloc(size[, fill[, encoding]])` + -* `list` {Buffer[] | Uint8Array[]} List of `Buffer` or [`Uint8Array`][] +* `list` {Buffer\[] | Uint8Array\[]} List of `Buffer` or [`Uint8Array`][] instances to concatenate. * `totalLength` {integer} Total length of the `Buffer` instances in `list` when concatenated. @@ -1023,11 +1039,12 @@ console.log(bufA.length); [`Buffer.allocUnsafe()`][] does. ### Static method: `Buffer.from(array)` + -* `array` {integer[]} +* `array` {integer\[]} Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. Array entries outside that range will be truncated to fit into it. @@ -1053,6 +1070,7 @@ appropriate for `Buffer.from()` variants. `Buffer` pool like [`Buffer.allocUnsafe()`][] does. ### Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])` + @@ -1168,6 +1186,7 @@ console.log(buf); ``` ### Static method: `Buffer.from(buffer)` + @@ -1209,6 +1228,7 @@ A `TypeError` will be thrown if `buffer` is not a `Buffer` or another type appropriate for `Buffer.from()` variants. ### Static method: `Buffer.from(object[, offsetOrEncoding[, length]])` + @@ -1267,6 +1287,7 @@ A `TypeError` will be thrown if `object` does not have the mentioned methods or is not of another type appropriate for `Buffer.from()` variants. ### Static method: `Buffer.from(string[, encoding])` + @@ -1309,6 +1330,7 @@ A `TypeError` will be thrown if `string` is not a string or another type appropriate for `Buffer.from()` variants. ### Static method: `Buffer.isBuffer(obj)` + @@ -1339,6 +1361,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false ``` ### Static method: `Buffer.isEncoding(encoding)` + @@ -1382,6 +1405,7 @@ console.log(Buffer.isEncoding('')); ``` ### Class property: `Buffer.poolSize` + @@ -1509,6 +1533,7 @@ new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length); ``` ### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])` + @@ -1721,6 +1747,7 @@ console.log(buf.toString()); ``` ### `buf.entries()` + @@ -1769,6 +1796,7 @@ for (const pair of buf.entries()) { ``` ### `buf.equals(otherBuffer)` + @@ -1979,6 +2009,7 @@ console.log(buf.includes('this', 4)); ``` ### `buf.indexOf(value[, byteOffset][, encoding])` + @@ -2155,6 +2187,7 @@ for (const key of buf.keys()) { ``` ### `buf.lastIndexOf(value[, byteOffset][, encoding])` + @@ -2326,6 +2360,7 @@ console.log(buf.length); ``` ### `buf.parent` + @@ -2335,6 +2370,7 @@ deprecated: v8.0.0 The `buf.parent` property is a deprecated alias for `buf.buffer`. ### `buf.readBigInt64BE([offset])` + @@ -3309,6 +3367,7 @@ console.log(buf.subarray(-5, -2).toString()); ``` ### `buf.slice([start[, end]])` + @@ -3374,7 +3434,7 @@ added: v5.10.0 * Returns: {Buffer} A reference to `buf`. Interprets `buf` as an array of unsigned 16-bit integers and swaps the -byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] +byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 2. ```mjs @@ -3433,6 +3493,7 @@ buf.swap16(); // Convert to big-endian UTF-16 text. ``` ### `buf.swap32()` + @@ -3440,7 +3501,7 @@ added: v5.10.0 * Returns: {Buffer} A reference to `buf`. Interprets `buf` as an array of unsigned 32-bit integers and swaps the -byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] +byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 4. ```mjs @@ -3482,13 +3543,14 @@ buf2.swap32(); ``` ### `buf.swap64()` + * Returns: {Buffer} A reference to `buf`. -Interprets `buf` as an array of 64-bit numbers and swaps byte order *in-place*. +Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 8. ```mjs @@ -3530,6 +3592,7 @@ buf2.swap64(); ``` ### `buf.toJSON()` + @@ -3581,6 +3644,7 @@ console.log(copy); ``` ### `buf.toString([encoding[, start[, end]]])` + @@ -3651,6 +3715,7 @@ console.log(buf2.toString(undefined, 0, 3)); ``` ### `buf.values()` + @@ -3717,6 +3782,7 @@ for (const value of buf) { ``` ### `buf.write(string[, offset[, length]][, encoding])` + @@ -3771,6 +3837,7 @@ console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); ``` ### `buf.writeBigInt64BE(value[, offset])` + @@ -4907,6 +5001,7 @@ and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** ### `buffer.btoa(data)` + @@ -4928,6 +5023,7 @@ and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** ### `buffer.INSPECT_MAX_BYTES` + @@ -4939,6 +5035,7 @@ Returns the maximum number of bytes that will be returned when [`util.inspect()`][] for more details on `buf.inspect()` behavior. ### `buffer.kMaxLength` + @@ -4948,6 +5045,7 @@ added: v3.0.0 An alias for [`buffer.constants.MAX_LENGTH`][]. ### `buffer.kStringMaxLength` + @@ -4957,6 +5055,7 @@ added: v3.0.0 An alias for [`buffer.constants.MAX_STRING_LENGTH`][]. ### `buffer.resolveObjectURL(id)` + @@ -4971,6 +5070,7 @@ Resolves a `'blob:nodedata:...'` an associated {Blob} object registered using a prior call to `URL.createObjectURL()`. ### `buffer.transcode(source, fromEnc, toEnc)` + @@ -5027,6 +5128,7 @@ the constructor always returned a `Buffer` instance, rather than a `SlowBuffer` instance. #### `new SlowBuffer(size)` + @@ -5038,11 +5140,13 @@ deprecated: v6.0.0 See [`Buffer.allocUnsafeSlow()`][]. ### Buffer constants + #### `buffer.constants.MAX_LENGTH` + @@ -5087,11 +5192,11 @@ differently based on what arguments are provided: * Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`) allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0, - the memory allocated for such `Buffer` instances is *not* initialized and - *can contain sensitive data*. Such `Buffer` instances *must* be subsequently + the memory allocated for such `Buffer` instances is _not_ initialized and + _can contain sensitive data_. Such `Buffer` instances _must_ be subsequently initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the entire `Buffer` before reading data from the `Buffer`. - While this behavior is *intentional* to improve performance, + While this behavior is _intentional_ to improve performance, development experience has demonstrated that a more explicit distinction is required between creating a fast-but-uninitialized `Buffer` versus creating a slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new @@ -5125,18 +5230,18 @@ the various forms of the `new Buffer()` constructor have been **deprecated** and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and [`Buffer.allocUnsafe()`][] methods. -*Developers should migrate all existing uses of the `new Buffer()` constructors -to one of these new APIs.* +_Developers should migrate all existing uses of the `new Buffer()` constructors +to one of these new APIs._ -* [`Buffer.from(array)`][] returns a new `Buffer` that *contains a copy* of the +* [`Buffer.from(array)`][] returns a new `Buffer` that _contains a copy_ of the provided octets. * [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] - returns a new `Buffer` that *shares the same allocated memory* as the given + returns a new `Buffer` that _shares the same allocated memory_ as the given [`ArrayBuffer`][]. -* [`Buffer.from(buffer)`][] returns a new `Buffer` that *contains a copy* of the +* [`Buffer.from(buffer)`][] returns a new `Buffer` that _contains a copy_ of the contents of the given `Buffer`. * [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new - `Buffer` that *contains a copy* of the provided string. + `Buffer` that _contains a copy_ of the provided string. * [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new initialized `Buffer` of the specified size. This method is slower than [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly @@ -5149,12 +5254,13 @@ to one of these new APIs.* potentially sensitive. `Buffer` instances returned by [`Buffer.allocUnsafe()`][] and -[`Buffer.from(array)`][] *may* be allocated off a shared internal memory pool +[`Buffer.from(array)`][] _may_ be allocated off a shared internal memory pool if `size` is less than or equal to half [`Buffer.poolSize`][]. Instances -returned by [`Buffer.allocUnsafeSlow()`][] *never* use the shared internal +returned by [`Buffer.allocUnsafeSlow()`][] _never_ use the shared internal memory pool. ### The `--zero-fill-buffers` command-line option + @@ -5176,14 +5282,14 @@ $ node --zero-fill-buffers ### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"? When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the -segment of allocated memory is *uninitialized* (it is not zeroed-out). While +segment of allocated memory is _uninitialized_ (it is not zeroed-out). While this design makes the allocation of memory quite fast, the allocated segment of memory might contain old data that is potentially sensitive. Using a `Buffer` -created by [`Buffer.allocUnsafe()`][] without *completely* overwriting the +created by [`Buffer.allocUnsafe()`][] without _completely_ overwriting the memory can allow this old data to be leaked when the `Buffer` memory is read. While there are clear performance advantages to using -[`Buffer.allocUnsafe()`][], extra care *must* be taken in order to avoid +[`Buffer.allocUnsafe()`][], extra care _must_ be taken in order to avoid introducing security vulnerabilities into an application. [ASCII]: https://en.wikipedia.org/wiki/ASCII diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 4170bbb5296ae0..9674590d057c2c 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -143,6 +143,7 @@ exec('"my script.cmd" a b', (err, stdout, stderr) => { ``` ### `child_process.exec(command[, options][, callback])` + * `file` {string} The name or path of the executable file to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `env` {Object} Environment key-value pairs. **Default:** `process.env`. @@ -379,6 +381,7 @@ controller.abort(); ``` ### `child_process.fork(modulePath[, args][, options])` + * `modulePath` {string} The module to run in the child. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `detached` {boolean} Prepare child to run independently of its parent @@ -417,7 +420,7 @@ changes: [`options.detached`][]). * `env` {Object} Environment key-value pairs. **Default:** `process.env`. * `execPath` {string} Executable used to create the child process. - * `execArgv` {string[]} List of string arguments passed to the executable. + * `execArgv` {string\[]} List of string arguments passed to the executable. **Default:** `process.execArgv`. * `gid` {number} Sets the group identity of the process (see setgid(2)). * `serialization` {string} Specify the kind of serialization used for sending @@ -492,6 +495,7 @@ if (process.argv[2] === 'child') { ``` ### `child_process.spawn(command[, args][, options])` + * `command` {string} The command to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `env` {Object} Environment key-value pairs. **Default:** `process.env`. @@ -556,7 +560,6 @@ changes: is allowed to run. **Default:** `undefined`. * `killSignal` {string|integer} The signal value to be used when the spawned process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`. - * Returns: {ChildProcess} The `child_process.spawn()` method spawns a new process using the given @@ -679,6 +682,7 @@ controller.abort(); // Stops the child process ``` #### `options.detached` + @@ -737,6 +741,7 @@ subprocess.unref(); ``` #### `options.stdio` + * `file` {string} The name or path of the executable file to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `input` {string|Buffer|TypedArray|DataView} The value which will be passed @@ -925,6 +931,7 @@ function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** ### `child_process.execSync(command[, options])` + * `command` {string} The command to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `input` {string|Buffer|TypedArray|DataView} The value which will be passed @@ -1072,6 +1080,7 @@ function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** ## Class: `ChildProcess` + @@ -1086,6 +1095,7 @@ use the [`child_process.spawn()`][], [`child_process.exec()`][], instances of `ChildProcess`. ### Event: `'close'` + @@ -1117,6 +1127,7 @@ ls.on('exit', (code) => { ``` ### Event: `'disconnect'` + @@ -1144,6 +1155,7 @@ against accidentally invoking handler functions multiple times. See also [`subprocess.kill()`][] and [`subprocess.send()`][]. ### Event: `'exit'` + @@ -1167,6 +1179,7 @@ re-raise the handled signal. See waitpid(2). ### Event: `'message'` + @@ -1187,6 +1200,7 @@ to represent. See [Advanced serialization][] for more details. ### Event: `'spawn'` + @@ -1204,6 +1218,7 @@ the `'spawn'` event will fire, though `bash` may fail to spawn `some-command`. This caveat also applies when using `{ shell: true }`. ### `subprocess.channel` + @@ -1226,6 +1242,7 @@ This method makes the IPC channel keep the event loop of the parent process running if `.unref()` has been called before. #### `subprocess.channel.unref()` + @@ -1234,6 +1251,7 @@ This method makes the IPC channel not keep the event loop of the parent process running, and lets it finish even while the channel is open. ### `subprocess.connected` + @@ -1245,6 +1263,7 @@ send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. ### `subprocess.disconnect()` + @@ -1271,6 +1290,7 @@ The `subprocess.exitCode` property indicates the exit code of the child process. If the child process is still running, the field will be `null`. ### `subprocess.kill([signal])` + @@ -1338,6 +1358,7 @@ setTimeout(() => { ``` ### `subprocess.killed` + @@ -1350,6 +1371,7 @@ successfully received a signal from `subprocess.kill()`. The `killed` property does not indicate that the child process has been terminated. ### `subprocess.pid` + @@ -1369,6 +1391,7 @@ grep.stdin.end(); ``` ### `subprocess.ref()` + @@ -1390,6 +1413,7 @@ subprocess.ref(); ``` ### `subprocess.send(message[, sendHandle[, options]][, callback])` + @@ -1615,6 +1640,7 @@ The `subprocess.stderr` property can be `null` if the child process could not be successfully spawned. ### `subprocess.stdin` + @@ -1636,6 +1662,7 @@ The `subprocess.stdin` property can be `undefined` if the child process could not be successfully spawned. ### `subprocess.stdio` + @@ -1679,6 +1706,7 @@ The `subprocess.stdio` property can be `undefined` if the child process could not be successfully spawned. ### `subprocess.stdout` + @@ -1707,6 +1735,7 @@ The `subprocess.stdout` property can be `null` if the child process could not be successfully spawned. ### `subprocess.unref()` + @@ -1752,6 +1781,7 @@ spawned, `'cmd.exe'` is used as a fallback if `process.env.ComSpec` is unavailable. ## Advanced serialization + @@ -49,6 +51,7 @@ meaning that the script is read from stdin, and the rest of the options are passed to that script. ### `--` + @@ -58,6 +61,7 @@ If no script filename or eval/print script is supplied prior to this, then the next argument is used as a script filename. ### `--abort-on-uncaught-exception` + @@ -70,6 +74,7 @@ If this flag is passed, the behavior can still be set to not abort through `domain` module that uses it). ### `--completion-bash` + @@ -82,6 +87,7 @@ $ source node_bash_completion ``` ### `-C=condition`, `--conditions=condition` + @@ -127,6 +134,7 @@ CPU.20190409.202950.15293.0.0.cpuprofile ``` ### `--cpu-prof-dir` + @@ -140,6 +148,7 @@ The default value is controlled by the [`--diagnostic-dir`][] command-line option. ### `--cpu-prof-interval` + @@ -150,6 +159,7 @@ Specify the sampling interval in microseconds for the CPU profiles generated by `--cpu-prof`. The default is 1000 microseconds. ### `--cpu-prof-name` + @@ -164,11 +174,13 @@ Set the directory to which all diagnostic output files are written. Defaults to current working directory. Affects the default output directory of: + * [`--cpu-prof-dir`][] * [`--heap-prof-dir`][] * [`--redirect-warnings`][] ### `--disable-proto=mode` + @@ -189,12 +202,14 @@ code from strings throw an exception instead. This does not affect the Node.js `vm` module. ### `--dns-result-order=order` + Set the default value of `verbatim` in [`dns.lookup()`][] and [`dnsPromises.lookup()`][]. The value could be: + * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. @@ -202,6 +217,7 @@ The default is `ipv4first` and [`dns.setDefaultResultOrder()`][] have higher priority than `--dns-result-order`. ### `--enable-fips` + @@ -210,6 +226,7 @@ Enable FIPS-compliant crypto at startup. (Requires Node.js to be built against FIPS-compatible OpenSSL.) ### `--enable-source-maps` + @@ -257,6 +277,7 @@ added: v12.9.0 Enable experimental JSON support for the ES Module loader. ### `--experimental-loader=module` + @@ -265,6 +286,7 @@ Specify the `module` of a custom experimental [ECMAScript Module loader][]. `module` may be either a path to a file, or an ECMAScript Module name. ### `--experimental-modules` + @@ -272,6 +294,7 @@ added: v8.5.0 Enable latest experimental modules features (deprecated). ### `--experimental-policy` + @@ -279,12 +302,15 @@ added: v11.8.0 Use the specified file as a security policy. ### `--no-experimental-repl-await` + - Use this flag to disable top-level await in REPL. + +Use this flag to disable top-level await in REPL. ### `--experimental-specifier-resolution=mode` + @@ -308,6 +335,7 @@ added: v9.6.0 Enable experimental ES Module support in the `vm` module. ### `--experimental-wasi-unstable-preview1` + @@ -329,6 +358,7 @@ added: v12.3.0 Enable experimental WebAssembly module support. ### `--force-context-aware` + @@ -336,6 +366,7 @@ added: v12.12.0 Disable loading native addons that are not [context-aware][]. ### `--force-fips` + @@ -344,6 +375,7 @@ Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) (Same requirements as `--enable-fips`.) ### `--frozen-intrinsics` + @@ -360,6 +392,7 @@ reference. Code may break under this flag. be added. ### `--heapsnapshot-near-heap-limit=max_count` + @@ -406,6 +439,7 @@ FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaS ``` ### `--heapsnapshot-signal=signal` + @@ -425,6 +459,7 @@ Heap.20190718.133405.15554.0.001.heapsnapshot ``` ### `--heap-prof` + @@ -447,6 +482,7 @@ Heap.20190409.202950.15293.0.001.heapprofile ``` ### `--heap-prof-dir` + @@ -460,6 +496,7 @@ The default value is controlled by the [`--diagnostic-dir`][] command-line option. ### `--heap-prof-interval` + @@ -467,9 +504,10 @@ added: v12.4.0 > Stability: 1 - Experimental Specify the average sampling interval in bytes for the heap profiles generated -by `--heap-prof`. The default is 512 * 1024 bytes. +by `--heap-prof`. The default is 512 \* 1024 bytes. ### `--heap-prof-name` + @@ -479,6 +517,7 @@ added: v12.4.0 Specify the file name of the heap profile generated by `--heap-prof`. ### `--icu-data-dir=file` + @@ -486,6 +525,7 @@ added: v0.11.15 Specify ICU data load path. (Overrides `NODE_ICU_DATA`.) ### `--input-type=type` + @@ -496,6 +536,7 @@ module. String input is input via `--eval`, `--print`, or `STDIN`. Valid values are `"commonjs"` and `"module"`. The default is `"commonjs"`. ### `--inspect-brk[=[host:]port]` + @@ -504,6 +545,7 @@ Activate inspector on `host:port` and break at start of user script. Default `host:port` is `127.0.0.1:9229`. ### `--inspect-port=[host:]port` + @@ -517,6 +559,7 @@ See the [security warning][] below regarding the `host` parameter usage. ### `--inspect[=[host:]port]` + @@ -528,7 +571,9 @@ and profile Node.js instances. The tools attach to Node.js instances via a tcp port and communicate using the [Chrome DevTools Protocol][]. + + #### Warning: binding inspector to a public IP:port combination is insecure Binding the inspector to a public IP (including `0.0.0.0`) with an open port is @@ -553,6 +598,7 @@ By default inspector websocket url is available in stderr and under `/json/list` endpoint on `http://host:port/json/list`. ### `--insecure-http-parser` + @@ -578,6 +625,7 @@ This flag is inherited from V8 and is subject to change upstream. It may disappear in a non-semver-major release. ### `--max-http-header-size=size` + @@ -598,6 +647,7 @@ added: v7.10.0 This option is a no-op. It is kept for compatibility. ### `--no-addons` + @@ -607,6 +657,7 @@ native addons. When `--no-addons` is specified, calling `process.dlopen` or requiring a native C++ addon will fail and throw an exception. ### `--no-deprecation` + @@ -614,6 +665,7 @@ added: v0.8.0 Silence deprecation warnings. ### `--no-force-async-hooks-checks` + @@ -622,6 +674,7 @@ Disables runtime checks for `async_hooks`. These will still be enabled dynamically when `async_hooks` is enabled. ### `--no-global-search-paths` + @@ -630,6 +683,7 @@ Do not search modules from global paths like `$HOME/.node_modules` and `$NODE_PATH`. ### `--no-warnings` + @@ -637,6 +691,7 @@ added: v6.0.0 Silence all process warnings (including deprecations). ### `--node-memory-debug` + @@ -645,6 +700,7 @@ Enable extra debug checks for memory leaks in Node.js internals. This is usually only useful for developers debugging Node.js itself. ### `--openssl-config=file` + @@ -654,6 +710,7 @@ used to enable FIPS-compliant crypto if Node.js is built against FIPS-enabled OpenSSL. ### `--pending-deprecation` + @@ -661,13 +718,14 @@ added: v8.0.0 Emit pending deprecation warnings. Pending deprecations are generally identical to a runtime deprecation with the -notable exception that they are turned *off* by default and will not be emitted +notable exception that they are turned _off_ by default and will not be emitted unless either the `--pending-deprecation` command-line flag, or the `NODE_PENDING_DEPRECATION=1` environment variable, is set. Pending deprecations are used to provide a kind of selective "early warning" mechanism that developers may leverage to detect deprecated API usage. ### `--policy-integrity=sri` + @@ -679,6 +737,7 @@ the specified integrity. It expects a [Subresource Integrity][] string as a parameter. ### `--preserve-symlinks` + @@ -713,7 +772,7 @@ symlink path for modules as opposed to the real path, allowing symbolically linked peer dependencies to be found. Note, however, that using `--preserve-symlinks` can have other side effects. -Specifically, symbolically linked *native* modules can fail to load if those +Specifically, symbolically linked _native_ modules can fail to load if those are linked from more than one location in the dependency tree (Node.js would see those as two separate modules and would attempt to load the module multiple times, causing an exception to be thrown). @@ -723,6 +782,7 @@ The `--preserve-symlinks` flag does not apply to the main module, which allows behavior for the main module, also use `--preserve-symlinks-main`. ### `--preserve-symlinks-main` + @@ -742,6 +802,7 @@ resolving relative paths. See `--preserve-symlinks` for more information. ### `--prof` + @@ -749,6 +810,7 @@ added: v2.0.0 Generate V8 profiler output. ### `--prof-process` + @@ -756,6 +818,7 @@ added: v5.2.0 Process V8 profiler output generated using the V8 option `--prof`. ### `--redirect-warnings=file` + @@ -770,6 +833,7 @@ will be written to is controlled by the [`--diagnostic-dir`]() command-line option. ### `--report-compact` + @@ -917,6 +988,7 @@ The secure heap is not available on Windows. See [`CRYPTO_secure_malloc_init`][] for more details. ### `--secure-heap-min=n` + @@ -927,6 +999,7 @@ The maximum value is the lesser of `--secure-heap` or `2147483647`. The value given must be a power of two. ### `--throw-deprecation` + @@ -934,6 +1007,7 @@ added: v0.11.14 Throw errors for deprecations. ### `--title=title` + @@ -941,6 +1015,7 @@ added: v10.7.0 Set `process.title` on startup. ### `--tls-cipher-list=list` + @@ -949,6 +1024,7 @@ Specify an alternative default TLS cipher list. Requires Node.js to be built with crypto support (default). ### `--tls-keylog=file` + @@ -978,6 +1056,7 @@ Set default [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.3'. Use to enable support for TLSv1.3. ### `--tls-min-v1.0` + @@ -1017,6 +1099,7 @@ Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.3'. Use to disable support for TLSv1.2, which is not as secure as TLSv1.3. ### `--trace-atomics-wait` + @@ -1044,6 +1127,7 @@ The fields here correspond to: * The timeout passed to `Atomics.wait` ### `--trace-deprecation` + @@ -1051,6 +1135,7 @@ added: v0.8.0 Print stack traces for deprecations. ### `--trace-event-categories` + @@ -1059,6 +1144,7 @@ A comma separated list of categories that should be traced when trace event tracing is enabled using `--trace-events-enabled`. ### `--trace-event-file-pattern` + @@ -1067,6 +1153,7 @@ Template string specifying the filepath for the trace event data, it supports `${rotation}` and `${pid}`. ### `--trace-events-enabled` + @@ -1074,6 +1161,7 @@ added: v7.7.0 Enables the collection of trace event tracing information. ### `--trace-exit` + @@ -1101,6 +1191,7 @@ Prints a stack trace whenever synchronous I/O is detected after the first turn of the event loop. ### `--trace-tls` + @@ -1109,6 +1200,7 @@ Prints TLS packet trace information to `stderr`. This can be used to debug TLS connection problems. ### `--trace-uncaught` + @@ -1121,6 +1213,7 @@ to be an `Error` instance). Enabling this option may affect garbage collection behavior negatively. ### `--trace-warnings` + @@ -1128,6 +1221,7 @@ added: v6.0.0 Print stack traces for process warnings (including deprecations). ### `--track-heap-objects` + @@ -1135,6 +1229,7 @@ added: v2.4.0 Track heap object allocations for heap snapshots. ### `--unhandled-rejections=mode` + @@ -1179,6 +1275,7 @@ environment variables. See `SSL_CERT_DIR` and `SSL_CERT_FILE`. ### `--use-largepages=mode` + @@ -1204,6 +1303,7 @@ added: v0.1.3 Print V8 command-line options. ### `--v8-pool-size=num` + @@ -1217,6 +1317,7 @@ If the value provided is larger than V8's maximum, then the largest value will be chosen. ### `--zero-fill-buffers` + @@ -1225,6 +1326,7 @@ Automatically zero-fills all newly allocated [`Buffer`][] and [`SlowBuffer`][] instances. ### `-c`, `--check` + @@ -1262,6 +1366,7 @@ Print node command-line options. The output of this option is less detailed than this document. ### `-i`, `--interactive` + @@ -1269,6 +1374,7 @@ added: v0.7.7 Opens the REPL even if stdin does not appear to be a terminal. ### `-p`, `--print "script"` + @@ -1293,6 +1400,7 @@ Only CommonJS modules are supported. Attempting to preload a ES6 Module using `--require` will fail with an error. ### `-v`, `--version` + @@ -1314,7 +1422,9 @@ When `FORCE_COLOR` is used and set to a supported value, both the `NO_COLOR`, and `NODE_DISABLE_COLORS` environment variables are ignored. Any other value will result in colorized output being disabled. + ### `NODE_DEBUG=module[,…]` + @@ -1326,6 +1436,7 @@ added: v0.1.32 `','`-separated list of core C++ modules that should print debug information. ### `NODE_DISABLE_COLORS=1` + @@ -1333,6 +1444,7 @@ added: v0.3.0 When set, colors will not be used in the REPL. ### `NODE_EXTRA_CA_CERTS=file` + @@ -1354,6 +1466,7 @@ process is first launched. Changing the value at runtime using `process.env.NODE_EXTRA_CA_CERTS` has no effect on the current process. ### `NODE_ICU_DATA=file` + @@ -1362,6 +1475,7 @@ Data path for ICU (`Intl` object) data. Will extend linked-in data when compiled with small-icu support. ### `NODE_NO_WARNINGS=1` + @@ -1369,6 +1483,7 @@ added: v6.11.0 When set to `1`, process warnings are silenced. ### `NODE_OPTIONS=options...` + @@ -1404,7 +1519,9 @@ node --require "./a.js" --require "./b.js" ``` Node.js options that are allowed are: + + * `--conditions`, `-C` * `--diagnostic-dir` * `--disable-proto` @@ -1489,10 +1606,13 @@ Node.js options that are allowed are: * `--use-openssl-ca` * `--v8-pool-size` * `--zero-fill-buffers` + V8 options that are allowed are: + + * `--abort-on-uncaught-exception` * `--disallow-code-generation-from-strings` * `--huge-max-old-generation-size` @@ -1504,12 +1624,14 @@ V8 options that are allowed are: * `--perf-prof-unwinding-info` * `--perf-prof` * `--stack-trace-limit` + `--perf-basic-prof-only-functions`, `--perf-basic-prof`, `--perf-prof-unwinding-info`, and `--perf-prof` are only available on Linux. ### `NODE_PATH=path[:…]` + @@ -1519,6 +1641,7 @@ added: v0.1.32 On Windows, this is a `';'`-separated list instead. ### `NODE_PENDING_DEPRECATION=1` + @@ -1526,7 +1649,7 @@ added: v8.0.0 When set to `1`, emit pending deprecation warnings. Pending deprecations are generally identical to a runtime deprecation with the -notable exception that they are turned *off* by default and will not be emitted +notable exception that they are turned _off_ by default and will not be emitted unless either the `--pending-deprecation` command-line flag, or the `NODE_PENDING_DEPRECATION=1` environment variable, is set. Pending deprecations are used to provide a kind of selective "early warning" mechanism that @@ -1538,6 +1661,7 @@ Set the number of pending pipe instance handles when the pipe server is waiting for connections. This setting applies to Windows only. ### `NODE_PRESERVE_SYMLINKS=1` + @@ -1546,6 +1670,7 @@ When set to `1`, instructs the module loader to preserve symbolic links when resolving and caching modules. ### `NODE_REDIRECT_WARNINGS=file` + @@ -1557,6 +1682,7 @@ warning to the file, the warning will be written to stderr instead. This is equivalent to using the `--redirect-warnings=file` command-line flag. ### `NODE_REPL_HISTORY=file` + @@ -1566,6 +1692,7 @@ Path to the file used to store the persistent REPL history. The default path is to an empty string (`''` or `' '`) disables persistent REPL history. ### `NODE_REPL_EXTERNAL_MODULE=file` + @@ -1672,18 +1800,20 @@ and the line lengths of the source file (in the key `lineLengths`). environment variable is arbitrary. ### `OPENSSL_CONF=file` + Load an OpenSSL configuration file on startup. Among other uses, this can be -used to enable FIPS-compliant crypto if Node.js is built with `./configure ---openssl-fips`. +used to enable FIPS-compliant crypto if Node.js is built with +`./configure --openssl-fips`. If the [`--openssl-config`][] command-line option is used, the environment variable is ignored. ### `SSL_CERT_DIR=dir` + @@ -1696,6 +1826,7 @@ variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node. ### `SSL_CERT_FILE=file` + @@ -1708,6 +1839,7 @@ variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node. ### `TZ` + @@ -157,6 +158,7 @@ In the primary it can be obtained using `cluster.workers`. In a worker it can be obtained using `cluster.worker`. ### Event: `'disconnect'` + @@ -170,6 +172,7 @@ cluster.fork().on('disconnect', () => { ``` ### Event: `'error'` + @@ -179,6 +182,7 @@ This event is the same as the one provided by [`child_process.fork()`][]. Within a worker, `process.on('error')` may also be used. ### Event: `'exit'` + @@ -220,6 +224,7 @@ worker.on('exit', (code, signal) => { ``` ### Event: `'listening'` + @@ -247,6 +252,7 @@ cluster.fork().on('listening', (address) => { It is not emitted in the worker. ### Event: `'message'` + @@ -351,6 +357,7 @@ if (cluster.isPrimary) { ``` ### Event: `'online'` + @@ -366,6 +373,7 @@ cluster.fork().on('online', () => { It is not emitted in the worker. ### `worker.disconnect()` + @@ -462,6 +471,7 @@ worker.kill(); ``` ### `worker.id` + @@ -475,6 +485,7 @@ While a worker is alive, this is the key that indexes it in `cluster.workers`. ### `worker.isConnected()` + @@ -484,6 +495,7 @@ IPC channel, `false` otherwise. A worker is connected to its primary after it has been created. It is disconnected after the `'disconnect'` event is emitted. ### `worker.isDead()` + @@ -556,6 +568,7 @@ if (cluster.isPrimary) { ``` ### `worker.kill([signal])` + @@ -581,6 +594,7 @@ In a worker, `process.kill()` exists, but it is not this function; it is [`kill()`][]. ### `worker.process` + @@ -598,6 +612,7 @@ on `process` and `.exitedAfterDisconnect` is not `true`. This protects against accidental disconnection. ### `worker.send(message[, sendHandle[, options]][, callback])` + @@ -661,6 +677,7 @@ cluster.on('disconnect', (worker) => { ``` ## Event: `'exit'` + @@ -685,6 +702,7 @@ cluster.on('exit', (worker, code, signal) => { See [`child_process` event: `'exit'`][]. ## Event: `'fork'` + @@ -713,6 +731,7 @@ cluster.on('exit', (worker, code, signal) => { ``` ## Event: `'listening'` + @@ -744,6 +763,7 @@ The `addressType` is one of: * `'udp4'` or `'udp6'` (UDP v4 or v6) ## Event: `'message'` + @@ -779,6 +800,7 @@ cluster.on('online', (worker) => { ``` ## Event: `'setup'` + @@ -794,6 +816,7 @@ The `settings` object is the `cluster.settings` object at the time If accuracy is important, use `cluster.settings`. ## `cluster.disconnect([callback])` + @@ -812,6 +835,7 @@ finished. This can only be called from the primary process. ## `cluster.fork([env])` + @@ -824,6 +848,7 @@ Spawn a new worker process. This can only be called from the primary process. ## `cluster.isMaster` + @@ -844,6 +870,7 @@ by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is undefined, then `isPrimary` is `true`. ## `cluster.isWorker` + @@ -853,6 +880,7 @@ added: v0.6.0 True if the process is not a primary (it is the negation of `cluster.isPrimary`). ## `cluster.schedulingPolicy` + @@ -871,6 +899,7 @@ distribute IOCP handles without incurring a large performance hit. values are `'rr'` and `'none'`. ## `cluster.settings` + * {Object} - * `execArgv` {string[]} List of string arguments passed to the Node.js + * `execArgv` {string\[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`. * `exec` {string} File path to worker file. **Default:** `process.argv[1]`. - * `args` {string[]} String arguments passed to worker. + * `args` {string\[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`. * `cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process). @@ -925,6 +954,7 @@ contain the settings, including the default values. This object is not intended to be changed or set manually. ## `cluster.setupMaster([settings])` + @@ -990,6 +1021,7 @@ cluster.fork(); // http worker This can only be called from the primary process. ## `cluster.worker` + @@ -1023,6 +1055,7 @@ if (cluster.isPrimary) { ``` ## `cluster.workers` + diff --git a/doc/api/console.md b/doc/api/console.md index 411366ab2f6842..5c8b4ecc64d9b4 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -17,7 +17,7 @@ The module exports two specific components: [`process.stderr`][]. The global `console` can be used without calling `require('console')`. -***Warning***: The global console object's methods are neither consistently +_**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [note on process I/O][] for more information. @@ -65,6 +65,7 @@ myConsole.warn(`Danger ${name}! Danger!`); ``` ## Class: `Console` + @@ -192,6 +197,7 @@ will clear only the output in the current terminal viewport for the Node.js binary. ### `console.count([label])` + @@ -202,6 +208,7 @@ Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + ```js > console.count() default: 1 @@ -225,6 +232,7 @@ undefined ``` ### `console.countReset([label])` + @@ -234,6 +242,7 @@ added: v8.3.0 Resets the internal counter specific to `label`. + ```js > console.count('abc'); abc: 1 @@ -247,6 +256,7 @@ undefined ``` ### `console.debug(data[, ...args])` + @@ -273,13 +284,14 @@ added: v0.1.101 formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`. **Default:** `2`. * `colors` {boolean} If `true`, then the output will be styled with ANSI color - codes. Colors are customizable; - see [customizing `util.inspect()` colors][]. **Default:** `false`. + codes. Colors are customizable; + see [customizing `util.inspect()` colors][]. **Default:** `false`. Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`. This function bypasses any custom `inspect()` function defined on `obj`. ### `console.dirxml(...data)` + @@ -319,6 +332,7 @@ If formatting elements (e.g. `%d`) are not found in the first string then values are concatenated. See [`util.format()`][] for more information. ### `console.group([...label])` + @@ -332,6 +346,7 @@ If one or more `label`s are provided, those are printed first without the additional indentation. ### `console.groupCollapsed()` + @@ -339,6 +354,7 @@ additional indentation. An alias for [`console.group()`][]. ### `console.groupEnd()` + @@ -347,6 +363,7 @@ Decreases indentation of subsequent lines by spaces for `groupIndentation` length. ### `console.info([data][, ...args])` + @@ -357,6 +374,7 @@ added: v0.1.100 The `console.info()` function is an alias for [`console.log()`][]. ### `console.log([data][, ...args])` + @@ -380,12 +398,13 @@ console.log('count:', count); See [`util.format()`][] for more information. ### `console.table(tabularData[, properties])` + * `tabularData` {any} -* `properties` {string[]} Alternate properties for constructing the table. +* `properties` {string\[]} Alternate properties for constructing the table. Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just @@ -417,6 +436,7 @@ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); ``` ### `console.time([label])` + @@ -430,6 +450,7 @@ suitable time units to `stdout`. For example, if the elapsed time is 3869ms, `console.timeEnd()` displays "3.869s". ### `console.timeEnd([label])` + @@ -475,6 +497,7 @@ console.timeEnd('process'); ``` ### `console.trace([message][, ...args])` + @@ -502,6 +525,7 @@ console.trace('Show me'); ``` ### `console.warn([data][, ...args])` + @@ -512,11 +536,13 @@ added: v0.1.100 The `console.warn()` function is an alias for [`console.error()`][]. ## Inspector only methods + The following methods are exposed by the V8 engine in the general API but do not display anything unless used in conjunction with the [inspector][] (`--inspect` flag). ### `console.profile([label])` + @@ -536,6 +562,7 @@ console.profileEnd('MyLabel'); ``` ### `console.profileEnd([label])` + @@ -551,6 +578,7 @@ If this method is called without a label, the most recently started profile is stopped. ### `console.timeStamp([label])` + diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 139a669c03efe6..b23bee42e95bc6 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -52,7 +52,7 @@ try { When using the lexical ESM `import` keyword, the error can only be caught if a handler for `process.on('uncaughtException')` is registered -*before* any attempt to load the module is made -- using, for instance, +_before_ any attempt to load the module is made -- using, for instance, a preload module. When using ESM, if there is a chance that the code may be run on a build @@ -69,6 +69,7 @@ try { ``` ## Class: `Certificate` + @@ -84,6 +85,7 @@ data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC implementation][] internally. ### Static method: `Certificate.exportChallenge(spkac[, encoding])` + @@ -234,6 +239,7 @@ console.log(challenge.toString('utf8')); ``` #### `certificate.exportPublicKey(spkac[, encoding])` + @@ -262,6 +268,7 @@ console.log(publicKey); ``` #### `certificate.verifySpkac(spkac[, encoding])` + @@ -292,6 +299,7 @@ console.log(cert.verifySpkac(Buffer.from(spkac))); ``` ## Class: `Cipher` + @@ -515,6 +523,7 @@ scrypt(password, 'salt', 24, (err, key) => { ``` ### `cipher.final([outputEncoding])` + @@ -529,6 +538,7 @@ longer be used to encrypt data. Attempts to call `cipher.final()` more than once will result in an error being thrown. ### `cipher.getAuthTag()` + @@ -542,6 +552,7 @@ The `cipher.getAuthTag()` method should only be called after encryption has been completed using the [`cipher.final()`][] method. ### `cipher.setAAD(buffer[, options])` + @@ -563,6 +574,7 @@ length of the plaintext in bytes. See [CCM mode][]. The `cipher.setAAD()` method must be called before [`cipher.update()`][]. ### `cipher.setAutoPadding([autoPadding])` + @@ -583,6 +595,7 @@ The `cipher.setAutoPadding()` method must be called before [`cipher.final()`][]. ### `cipher.update(data[, inputEncoding][, outputEncoding])` + @@ -812,6 +826,7 @@ console.log(decrypted); ``` ### `decipher.final([outputEncoding])` + @@ -826,6 +841,7 @@ no longer be used to decrypt data. Attempts to call `decipher.final()` more than once will result in an error being thrown. ### `decipher.setAAD(buffer[, options])` + @@ -911,6 +929,7 @@ The `decipher.setAutoPadding()` method must be called before [`decipher.final()`][]. ### `decipher.update(data[, inputEncoding][, outputEncoding])` + @@ -997,6 +1017,7 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ### `diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` + @@ -1018,6 +1039,7 @@ If `outputEncoding` is given a string is returned; otherwise, a [`Buffer`][] is returned. ### `diffieHellman.generateKeys([encoding])` + @@ -1032,6 +1054,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getGenerator([encoding])` + @@ -1044,6 +1067,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getPrime([encoding])` + @@ -1056,6 +1080,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getPrivateKey([encoding])` + @@ -1068,6 +1093,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getPublicKey([encoding])` + @@ -1080,6 +1106,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.setPrivateKey(privateKey[, encoding])` + @@ -1093,6 +1120,7 @@ to be a string. If no `encoding` is provided, `privateKey` is expected to be a [`Buffer`][], `TypedArray`, or `DataView`. ### `diffieHellman.setPublicKey(publicKey[, encoding])` + @@ -1106,6 +1134,7 @@ to be a string. If no `encoding` is provided, `publicKey` is expected to be a [`Buffer`][], `TypedArray`, or `DataView`. ### `diffieHellman.verifyError` + @@ -1122,6 +1151,7 @@ module): * `DH_NOT_SUITABLE_GENERATOR` ## Class: `DiffieHellmanGroup` + @@ -1157,6 +1187,7 @@ modp18 ``` ## Class: `ECDH` + @@ -1214,6 +1245,7 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ### Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])` + @@ -1286,6 +1318,7 @@ console.log(uncompressedKey === ecdh.getPublicKey('hex')); ``` ### `ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` + @@ -1341,6 +1375,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `ecdh.getPrivateKey([encoding])` + @@ -1352,6 +1387,7 @@ If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is returned. ### `ecdh.getPublicKey([encoding][, format])` + @@ -1369,6 +1405,7 @@ If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is returned. ### `ecdh.setPrivateKey(privateKey[, encoding])` + @@ -1386,6 +1423,7 @@ created, an error is thrown. Upon setting the private key, the associated public point (key) is also generated and set in the `ECDH` object. ### `ecdh.setPublicKey(publicKey[, encoding])` + @@ -1580,6 +1619,7 @@ console.log(hash.digest('hex')); ``` ### `hash.copy([options])` + @@ -1638,6 +1678,7 @@ console.log(hash.copy().digest('hex')); ``` ### `hash.digest([encoding])` + @@ -1654,6 +1695,7 @@ The `Hash` object can not be used again after `hash.digest()` method has been called. Multiple calls will cause an error to be thrown. ### `hash.update(data[, inputEncoding])` + @@ -1796,6 +1839,7 @@ console.log(hmac.digest('hex')); ``` ### `hmac.digest([encoding])` + @@ -1811,6 +1855,7 @@ The `Hmac` object can not be used again after `hmac.digest()` has been called. Multiple calls to `hmac.digest()` will result in an error being thrown. ### `hmac.update(data[, inputEncoding])` + @@ -1906,6 +1953,7 @@ const { ``` ### `keyObject.asymmetricKeyDetails` + @@ -2038,6 +2089,7 @@ For secret keys, this property represents the size of the key in bytes. This property is `undefined` for asymmetric keys. ### `keyObject.type` + @@ -2049,6 +2101,7 @@ Depending on the type of this `KeyObject`, this property is either or `'private'` for private (asymmetric) keys. ## Class: `Sign` + @@ -2164,6 +2217,7 @@ console.log(verify.verify(publicKey, signature)); ``` ### `sign.sign(privateKey[, outputEncoding])` + + * `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `dsaEncoding` {string} * `padding` {integer} * `saltLength` {integer} * `outputEncoding` {string} The [encoding][] of the return value. * Returns: {Buffer | string} + Calculates the signature on all the data passed through using either @@ -2207,6 +2263,7 @@ object, the following additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -2227,6 +2284,7 @@ The `Sign` object can not be again used after `sign.sign()` method has been called. Multiple calls to `sign.sign()` will result in an error being thrown. ### `sign.update(data[, inputEncoding])` + @@ -2267,6 +2326,7 @@ The [`crypto.createVerify()`][] method is used to create `Verify` instances. See [`Sign`][] for examples. ### `verify.update(data[, inputEncoding])` + + * `object` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `dsaEncoding` {string} * `padding` {integer} @@ -2318,6 +2380,7 @@ changes: * `signatureEncoding` {string} The [encoding][] of the `signature` string. * Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key. + Verifies the provided data using the given `object` and `signature`. @@ -2331,6 +2394,7 @@ object, the following additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -2358,6 +2422,7 @@ Because public keys can be derived from private keys, a private key may be passed instead of a public key. ## Class: `X509Certificate` + @@ -2382,6 +2447,7 @@ console.log(x509.subject); ``` ### `new X509Certificate(buffer)` + @@ -2390,6 +2456,7 @@ added: v15.6.0 X509 Certificate. ### `x509.ca` + @@ -2398,6 +2465,7 @@ added: v15.6.0 certificate. ### `x509.checkEmail(email[, options])` + @@ -2415,6 +2483,7 @@ added: v15.6.0 Checks whether the certificate matches the given email address. ### `x509.checkHost(name[, options])` + @@ -2432,6 +2501,7 @@ added: v15.6.0 Checks whether the certificate matches the given host name. ### `x509.checkIP(ip[, options])` + @@ -2449,6 +2519,7 @@ added: v15.6.0 Checks whether the certificate matches the given IP address (IPv4 or IPv6). ### `x509.checkIssued(otherCert)` + @@ -2459,6 +2530,7 @@ added: v15.6.0 Checks whether this certificate was issued by the given `otherCert`. ### `x509.checkPrivateKey(privateKey)` + @@ -2470,6 +2542,7 @@ Checks whether the public key for this certificate is consistent with the given private key. ### `x509.fingerprint` + @@ -2479,6 +2552,7 @@ added: v15.6.0 The SHA-1 fingerprint of this certificate. ### `x509.fingerprint256` + @@ -2488,6 +2562,7 @@ added: v15.6.0 The SHA-256 fingerprint of this certificate. ### `x509.infoAccess` + @@ -2497,6 +2572,7 @@ added: v15.6.0 The information access content of this certificate. ### `x509.issuer` + @@ -2506,6 +2582,7 @@ added: v15.6.0 The issuer identification included in this certificate. ### `x509.issuerCertificate` + @@ -2516,15 +2593,17 @@ The issuer certificate or `undefined` if the issuer certificate is not available. ### `x509.keyUsage` + -* Type: {string[]} +* Type: {string\[]} An array detailing the key usages for this certificate. ### `x509.publicKey` + @@ -2534,6 +2613,7 @@ added: v15.6.0 The public key {KeyObject} for this certificate. ### `x509.raw` + @@ -2543,6 +2623,7 @@ added: v15.6.0 A `Buffer` containing the DER encoding of this certificate. ### `x509.serialNumber` + @@ -2552,6 +2633,7 @@ added: v15.6.0 The serial number of this certificate. ### `x509.subject` + @@ -2561,6 +2643,7 @@ added: v15.6.0 The complete subject of this certificate. ### `x509.subjectAltName` + @@ -2570,6 +2653,7 @@ added: v15.6.0 The subject alternative name specified for this certificate. ### `x509.toJSON()` + @@ -2581,6 +2665,7 @@ There is no standard JSON encoding for X509 certificates. The certificate. ### `x509.toLegacyObject()` + @@ -2591,6 +2676,7 @@ Returns information about this certificate using the legacy [certificate object][] encoding. ### `x509.toString()` + @@ -2600,6 +2686,7 @@ added: v15.6.0 Returns the PEM-encoded certificate. ### `x509.validFrom` + @@ -2609,6 +2696,7 @@ added: v15.6.0 The date/time from which this certificate is considered valid. ### `x509.validTo` + @@ -2618,6 +2706,7 @@ added: v15.6.0 The date/time until which this certificate is considered valid. ### `x509.verify(publicKey)` + @@ -2631,6 +2720,7 @@ Does not perform any other validation checks on the certificate. ## `crypto` module methods and properties ### `crypto.constants` + @@ -2640,6 +2730,7 @@ added: v6.3.0 described in [Crypto constants][]. ### `crypto.DEFAULT_ENCODING` + @@ -2695,6 +2788,7 @@ added: v15.8.0 Checks the primality of the `candidate`. ### `crypto.checkPrimeSync(candidate[, options])` + @@ -2715,6 +2809,7 @@ added: v15.8.0 Checks the primality of the `candidate`. ### `crypto.createCipher(algorithm, password[, options])` + @@ -2988,6 +3088,7 @@ Creates a `DiffieHellman` key exchange object and generates a prime of If `generator` is not specified, the value `2` is used. ### `crypto.createDiffieHellmanGroup(name)` + @@ -2998,6 +3099,7 @@ added: v0.9.3 An alias for [`crypto.getDiffieHellman()`][] ### `crypto.createECDH(curveName)` + @@ -3012,6 +3114,7 @@ OpenSSL releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. ### `crypto.createHash(algorithm[, options])` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView} * `key`: {string|ArrayBuffer|Buffer|TypedArray|DataView|Object} The key material, either in PEM, DER, or JWK format. * `format`: {string} Must be `'pem'`, `'der'`, or '`'jwk'`. **Default:** `'pem'`. * `type`: {string} Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is - required only if the `format` is `'der'` and ignored otherwise. + required only if the `format` is `'der'` and ignored otherwise. * `passphrase`: {string | Buffer} The passphrase to use for decryption. * `encoding`: {string} The string encoding to use when `key` is a string. * Returns: {KeyObject} + Creates and returns a new key object containing a private key. If `key` is a @@ -3209,6 +3316,7 @@ If the private key is encrypted, a `passphrase` must be specified. The length of the passphrase is limited to 1024 bytes. ### `crypto.createPublicKey(key)` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView} * `key`: {string|ArrayBuffer|Buffer|TypedArray|DataView|Object} The key material, either in PEM, DER, or JWK format. * `format`: {string} Must be `'pem'`, `'der'`, or `'jwk'`. **Default:** `'pem'`. * `type`: {string} Must be `'pkcs1'` or `'spki'`. This option is - required only if the `format` is `'der'` and ignored otherwise. + required only if the `format` is `'der'` and ignored otherwise. * `encoding` {string} The string encoding to use when `key` is a string. * Returns: {KeyObject} + Creates and returns a new key object containing a public key. If `key` is a @@ -3256,6 +3366,7 @@ extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type and it will be impossible to extract the private key from the returned object. ### `crypto.createSecretKey(key[, encoding])` + @@ -3293,6 +3405,7 @@ algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest algorithm names. ### `crypto.createVerify(algorithm[, options])` + @@ -3313,6 +3426,7 @@ algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest algorithm names. ### `crypto.diffieHellman(options)` + @@ -3372,6 +3487,7 @@ generateKey('hmac', { length: 64 }, (err, key) => { ``` ### `crypto.generateKeyPair(type, options, callback)` + @@ -3630,6 +3748,7 @@ console.log(key.export().toString('hex')); // e89..........41e ``` ### `crypto.generatePrime(size[, options[, callback]])` + @@ -3672,6 +3791,7 @@ in an {ArrayBuffer}. If the `bigint` option is `true`, then a {bigint} is provided. ### `crypto.generatePrimeSync(size[, options])` + @@ -3712,6 +3832,7 @@ in an {ArrayBuffer}. If the `bigint` option is `true`, then a {bigint} is provided. ### `crypto.getCipherInfo(nameOrNid[, options])` + @@ -3741,11 +3862,12 @@ cipher, use the `keyLength` and `ivLength` options. If the given values are unacceptable, `undefined` will be returned. ### `crypto.getCiphers()` + -* Returns: {string[]} An array with the names of the supported cipher +* Returns: {string\[]} An array with the names of the supported cipher algorithms. ```mjs @@ -3765,11 +3887,12 @@ console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] ``` ### `crypto.getCurves()` + -* Returns: {string[]} An array with the names of the supported elliptic curves. +* Returns: {string\[]} An array with the names of the supported elliptic curves. ```mjs const { @@ -3788,6 +3911,7 @@ console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` ### `crypto.getDiffieHellman(groupName)` + @@ -3844,6 +3968,7 @@ console.log(aliceSecret === bobSecret); ``` ### `crypto.getFips()` + @@ -3853,11 +3978,12 @@ added: v10.0.0 the return type of this API to a {boolean}. ### `crypto.getHashes()` + -* Returns: {string[]} An array of the names of the supported hash algorithms, +* Returns: {string\[]} An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. ```mjs @@ -3877,6 +4003,7 @@ console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` ### `crypto.hkdf(digest, ikm, salt, info, keylen, callback)` + @@ -3930,6 +4057,7 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { ``` ### `crypto.hkdfSync(digest, ikm, salt, info, keylen)` + @@ -3977,6 +4105,7 @@ console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' ``` ### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)` + + * `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'` * `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to - use for OAEP padding. If not specified, no label is used. + use for OAEP padding. If not specified, no label is used. * `padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the decrypted content. + Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using @@ -4214,6 +4347,7 @@ object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. ### `crypto.privateEncrypt(privateKey, buffer)` + + * `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} A PEM encoded private key. @@ -4241,6 +4376,7 @@ changes: or `passphrase` are strings. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the encrypted content. + Encrypts `buffer` with `privateKey`. The returned data can be decrypted using @@ -4252,6 +4388,7 @@ object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. ### `crypto.publicDecrypt(key, buffer)` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} An optional passphrase for the private key. @@ -4277,6 +4415,7 @@ changes: or `passphrase` are strings. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the decrypted content. + Decrypts `buffer` with `key`.`buffer` was previously encrypted using @@ -4291,6 +4430,7 @@ Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key. ### `crypto.publicEncrypt(key, buffer)` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} A PEM encoded public or private key, {KeyObject}, or {CryptoKey}. @@ -4329,6 +4470,7 @@ changes: `oaepLabel`, or `passphrase` are strings. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the encrypted content. + Encrypts the content of `buffer` with `key` and returns a new @@ -4344,6 +4486,7 @@ Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key. ### `crypto.randomBytes(size[, callback])` + @@ -4756,6 +4903,7 @@ Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator. ### `crypto.scrypt(password, salt, keylen[, options], callback)` + @@ -4930,6 +5080,7 @@ added: v15.6.0 allocated bytes. ### `crypto.setEngine(engine[, flags])` + @@ -4964,6 +5115,7 @@ The flags below are deprecated in OpenSSL-1.1.0. * `crypto.constants.ENGINE_METHOD_STORE` ### `crypto.setFips(bool)` + @@ -4974,6 +5126,7 @@ Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. ### `crypto.sign(algorithm, data, key[, callback])` + + * `algorithm` {string | null | undefined} * `data` {ArrayBuffer|Buffer|TypedArray|DataView} * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} @@ -4995,6 +5149,7 @@ changes: * `err` {Error} * `signature` {Buffer} * Returns: {Buffer} if the `callback` function is not provided. + Calculates and returns the signature for `data` using the given private key and @@ -5010,6 +5165,7 @@ additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -5024,6 +5180,7 @@ additional properties can be passed: If the `callback` function is provided this function uses libuv's threadpool. ### `crypto.timingSafeEqual(a, b)` + + * `algorithm` {string|null|undefined} * `data` {ArrayBuffer| Buffer|TypedArray|DataView} * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} @@ -5081,6 +5240,7 @@ changes: * Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key if the `callback` function is not provided. + Verifies the given signature for `data` using the given key and algorithm. If @@ -5096,6 +5256,7 @@ additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -5115,6 +5276,7 @@ key may be passed for `key`. If the `callback` function is provided this function uses libuv's threadpool. ### `crypto.webcrypto` + @@ -5242,7 +5404,7 @@ mode must adhere to certain restrictions when using the cipher API: * As CCM processes the whole message at once, `update()` must be called exactly once. * Even though calling `update()` is sufficient to encrypt/decrypt the message, - applications *must* call `final()` to compute or verify the + applications _must_ call `final()` to compute or verify the authentication tag. ```mjs diff --git a/doc/api/debugger.md b/doc/api/debugger.md index b155738b073165..c5e019e5412278 100644 --- a/doc/api/debugger.md +++ b/doc/api/debugger.md @@ -32,6 +32,7 @@ Inserting the statement `debugger;` into the source code of a script will enable a breakpoint at that position in the code: + ```js // myscript.js global.x = 5; diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 8beb77603ab8fc..0d9d00582bb66b 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -42,6 +42,7 @@ However, the deprecation identifier will not be modified. ## List of deprecated APIs ### DEP0001: `http.OutgoingMessage.prototype.flush` + + Type: Documentation-only (supports [`--pending-deprecation`][]) The `process._tickCallback` property was never documented as an officially supported API. ### DEP0135: `WriteStream.open()` and `ReadStream.open()` are internal + + Type: Runtime `Transform._transformState` will be removed in future versions where it is no longer required due to simplification of the implementation. ### DEP0144: `module.parent` + @@ -68,6 +69,7 @@ New instances of `dgram.Socket` are created using [`dgram.createSocket()`][]. The `new` keyword is not to be used to create `dgram.Socket` instances. ### Event: `'close'` + @@ -76,6 +78,7 @@ The `'close'` event is emitted after a socket is closed with [`close()`][]. Once triggered, no new `'message'` events will be emitted on this socket. ### Event: `'connect'` + @@ -84,6 +87,7 @@ The `'connect'` event is emitted after a socket is associated to a remote address as a result of a successful [`connect()`][] call. ### Event: `'error'` + @@ -94,6 +98,7 @@ The `'error'` event is emitted whenever any error occurs. The event handler function is passed a single `Error` object. ### Event: `'listening'` + @@ -105,6 +110,7 @@ Until the `dgram.Socket` is listening, the underlying system resources do not exist and calls such as `socket.address()` and `socket.setTTL()` will fail. ### Event: `'message'` + @@ -126,6 +132,7 @@ address field set to `'fe80::2618:1234:ab11:3b9c%en0'`, where `'%en0'` is the interface name as a zone ID suffix. ### `socket.addMembership(multicastAddress[, multicastInterface])` + @@ -177,11 +184,13 @@ if (cluster.isPrimary) { ``` ### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` + + * `sourceAddress` {string} * `groupAddress` {string} * `multicastInterface` {string} @@ -197,6 +206,7 @@ When called on an unbound socket, this method will implicitly bind to a random port, listening on all interfaces. ### `socket.address()` + @@ -210,6 +220,7 @@ properties. This method throws `EBADF` if called on an unbound socket. ### `socket.bind([port][, address][, callback])` + @@ -343,6 +355,7 @@ socket.bind({ ``` ### `socket.close([callback])` + @@ -353,6 +366,7 @@ Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the [`'close'`][] event. ### `socket.connect(port[, address][, callback])` + @@ -372,6 +386,7 @@ is emitted and the optional `callback` function is called. In case of failure, the `callback` is called or, failing this, an `'error'` event is emitted. ### `socket.disconnect()` + @@ -382,6 +397,7 @@ disconnected socket will result in an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception. ### `socket.dropMembership(multicastAddress[, multicastInterface])` + @@ -398,6 +414,7 @@ If `multicastInterface` is not specified, the operating system will attempt to drop membership on all valid interfaces. ### `socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` + @@ -427,6 +445,7 @@ added: v8.7.0 This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.getSendBufferSize()` + @@ -436,6 +455,7 @@ added: v8.7.0 This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.ref()` + @@ -454,6 +474,7 @@ The `socket.ref()` method returns a reference to the socket so calls can be chained. ### `socket.remoteAddress()` + @@ -465,6 +486,7 @@ endpoint. This method throws an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception if the socket is not connected. ### `socket.send(msg[, offset, length][, port][, address][, callback])` + @@ -665,16 +688,17 @@ packets may be sent to a local interface's broadcast address. This method throws `EBADF` if called on an unbound socket. ### `socket.setMulticastInterface(multicastInterface)` + * `multicastInterface` {string} -*All references to scope in this section are referring to +_All references to scope in this section are referring to [IPv6 Zone Indices][], which are defined by [RFC 4007][]. In string form, an IP with a scope index is written as `'IP%scope'` where scope is an interface name -or interface number.* +or interface number._ Sets the default outgoing multicast interface of the socket to a chosen interface or back to system interface selection. The `multicastInterface` must @@ -715,6 +739,7 @@ socket.bind(1234, () => { ``` #### Example: IPv4 outgoing multicast interface + All systems use an IP of the host on the desired physical interface: ```js @@ -727,10 +752,10 @@ socket.bind(1234, () => { #### Call results -A call on a socket that is not ready to send or no longer open may throw a *Not -running* [`Error`][]. +A call on a socket that is not ready to send or no longer open may throw a _Not +running_ [`Error`][]. -If `multicastInterface` can not be parsed into an IP then an *EINVAL* +If `multicastInterface` can not be parsed into an IP then an _EINVAL_ [`System Error`][] is thrown. On IPv4, if `multicastInterface` is a valid address but does not match any @@ -745,6 +770,7 @@ used to return control of the sockets default outgoing interface to the system for future multicast packets. ### `socket.setMulticastLoopback(flag)` + @@ -757,6 +783,7 @@ multicast packets will also be received on the local interface. This method throws `EBADF` if called on an unbound socket. ### `socket.setMulticastTTL(ttl)` + @@ -774,6 +801,7 @@ The `ttl` argument may be between 0 and 255. The default on most systems is `1`. This method throws `EBADF` if called on an unbound socket. ### `socket.setRecvBufferSize(size)` + @@ -786,6 +814,7 @@ in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.setSendBufferSize(size)` + @@ -798,6 +827,7 @@ in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.setTTL(ttl)` + @@ -816,6 +846,7 @@ is 64. This method throws `EBADF` if called on an unbound socket. ### `socket.unref()` + @@ -836,6 +867,7 @@ chained. ## `dgram` module functions ### `dgram.createSocket(options[, callback])` + diff --git a/doc/api/dns.md b/doc/api/dns.md index ac7f7156043184..48796f9c846f30 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -52,6 +52,7 @@ dns.resolve4('archive.org', (err, addresses) => { See the [Implementation considerations section][] for more information. ## Class: `dns.Resolver` + @@ -94,6 +95,7 @@ The following methods from the `dns` module are available: * [`resolver.setServers()`][`dns.setServers()`] ### `Resolver([options])` + @@ -123,6 +126,7 @@ Cancel all outstanding DNS queries made by this resolver. The corresponding callbacks will be called with an error with code `ECANCELLED`. ### `resolver.setLocalAddress([ipv4][, ipv6])` + @@ -144,17 +148,19 @@ servers, and the v6 local address when making requests to IPv6 DNS servers. The `rrtype` of resolution requests has no impact on the local address used. ## `dns.getServers()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array of IP address strings, formatted according to [RFC 5952][], that are currently configured for DNS resolution. A string will include a port section if a custom port is used. + ```js [ '4.4.4.4', @@ -165,6 +171,7 @@ section if a custom port is used. ``` ## `dns.lookup(hostname[, options], callback)` + @@ -297,6 +306,7 @@ If this method is invoked as its [`util.promisify()`][]ed version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. ## `dns.resolve(hostname[, rrtype], callback)` + @@ -305,15 +315,15 @@ added: v0.1.27 * `rrtype` {string} Resource record type. **Default:** `'A'`. * `callback` {Function} * `err` {Error} - * `records` {string[] | Object[] | Object} + * `records` {string\[] | Object\[] | Object} Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource records. The type and structure of individual results varies based on `rrtype`: -| `rrtype` | `records` contains | Result type | Shorthand method | -|-----------|--------------------------------|-------------|--------------------------| +| `rrtype` | `records` contains | Result type | Shorthand method | +| --------- | ------------------------------ | ----------- | ------------------------ | | `'A'` | IPv4 addresses (default) | {string} | [`dns.resolve4()`][] | | `'AAAA'` | IPv6 addresses | {string} | [`dns.resolve6()`][] | | `'ANY'` | any records | {Object} | [`dns.resolveAny()`][] | @@ -325,12 +335,13 @@ records. The type and structure of individual results varies based on `rrtype`: | `'PTR'` | pointer records | {string} | [`dns.resolvePtr()`][] | | `'SOA'` | start of authority records | {Object} | [`dns.resolveSoa()`][] | | `'SRV'` | service records | {Object} | [`dns.resolveSrv()`][] | -| `'TXT'` | text records | {string[]} | [`dns.resolveTxt()`][] | +| `'TXT'` | text records | {string\[]} | [`dns.resolveTxt()`][] | On error, `err` is an [`Error`][] object, where `err.code` is one of the [DNS error codes](). ## `dns.resolve4(hostname[, options], callback)` + + ```js [ { type: 'A', address: '127.0.0.1', ttl: 299 }, { type: 'CNAME', value: 'example.com' }, @@ -429,6 +442,7 @@ queries. It may be better to call individual methods like [`dns.resolve4()`][], [`dns.resolveMx()`][], and so on. For more details, see [RFC 8482][]. ## `dns.resolveCname(hostname, callback)` + @@ -436,7 +450,7 @@ added: v0.3.2 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {string[]} + * `addresses` {string\[]} Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function @@ -444,6 +458,7 @@ will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). ## `dns.resolveCaa(hostname, callback)` + @@ -451,7 +466,7 @@ added: v15.0.0 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `records` {Object[]} + * `records` {Object\[]} Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function @@ -460,6 +475,7 @@ available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). ## `dns.resolveMx(hostname, callback)` + @@ -467,7 +483,7 @@ added: v0.1.27 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {Object[]} + * `addresses` {Object\[]} Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will @@ -475,6 +491,7 @@ contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). ## `dns.resolveNaptr(hostname, callback)` + @@ -482,7 +499,7 @@ added: v0.9.12 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {Object[]} + * `addresses` {Object\[]} Uses the DNS protocol to resolve regular expression based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` @@ -496,6 +513,7 @@ function will contain an array of objects with the following properties: * `preference` + ```js { flags: 's', @@ -508,6 +526,7 @@ function will contain an array of objects with the following properties: ``` ## `dns.resolveNs(hostname, callback)` + @@ -515,7 +534,7 @@ added: v0.1.90 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {string[]} + * `addresses` {string\[]} Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will @@ -523,6 +542,7 @@ contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). ## `dns.resolvePtr(hostname, callback)` + @@ -530,13 +550,14 @@ added: v6.0.0 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {string[]} + * `addresses` {string\[]} Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will be an array of strings containing the reply records. ## `dns.resolveSoa(hostname, callback)` + @@ -559,6 +580,7 @@ be an object with the following properties: * `minttl` + ```js { nsname: 'ns.example.com', @@ -572,6 +594,7 @@ be an object with the following properties: ``` ## `dns.resolveSrv(hostname, callback)` + @@ -579,7 +602,7 @@ added: v0.1.27 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {Object[]} + * `addresses` {Object\[]} Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will @@ -591,6 +614,7 @@ be an array of objects with the following properties: * `name` + ```js { priority: 10, @@ -601,15 +625,18 @@ be an array of objects with the following properties: ``` ## `dns.resolveTxt(hostname, callback)` + + * `hostname` {string} * `callback` {Function} * `err` {Error} - * `records` <string[][]> + * `records` \ + Uses the DNS protocol to resolve text queries (`TXT` records) for the @@ -620,6 +647,7 @@ one record. Depending on the use case, these could be either joined together or treated separately. ## `dns.reverse(ip, callback)` + @@ -627,7 +655,7 @@ added: v0.1.16 * `ip` {string} * `callback` {Function} * `err` {Error} - * `hostnames` {string[]} + * `hostnames` {string\[]} Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names. @@ -636,6 +664,7 @@ On error, `err` is an [`Error`][] object, where `err.code` is one of the [DNS error codes][]. ## `dns.setDefaultResultOrder(order)` + @@ -644,6 +673,7 @@ added: v16.4.0 Set the default value of `verbatim` in [`dns.lookup()`][] and [`dnsPromises.lookup()`][]. The value could be: + * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. @@ -653,11 +683,12 @@ priority than [`--dns-result-order`][]. When using [worker threads][], dns orders in workers. ## `dns.setServers(servers)` + -* `servers` {string[]} array of [RFC 5952][] formatted addresses +* `servers` {string\[]} array of [RFC 5952][] formatted addresses Sets the IP address and port of servers to be used when performing DNS resolution. The `servers` argument is an array of [RFC 5952][] formatted @@ -678,17 +709,18 @@ The `dns.setServers()` method must not be called while a DNS query is in progress. The [`dns.setServers()`][] method affects only [`dns.resolve()`][], -`dns.resolve*()` and [`dns.reverse()`][] (and specifically *not* +`dns.resolve*()` and [`dns.reverse()`][] (and specifically _not_ [`dns.lookup()`][]). This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). That is, if attempting to resolve with the first server provided results in a -`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with +`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error. ## DNS promises API + @@ -754,6 +787,7 @@ The following methods from the `dnsPromises` API are available: * [`resolver.setServers()`][`dnsPromises.setServers()`] ### `resolver.cancel()` + @@ -762,17 +796,19 @@ Cancel all outstanding DNS queries made by this resolver. The corresponding promises will be rejected with an error with code `ECANCELLED`. ### `dnsPromises.getServers()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array of IP address strings, formatted according to [RFC 5952][], that are currently configured for DNS resolution. A string will include a port section if a custom port is used. + ```js [ '4.4.4.4', @@ -783,6 +819,7 @@ section if a custom port is used. ``` ### `dnsPromises.lookup(hostname[, options])` + @@ -849,6 +886,7 @@ dnsPromises.lookup('example.com', options).then((result) => { ``` ### `dnsPromises.lookupService(address, port)` + @@ -875,6 +913,7 @@ dnsPromises.lookupService('127.0.0.1', 22).then((result) => { ``` ### `dnsPromises.resolve(hostname[, rrtype])` + @@ -887,12 +926,12 @@ of the resource records. When successful, the `Promise` is resolved with an array of resource records. The type and structure of individual results vary based on `rrtype`: -| `rrtype` | `records` contains | Result type | Shorthand method | -|-----------|--------------------------------|-------------|--------------------------| +| `rrtype` | `records` contains | Result type | Shorthand method | +| --------- | ------------------------------ | ----------- | -------------------------------- | | `'A'` | IPv4 addresses (default) | {string} | [`dnsPromises.resolve4()`][] | | `'AAAA'` | IPv6 addresses | {string} | [`dnsPromises.resolve6()`][] | | `'ANY'` | any records | {Object} | [`dnsPromises.resolveAny()`][] | -| `'CAA'` | CA authorization records | {Object} | [`dnsPromises.resolveCaa()`][] | +| `'CAA'` | CA authorization records | {Object} | [`dnsPromises.resolveCaa()`][] | | `'CNAME'` | canonical name records | {string} | [`dnsPromises.resolveCname()`][] | | `'MX'` | mail exchange records | {Object} | [`dnsPromises.resolveMx()`][] | | `'NAPTR'` | name authority pointer records | {Object} | [`dnsPromises.resolveNaptr()`][] | @@ -900,12 +939,13 @@ based on `rrtype`: | `'PTR'` | pointer records | {string} | [`dnsPromises.resolvePtr()`][] | | `'SOA'` | start of authority records | {Object} | [`dnsPromises.resolveSoa()`][] | | `'SRV'` | service records | {Object} | [`dnsPromises.resolveSrv()`][] | -| `'TXT'` | text records | {string[]} | [`dnsPromises.resolveTxt()`][] | +| `'TXT'` | text records | {string\[]} | [`dnsPromises.resolveTxt()`][] | On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` is one of the [DNS error codes](). ### `dnsPromises.resolve4(hostname[, options])` + @@ -922,6 +962,7 @@ Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). ### `dnsPromises.resolve6(hostname[, options])` + @@ -938,6 +979,7 @@ Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the addresses. ### `dnsPromises.resolveAny(hostname)` + @@ -950,22 +992,23 @@ records. Each object has a property `type` that indicates the type of the current record. And depending on the `type`, additional properties will be present on the object: -| Type | Properties | -|------|------------| -| `'A'` | `address`/`ttl` | -| `'AAAA'` | `address`/`ttl` | -| `'CNAME'` | `value` | -| `'MX'` | Refer to [`dnsPromises.resolveMx()`][] | -| `'NAPTR'` | Refer to [`dnsPromises.resolveNaptr()`][] | -| `'NS'` | `value` | -| `'PTR'` | `value` | -| `'SOA'` | Refer to [`dnsPromises.resolveSoa()`][] | -| `'SRV'` | Refer to [`dnsPromises.resolveSrv()`][] | -| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dnsPromises.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` | +| Type | Properties | +| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `'A'` | `address`/`ttl` | +| `'AAAA'` | `address`/`ttl` | +| `'CNAME'` | `value` | +| `'MX'` | Refer to [`dnsPromises.resolveMx()`][] | +| `'NAPTR'` | Refer to [`dnsPromises.resolveNaptr()`][] | +| `'NS'` | `value` | +| `'PTR'` | `value` | +| `'SOA'` | Refer to [`dnsPromises.resolveSoa()`][] | +| `'SRV'` | Refer to [`dnsPromises.resolveSrv()`][] | +| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dnsPromises.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` | Here is an example of the result object: + ```js [ { type: 'A', address: '127.0.0.1', ttl: 299 }, { type: 'CNAME', value: 'example.com' }, @@ -983,6 +1026,7 @@ Here is an example of the result object: ``` ### `dnsPromises.resolveCaa(hostname)` + @@ -996,6 +1040,7 @@ certification authority authorization records available for the `hostname` 'pki.example.com'}]`). ### `dnsPromises.resolveCname(hostname)` + @@ -1007,6 +1052,7 @@ the `Promise` is resolved with an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). ### `dnsPromises.resolveMx(hostname)` + @@ -1019,6 +1065,7 @@ containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). ### `dnsPromises.resolveNaptr(hostname)` + @@ -1037,6 +1084,7 @@ of objects with the following properties: * `preference` + ```js { flags: 's', @@ -1049,6 +1097,7 @@ of objects with the following properties: ``` ### `dnsPromises.resolveNs(hostname)` + @@ -1061,6 +1110,7 @@ records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). ### `dnsPromises.resolvePtr(hostname)` + @@ -1072,6 +1122,7 @@ Uses the DNS protocol to resolve pointer records (`PTR` records) for the containing the reply records. ### `dnsPromises.resolveSoa(hostname)` + @@ -1091,6 +1142,7 @@ following properties: * `minttl` + ```js { nsname: 'ns.example.com', @@ -1104,6 +1156,7 @@ following properties: ``` ### `dnsPromises.resolveSrv(hostname)` + @@ -1120,6 +1173,7 @@ the following properties: * `name` + ```js { priority: 10, @@ -1130,6 +1184,7 @@ the following properties: ``` ### `dnsPromises.resolveTxt(hostname)` + @@ -1144,6 +1199,7 @@ one record. Depending on the use case, these could be either joined together or treated separately. ### `dnsPromises.reverse(ip)` + @@ -1157,6 +1213,7 @@ On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` is one of the [DNS error codes](). ### `dnsPromises.setDefaultResultOrder(order)` + @@ -1165,6 +1222,7 @@ added: v16.4.0 Set the default value of `verbatim` in [`dns.lookup()`][] and [`dnsPromises.lookup()`][]. The value could be: + * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. @@ -1174,11 +1232,12 @@ higher priority than [`--dns-result-order`][]. When using [worker threads][], default dns orders in workers. ### `dnsPromises.setServers(servers)` + -* `servers` {string[]} array of [RFC 5952][] formatted addresses +* `servers` {string\[]} array of [RFC 5952][] formatted addresses Sets the IP address and port of servers to be used when performing DNS resolution. The `servers` argument is an array of [RFC 5952][] formatted @@ -1201,7 +1260,7 @@ progress. This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). That is, if attempting to resolve with the first server provided results in a -`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with +`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error. diff --git a/doc/api/documentation.md b/doc/api/documentation.md index 9100354b361644..be5e7671f8d18c 100644 --- a/doc/api/documentation.md +++ b/doc/api/documentation.md @@ -51,11 +51,13 @@ modifications occur. To avoid surprises, use of an Experimental feature may need a command-line flag. Experimental features may also emit a [warning][]. ## Stability overview + ## JSON output + diff --git a/doc/api/domain.md b/doc/api/domain.md index 02833e36e7ba1c..9552b3bbcd478c 100644 --- a/doc/api/domain.md +++ b/doc/api/domain.md @@ -1,4 +1,5 @@ # Domain + + + ```js const fs = require('fs'); fs.readFile('a file that does not exist', (err, data) => { @@ -101,7 +102,7 @@ and [event emitter-based][] APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail). -For *all* [`EventEmitter`][] objects, if an `'error'` event handler is not +For _all_ [`EventEmitter`][] objects, if an `'error'` event handler is not provided, the error will be thrown, causing the Node.js process to report an uncaught exception and crash unless either: The [`domain`][domains] module is used appropriately or a handler has been registered for the @@ -118,8 +119,8 @@ setImmediate(() => { }); ``` -Errors generated in this way *cannot* be intercepted using `try…catch` as -they are thrown *after* the calling code has already exited. +Errors generated in this way _cannot_ be intercepted using `try…catch` as +they are thrown _after_ the calling code has already exited. Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated. @@ -199,7 +200,7 @@ provided text message. If an object is passed as `message`, the text message is generated by calling `message.toString()`. The `error.stack` property will represent the point in the code at which `new Error()` was called. Stack traces are dependent on [V8's stack trace API][]. Stack traces extend only to either -(a) the beginning of *synchronous code execution*, or (b) the number of frames +(a) the beginning of _synchronous code execution_, or (b) the number of frames given by the property `Error.stackTraceLimit`, whichever is smaller. ### `Error.captureStackTrace(targetObject[, constructorOpt])` @@ -247,7 +248,7 @@ collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes -will affect any stack trace captured *after* the value has been changed. +will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. @@ -269,7 +270,7 @@ about specific codes. The `error.message` property is the string description of the error as set by calling `new Error(message)`. The `message` passed to the constructor will also appear in the first line of the stack trace of the `Error`, however changing -this property after the `Error` object is created *may not* change the first +this property after the `Error` object is created _may not_ change the first line of the stack trace (for example, when `error.stack` is read before this property is changed). @@ -341,7 +342,7 @@ The location information will be one of: * `native`, if the frame represents a call internal to V8 (as in `[].forEach`). * `plain-filename.js:line:column`, if the frame represents a call internal - to Node.js. + to Node.js. * `/absolute/path/to/file.js:line:column`, if the frame represents a call in a user program, or its dependencies. @@ -372,7 +373,7 @@ require('net').connect(-1); // Throws "RangeError: "port" option should be >= 0 and < 65536: -1" ``` -Node.js will generate and throw `RangeError` instances *immediately* as a form +Node.js will generate and throw `RangeError` instances _immediately_ as a form of argument validation. ## Class: `ReferenceError` @@ -570,7 +571,7 @@ require('url').parse(() => { }); // Throws TypeError, since it expected a string. ``` -Node.js will generate and throw `TypeError` instances *immediately* as a form +Node.js will generate and throw `TypeError` instances _immediately_ as a form of argument validation. ## Exceptions vs. errors @@ -580,11 +581,11 @@ of argument validation. A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a `throw` statement. While it is not required that these values are instances of `Error` or classes which inherit from -`Error`, all exceptions thrown by Node.js or the JavaScript runtime *will* be +`Error`, all exceptions thrown by Node.js or the JavaScript runtime _will_ be instances of `Error`. -Some exceptions are *unrecoverable* at the JavaScript layer. Such exceptions -will *always* cause the Node.js process to crash. Examples include `assert()` +Some exceptions are _unrecoverable_ at the JavaScript layer. Such exceptions +will _always_ cause the Node.js process to crash. Examples include `assert()` checks or `abort()` calls in the C++ layer. ## OpenSSL errors @@ -611,13 +612,17 @@ The OpenSSL library the error originates in. A human-readable string describing the reason for the error. + ## Node.js error codes + ### `ABORT_ERR` + + Used when an operation has been aborted (typically using an `AbortController`). APIs _not_ using `AbortSignal`s typically do not raise an error with this code. @@ -626,6 +631,7 @@ This code does not use the regular `ERR_*` convention Node.js errors use in order to be compatible with the web platform's `AbortError`. + ### `ERR_AMBIGUOUS_ARGUMENT` A function argument is being used in a way that suggests that the function @@ -636,12 +642,14 @@ is the expected message rather than the message the `AssertionError` will display if `block` does not throw. + ### `ERR_ARG_NOT_ITERABLE` An iterable argument (i.e. a value that works with `for...of` loops) was required, but not provided to a Node.js API. + ### `ERR_ASSERTION` A special type of error that can be triggered whenever Node.js detects an @@ -649,28 +657,33 @@ exceptional logic violation that should never occur. These are raised typically by the `assert` module. + ### `ERR_ASYNC_CALLBACK` An attempt was made to register something that is not a function as an `AsyncHooks` callback. + ### `ERR_ASYNC_TYPE` The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API. + ### `ERR_BROTLI_COMPRESSION_FAILED` Data passed to a Brotli stream was not successfully compressed. + ### `ERR_BROTLI_INVALID_PARAM` An invalid parameter key was passed during construction of a Brotli stream. + ### `ERR_BUFFER_CONTEXT_NOT_AVAILABLE` An attempt was made to create a Node.js `Buffer` instance from addon or embedder @@ -684,39 +697,47 @@ prototype of the resulting object. `Uint8Array`s are generally accepted in all Node.js core APIs where `Buffer`s are; they are available in all Contexts. + ### `ERR_BUFFER_OUT_OF_BOUNDS` An operation outside the bounds of a `Buffer` was attempted. + ### `ERR_BUFFER_TOO_LARGE` An attempt has been made to create a `Buffer` larger than the maximum allowed size. + ### `ERR_CANNOT_WATCH_SIGINT` Node.js was unable to watch for the `SIGINT` signal. + ### `ERR_CHILD_CLOSED_BEFORE_REPLY` A child process was closed before the parent received a reply. + ### `ERR_CHILD_PROCESS_IPC_REQUIRED` Used when a child process is being forked without specifying an IPC channel. + ### `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option. + ### `ERR_CLOSED_MESSAGE_PORT` + @@ -746,11 +770,13 @@ added: v12.5.0 A class constructor was called that is not callable. + ### `ERR_CONSTRUCT_CALL_REQUIRED` A constructor for a class was called without `new`. + ### `ERR_CONTEXT_NOT_INITIALIZED` The vm context passed into the API is not yet initialized. This could happen @@ -759,18 +785,21 @@ context, for example, when the allocation fails or the maximum call stack size is reached when the context is created. + ### `ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED` A client certificate engine was requested that is not supported by the version of OpenSSL being used. + ### `ERR_CRYPTO_ECDH_INVALID_FORMAT` An invalid value for the `format` argument was passed to the `crypto.ECDH()` class `getPublicKey()` method. + ### `ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` An invalid value for the `key` argument has been passed to the @@ -778,46 +807,55 @@ An invalid value for the `key` argument has been passed to the key lies outside of the elliptic curve. + ### `ERR_CRYPTO_ENGINE_UNKNOWN` An invalid crypto engine identifier was passed to [`require('crypto').setEngine()`][]. + ### `ERR_CRYPTO_FIPS_FORCED` The [`--force-fips`][] command-line argument was used but there was an attempt to enable or disable FIPS mode in the `crypto` module. + ### `ERR_CRYPTO_FIPS_UNAVAILABLE` An attempt was made to enable or disable FIPS mode, but FIPS mode was not available. + ### `ERR_CRYPTO_HASH_FINALIZED` [`hash.digest()`][] was called multiple times. The `hash.digest()` method must be called no more than one time per instance of a `Hash` object. + ### `ERR_CRYPTO_HASH_UPDATE_FAILED` [`hash.update()`][] failed for any reason. This should rarely, if ever, happen. + ### `ERR_CRYPTO_INCOMPATIBLE_KEY` The given crypto keys are incompatible with the attempted operation. + ### `ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS` The selected public or private key encoding is incompatible with other options. + ### `ERR_CRYPTO_INITIALIZATION_FAILED` + @@ -825,7 +863,9 @@ added: v15.0.0 Initialization of the crypto subsystem failed. + ### `ERR_CRYPTO_INVALID_AUTH_TAG` + @@ -833,7 +873,9 @@ added: v15.0.0 An invalid authentication tag was provided. + ### `ERR_CRYPTO_INVALID_COUNTER` + @@ -841,7 +883,9 @@ added: v15.0.0 An invalid counter was provided for a counter-mode cipher. + ### `ERR_CRYPTO_INVALID_CURVE` + @@ -849,12 +893,15 @@ added: v15.0.0 An invalid elliptic-curve was provided. + ### `ERR_CRYPTO_INVALID_DIGEST` An invalid [crypto digest algorithm][] was specified. + ### `ERR_CRYPTO_INVALID_IV` + @@ -862,7 +909,9 @@ added: v15.0.0 An invalid initialization vector was provided. + ### `ERR_CRYPTO_INVALID_JWK` + @@ -870,12 +919,15 @@ added: v15.0.0 An invalid JSON Web Key was provided. + ### `ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE` The given crypto key object's type is invalid for the attempted operation. + ### `ERR_CRYPTO_INVALID_KEYLEN` + @@ -883,7 +935,9 @@ added: v15.0.0 An invalid key length was provided. + ### `ERR_CRYPTO_INVALID_KEYPAIR` + @@ -891,7 +945,9 @@ added: v15.0.0 An invalid key pair was provided. + ### `ERR_CRYPTO_INVALID_KEYTYPE` + @@ -899,7 +955,9 @@ added: v15.0.0 An invalid key type was provided. + ### `ERR_CRYPTO_INVALID_MESSAGELEN` + @@ -907,7 +965,9 @@ added: v15.0.0 An invalid message length was provided. + ### `ERR_CRYPTO_INVALID_SCRYPT_PARAMS` + @@ -915,13 +975,16 @@ added: v15.0.0 Invalid scrypt algorithm parameters were provided. + ### `ERR_CRYPTO_INVALID_STATE` A crypto method was used on an object that was in an invalid state. For instance, calling [`cipher.getAuthTag()`][] before calling `cipher.final()`. + ### `ERR_CRYPTO_INVALID_TAG_LENGTH` + @@ -929,7 +992,9 @@ added: v15.0.0 An invalid authentication tag length was provided. + ### `ERR_CRYPTO_JOB_INIT_FAILED` + @@ -937,19 +1002,23 @@ added: v15.0.0 Initialization of an asynchronous crypto operation failed. + ### `ERR_CRYPTO_JWK_UNSUPPORTED_CURVE` Key's Elliptic Curve is not registered for use in the [JSON Web Key Elliptic Curve Registry][]. + ### `ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE` Key's Asymmetric Key Type is not registered for use in the [JSON Web Key Types Registry][]. + ### `ERR_CRYPTO_OPERATION_FAILED` + @@ -957,47 +1026,56 @@ added: v15.0.0 A crypto operation failed for an otherwise unspecified reason. + ### `ERR_CRYPTO_PBKDF2_ERROR` The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js. + ### `ERR_CRYPTO_SCRYPT_INVALID_PARAMETER` One or more [`crypto.scrypt()`][] or [`crypto.scryptSync()`][] parameters are outside their legal range. + ### `ERR_CRYPTO_SCRYPT_NOT_SUPPORTED` Node.js was compiled without `scrypt` support. Not possible with the official release binaries but can happen with custom builds, including distro builds. + ### `ERR_CRYPTO_SIGN_KEY_REQUIRED` A signing `key` was not provided to the [`sign.sign()`][] method. + ### `ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH` [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. + ### `ERR_CRYPTO_UNKNOWN_CIPHER` An unknown cipher was specified. + ### `ERR_CRYPTO_UNKNOWN_DH_GROUP` An unknown Diffie-Hellman group name was given. See [`crypto.getDiffieHellman()`][] for a list of valid group names. + ### `ERR_CRYPTO_UNSUPPORTED_OPERATION` + @@ -1005,7 +1083,9 @@ added: v15.0.0 An attempt to invoke an unsupported crypto operation was made. + ### `ERR_DEBUGGER_ERROR` + @@ -1013,7 +1093,9 @@ added: v16.4.0 An error occurred with the [debugger][]. + ### `ERR_DEBUGGER_STARTUP_ERROR` + @@ -1021,7 +1103,9 @@ added: v16.4.0 The [debugger][] timed out waiting for the required host/port to be free. + ### `ERR_DLOPEN_DISABLED` + @@ -1029,7 +1113,9 @@ added: v16.10.0 Loading native addons has been disabled using [`--no-addons`][]. + ### `ERR_DLOPEN_FAILED` + @@ -1037,12 +1123,15 @@ added: v15.0.0 A call to `process.dlopen()` failed. + ### `ERR_DIR_CLOSED` The [`fs.Dir`][] was previously closed. + ### `ERR_DIR_CONCURRENT_OPERATION` + @@ -1051,11 +1140,13 @@ A synchronous read or close call was attempted on an [`fs.Dir`][] which has ongoing asynchronous operations. + ### `ERR_DNS_SET_SERVERS_FAILED` `c-ares` failed to set the DNS server. + ### `ERR_DOMAIN_CALLBACK_NOT_AVAILABLE` The `domain` module was not usable since it could not establish the required @@ -1064,6 +1155,7 @@ error handling hooks, because earlier point in time. + ### `ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE` [`process.setUncaughtExceptionCaptureCallback()`][] could not be called @@ -1073,28 +1165,33 @@ The stack trace is extended to include the point in time at which the `domain` module had been loaded. + ### `ERR_ENCODING_INVALID_ENCODED_DATA` Data provided to `TextDecoder()` API was invalid according to the encoding provided. + ### `ERR_ENCODING_NOT_SUPPORTED` Encoding provided to `TextDecoder()` API was not one of the [WHATWG Supported Encodings][]. + ### `ERR_EVAL_ESM_CANNOT_PRINT` `--print` cannot be used with ESM input. + ### `ERR_EVENT_RECURSION` Thrown when an attempt is made to recursively dispatch an event on `EventTarget`. + ### `ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE` The JS execution context is not associated with a Node.js environment. @@ -1102,13 +1199,16 @@ This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly. + ### `ERR_FALSY_VALUE_REJECTION` A `Promise` that was callbackified via `util.callbackify()` was rejected with a falsy value. + ### `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` + @@ -1117,7 +1217,9 @@ Used when a feature that is not available to the current platform which is running Node.js is used. + ### `ERR_FS_CP_DIR_TO_NON_DIR` + @@ -1126,7 +1228,9 @@ An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using [`fs.cp()`][]. + ### `ERR_FS_CP_EEXIST` + @@ -1135,7 +1239,9 @@ An attempt was made to copy over a file that already existed with [`fs.cp()`][], with the `force` and `errorOnExist` set to `true`. + ### `ERR_FS_CP_EINVAL` + @@ -1143,7 +1249,9 @@ added: v16.7.0 When using [`fs.cp()`][], `src` or `dest` pointed to an invalid path. + ### `ERR_FS_CP_FIFO_PIPE` + @@ -1151,7 +1259,9 @@ added: v16.7.0 An attempt was made to copy a named pipe with [`fs.cp()`][]. + ### `ERR_FS_CP_NON_DIR_TO_DIR` + @@ -1160,7 +1270,9 @@ An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using [`fs.cp()`][]. + ### `ERR_FS_CP_SOCKET` + @@ -1168,7 +1280,9 @@ added: v16.7.0 An attempt was made to copy to a socket with [`fs.cp()`][]. + ### `ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY` + @@ -1177,7 +1291,9 @@ When using [`fs.cp()`][], a symlink in `dest` pointed to a subdirectory of `src`. + ### `ERR_FS_CP_UNKNOWN` + @@ -1185,137 +1301,162 @@ added: v16.7.0 An attempt was made to copy to an unknown file type with [`fs.cp()`][]. + ### `ERR_FS_EISDIR` Path is a directory. + ### `ERR_FS_FILE_TOO_LARGE` An attempt has been made to read a file whose size is larger than the maximum allowed size for a `Buffer`. + ### `ERR_FS_INVALID_SYMLINK_TYPE` An invalid symlink type was passed to the [`fs.symlink()`][] or [`fs.symlinkSync()`][] methods. + ### `ERR_HTTP_HEADERS_SENT` An attempt was made to add more headers after the headers had already been sent. + ### `ERR_HTTP_INVALID_HEADER_VALUE` An invalid HTTP header value was specified. + ### `ERR_HTTP_INVALID_STATUS_CODE` Status code was outside the regular status code range (100-999). + ### `ERR_HTTP_REQUEST_TIMEOUT` The client has not sent the entire request within the allowed time. + ### `ERR_HTTP_SOCKET_ENCODING` Changing the socket encoding is not allowed per [RFC 7230 Section 3][]. + ### `ERR_HTTP_TRAILER_INVALID` The `Trailer` header was set even though the transfer encoding does not support that. + ### `ERR_HTTP2_ALTSVC_INVALID_ORIGIN` HTTP/2 ALTSVC frames require a valid origin. + ### `ERR_HTTP2_ALTSVC_LENGTH` HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes. + ### `ERR_HTTP2_CONNECT_AUTHORITY` For HTTP/2 requests using the `CONNECT` method, the `:authority` pseudo-header is required. + ### `ERR_HTTP2_CONNECT_PATH` For HTTP/2 requests using the `CONNECT` method, the `:path` pseudo-header is forbidden. + ### `ERR_HTTP2_CONNECT_SCHEME` For HTTP/2 requests using the `CONNECT` method, the `:scheme` pseudo-header is forbidden. + ### `ERR_HTTP2_ERROR` A non-specific HTTP/2 error has occurred. + ### `ERR_HTTP2_GOAWAY_SESSION` New HTTP/2 Streams may not be opened after the `Http2Session` has received a `GOAWAY` frame from the connected peer. + ### `ERR_HTTP2_HEADER_SINGLE_VALUE` Multiple values were provided for an HTTP/2 header field that was required to have only a single value. + ### `ERR_HTTP2_HEADERS_AFTER_RESPOND` An additional headers was specified after an HTTP/2 response was initiated. + ### `ERR_HTTP2_HEADERS_SENT` An attempt was made to send multiple response headers. + ### `ERR_HTTP2_INFO_STATUS_NOT_ALLOWED` Informational HTTP status codes (`1xx`) may not be set as the response status code on HTTP/2 responses. + ### `ERR_HTTP2_INVALID_CONNECTION_HEADERS` HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses. + ### `ERR_HTTP2_INVALID_HEADER_VALUE` An invalid HTTP/2 header value was specified. + ### `ERR_HTTP2_INVALID_INFO_STATUS` An invalid HTTP informational status code has been specified. Informational status codes must be an integer between `100` and `199` (inclusive). + ### `ERR_HTTP2_INVALID_ORIGIN` HTTP/2 `ORIGIN` frames require a valid origin. + ### `ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH` Input `Buffer` and `Uint8Array` instances passed to the @@ -1323,28 +1464,33 @@ Input `Buffer` and `Uint8Array` instances passed to the six. + ### `ERR_HTTP2_INVALID_PSEUDOHEADER` Only valid HTTP/2 pseudoheaders (`:status`, `:path`, `:authority`, `:scheme`, and `:method`) may be used. + ### `ERR_HTTP2_INVALID_SESSION` An action was performed on an `Http2Session` object that had already been destroyed. + ### `ERR_HTTP2_INVALID_SETTING_VALUE` An invalid value has been specified for an HTTP/2 setting. + ### `ERR_HTTP2_INVALID_STREAM` An operation was performed on a stream that had already been destroyed. + ### `ERR_HTTP2_MAX_PENDING_SETTINGS_ACK` Whenever an HTTP/2 `SETTINGS` frame is sent to a connected peer, the peer is @@ -1354,68 +1500,80 @@ be sent at any given time. This error code is used when that limit has been reached. + ### `ERR_HTTP2_NESTED_PUSH` An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted. + ### `ERR_HTTP2_NO_MEM` Out of memory when using the `http2session.setLocalWindowSize(windowSize)` API. + ### `ERR_HTTP2_NO_SOCKET_MANIPULATION` An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an `Http2Session`. + ### `ERR_HTTP2_ORIGIN_LENGTH` HTTP/2 `ORIGIN` frames are limited to a length of 16382 bytes. + ### `ERR_HTTP2_OUT_OF_STREAMS` The number of streams created on a single HTTP/2 session reached the maximum limit. + ### `ERR_HTTP2_PAYLOAD_FORBIDDEN` A message payload was specified for an HTTP response code for which a payload is forbidden. + ### `ERR_HTTP2_PING_CANCEL` An HTTP/2 ping was canceled. + ### `ERR_HTTP2_PING_LENGTH` HTTP/2 ping payloads must be exactly 8 bytes in length. + ### `ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED` An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the `:` prefix. + ### `ERR_HTTP2_PUSH_DISABLED` An attempt was made to create a push stream, which had been disabled by the client. + ### `ERR_HTTP2_SEND_FILE` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to send a directory. + ### `ERR_HTTP2_SEND_FILE_NOSEEK` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to @@ -1423,50 +1581,59 @@ send something other than a regular file, but `offset` or `length` options were provided. + ### `ERR_HTTP2_SESSION_ERROR` The `Http2Session` closed with a non-zero error code. + ### `ERR_HTTP2_SETTINGS_CANCEL` The `Http2Session` settings canceled. + ### `ERR_HTTP2_SOCKET_BOUND` An attempt was made to connect a `Http2Session` object to a `net.Socket` or `tls.TLSSocket` that had already been bound to another `Http2Session` object. + ### `ERR_HTTP2_SOCKET_UNBOUND` An attempt was made to use the `socket` property of an `Http2Session` that has already been closed. + ### `ERR_HTTP2_STATUS_101` Use of the `101` Informational status code is forbidden in HTTP/2. + ### `ERR_HTTP2_STATUS_INVALID` An invalid HTTP status code has been specified. Status codes must be an integer between `100` and `599` (inclusive). + ### `ERR_HTTP2_STREAM_CANCEL` An `Http2Stream` was destroyed before any data was transmitted to the connected peer. + ### `ERR_HTTP2_STREAM_ERROR` A non-zero error code was been specified in an `RST_STREAM` frame. + ### `ERR_HTTP2_STREAM_SELF_DEPENDENCY` When setting the priority for an HTTP/2 stream, the stream may be marked as @@ -1474,7 +1641,9 @@ a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself. + ### `ERR_HTTP2_TOO_MANY_INVALID_FRAMES` + @@ -1483,11 +1652,13 @@ The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the `maxSessionInvalidFrames` option, has been exceeded. + ### `ERR_HTTP2_TRAILERS_ALREADY_SENT` Trailing headers have already been sent on the `Http2Stream`. + ### `ERR_HTTP2_TRAILERS_NOT_READY` The `http2stream.sendTrailers()` method cannot be called until after the @@ -1496,23 +1667,27 @@ The `http2stream.sendTrailers()` method cannot be called until after the is set for the `Http2Stream`. + ### `ERR_HTTP2_UNSUPPORTED_PROTOCOL` `http2.connect()` was passed a URL that uses any protocol other than `http:` or `https:`. + ### `ERR_ILLEGAL_CONSTRUCTOR` An attempt was made to construct an object using a non-public constructor. + ### `ERR_INCOMPATIBLE_OPTION_PAIR` An option pair is incompatible with each other and cannot be used at the same time. + ### `ERR_INPUT_TYPE_NOT_ALLOWED` > Stability: 1 - Experimental @@ -1521,6 +1696,7 @@ The `--input-type` flag was used to attempt to execute a file. This flag can only be used with input via `--eval`, `--print` or `STDIN`. + ### `ERR_INSPECTOR_ALREADY_ACTIVATED` While using the `inspector` module, an attempt was made to activate the @@ -1528,104 +1704,123 @@ inspector when it already started to listen on a port. Use `inspector.close()` before activating it on a different address. + ### `ERR_INSPECTOR_ALREADY_CONNECTED` While using the `inspector` module, an attempt was made to connect when the inspector was already connected. + ### `ERR_INSPECTOR_CLOSED` While using the `inspector` module, an attempt was made to use the inspector after the session had already closed. + ### `ERR_INSPECTOR_COMMAND` An error occurred while issuing a command via the `inspector` module. + ### `ERR_INSPECTOR_NOT_ACTIVE` The `inspector` is not active when `inspector.waitForDebugger()` is called. + ### `ERR_INSPECTOR_NOT_AVAILABLE` The `inspector` module is not available for use. + ### `ERR_INSPECTOR_NOT_CONNECTED` While using the `inspector` module, an attempt was made to use the inspector before it was connected. + ### `ERR_INSPECTOR_NOT_WORKER` An API was called on the main thread that can only be used from the worker thread. + ### `ERR_INTERNAL_ASSERTION` There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at . + ### `ERR_INVALID_ADDRESS_FAMILY` The provided address family is not understood by the Node.js API. + ### `ERR_INVALID_ARG_TYPE` An argument of the wrong type was passed to a Node.js API. + ### `ERR_INVALID_ARG_VALUE` An invalid or unsupported value was passed for a given argument. + ### `ERR_INVALID_ASYNC_ID` An invalid `asyncId` or `triggerAsyncId` was passed using `AsyncHooks`. An id less than -1 should never happen. + ### `ERR_INVALID_BUFFER_SIZE` A swap was performed on a `Buffer` but its size was not compatible with the operation. + ### `ERR_INVALID_CALLBACK` A callback function was required but was not been provided to a Node.js API. + ### `ERR_INVALID_CHAR` Invalid characters were detected in headers. + ### `ERR_INVALID_CURSOR_POS` A cursor on a given stream cannot be moved to a specified row without a specified column. + ### `ERR_INVALID_FD` A file descriptor ('fd') was not valid (e.g. it was a negative value). + ### `ERR_INVALID_FD_TYPE` A file descriptor ('fd') type was not valid. + ### `ERR_INVALID_FILE_URL_HOST` A Node.js API that consumes `file:` URLs (such as certain functions in the @@ -1634,6 +1829,7 @@ situation can only occur on Unix-like systems where only `localhost` or an empty host is supported. + ### `ERR_INVALID_FILE_URL_PATH` A Node.js API that consumes `file:` URLs (such as certain functions in the @@ -1641,6 +1837,7 @@ A Node.js API that consumes `file:` URLs (such as certain functions in the semantics for determining whether a path can be used is platform-dependent. + ### `ERR_INVALID_HANDLE_TYPE` An attempt was made to send an unsupported "handle" over an IPC communication @@ -1648,17 +1845,21 @@ channel to a child process. See [`subprocess.send()`][] and [`process.send()`][] for more information. + ### `ERR_INVALID_HTTP_TOKEN` An invalid HTTP token was supplied. + ### `ERR_INVALID_IP_ADDRESS` An IP address is not valid. + ### `ERR_INVALID_MODULE` + @@ -1667,65 +1868,77 @@ An attempt was made to load a module that does not exist or was otherwise not valid. + ### `ERR_INVALID_MODULE_SPECIFIER` The imported module string is an invalid URL, package name, or package subpath specifier. + ### `ERR_INVALID_PACKAGE_CONFIG` An invalid [`package.json`][] file failed parsing. + ### `ERR_INVALID_PACKAGE_TARGET` The `package.json` [`"exports"`][] field contains an invalid target mapping value for the attempted module resolution. + ### `ERR_INVALID_PERFORMANCE_MARK` While using the Performance Timing API (`perf_hooks`), a performance mark is invalid. + ### `ERR_INVALID_PROTOCOL` An invalid `options.protocol` was passed to `http.request()`. + ### `ERR_INVALID_REPL_EVAL_CONFIG` Both `breakEvalOnSigint` and `eval` options were set in the [`REPL`][] config, which is not supported. + ### `ERR_INVALID_REPL_INPUT` The input may not be used in the [`REPL`][]. The conditions under which this error is used are described in the [`REPL`][] documentation. + ### `ERR_INVALID_RETURN_PROPERTY` Thrown in case a function option does not provide a valid value for one of its returned object properties on execution. + ### `ERR_INVALID_RETURN_PROPERTY_VALUE` Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution. + ### `ERR_INVALID_RETURN_VALUE` Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise. + ### `ERR_INVALID_STATE` + @@ -1735,6 +1948,7 @@ For instance, an object may have already been destroyed, or may be performing another operation. + ### `ERR_INVALID_SYNC_FORK_INPUT` A `Buffer`, `TypedArray`, `DataView` or `string` was provided as stdio input to @@ -1742,6 +1956,7 @@ an asynchronous fork. See the documentation for the [`child_process`][] module for more information. + ### `ERR_INVALID_THIS` A Node.js API function was called with an incompatible `this` value. @@ -1755,11 +1970,13 @@ urlSearchParams.has.call(buf, 'foo'); ``` + ### `ERR_INVALID_TRANSFER_OBJECT` An invalid transfer object was passed to `postMessage()`. + ### `ERR_INVALID_TUPLE` An element in the `iterable` provided to the [WHATWG][WHATWG URL API] @@ -1768,11 +1985,13 @@ represent a `[name, value]` tuple – that is, if an element is not iterable, or does not consist of exactly two elements. + ### `ERR_INVALID_URI` An invalid URI was passed. + ### `ERR_INVALID_URL` An invalid URL was passed to the [WHATWG][WHATWG URL API] @@ -1781,6 +2000,7 @@ typically has an additional property `'input'` that contains the URL that failed to parse. + ### `ERR_INVALID_URL_SCHEME` An attempt was made to use a URL of an incompatible scheme (protocol) for a @@ -1789,11 +2009,13 @@ specific purpose. It is only used in the [WHATWG URL API][] support in the in other Node.js APIs as well in the future. + ### `ERR_IPC_CHANNEL_CLOSED` An attempt was made to use an IPC communication channel that was already closed. + ### `ERR_IPC_DISCONNECTED` An attempt was made to disconnect an IPC communication channel that was already @@ -1801,6 +2023,7 @@ disconnected. See the documentation for the [`child_process`][] module for more information. + ### `ERR_IPC_ONE_PIPE` An attempt was made to create a child Node.js process using more than one IPC @@ -1808,6 +2031,7 @@ communication channel. See the documentation for the [`child_process`][] module for more information. + ### `ERR_IPC_SYNC_FORK` An attempt was made to open an IPC communication channel with a synchronously @@ -1815,6 +2039,7 @@ forked Node.js process. See the documentation for the [`child_process`][] module for more information. + ### `ERR_MANIFEST_ASSERT_INTEGRITY` An attempt was made to load a resource, but the resource did not match the @@ -1822,6 +2047,7 @@ integrity defined by the policy manifest. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_DEPENDENCY_MISSING` An attempt was made to load a resource, but the resource was not listed as a @@ -1829,6 +2055,7 @@ dependency from the location that attempted to load it. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_INTEGRITY_MISMATCH` An attempt was made to load a policy manifest, but the manifest had multiple @@ -1837,6 +2064,7 @@ entries to match in order to resolve this error. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_INVALID_RESOURCE_FIELD` A policy manifest resource had an invalid value for one of its fields. Update @@ -1844,6 +2072,7 @@ the manifest entry to match in order to resolve this error. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_INVALID_SPECIFIER` A policy manifest resource had an invalid value for one of its dependency @@ -1851,31 +2080,37 @@ mappings. Update the manifest entry to match to resolve this error. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_PARSE_POLICY` An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_TDZ` An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js. + ### `ERR_MANIFEST_UNKNOWN_ONERROR` A policy manifest was loaded, but had an unknown value for its "onerror" behavior. See the documentation for [policy][] manifests for more information. + ### `ERR_MEMORY_ALLOCATION_FAILED` An attempt was made to allocate memory (usually in the C++ layer) but it failed. + ### `ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE` + @@ -1935,6 +2177,7 @@ transferable object types has been expanded to cover more types than `MessagePort`. + ### `ERR_MODULE_NOT_FOUND` > Stability: 1 - Experimental @@ -1942,6 +2185,7 @@ transferable object types has been expanded to cover more types than An [ES Module][] could not be resolved. + ### `ERR_MULTIPLE_CALLBACK` A callback was called more than once. @@ -1951,41 +2195,48 @@ can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once. + ### `ERR_NAPI_CONS_FUNCTION` While using `Node-API`, a constructor passed was not a function. + ### `ERR_NAPI_INVALID_DATAVIEW_ARGS` While calling `napi_create_dataview()`, a given `offset` was outside the bounds of the dataview or `offset + length` was larger than a length of given `buffer`. + ### `ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT` While calling `napi_create_typedarray()`, the provided `offset` was not a multiple of the element size. + ### `ERR_NAPI_INVALID_TYPEDARRAY_LENGTH` While calling `napi_create_typedarray()`, `(length * size_of_element) + byte_offset` was larger than the length of given `buffer`. + ### `ERR_NAPI_TSFN_CALL_JS` An error occurred while invoking the JavaScript portion of the thread-safe function. + ### `ERR_NAPI_TSFN_GET_UNDEFINED` An error occurred while attempting to retrieve the JavaScript `undefined` value. + ### `ERR_NAPI_TSFN_START_IDLE_LOOP` On the main thread, values are removed from the queue associated with the @@ -1993,40 +2244,47 @@ thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop. + ### `ERR_NAPI_TSFN_STOP_IDLE_LOOP` Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop. + ### `ERR_NO_CRYPTO` An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support. + ### `ERR_NO_ICU` An attempt was made to use features that require [ICU][], but Node.js was not compiled with ICU support. + ### `ERR_NON_CONTEXT_AWARE_DISABLED` A non-context-aware native addon was loaded in a process that disallows them. + ### `ERR_OUT_OF_RANGE` A given value is out of the accepted range. + ### `ERR_PACKAGE_IMPORT_NOT_DEFINED` The `package.json` [`"imports"`][] field does not define the given internal package specifier mapping. + ### `ERR_PACKAGE_PATH_NOT_EXPORTED` The `package.json` [`"exports"`][] field does not export the requested subpath. @@ -2034,16 +2292,19 @@ Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL. + ### `ERR_PERFORMANCE_INVALID_TIMESTAMP` An invalid timestamp value was provided for a performance mark or measure. + ### `ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS` Invalid options were provided for a performance measure. + ### `ERR_PROTO_ACCESS` Accessing `Object.prototype.__proto__` has been forbidden using @@ -2052,6 +2313,7 @@ Accessing `Object.prototype.__proto__` has been forbidden using object. + ### `ERR_REQUIRE_ESM` > Stability: 1 - Experimental @@ -2059,17 +2321,20 @@ object. An attempt was made to `require()` an [ES Module][]. + ### `ERR_SCRIPT_EXECUTION_INTERRUPTED` -Script execution was interrupted by `SIGINT` (For example, -Ctrl+C was pressed.) +Script execution was interrupted by `SIGINT` (For +example, Ctrl+C was pressed.) + ### `ERR_SCRIPT_EXECUTION_TIMEOUT` Script execution timed out, possibly due to bugs in the script being executed. + ### `ERR_SERVER_ALREADY_LISTEN` The [`server.listen()`][] method was called while a `net.Server` was already @@ -2077,6 +2342,7 @@ listening. This applies to all instances of `net.Server`, including HTTP, HTTPS, and HTTP/2 `Server` instances. + ### `ERR_SERVER_NOT_RUNNING` The [`server.close()`][] method was called when a `net.Server` was not @@ -2084,55 +2350,65 @@ running. This applies to all instances of `net.Server`, including HTTP, HTTPS, and HTTP/2 `Server` instances. + ### `ERR_SOCKET_ALREADY_BOUND` An attempt was made to bind a socket that has already been bound. + ### `ERR_SOCKET_BAD_BUFFER_SIZE` An invalid (negative) size was passed for either the `recvBufferSize` or `sendBufferSize` options in [`dgram.createSocket()`][]. + ### `ERR_SOCKET_BAD_PORT` An API function expecting a port >= 0 and < 65536 received an invalid value. + ### `ERR_SOCKET_BAD_TYPE` An API function expecting a socket type (`udp4` or `udp6`) received an invalid value. + ### `ERR_SOCKET_BUFFER_SIZE` While using [`dgram.createSocket()`][], the size of the receive or send `Buffer` could not be determined. + ### `ERR_SOCKET_CLOSED` An attempt was made to operate on an already closed socket. + ### `ERR_SOCKET_DGRAM_IS_CONNECTED` A [`dgram.connect()`][] call was made on an already connected socket. + ### `ERR_SOCKET_DGRAM_NOT_CONNECTED` A [`dgram.disconnect()`][] or [`dgram.remoteAddress()`][] call was made on a disconnected socket. + ### `ERR_SOCKET_DGRAM_NOT_RUNNING` A call was made and the UDP subsystem was not running. + ### `ERR_SRI_PARSE` A string was provided for a Subresource Integrity check, but was unable to be @@ -2140,46 +2416,54 @@ parsed. Check the format of integrity attributes by looking at the [Subresource Integrity specification][]. + ### `ERR_STREAM_ALREADY_FINISHED` A stream method was called that cannot complete because the stream was finished. + ### `ERR_STREAM_CANNOT_PIPE` An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream. + ### `ERR_STREAM_DESTROYED` A stream method was called that cannot complete because the stream was destroyed using `stream.destroy()`. + ### `ERR_STREAM_NULL_VALUES` An attempt was made to call [`stream.write()`][] with a `null` chunk. + ### `ERR_STREAM_PREMATURE_CLOSE` An error returned by `stream.finished()` and `stream.pipeline()`, when a stream or a pipeline ends non gracefully with no explicit error. + ### `ERR_STREAM_PUSH_AFTER_EOF` An attempt was made to call [`stream.push()`][] after a `null`(EOF) had been pushed to the stream. + ### `ERR_STREAM_UNSHIFT_AFTER_END_EVENT` An attempt was made to call [`stream.unshift()`][] after the `'end'` event was emitted. + ### `ERR_STREAM_WRAP` Prevents an abort if a string decoder was set on the Socket or if the decoder @@ -2193,24 +2477,28 @@ instance.setEncoding('utf8'); ``` + ### `ERR_STREAM_WRITE_AFTER_END` An attempt was made to call [`stream.write()`][] after `stream.end()` has been called. + ### `ERR_STRING_TOO_LONG` An attempt has been made to create a string longer than the maximum allowed length. + ### `ERR_SYNTHETIC` An artificial error object used to capture the call stack for diagnostic reports. + ### `ERR_SYSTEM_ERROR` An unspecified or non-specific system error has occurred within the Node.js @@ -2218,12 +2506,14 @@ process. The error object will have an `err.info` object property with additional details. + ### `ERR_TLS_CERT_ALTNAME_INVALID` While using TLS, the host name/IP of the peer did not match any of the `subjectAltNames` in its certificate. + ### `ERR_TLS_DH_PARAM_SIZE` While using TLS, the parameter offered for the Diffie-Hellman (`DH`) @@ -2232,13 +2522,16 @@ than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security. + ### `ERR_TLS_HANDSHAKE_TIMEOUT` A TLS/SSL handshake timed out. In this case, the server must also abort the connection. + ### `ERR_TLS_INVALID_CONTEXT` + @@ -2246,18 +2539,22 @@ added: v13.3.0 The context must be a `SecureContext`. + ### `ERR_TLS_INVALID_PROTOCOL_METHOD` The specified `secureProtocol` method is invalid. It is either unknown, or disabled because it is insecure. + ### `ERR_TLS_INVALID_PROTOCOL_VERSION` Valid TLS protocol versions are `'TLSv1'`, `'TLSv1.1'`, or `'TLSv1.2'`. + ### `ERR_TLS_INVALID_STATE` + + ```js import './'; // unsupported import './index.js'; // supported @@ -2407,22 +2727,26 @@ import 'package-name'; // supported ``` + ### `ERR_UNSUPPORTED_ESM_URL_SCHEME` `import` with URL schemes other than `file` and `data` is unsupported. + ### `ERR_VALID_PERFORMANCE_ENTRY_TYPE` While using the Performance Timing API (`perf_hooks`), no valid performance entry types are found. + ### `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING` A dynamic import callback was not specified. + ### `ERR_VM_MODULE_ALREADY_LINKED` The module attempted to be linked is not eligible for linking, because of one of @@ -2433,96 +2757,115 @@ the following reasons: * Linking has failed for this module (`linkingStatus` is `'errored'`) + ### `ERR_VM_MODULE_CACHED_DATA_REJECTED` The `cachedData` option passed to a module constructor is invalid. + ### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA` Cached data cannot be created for modules which have already been evaluated. + ### `ERR_VM_MODULE_DIFFERENT_CONTEXT` The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context. + ### `ERR_VM_MODULE_LINKING_ERRORED` The linker function returned a module for which linking has failed. + ### `ERR_VM_MODULE_LINK_FAILURE` The module was unable to be linked due to a failure. + ### `ERR_VM_MODULE_NOT_MODULE` The fulfilled value of a linking promise is not a `vm.Module` object. + ### `ERR_VM_MODULE_STATUS` The current module's status does not allow for this operation. The specific meaning of the error depends on the specific function. + ### `ERR_WASI_ALREADY_STARTED` The WASI instance has already started. + ### `ERR_WASI_NOT_STARTED` The WASI instance has not been started. + ### `ERR_WORKER_INIT_FAILED` The `Worker` initialization failed. + ### `ERR_WORKER_INVALID_EXEC_ARGV` The `execArgv` option passed to the `Worker` constructor contains invalid flags. + ### `ERR_WORKER_NOT_RUNNING` An operation failed because the `Worker` instance is not currently running. + ### `ERR_WORKER_OUT_OF_MEMORY` The `Worker` instance terminated because it reached its memory limit. + ### `ERR_WORKER_PATH` The path for the main script of a worker is neither an absolute path nor a relative path starting with `./` or `../`. + ### `ERR_WORKER_UNSERIALIZABLE_ERROR` All attempts at serializing an uncaught exception from a worker thread failed. + ### `ERR_WORKER_UNSUPPORTED_OPERATION` The requested functionality is not supported in worker threads. + ### `ERR_ZLIB_INITIALIZATION_FAILED` Creation of a [`zlib`][] object failed due to incorrect configuration. + ### `HPE_HEADER_OVERFLOW` + + A module file could not be resolved while attempting a [`require()`][] or `import` operation. @@ -2566,7 +2913,9 @@ A module file could not be resolved while attempting a [`require()`][] or > been removed. + ### `ERR_CANNOT_TRANSFER_OBJECT` + -HTTP/2 informational headers must only be sent *prior* to calling the +HTTP/2 informational headers must only be sent _prior_ to calling the `Http2Stream.prototype.respond()` method. + ### `ERR_HTTP2_STREAM_CLOSED` + + A given index was out of the accepted range (e.g. negative offsets). + ### `ERR_INVALID_OPT_VALUE` + @@ -2682,7 +3054,9 @@ in Node.js v15.0.0, because it is no longer accurate as other types of transferable objects also exist now. + ### `ERR_NAPI_CONS_PROTOTYPE_OBJECT` + @@ -2706,7 +3083,9 @@ An operation failed. This is typically used to signal the general failure of an asynchronous operation. + ### `ERR_OUTOFMEMORY` + diff --git a/doc/api/esm.md b/doc/api/esm.md index c33a53188ca209..46750050ee90d6 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -82,9 +82,8 @@ provides interoperability between them and its original module format, [CommonJS][]. - - - + + ## Enabling @@ -98,20 +97,8 @@ via the `.mjs` file extension, the `package.json` [`"type"`][] field, or the details. - - - - - - - - - - - - - - + + ## Packages @@ -291,6 +278,7 @@ const buffer = readFileSync(new URL('./data.proto', import.meta.url)); ``` ### `import.meta.resolve(specifier[, parent])` + + ```js const dependencyAsset = await import.meta.resolve('component-lib/asset.css'); ``` @@ -323,6 +312,7 @@ const dependencyAsset = await import.meta.resolve('component-lib/asset.css'); from which to resolve from: + ```js await import.meta.resolve('./dep', import.meta.url); ``` @@ -359,6 +349,7 @@ When importing a CommonJS module, it can be reliably imported using the ES module default import or its corresponding sugar syntax: + ```js import { default as cjs } from 'cjs'; @@ -381,6 +372,7 @@ This Module Namespace Exotic Object can be directly observed either when using `import * as m from 'cjs'` or a dynamic import: + ```js import * as m from 'cjs'; console.log(m); @@ -405,6 +397,7 @@ exports.name = 'exported'; The preceding module supports named imports in ES modules: + ```js import { name } from './cjs.cjs'; console.log(name); @@ -458,6 +451,7 @@ JSON imports are still experimental and only supported via the Local JSON files can be loaded relative to `import.meta.url` with `fs` directly: + ```js import { readFile } from 'fs/promises'; const json = JSON.parse(await readFile(new URL('./dat.json', import.meta.url))); @@ -518,6 +512,7 @@ same path. Assuming an `index.mjs` with + ```js import packageConfig from './package.json'; ``` @@ -570,6 +565,7 @@ within modules as per the [ECMAScript Top-Level `await` proposal][]. Assuming an `a.mjs` with + ```js export const five = await Promise.resolve(5); ``` @@ -611,12 +607,12 @@ CommonJS modules loaded. * `specifier` {string} * `context` {Object} - * `conditions` {string[]} + * `conditions` {string\[]} * `parentURL` {string|undefined} * `defaultResolve` {Function} The Node.js default resolver. * Returns: {Object} * `format` {string|null|undefined} - `'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'` + `'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'` * `url` {string} The absolute url to the import target (such as `file://…`) The `resolve` hook returns the resolved file URL for a given module specifier @@ -687,7 +683,7 @@ export async function resolve(specifier, context, defaultResolve) { * `url` {string} * `context` {Object} * `format` {string|null|undefined} The format optionally supplied by the - `resolve` hook. + `resolve` hook. * `defaultLoad` {Function} * Returns: {Object} * `format` {string} @@ -1020,16 +1016,16 @@ The resolver has the following properties: * Relative and absolute URL resolution * No default extensions * No folder mains -* Bare specifier package resolution lookup through node_modules +* Bare specifier package resolution lookup through node\_modules ### Resolver algorithm The algorithm to load an ES module specifier is given through the -**ESM_RESOLVE** method below. It returns the resolved URL for a +**ESM\_RESOLVE** method below. It returns the resolved URL for a module specifier relative to a parentURL. The algorithm to determine the module format of a resolved URL is -provided by **ESM_FORMAT**, which returns the unique module +provided by **ESM\_FORMAT**, which returns the unique module format for any file. The _"module"_ format is returned for an ECMAScript Module, while the _"commonjs"_ format is used to indicate loading through the legacy CommonJS loader. Additional formats such as _"addon"_ can be extended in @@ -1042,6 +1038,7 @@ _defaultConditions_ is the conditional environment name array, `["node", "import"]`. The resolver can throw the following errors: + * _Invalid Module Specifier_: Module specifier is an invalid URL, package name or package subpath specifier. * _Invalid Package Configuration_: package.json configuration is invalid or @@ -1057,286 +1054,286 @@ The resolver can throw the following errors: ### Resolver Algorithm Specification -**ESM_RESOLVE**(_specifier_, _parentURL_) +**ESM\_RESOLVE**(_specifier_, _parentURL_) > 1. Let _resolved_ be **undefined**. -> 1. If _specifier_ is a valid URL, then +> 2. If _specifier_ is a valid URL, then > 1. Set _resolved_ to the result of parsing and reserializing > _specifier_ as a URL. -> 1. Otherwise, if _specifier_ starts with _"/"_, _"./"_ or _"../"_, then +> 3. Otherwise, if _specifier_ starts with _"/"_, _"./"_ or _"../"_, then > 1. Set _resolved_ to the URL resolution of _specifier_ relative to > _parentURL_. -> 1. Otherwise, if _specifier_ starts with _"#"_, then +> 4. Otherwise, if _specifier_ starts with _"#"_, then > 1. Set _resolved_ to the destructured value of the result of -> **PACKAGE_IMPORTS_RESOLVE**(_specifier_, _parentURL_, +> **PACKAGE\_IMPORTS\_RESOLVE**(_specifier_, _parentURL_, > _defaultConditions_). -> 1. Otherwise, +> 5. Otherwise, > 1. Note: _specifier_ is now a bare specifier. -> 1. Set _resolved_ the result of -> **PACKAGE_RESOLVE**(_specifier_, _parentURL_). -> 1. If _resolved_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_ +> 2. Set _resolved_ the result of +> **PACKAGE\_RESOLVE**(_specifier_, _parentURL_). +> 6. If _resolved_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_ > and _"%5C"_ respectively), then > 1. Throw an _Invalid Module Specifier_ error. -> 1. If the file at _resolved_ is a directory, then +> 7. If the file at _resolved_ is a directory, then > 1. Throw an _Unsupported Directory Import_ error. -> 1. If the file at _resolved_ does not exist, then +> 8. If the file at _resolved_ does not exist, then > 1. Throw a _Module Not Found_ error. -> 1. Set _resolved_ to the real path of _resolved_. -> 1. Let _format_ be the result of **ESM_FORMAT**(_resolved_). -> 1. Load _resolved_ as module format, _format_. -> 1. Return _resolved_. +> 9. Set _resolved_ to the real path of _resolved_. +> 10. Let _format_ be the result of **ESM\_FORMAT**(_resolved_). +> 11. Load _resolved_ as module format, _format_. +> 12. Return _resolved_. -**PACKAGE_RESOLVE**(_packageSpecifier_, _parentURL_) +**PACKAGE\_RESOLVE**(_packageSpecifier_, _parentURL_) > 1. Let _packageName_ be **undefined**. -> 1. If _packageSpecifier_ is an empty string, then +> 2. If _packageSpecifier_ is an empty string, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. If _packageSpecifier_ does not start with _"@"_, then +> 3. If _packageSpecifier_ does not start with _"@"_, then > 1. Set _packageName_ to the substring of _packageSpecifier_ until the first > _"/"_ separator or the end of the string. -> 1. Otherwise, +> 4. Otherwise, > 1. If _packageSpecifier_ does not contain a _"/"_ separator, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. Set _packageName_ to the substring of _packageSpecifier_ +> 2. Set _packageName_ to the substring of _packageSpecifier_ > until the second _"/"_ separator or the end of the string. -> 1. If _packageName_ starts with _"."_ or contains _"\\"_ or _"%"_, then +> 5. If _packageName_ starts with _"."_ or contains _"\\"_ or _"%"_, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. Let _packageSubpath_ be _"."_ concatenated with the substring of -> _packageSpecifier_ from the position at the length of _packageName_. -> 1. Let _selfUrl_ be the result of -> **PACKAGE_SELF_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_). -> 1. If _selfUrl_ is not **undefined**, return _selfUrl_. -> 1. If _packageSubpath_ is _"."_ and _packageName_ is a Node.js builtin +> 6. Let _packageSubpath_ be _"."_ concatenated with the substring of +> _packageSpecifier_ from the position at the length of _packageName_. +> 7. Let _selfUrl_ be the result of +> **PACKAGE\_SELF\_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_). +> 8. If _selfUrl_ is not **undefined**, return _selfUrl_. +> 9. If _packageSubpath_ is _"."_ and _packageName_ is a Node.js builtin > module, then > 1. Return the string _"node:"_ concatenated with _packageSpecifier_. -> 1. While _parentURL_ is not the file system root, -> 1. Let _packageURL_ be the URL resolution of _"node_modules/"_ -> concatenated with _packageSpecifier_, relative to _parentURL_. -> 1. Set _parentURL_ to the parent folder URL of _parentURL_. -> 1. If the folder at _packageURL_ does not exist, then -> 1. Set _parentURL_ to the parent URL path of _parentURL_. -> 1. Continue the next loop iteration. -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). -> 1. If _pjson_ is not **null** and _pjson_._exports_ is not **null** or -> **undefined**, then -> 1. Let _exports_ be _pjson.exports_. -> 1. Return the _resolved_ destructured value of the result of -> **PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _packageSubpath_, +> 10. While _parentURL_ is not the file system root, +> 1. Let _packageURL_ be the URL resolution of _"node\_modules/"_ +> concatenated with _packageSpecifier_, relative to _parentURL_. +> 2. Set _parentURL_ to the parent folder URL of _parentURL_. +> 3. If the folder at _packageURL_ does not exist, then +> 1. Set _parentURL_ to the parent URL path of _parentURL_. +> 2. Continue the next loop iteration. +> 4. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_). +> 5. If _pjson_ is not **null** and _pjson_._exports_ is not **null** or +> **undefined**, then +> 1. Let _exports_ be _pjson.exports_. +> 2. Return the _resolved_ destructured value of the result of +> **PACKAGE\_EXPORTS\_RESOLVE**(_packageURL_, _packageSubpath_, > _pjson.exports_, _defaultConditions_). -> 1. Otherwise, if _packageSubpath_ is equal to _"."_, then -> 1. Return the result applying the legacy **LOAD_AS_DIRECTORY** -> CommonJS resolver to _packageURL_, throwing a _Module Not Found_ -> error for no resolution. -> 1. Otherwise, -> 1. Return the URL resolution of _packageSubpath_ in _packageURL_. -> 1. Throw a _Module Not Found_ error. - -**PACKAGE_SELF_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_) - -> 1. Let _packageURL_ be the result of **READ_PACKAGE_SCOPE**(_parentURL_). -> 1. If _packageURL_ is **null**, then +> 6. Otherwise, if _packageSubpath_ is equal to _"."_, then +> 1. Return the result applying the legacy **LOAD\_AS\_DIRECTORY** +> CommonJS resolver to _packageURL_, throwing a _Module Not Found_ +> error for no resolution. +> 7. Otherwise, +> 1. Return the URL resolution of _packageSubpath_ in _packageURL_. +> 11. Throw a _Module Not Found_ error. + +**PACKAGE\_SELF\_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_) + +> 1. Let _packageURL_ be the result of **READ\_PACKAGE\_SCOPE**(_parentURL_). +> 2. If _packageURL_ is **null**, then > 1. Return **undefined**. -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). -> 1. If _pjson_ is **null** or if _pjson_._exports_ is **null** or +> 3. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_). +> 4. If _pjson_ is **null** or if _pjson_._exports_ is **null** or > **undefined**, then > 1. Return **undefined**. -> 1. If _pjson.name_ is equal to _packageName_, then +> 5. If _pjson.name_ is equal to _packageName_, then > 1. Return the _resolved_ destructured value of the result of -> **PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _packageSubpath_, +> **PACKAGE\_EXPORTS\_RESOLVE**(_packageURL_, _packageSubpath_, > _pjson.exports_, _defaultConditions_). -> 1. Otherwise, return **undefined**. +> 6. Otherwise, return **undefined**. -**PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _subpath_, _exports_, _conditions_) +**PACKAGE\_EXPORTS\_RESOLVE**(_packageURL_, _subpath_, _exports_, _conditions_) > 1. If _exports_ is an Object with both a key starting with _"."_ and a key not > starting with _"."_, throw an _Invalid Package Configuration_ error. -> 1. If _subpath_ is equal to _"."_, then +> 2. If _subpath_ is equal to _"."_, then > 1. Let _mainExport_ be **undefined**. -> 1. If _exports_ is a String or Array, or an Object containing no keys +> 2. If _exports_ is a String or Array, or an Object containing no keys > starting with _"."_, then > 1. Set _mainExport_ to _exports_. -> 1. Otherwise if _exports_ is an Object containing a _"."_ property, then -> 1. Set _mainExport_ to _exports_\[_"."_\]. -> 1. If _mainExport_ is not **undefined**, then -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. Otherwise if _exports_ is an Object containing a _"."_ property, then +> 1. Set _mainExport_ to _exports_\[_"."_]. +> 4. If _mainExport_ is not **undefined**, then +> 1. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _mainExport_, _""_, **false**, **false**, > _conditions_). -> 1. If _resolved_ is not **null** or **undefined**, then +> 2. If _resolved_ is not **null** or **undefined**, then > 1. Return _resolved_. -> 1. Otherwise, if _exports_ is an Object and all keys of _exports_ start with +> 3. Otherwise, if _exports_ is an Object and all keys of _exports_ start with > _"."_, then > 1. Let _matchKey_ be the string _"./"_ concatenated with _subpath_. -> 1. Let _resolvedMatch_ be result of **PACKAGE_IMPORTS_EXPORTS_RESOLVE**( +> 2. Let _resolvedMatch_ be result of **PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**( > _matchKey_, _exports_, _packageURL_, **false**, _conditions_). -> 1. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then +> 3. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then > 1. Return _resolvedMatch_. -> 1. Throw a _Package Path Not Exported_ error. +> 4. Throw a _Package Path Not Exported_ error. -**PACKAGE_IMPORTS_RESOLVE**(_specifier_, _parentURL_, _conditions_) +**PACKAGE\_IMPORTS\_RESOLVE**(_specifier_, _parentURL_, _conditions_) > 1. Assert: _specifier_ begins with _"#"_. -> 1. If _specifier_ is exactly equal to _"#"_ or starts with _"#/"_, then +> 2. If _specifier_ is exactly equal to _"#"_ or starts with _"#/"_, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. Let _packageURL_ be the result of **READ_PACKAGE_SCOPE**(_parentURL_). -> 1. If _packageURL_ is not **null**, then -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). -> 1. If _pjson.imports_ is a non-null Object, then +> 3. Let _packageURL_ be the result of **READ\_PACKAGE\_SCOPE**(_parentURL_). +> 4. If _packageURL_ is not **null**, then +> 1. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_). +> 2. If _pjson.imports_ is a non-null Object, then > 1. Let _resolvedMatch_ be the result of -> **PACKAGE_IMPORTS_EXPORTS_RESOLVE**(_specifier_, _pjson.imports_, +> **PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**(_specifier_, _pjson.imports_, > _packageURL_, **true**, _conditions_). -> 1. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then +> 2. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then > 1. Return _resolvedMatch_. -> 1. Throw a _Package Import Not Defined_ error. +> 5. Throw a _Package Import Not Defined_ error. -**PACKAGE_IMPORTS_EXPORTS_RESOLVE**(_matchKey_, _matchObj_, _packageURL_, +**PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**(_matchKey_, _matchObj_, _packageURL_, _isImports_, _conditions_) > 1. If _matchKey_ is a key of _matchObj_ and does not end in _"/"_ or contain -> _"*"_, then -> 1. Let _target_ be the value of _matchObj_\[_matchKey_\]. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> _"\*"_, then +> 1. Let _target_ be the value of _matchObj_\[_matchKey_]. +> 2. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _target_, _""_, **false**, _isImports_, _conditions_). -> 1. Return the object _{ resolved, exact: **true** }_. -> 1. Let _expansionKeys_ be the list of keys of _matchObj_ either ending in -> _"/"_ or containing only a single _"*"_, sorted by the sorting function -> **PATTERN_KEY_COMPARE** which orders in descending order of specificity. -> 1. For each key _expansionKey_ in _expansionKeys_, do +> 3. Return the object _{ resolved, exact: **true** }_. +> 2. Let _expansionKeys_ be the list of keys of _matchObj_ either ending in +> _"/"_ or containing only a single _"\*"_, sorted by the sorting function +> **PATTERN\_KEY\_COMPARE** which orders in descending order of specificity. +> 3. For each key _expansionKey_ in _expansionKeys_, do > 1. Let _patternBase_ be **null**. -> 1. If _expansionKey_ contains _"*"_, set _patternBase_ to the substring of -> _expansionKey_ up to but excluding the first _"*"_ character. -> 1. If _patternBase_ is not **null** and _matchKey_ starts with but is not +> 2. If _expansionKey_ contains _"\*"_, set _patternBase_ to the substring of +> _expansionKey_ up to but excluding the first _"\*"_ character. +> 3. If _patternBase_ is not **null** and _matchKey_ starts with but is not > equal to _patternBase_, then > 1. If _matchKey_ ends with _"/"_, throw an _Invalid Module Specifier_ > error. -> 1. Let _patternTrailer_ be the substring of _expansionKey_ from the -> index after the first _"*"_ character. -> 1. If _patternTrailer_ has zero length, or if _matchKey_ ends with +> 2. Let _patternTrailer_ be the substring of _expansionKey_ from the +> index after the first _"\*"_ character. +> 3. If _patternTrailer_ has zero length, or if _matchKey_ ends with > _patternTrailer_ and the length of _matchKey_ is greater than or > equal to the length of _expansionKey_, then -> 1. Let _target_ be the value of _matchObj_\[_expansionKey_\]. -> 1. Let _subpath_ be the substring of _matchKey_ starting at the +> 1. Let _target_ be the value of _matchObj_\[_expansionKey_]. +> 2. Let _subpath_ be the substring of _matchKey_ starting at the > index of the length of _patternBase_ up to the length of > _matchKey_ minus the length of _patternTrailer_. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _target_, _subpath_, **true**, _isImports_, > _conditions_). -> 1. Return the object _{ resolved, exact: **true** }_. -> 1. Otherwise if _patternBase_ is **null** and _matchKey_ starts with +> 4. Return the object _{ resolved, exact: **true** }_. +> 4. Otherwise if _patternBase_ is **null** and _matchKey_ starts with > _expansionKey_, then -> 1. Let _target_ be the value of _matchObj_\[_expansionKey_\]. -> 1. Let _subpath_ be the substring of _matchKey_ starting at the +> 1. Let _target_ be the value of _matchObj_\[_expansionKey_]. +> 2. Let _subpath_ be the substring of _matchKey_ starting at the > index of the length of _expansionKey_. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _target_, _subpath_, **false**, _isImports_, > _conditions_). -> 1. Return the object _{ resolved, exact: **false** }_. -> 1. Return the object _{ resolved: **null**, exact: **true** }_. - -**PATTERN_KEY_COMPARE**(_keyA_, _keyB_) - -> 1. Assert: _keyA_ ends with _"/"_ or contains only a single _"*"_. -> 1. Assert: _keyB_ ends with _"/"_ or contains only a single _"*"_. -> 1. Let _baseLengthA_ be the index of _"*"_ in _keyA_ plus one, if _keyA_ -> contains _"*"_, or the length of _keyA_ otherwise. -> 1. Let _baseLengthB_ be the index of _"*"_ in _keyB_ plus one, if _keyB_ -> contains _"*"_, or the length of _keyB_ otherwise. -> 1. If _baseLengthA_ is greater than _baseLengthB_, return -1. -> 1. If _baseLengthB_ is greater than _baseLengthA_, return 1. -> 1. If _keyA_ does not contain _"*"_, return 1. -> 1. If _keyB_ does not contain _"*"_, return -1. -> 1. If the length of _keyA_ is greater than the length of _keyB_, return -1. -> 1. If the length of _keyB_ is greater than the length of _keyA_, return 1. -> 1. Return 0. - -**PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_, _subpath_, _pattern_, +> 4. Return the object _{ resolved, exact: **false** }_. +> 4. Return the object _{ resolved: **null**, exact: **true** }_. + +**PATTERN\_KEY\_COMPARE**(_keyA_, _keyB_) + +> 1. Assert: _keyA_ ends with _"/"_ or contains only a single _"\*"_. +> 2. Assert: _keyB_ ends with _"/"_ or contains only a single _"\*"_. +> 3. Let _baseLengthA_ be the index of _"\*"_ in _keyA_ plus one, if _keyA_ +> contains _"\*"_, or the length of _keyA_ otherwise. +> 4. Let _baseLengthB_ be the index of _"\*"_ in _keyB_ plus one, if _keyB_ +> contains _"\*"_, or the length of _keyB_ otherwise. +> 5. If _baseLengthA_ is greater than _baseLengthB_, return -1. +> 6. If _baseLengthB_ is greater than _baseLengthA_, return 1. +> 7. If _keyA_ does not contain _"\*"_, return 1. +> 8. If _keyB_ does not contain _"\*"_, return -1. +> 9. If the length of _keyA_ is greater than the length of _keyB_, return -1. +> 10. If the length of _keyB_ is greater than the length of _keyA_, return 1. +> 11. Return 0. + +**PACKAGE\_TARGET\_RESOLVE**(_packageURL_, _target_, _subpath_, _pattern_, _internal_, _conditions_) > 1. If _target_ is a String, then > 1. If _pattern_ is **false**, _subpath_ has non-zero length and _target_ > does not end with _"/"_, throw an _Invalid Module Specifier_ error. -> 1. If _target_ does not start with _"./"_, then +> 2. If _target_ does not start with _"./"_, then > 1. If _internal_ is **true** and _target_ does not start with _"../"_ or > _"/"_ and is not a valid URL, then > 1. If _pattern_ is **true**, then -> 1. Return **PACKAGE_RESOLVE**(_target_ with every instance of -> _"*"_ replaced by _subpath_, _packageURL_ + _"/"_)_. -> 1. Return **PACKAGE_RESOLVE**(_target_ + _subpath_, -> _packageURL_ + _"/"_)_. -> 1. Otherwise, throw an _Invalid Package Target_ error. -> 1. If _target_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or -> _"node_modules"_ segments after the first segment, throw an +> 1. Return **PACKAGE\_RESOLVE**(_target_ with every instance of +> _"\*"_ replaced by _subpath_, _packageURL_ + _"/"_)\_. +> 2. Return **PACKAGE\_RESOLVE**(_target_ + _subpath_, +> _packageURL_ + _"/"_)\_. +> 2. Otherwise, throw an _Invalid Package Target_ error. +> 3. If _target_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or +> _"node\_modules"_ segments after the first segment, throw an > _Invalid Package Target_ error. -> 1. Let _resolvedTarget_ be the URL resolution of the concatenation of +> 4. Let _resolvedTarget_ be the URL resolution of the concatenation of > _packageURL_ and _target_. -> 1. Assert: _resolvedTarget_ is contained in _packageURL_. -> 1. If _subpath_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or -> _"node_modules"_ segments, throw an _Invalid Module Specifier_ error. -> 1. If _pattern_ is **true**, then +> 5. Assert: _resolvedTarget_ is contained in _packageURL_. +> 6. If _subpath_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or +> _"node\_modules"_ segments, throw an _Invalid Module Specifier_ error. +> 7. If _pattern_ is **true**, then > 1. Return the URL resolution of _resolvedTarget_ with every instance of -> _"*"_ replaced with _subpath_. -> 1. Otherwise, +> _"\*"_ replaced with _subpath_. +> 8. Otherwise, > 1. Return the URL resolution of the concatenation of _subpath_ and > _resolvedTarget_. -> 1. Otherwise, if _target_ is a non-null Object, then +> 2. Otherwise, if _target_ is a non-null Object, then > 1. If _exports_ contains any index property keys, as defined in ECMA-262 > [6.1.7 Array Index][], throw an _Invalid Package Configuration_ error. -> 1. For each property _p_ of _target_, in object insertion order as, +> 2. For each property _p_ of _target_, in object insertion order as, > 1. If _p_ equals _"default"_ or _conditions_ contains an entry for _p_, > then > 1. Let _targetValue_ be the value of the _p_ property in _target_. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 2. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _targetValue_, _subpath_, _pattern_, _internal_, > _conditions_). -> 1. If _resolved_ is equal to **undefined**, continue the loop. -> 1. Return _resolved_. -> 1. Return **undefined**. -> 1. Otherwise, if _target_ is an Array, then -> 1. If _target.length is zero, return **null**. -> 1. For each item _targetValue_ in _target_, do -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. If _resolved_ is equal to **undefined**, continue the loop. +> 4. Return _resolved_. +> 3. Return **undefined**. +> 3. Otherwise, if _target_ is an Array, then +> 1. If \_target.length is zero, return **null**. +> 2. For each item _targetValue_ in _target_, do +> 1. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _targetValue_, _subpath_, _pattern_, _internal_, > _conditions_), continuing the loop on any _Invalid Package Target_ > error. -> 1. If _resolved_ is **undefined**, continue the loop. -> 1. Return _resolved_. -> 1. Return or throw the last fallback resolution **null** return or error. -> 1. Otherwise, if _target_ is _null_, return **null**. -> 1. Otherwise throw an _Invalid Package Target_ error. +> 2. If _resolved_ is **undefined**, continue the loop. +> 3. Return _resolved_. +> 3. Return or throw the last fallback resolution **null** return or error. +> 4. Otherwise, if _target_ is _null_, return **null**. +> 5. Otherwise throw an _Invalid Package Target_ error. -**ESM_FORMAT**(_url_) +**ESM\_FORMAT**(_url_) > 1. Assert: _url_ corresponds to an existing file. -> 1. Let _pjson_ be the result of **READ_PACKAGE_SCOPE**(_url_). -> 1. If _url_ ends in _".mjs"_, then +> 2. Let _pjson_ be the result of **READ\_PACKAGE\_SCOPE**(_url_). +> 3. If _url_ ends in _".mjs"_, then > 1. Return _"module"_. -> 1. If _url_ ends in _".cjs"_, then +> 4. If _url_ ends in _".cjs"_, then > 1. Return _"commonjs"_. -> 1. If _pjson?.type_ exists and is _"module"_, then +> 5. If _pjson?.type_ exists and is _"module"_, then > 1. If _url_ ends in _".js"_, then > 1. Return _"module"_. -> 1. Throw an _Unsupported File Extension_ error. -> 1. Otherwise, +> 2. Throw an _Unsupported File Extension_ error. +> 6. Otherwise, > 1. Throw an _Unsupported File Extension_ error. -**READ_PACKAGE_SCOPE**(_url_) +**READ\_PACKAGE\_SCOPE**(_url_) > 1. Let _scopeURL_ be _url_. -> 1. While _scopeURL_ is not the file system root, +> 2. While _scopeURL_ is not the file system root, > 1. Set _scopeURL_ to the parent URL of _scopeURL_. -> 1. If _scopeURL_ ends in a _"node_modules"_ path segment, return **null**. -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_scopeURL_). -> 1. If _pjson_ is not **null**, then +> 2. If _scopeURL_ ends in a _"node\_modules"_ path segment, return **null**. +> 3. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_scopeURL_). +> 4. If _pjson_ is not **null**, then > 1. Return _pjson_. -> 1. Return **null**. +> 3. Return **null**. -**READ_PACKAGE_JSON**(_packageURL_) +**READ\_PACKAGE\_JSON**(_packageURL_) > 1. Let _pjsonURL_ be the resolution of _"package.json"_ within _packageURL_. -> 1. If the file at _pjsonURL_ does not exist, then +> 2. If the file at _pjsonURL_ does not exist, then > 1. Return **null**. -> 1. If the file at _packageURL_ does not parse as valid JSON, then +> 3. If the file at _packageURL_ does not parse as valid JSON, then > 1. Throw an _Invalid Package Configuration_ error. -> 1. Return the parsed JSON source of the file at _pjsonURL_. +> 4. Return the parsed JSON source of the file at _pjsonURL_. ### Customizing ESM specifier resolution algorithm @@ -1363,6 +1360,7 @@ success! ``` + [6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index [CommonJS]: modules.md [Conditional exports]: packages.md#conditional-exports diff --git a/doc/api/events.md b/doc/api/events.md index b6a075f2a77a98..b659f1fd8cbcc5 100644 --- a/doc/api/events.md +++ b/doc/api/events.md @@ -113,7 +113,7 @@ myEmitter.emit('event'); Using the `eventEmitter.once()` method, it is possible to register a listener that is called at most once for a particular event. Once the event is emitted, -the listener is unregistered and *then* called. +the listener is unregistered and _then_ called. ```js const myEmitter = new MyEmitter(); @@ -226,6 +226,7 @@ do not have a catch handler to avoid infinite error loops: the recommendation is to **not use `async` functions as `'error'` event handlers**. ## Class: `EventEmitter` + @@ -259,15 +261,15 @@ added: v0.1.26 * `eventName` {string|symbol} The name of the event being listened for * `listener` {Function} The event handler function -The `EventEmitter` instance will emit its own `'newListener'` event *before* +The `EventEmitter` instance will emit its own `'newListener'` event _before_ a listener is added to its internal array of listeners. Listeners registered for the `'newListener'` event are passed the event name and a reference to the listener being added. The fact that the event is triggered before adding the listener has a subtle -but important side effect: any *additional* listeners registered to the same -`name` *within* the `'newListener'` callback are inserted *before* the +but important side effect: any _additional_ listeners registered to the same +`name` _within_ the `'newListener'` callback are inserted _before_ the listener that is in the process of being added. ```js @@ -293,6 +295,7 @@ myEmitter.emit('event'); ``` ### Event: `'removeListener'` + @@ -320,6 +324,7 @@ added: v0.1.26 Alias for `emitter.on(eventName, listener)`. ### `emitter.emit(eventName[, ...args])` + @@ -368,6 +373,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5); ``` ### `emitter.eventNames()` + @@ -391,6 +397,7 @@ console.log(myEE.eventNames()); ``` ### `emitter.getMaxListeners()` + @@ -402,6 +409,7 @@ set by [`emitter.setMaxListeners(n)`][] or defaults to [`events.defaultMaxListeners`][]. ### `emitter.listenerCount(eventName)` + @@ -412,6 +420,7 @@ added: v3.2.0 Returns the number of listeners listening to the event named `eventName`. ### `emitter.listeners(eventName)` + * `eventName` {string|symbol} -* Returns: {Function[]} +* Returns: {Function\[]} Returns a copy of the array of listeners for the event named `eventName`. @@ -435,6 +444,7 @@ console.log(util.inspect(server.listeners('connection'))); ``` ### `emitter.off(eventName, listener)` + @@ -446,6 +456,7 @@ added: v10.0.0 Alias for [`emitter.removeListener()`][]. ### `emitter.on(eventName, listener)` + @@ -483,6 +494,7 @@ myEE.emit('foo'); ``` ### `emitter.once(eventName, listener)` + @@ -517,6 +529,7 @@ myEE.emit('foo'); ``` ### `emitter.prependListener(eventName, listener)` + @@ -525,7 +538,7 @@ added: v6.0.0 * `listener` {Function} The callback function * Returns: {EventEmitter} -Adds the `listener` function to the *beginning* of the listeners array for the +Adds the `listener` function to the _beginning_ of the listeners array for the event named `eventName`. No checks are made to see if the `listener` has already been added. Multiple calls passing the same combination of `eventName` and `listener` will result in the `listener` being added, and called, multiple @@ -540,6 +553,7 @@ server.prependListener('connection', (stream) => { Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.prependOnceListener(eventName, listener)` + @@ -549,7 +563,7 @@ added: v6.0.0 * Returns: {EventEmitter} Adds a **one-time** `listener` function for the event named `eventName` to the -*beginning* of the listeners array. The next time `eventName` is triggered, this +_beginning_ of the listeners array. The next time `eventName` is triggered, this listener is removed, and then invoked. ```js @@ -561,6 +575,7 @@ server.prependOnceListener('connection', (stream) => { Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.removeAllListeners([eventName])` + @@ -577,6 +592,7 @@ component or module (e.g. sockets or file streams). Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.removeListener(eventName, listener)` + @@ -604,8 +620,8 @@ called multiple times to remove each instance. Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any -`removeListener()` or `removeAllListeners()` calls *after* emitting and -*before* the last listener finishes execution will not remove them from +`removeListener()` or `removeAllListeners()` calls _after_ emitting and +_before_ the last listener finishes execution will not remove them from `emit()` in progress. Subsequent events behave as expected. ```js @@ -639,7 +655,7 @@ myEmitter.emit('event'); ``` Because listeners are managed using an internal array, calling this will -change the position indices of any listener registered *after* the listener +change the position indices of any listener registered _after_ the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the `emitter.listeners()` method will need to be recreated. @@ -667,6 +683,7 @@ ee.emit('ping'); Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.setMaxListeners(n)` + @@ -683,12 +700,13 @@ modified for this specific `EventEmitter` instance. The value can be set to Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.rawListeners(eventName)` + * `eventName` {string|symbol} -* Returns: {Function[]} +* Returns: {Function\[]} Returns a copy of the array of listeners for the event named `eventName`, including any wrappers (such as those created by `.once()`). @@ -718,6 +736,7 @@ emitter.emit('log'); ``` ### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])` + @@ -763,12 +783,12 @@ added: v0.11.2 By default, a maximum of `10` listeners can be registered for any single event. This limit can be changed for individual `EventEmitter` instances using the [`emitter.setMaxListeners(n)`][] method. To change the default -for *all* `EventEmitter` instances, the `events.defaultMaxListeners` +for _all_ `EventEmitter` instances, the `events.defaultMaxListeners` property can be used. If this value is not a positive number, a `RangeError` is thrown. Take caution when setting the `events.defaultMaxListeners` because the -change affects *all* `EventEmitter` instances, including those created before +change affects _all_ `EventEmitter` instances, including those created before the change is made. However, calling [`emitter.setMaxListeners(n)`][] still has precedence over `events.defaultMaxListeners`. @@ -796,6 +816,7 @@ listeners, respectively. Its `name` property is set to `'MaxListenersExceededWarning'`. ## `events.errorMonitor` + + * `emitterOrTarget` {EventEmitter|EventTarget} * `eventName` {string|symbol} -* Returns: {Function[]} +* Returns: {Function\[]} Returns a copy of the array of listeners for the event named `eventName`. @@ -845,6 +868,7 @@ const { getEventListeners, EventEmitter } = require('events'); ``` ## `events.once(emitter, name[, options])` + * `n` {number} A non-negative number. The maximum number of listeners per `EventTarget` event. -* `...eventsTargets` {EventTarget[]|EventEmitter[]} Zero or more {EventTarget} +* `...eventsTargets` {EventTarget\[]|EventEmitter\[]} Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} objects. @@ -1137,7 +1166,9 @@ setMaxListeners(5, target, emitter); ``` + ## `EventTarget` and `Event` API + @@ -1292,6 +1325,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.cancelBubble()` + @@ -1300,6 +1334,7 @@ Alias for `event.stopPropagation()`. This is not used in Node.js and is provided purely for completeness. #### `event.cancelable` + @@ -1307,6 +1342,7 @@ added: v14.5.0 * Type: {boolean} True if the event was created with the `cancelable` option. #### `event.composed` + @@ -1316,6 +1352,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.composedPath()` + @@ -1325,6 +1362,7 @@ empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. #### `event.currentTarget` + @@ -1334,6 +1372,7 @@ added: v14.5.0 Alias for `event.target`. #### `event.defaultPrevented` + @@ -1344,6 +1383,7 @@ Is `true` if `cancelable` is `true` and `event.preventDefault()` has been called. #### `event.eventPhase` + @@ -1354,6 +1394,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.isTrusted` + @@ -1364,6 +1405,7 @@ The {AbortSignal} `"abort"` event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. #### `event.preventDefault()` + @@ -1371,6 +1413,7 @@ added: v14.5.0 Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. #### `event.returnValue` + @@ -1380,6 +1423,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.srcElement` + @@ -1389,6 +1433,7 @@ added: v14.5.0 Alias for `event.target`. #### `event.stopImmediatePropagation()` + @@ -1396,6 +1441,7 @@ added: v14.5.0 Stops the invocation of event listeners after the current one completes. #### `event.stopPropagation()` + @@ -1403,6 +1449,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.target` + @@ -1410,6 +1457,7 @@ added: v14.5.0 * Type: {EventTarget} The `EventTarget` dispatching the event. #### `event.timeStamp` + @@ -1419,6 +1467,7 @@ added: v14.5.0 The millisecond timestamp when the `Event` object was created. #### `event.type` + @@ -1428,6 +1477,7 @@ added: v14.5.0 The event type identifier. ### Class: `EventTarget` + #### `eventTarget.addEventListener(type, listener[, options])` + @@ -1480,6 +1531,7 @@ target.removeEventListener('foo', handler, { capture: true }); ``` #### `eventTarget.dispatchEvent(event)` + @@ -1494,6 +1546,7 @@ The registered event listeners is synchronously invoked in the order they were registered. #### `eventTarget.removeEventListener(type, listener)` + @@ -1506,6 +1559,7 @@ added: v14.5.0 Removes the `listener` from the list of handlers for event `type`. ### Class: `NodeEventTarget` + @@ -1516,12 +1570,15 @@ The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` that emulates a subset of the `EventEmitter` API. #### `nodeEventTarget.addListener(type, listener[, options])` + * `type` {string} + * `listener` {Function|EventListener} + * `options` {Object} * `once` {boolean} @@ -1533,16 +1590,18 @@ equivalent `EventEmitter` API. The only difference between `addListener()` and `EventTarget`. #### `nodeEventTarget.eventNames()` + -* Returns: {string[]} +* Returns: {string\[]} Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. #### `nodeEventTarget.listenerCount(type)` + @@ -1555,11 +1614,13 @@ Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. #### `nodeEventTarget.off(type, listener)` + * `type` {string} + * `listener` {Function|EventListener} * Returns: {EventTarget} this @@ -1567,12 +1628,15 @@ added: v14.5.0 Node.js-specific alias for `eventTarget.removeListener()`. #### `nodeEventTarget.on(type, listener[, options])` + * `type` {string} + * `listener` {Function|EventListener} + * `options` {Object} * `once` {boolean} @@ -1581,12 +1645,15 @@ added: v14.5.0 Node.js-specific alias for `eventTarget.addListener()`. #### `nodeEventTarget.once(type, listener[, options])` + * `type` {string} + * `listener` {Function|EventListener} + * `options` {Object} * Returns: {EventTarget} this @@ -1596,6 +1663,7 @@ listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. #### `nodeEventTarget.removeAllListeners([type])` + @@ -1609,11 +1677,13 @@ removes all registered listeners for `type`, otherwise removes all registered listeners. #### `nodeEventTarget.removeListener(type, listener)` + * `type` {string} + * `listener` {Function|EventListener} * Returns: {EventTarget} this diff --git a/doc/api/fs.md b/doc/api/fs.md index f09063a575d5f2..c277c7874f9f88 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -122,6 +122,7 @@ try { ``` ## Promises API + @@ -165,6 +167,7 @@ it can be unreliable and the file may not be closed. Instead, always explicitly close {FileHandle}s. Node.js may change this behavior in the future. #### Event: `'close'` + @@ -173,6 +176,7 @@ The `'close'` event is emitted when the {FileHandle} has been closed and can no longer be used. #### `filehandle.appendFile(data[, options])` + @@ -189,6 +193,7 @@ to with [`fsPromises.open()`][]. Therefore, this is equivalent to [`filehandle.writeFile()`][]. #### `filehandle.chmod(mode)` + @@ -199,6 +204,7 @@ added: v10.0.0 Modifies the permissions on the file. See chmod(2). #### `filehandle.chown(uid, gid)` + @@ -210,6 +216,7 @@ added: v10.0.0 Changes the ownership of the file. A wrapper for chown(2). #### `filehandle.close()` + @@ -231,6 +238,7 @@ try { ``` #### `filehandle.createReadStream([options])` + @@ -250,7 +258,7 @@ returned by this method has a default `highWaterMark` of 64 kb. `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start counting at 0, allowed values are in the -[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `start` is +\[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `start` is omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from the current file position. The `encoding` can be any one of those accepted by {Buffer}. @@ -297,6 +305,7 @@ fd.createReadStream({ start: 90, end: 99 }); ``` #### `filehandle.createWriteStream([options])` + @@ -310,9 +319,9 @@ added: v16.11.0 `options` may also include a `start` option to allow writing data at some position past the beginning of the file, allowed values are in the -[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than replacing -it may require the `flags` `open` option to be set to `r+` rather than the -default `r`. The `encoding` can be any one of those accepted by {Buffer}. +\[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than +replacing it may require the `flags` `open` option to be set to `r+` rather than +the default `r`. The `encoding` can be any one of those accepted by {Buffer}. If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, @@ -324,6 +333,7 @@ By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. #### `filehandle.datasync()` + @@ -337,6 +347,7 @@ fdatasync(2) documentation for details. Unlike `filehandle.sync` this method does not flush modified metadata. #### `filehandle.fd` + @@ -344,6 +355,7 @@ added: v10.0.0 * {number} The numeric file descriptor managed by the {FileHandle} object. #### `filehandle.read(buffer, offset, length, position)` + @@ -367,11 +379,13 @@ If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. #### `filehandle.read([options])` + + * `options` {Object} * `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the file data read. **Default:** `Buffer.alloc(16384)` @@ -394,6 +408,7 @@ If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. #### `filehandle.readFile(options)` + @@ -417,24 +432,26 @@ position till the end of the file. It doesn't always read from the beginning of the file. #### `filehandle.readv(buffers[, position])` + -* `buffers` {Buffer[]|TypedArray[]|DataView[]} +* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} * `position` {integer} The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. * Returns: {Promise} Fulfills upon success an object containing two properties: * `bytesRead` {integer} the number of bytes read - * `buffers` {Buffer[]|TypedArray[]|DataView[]} property containing + * `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} property containing a reference to the `buffers` input. Read from a file and write to an array of {ArrayBufferView}s #### `filehandle.stat([options])` + @@ -461,6 +479,7 @@ device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. #### `filehandle.truncate(len)` + @@ -493,6 +512,7 @@ extended part is filled with null bytes (`'\0'`): If `len` is negative then `0` will be used. #### `filehandle.utimes(atime, mtime)` + @@ -505,6 +525,7 @@ Change the file system timestamps of the object referenced by the {FileHandle} then resolves the promise with no arguments upon success. #### `filehandle.write(buffer[, offset[, length[, position]]])` + -* `buffers` {Buffer[]|TypedArray[]|DataView[]} +* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} * `position` {integer} The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current position. @@ -643,7 +667,7 @@ Write an array of {ArrayBufferView}s to the file. The promise is resolved with an object containing a two properties: * `bytesWritten` {integer} the number of bytes written -* `buffers` {Buffer[]|TypedArray[]|DataView[]} a reference to the `buffers` +* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} a reference to the `buffers` input. It is unsafe to call `writev()` multiple times on the same file without waiting @@ -654,6 +678,7 @@ The kernel ignores the position argument and always appends the data to the end of the file. ### `fsPromises.access(path[, mode])` + @@ -692,6 +717,7 @@ calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. ### `fsPromises.appendFile(path, data[, options])` + @@ -716,6 +742,7 @@ The `path` may be specified as a {FileHandle} that has been opened for appending (using `fsPromises.open()`). ### `fsPromises.chmod(path, mode)` + @@ -727,6 +754,7 @@ added: v10.0.0 Changes the permissions of a file. ### `fsPromises.chown(path, uid, gid)` + @@ -739,6 +767,7 @@ added: v10.0.0 Changes the ownership of a file. ### `fsPromises.copyFile(src, dest[, mode])` + @@ -808,7 +838,7 @@ added: v16.7.0 * `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. Can also return a `Promise` that resolves to `true` or `false` **Default:** `undefined`. - * `force` {boolean} overwrite existing file or directory. _The copy + * `force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. **Default:** `true`. @@ -824,6 +854,7 @@ When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fsPromises.lchmod(path, mode)` + @@ -837,6 +868,7 @@ Changes the permissions on a symbolic link. This method is only implemented on macOS. ### `fsPromises.lchown(path, uid, gid)` + @@ -882,6 +916,7 @@ Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. ### `fsPromises.lstat(path[, options])` + @@ -923,6 +959,7 @@ property indicating whether parent directories should be created. Calling rejection only when `recursive` is false. ### `fsPromises.mkdtemp(prefix[, options])` + + * `path` {string|Buffer|URL} * `options` {string|Object} * `encoding` {string} **Default:** `'utf8'` @@ -1146,6 +1189,7 @@ the link path returned. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a {Buffer} object. ### `fsPromises.realpath(path[, options])` + @@ -1170,6 +1214,7 @@ be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fsPromises.rename(oldPath, newPath)` + @@ -1181,6 +1226,7 @@ added: v10.0.0 Renames `oldPath` to `newPath`. ### `fsPromises.rmdir(path[, options])` + @@ -1264,6 +1311,7 @@ added: v14.14.0 Removes files and directories (modeled on the standard POSIX `rm` utility). ### `fsPromises.stat(path[, options])` + @@ -1298,6 +1347,7 @@ to be absolute. When using `'junction'`, the `target` argument will automatically be normalized to absolute path. ### `fsPromises.truncate(path[, len])` + @@ -1310,6 +1360,7 @@ Truncates (shortens or extends the length) of the content at `path` to `len` bytes. ### `fsPromises.unlink(path)` + @@ -1323,6 +1374,7 @@ path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail. ### `fsPromises.utimes(path, atime, mtime)` + @@ -1342,6 +1394,7 @@ The `atime` and `mtime` arguments follow these rules: `-Infinity`, an `Error` will be thrown. ### `fsPromises.watch(filename[, options])` + @@ -1355,7 +1408,7 @@ added: v15.9.0 specified, and only on supported platforms (See [caveats][]). **Default:** `false`. * `encoding` {string} Specifies the character encoding to be used for the - filename passed to the listener. **Default:** `'utf8'`. + filename passed to the listener. **Default:** `'utf8'`. * `signal` {AbortSignal} An {AbortSignal} used to signal when the watcher should stop. * Returns: {AsyncIterator} of objects with the properties: @@ -1391,6 +1444,7 @@ disappears in the directory. All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`. ### `fsPromises.writeFile(file, data[, options])` + @@ -1959,7 +2020,7 @@ added: v16.7.0 * `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. Can also return a `Promise` that resolves to `true` or `false` **Default:** `undefined`. - * `force` {boolean} overwrite existing file or directory. _The copy + * `force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. **Default:** `true`. @@ -1975,6 +2036,7 @@ When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fs.createReadStream(path[, options])` + + * `fd` {integer} * `options` {Object} * `buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)` @@ -2976,6 +3059,7 @@ Similar to the [`fs.read()`][] function, this version takes an optional above values. ### `fs.readdir(path[, options], callback)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * `callback` {Function} * `err` {Error} * `bytesRead` {integer} - * `buffers` {ArrayBufferView[]} + * `buffers` {ArrayBufferView\[]} Read from a file specified by `fd` and write to an array of `ArrayBufferView`s using `readv()`. @@ -3223,6 +3310,7 @@ If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesRead` and `buffers` properties. ### `fs.realpath(path[, options], callback)` + @@ -3311,6 +3400,7 @@ be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fs.rename(oldPath, newPath, callback)` + @@ -3451,6 +3543,7 @@ utility). No arguments other than a possible exception are given to the completion callback. ### `fs.stat(path[, options], callback)` + @@ -3713,7 +3810,7 @@ added: v0.1.31 `fs.watchFile()` Stop watching for changes on `filename`. If `listener` is specified, only that -particular listener is removed. Otherwise, *all* listeners are removed, +particular listener is removed. Otherwise, _all_ listeners are removed, effectively stopping watching of `filename`. Calling `fs.unwatchFile()` with a filename that is not being watched is a @@ -3724,6 +3821,7 @@ Using [`fs.watch()`][] is more efficient than `fs.watchFile()` and and `fs.unwatchFile()` when possible. ### `fs.utimes(path, atime, mtime, callback)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * `callback` {Function} * `err` {Error} * `bytesWritten` {integer} - * `buffers` {ArrayBufferView[]} + * `buffers` {ArrayBufferView\[]} Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. @@ -4270,6 +4374,7 @@ The synchronous APIs perform all operations synchronously, blocking the event loop until the operation completes or fails. ### `fs.accessSync(path[, mode])` + @@ -4419,6 +4528,7 @@ through any other `fs` operation may lead to undefined behavior. See the POSIX close(2) documentation for more detail. ### `fs.copyFileSync(src, dest[, mode])` + @@ -4477,7 +4588,7 @@ added: v16.7.0 exists, throw an error. **Default:** `false`. * `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. **Default:** `undefined` - * `force` {boolean} overwrite existing file or directory. _The copy + * `force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. **Default:** `true`. @@ -4492,6 +4603,7 @@ When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fs.existsSync(path)` + @@ -4533,6 +4646,7 @@ Sets the permissions on the file. Returns `undefined`. See the POSIX fchmod(2) documentation for more detail. ### `fs.fchownSync(fd, uid, gid)` + @@ -4546,6 +4660,7 @@ Sets the owner of the file. Returns `undefined`. See the POSIX fchown(2) documentation for more detail. ### `fs.fdatasyncSync(fd)` + @@ -4557,6 +4672,7 @@ operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns `undefined`. ### `fs.fstatSync(fd[, options])` + @@ -4588,6 +4705,7 @@ device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. Returns `undefined`. ### `fs.ftruncateSync(fd[, len])` + @@ -4601,6 +4719,7 @@ For detailed information, see the documentation of the asynchronous version of this API: [`fs.ftruncate()`][]. ### `fs.futimesSync(fd, atime, mtime)` + @@ -4631,6 +4751,7 @@ This method is only implemented on macOS. See the POSIX lchmod(2) documentation for more detail. ### `fs.lchownSync(path, uid, gid)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * Returns: {number} The number of bytes read. @@ -4987,6 +5121,7 @@ For detailed information, see the documentation of the asynchronous version of this API: [`fs.readv()`][]. ### `fs.realpathSync(path[, options])` + @@ -5040,6 +5176,7 @@ be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fs.renameSync(oldPath, newPath)` + @@ -5143,6 +5282,7 @@ Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. ### `fs.statSync(path[, options])` + @@ -5212,6 +5354,7 @@ Passing a file descriptor is deprecated and may result in an error being thrown in the future. ### `fs.unlinkSync(path)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * Returns: {number} The number of bytes written. @@ -5379,6 +5527,7 @@ The common objects are shared by all of the file system API variants (promise, callback, and synchronous). ### Class: `fs.Dir` + @@ -5404,6 +5553,7 @@ When using the async iterator, the {fs.Dir} object will be automatically closed after the iterator exits. #### `dir.close()` + @@ -5417,6 +5567,7 @@ A promise is returned that will be resolved after the resource has been closed. #### `dir.close(callback)` + @@ -5430,6 +5581,7 @@ Subsequent reads will result in errors. The `callback` will be called after the resource handle has been closed. #### `dir.closeSync()` + @@ -5438,6 +5590,7 @@ Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors. #### `dir.path` + @@ -5448,6 +5601,7 @@ The read-only path of this directory as was provided to [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][]. #### `dir.read()` + @@ -5466,6 +5620,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir.read(callback)` + @@ -5486,6 +5641,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir.readSync()` + @@ -5503,6 +5659,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir[Symbol.asyncIterator]()` + @@ -5523,6 +5680,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. ### Class: `fs.Dirent` + @@ -5536,6 +5694,7 @@ the `withFileTypes` option set to `true`, the resulting array is filled with {fs.Dirent} objects, rather than strings or {Buffer}s. #### `dirent.isBlockDevice()` + @@ -5545,6 +5704,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a block device. #### `dirent.isCharacterDevice()` + @@ -5554,6 +5714,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a character device. #### `dirent.isDirectory()` + @@ -5564,6 +5725,7 @@ Returns `true` if the {fs.Dirent} object describes a file system directory. #### `dirent.isFIFO()` + @@ -5574,6 +5736,7 @@ Returns `true` if the {fs.Dirent} object describes a first-in-first-out (FIFO) pipe. #### `dirent.isFile()` + @@ -5583,6 +5746,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a regular file. #### `dirent.isSocket()` + @@ -5592,6 +5756,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a socket. #### `dirent.isSymbolicLink()` + @@ -5601,6 +5766,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a symbolic link. #### `dirent.name` + @@ -5612,6 +5778,7 @@ value is determined by the `options.encoding` passed to [`fs.readdir()`][] or [`fs.readdirSync()`][]. ### Class: `fs.FSWatcher` + @@ -5625,6 +5792,7 @@ All {fs.FSWatcher} objects emit a `'change'` event whenever a specific watched file is modified. #### Event: `'change'` + @@ -5652,6 +5820,7 @@ watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => { ``` #### Event: `'close'` + @@ -5660,6 +5829,7 @@ Emitted when the watcher stops watching for changes. The closed {fs.FSWatcher} object is no longer usable in the event handler. #### Event: `'error'` + @@ -5670,6 +5840,7 @@ Emitted when an error occurs while watching the file. The errored {fs.FSWatcher} object is no longer usable in the event handler. #### `watcher.close()` + @@ -5678,6 +5849,7 @@ Stop watching for changes on the given {fs.FSWatcher}. Once stopped, the {fs.FSWatcher} object is no longer usable. #### `watcher.ref()` + @@ -5764,6 +5941,7 @@ Instances of {fs.ReadStream} are created and returned using the [`fs.createReadStream()`][] function. #### Event: `'close'` + @@ -5771,6 +5949,7 @@ added: v0.1.93 Emitted when the {fs.ReadStream}'s underlying file descriptor has been closed. #### Event: `'open'` + @@ -5780,6 +5959,7 @@ added: v0.1.93 Emitted when the {fs.ReadStream}'s file descriptor has been opened. #### Event: `'ready'` + @@ -5789,6 +5969,7 @@ Emitted when the {fs.ReadStream} is ready to be used. Fires immediately after `'open'`. #### `readStream.bytesRead` + @@ -5798,6 +5979,7 @@ added: v6.4.0 The number of bytes that have been read so far. #### `readStream.path` + @@ -5811,6 +5993,7 @@ argument to `fs.createReadStream()`. If `path` is passed as a string, then `readStream.path` will be `undefined`. #### `readStream.pending` + @@ -5899,6 +6084,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a block device. #### `stats.isCharacterDevice()` + @@ -5908,6 +6094,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a character device. #### `stats.isDirectory()` + @@ -5921,6 +6108,7 @@ always return `false`. This is because [`fs.lstat()`][] returns information about a symbolic link itself and not the path it resolves to. #### `stats.isFIFO()` + @@ -5931,6 +6119,7 @@ Returns `true` if the {fs.Stats} object describes a first-in-first-out (FIFO) pipe. #### `stats.isFile()` + @@ -5940,6 +6129,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a regular file. #### `stats.isSocket()` + @@ -5949,6 +6139,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a socket. #### `stats.isSymbolicLink()` + @@ -6020,6 +6211,7 @@ The file system block size for i/o operations. The number of blocks allocated for this file. #### `stats.atimeMs` + @@ -6030,6 +6222,7 @@ The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch. #### `stats.mtimeMs` + @@ -6040,6 +6233,7 @@ The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch. #### `stats.ctimeMs` + @@ -6050,6 +6244,7 @@ The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch. #### `stats.birthtimeMs` + @@ -6060,6 +6255,7 @@ The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch. #### `stats.atimeNs` + @@ -6072,6 +6268,7 @@ The timestamp indicating the last time this file was accessed expressed in nanoseconds since the POSIX Epoch. #### `stats.mtimeNs` + @@ -6084,6 +6281,7 @@ The timestamp indicating the last time this file was modified expressed in nanoseconds since the POSIX Epoch. #### `stats.ctimeNs` + @@ -6096,6 +6294,7 @@ The timestamp indicating the last time the file status was changed expressed in nanoseconds since the POSIX Epoch. #### `stats.birthtimeNs` + @@ -6108,6 +6307,7 @@ The timestamp indicating the creation time of this file expressed in nanoseconds since the POSIX Epoch. #### `stats.atime` + @@ -6117,6 +6317,7 @@ added: v0.11.13 The timestamp indicating the last time this file was accessed. #### `stats.mtime` + @@ -6126,6 +6327,7 @@ added: v0.11.13 The timestamp indicating the last time this file was modified. #### `stats.ctime` + @@ -6135,6 +6337,7 @@ added: v0.11.13 The timestamp indicating the last time the file status was changed. #### `stats.birthtime` + @@ -6184,6 +6387,7 @@ Prior to Node.js 0.12, the `ctime` held the `birthtime` on Windows systems. As of 0.12, `ctime` is not "creation time", and on Unix systems, it never was. ### Class: `fs.WriteStream` + @@ -6194,6 +6398,7 @@ Instances of {fs.WriteStream} are created and returned using the [`fs.createWriteStream()`][] function. #### Event: `'close'` + @@ -6201,6 +6406,7 @@ added: v0.1.93 Emitted when the {fs.WriteStream}'s underlying file descriptor has been closed. #### Event: `'open'` + @@ -6210,6 +6416,7 @@ added: v0.1.93 Emitted when the {fs.WriteStream}'s file is opened. #### Event: `'ready'` + @@ -6219,6 +6426,7 @@ Emitted when the {fs.WriteStream} is ready to be used. Fires immediately after `'open'`. #### `writeStream.bytesWritten` + @@ -6227,6 +6435,7 @@ The number of bytes written so far. Does not include data that is still queued for writing. #### `writeStream.close([callback])` + @@ -6239,6 +6448,7 @@ callback that will be executed once the `writeStream` is closed. #### `writeStream.path` + @@ -6249,6 +6459,7 @@ argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then `writeStream.path` will be a {Buffer}. #### `writeStream.pending` + @@ -6668,9 +6879,11 @@ try { ``` #### File URL paths + + For most `fs` module functions, the `path` or `filename` argument may be passed as a {URL} object using the `file:` protocol. @@ -6792,7 +7005,7 @@ example `fs.readdirSync('C:\\')` can potentially return a different result than On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric -identifier called a *file descriptor*. At the system-level, all file system +identifier called a _file descriptor_. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the diff --git a/doc/api/globals.md b/doc/api/globals.md index db071e2cb95dfb..c7e539ca41aade 100644 --- a/doc/api/globals.md +++ b/doc/api/globals.md @@ -19,6 +19,7 @@ that are part of the JavaScript language itself, which are also globally accessible. ## Class: `AbortController` + @@ -52,6 +54,7 @@ Triggers the abort signal, causing the `abortController.signal` to emit the `'abort'` event. ### `abortController.signal` + @@ -59,6 +62,7 @@ added: v15.0.0 * Type: {AbortSignal} ### Class: `AbortSignal` + @@ -69,6 +73,7 @@ The `AbortSignal` is used to notify observers when the `abortController.abort()` method is called. #### Static method: `AbortSignal.abort()` + @@ -78,6 +83,7 @@ added: v15.12.0 Returns a new already aborted `AbortSignal`. #### Event: `'abort'` + @@ -112,6 +118,7 @@ removed as soon as the `'abort'` event is handled. Failure to do so may result in memory leaks. #### `abortSignal.aborted` + @@ -119,6 +126,7 @@ added: v15.0.0 * Type: {boolean} True after the `AbortController` has been aborted. #### `abortSignal.onabort` + @@ -129,6 +137,7 @@ An optional callback function that may be set by user code to be notified when the `abortController.abort()` function has been called. ## Class: `Buffer` + @@ -148,6 +157,7 @@ This variable may appear to be global but is not. See [`__dirname`][]. This variable may appear to be global but is not. See [`__filename`][]. ## `atob(data)` + @@ -157,6 +167,7 @@ added: v16.0.0 Global alias for [`buffer.atob()`][]. ## `btoa(data)` + @@ -166,6 +177,7 @@ added: v16.0.0 Global alias for [`buffer.btoa()`][]. ## `clearImmediate(immediateObject)` + @@ -175,6 +187,7 @@ added: v0.9.1 [`clearImmediate`][] is described in the [timers][] section. ## `clearInterval(intervalObject)` + @@ -184,6 +197,7 @@ added: v0.0.1 [`clearInterval`][] is described in the [timers][] section. ## `clearTimeout(timeoutObject)` + @@ -193,6 +207,7 @@ added: v0.0.1 [`clearTimeout`][] is described in the [timers][] section. ## `console` + @@ -204,6 +219,7 @@ added: v0.1.100 Used to print to stdout and stderr. See the [`console`][] section. ## `Event` + @@ -250,6 +268,7 @@ Node.js this is different. The top-level scope is not the global scope; `var something` inside a Node.js module will be local to that module. ## `MessageChannel` + @@ -259,6 +278,7 @@ added: v15.0.0 The `MessageChannel` class. See [`MessageChannel`][] for more details. ## `MessageEvent` + @@ -268,6 +288,7 @@ added: v15.0.0 The `MessageEvent` class. See [`MessageEvent`][] for more details. ## `MessagePort` + @@ -285,6 +306,7 @@ This variable may appear to be global but is not. See [`module`][]. The [`perf_hooks.performance`][] object. ## `process` + @@ -296,6 +318,7 @@ added: v0.1.7 The process object. See the [`process` object][] section. ## `queueMicrotask(callback)` + @@ -339,6 +362,7 @@ DataHandler.prototype.load = async function load(key) { This variable may appear to be global but is not. See [`require()`][]. ## `setImmediate(callback[, ...args])` + @@ -348,6 +372,7 @@ added: v0.9.1 [`setImmediate`][] is described in the [timers][] section. ## `setInterval(callback, delay[, ...args])` + @@ -357,6 +382,7 @@ added: v0.0.1 [`setInterval`][] is described in the [timers][] section. ## `setTimeout(callback, delay[, ...args])` + @@ -366,6 +392,7 @@ added: v0.0.1 [`setTimeout`][] is described in the [timers][] section. ## `TextDecoder` + @@ -375,6 +402,7 @@ added: v11.0.0 The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section. ## `TextEncoder` + @@ -384,6 +412,7 @@ added: v11.0.0 The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section. ## `URL` + @@ -393,6 +422,7 @@ added: v10.0.0 The WHATWG `URL` class. See the [`URL`][] section. ## `URLSearchParams` + @@ -402,6 +432,7 @@ added: v10.0.0 The WHATWG `URLSearchParams` class. See the [`URLSearchParams`][] section. ## `WebAssembly` + diff --git a/doc/api/http.md b/doc/api/http.md index 74b0f9975fd5bb..70133e1e509598 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -17,6 +17,7 @@ user is able to stream data. HTTP message headers are represented by an object like this: + ```js { 'content-length': '123', 'content-type': 'text/plain', @@ -40,6 +41,7 @@ example, the previous message header object might have a `rawHeaders` list like the following: + ```js [ 'ConTent-Length', '123456', 'content-LENGTH', '123', @@ -50,6 +52,7 @@ list like the following: ``` ## Class: `http.Agent` + @@ -110,6 +113,7 @@ http.get({ ``` ### `new Agent([options])` + @@ -213,6 +218,7 @@ type other than {net.Socket}. `callback` has a signature of `(err, stream)`. ### `agent.keepSocketAlive(socket)` + @@ -236,6 +242,7 @@ The `socket` argument can be an instance of {net.Socket}, a subclass of {stream.Duplex}. ### `agent.reuseSocket(socket, request)` + @@ -256,6 +263,7 @@ The `socket` argument can be an instance of {net.Socket}, a subclass of {stream.Duplex}. ### `agent.destroy()` + @@ -269,6 +277,7 @@ sockets might stay open for quite a long time before the server terminates them. ### `agent.freeSockets` + @@ -306,6 +316,7 @@ the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability. ### `agent.maxFreeSockets` + @@ -317,6 +328,7 @@ sets the maximum number of sockets that will be left open in the free state. ### `agent.maxSockets` + @@ -327,6 +339,7 @@ By default set to `Infinity`. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of [`agent.getName()`][]. ### `agent.maxTotalSockets` + @@ -376,7 +392,7 @@ added: v0.1.17 This object is created internally and returned from [`http.request()`][]. It represents an _in-progress_ request whose header has already been queued. The header is still mutable using the [`setHeader(name, value)`][], - [`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will +[`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will be sent along with the first data chunk or when calling [`request.end()`][]. To get the response, add a listener for [`'response'`][] to the request object. @@ -403,6 +419,7 @@ Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not. ### Event: `'abort'` + @@ -488,6 +506,7 @@ proxy.listen(1337, '127.0.0.1', () => { ``` ### Event: `'continue'` + @@ -497,6 +516,7 @@ the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body. ### Event: `'information'` + @@ -508,7 +528,7 @@ added: v10.0.0 * `statusCode` {integer} * `statusMessage` {string} * `headers` {Object} - * `rawHeaders` {string[]} + * `rawHeaders` {string\[]} Emitted when the server sends a 1xx intermediate response (excluding 101 Upgrade). The listeners of this event will receive an object containing the @@ -539,6 +559,7 @@ upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the [`'upgrade'`][] event instead. ### Event: `'response'` + @@ -549,6 +570,7 @@ Emitted when a response is received to this request. This event is emitted only once. ### Event: `'socket'` + @@ -560,6 +582,7 @@ a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. ### Event: `'timeout'` + @@ -570,6 +593,7 @@ that the socket has been idle. The request must be destroyed manually. See also: [`request.setTimeout()`][]. ### Event: `'upgrade'` + @@ -631,6 +655,7 @@ server.listen(1337, '127.0.0.1', () => { ``` ### `request.abort()` + @@ -760,6 +792,7 @@ data is not sent until possibly much later. `request.flushHeaders()` bypasses the optimization and kickstarts the request. ### `request.getHeader(name)` + @@ -784,11 +817,12 @@ const cookie = request.getHeader('Cookie'); ``` ### `request.getRawHeaderNames()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set. @@ -808,6 +842,7 @@ const headerNames = request.getRawHeaderNames(); Limits maximum response headers count. If set to 0, no limit will be applied. ### `request.path` + @@ -815,6 +850,7 @@ added: v0.4.0 * {string} The request path. ### `request.method` + @@ -822,6 +858,7 @@ added: v0.1.97 * {string} The request method. ### `request.host` + @@ -853,6 +892,7 @@ request.removeHeader('Content-Type'); ``` ### `request.reusedSocket` + @@ -935,6 +976,7 @@ request.setHeader('Cookie', ['type=ninja', 'language=javascript']); ``` ### `request.setNoDelay([noDelay])` + @@ -945,6 +987,7 @@ Once a socket is assigned to this request and is connected [`socket.setNoDelay()`][] will be called. ### `request.setSocketKeepAlive([enable][, initialDelay])` + @@ -956,6 +999,7 @@ Once a socket is assigned to this request and is connected [`socket.setKeepAlive()`][] will be called. ### `request.setTimeout(timeout[, callback])` + @@ -1003,6 +1048,7 @@ a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `request.writableEnded` + @@ -1014,6 +1060,7 @@ does not indicate whether the data has been flushed, for this use [`request.writableFinished`][] instead. ### `request.writableFinished` + @@ -1024,6 +1071,7 @@ Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. ### `request.write(chunk[, encoding][, callback])` + @@ -1053,6 +1101,7 @@ When `write` function is called with empty string or buffer, it does nothing and waits for more input. ## Class: `http.Server` + @@ -1060,6 +1109,7 @@ added: v0.1.17 * Extends: {net.Server} ### Event: `'checkContinue'` + @@ -1080,6 +1130,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. ### Event: `'checkExpectation'` + @@ -1095,6 +1146,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. ### Event: `'clientError'` + @@ -1179,6 +1232,7 @@ added: v0.1.4 Emitted when the server closes. ### Event: `'connect'` + @@ -1201,6 +1255,7 @@ event listener, meaning it will need to be bound in order to handle data sent to the server on that socket. ### Event: `'connection'` + @@ -1225,6 +1280,7 @@ a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. ### Event: `'request'` + @@ -1236,6 +1292,7 @@ Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections). ### Event: `'upgrade'` + @@ -1271,6 +1329,7 @@ added: v0.1.90 Stops the server from accepting new connections. See [`net.Server.close()`][]. ### `server.headersTimeout` + @@ -1305,6 +1365,7 @@ added: v5.7.0 * {boolean} Indicates whether or not the server is listening for connections. ### `server.maxHeadersCount` + @@ -1314,6 +1375,7 @@ added: v0.7.0 Limits maximum incoming headers count. If set to 0, no limit will be applied. ### `server.requestTimeout` + @@ -1331,6 +1393,7 @@ potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front. ### `server.setTimeout([msecs][, callback])` + @@ -1371,6 +1435,7 @@ but will not actually close the connection, subsequent requests sent after the limit is reached will get `503 Service Unavailable` as a response. ### `server.timeout` + @@ -1411,6 +1477,7 @@ The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. ## Class: `http.ServerResponse` + @@ -1421,6 +1488,7 @@ This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. ### Event: `'close'` + @@ -1429,6 +1497,7 @@ Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion). ### Event: `'finish'` + @@ -1439,6 +1508,7 @@ handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet. ### `response.addTrailers(headers)` + @@ -1467,6 +1537,7 @@ Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. ### `response.connection` + @@ -1534,6 +1609,7 @@ added: v1.6.0 Flushes the response headers. See also: [`request.flushHeaders()`][]. ### `response.getHeader(name)` + @@ -1558,11 +1634,12 @@ const setCookie = response.getHeader('set-cookie'); ``` ### `response.getHeaderNames()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array containing the unique names of the current outgoing headers. All header names are lowercase. @@ -1576,6 +1653,7 @@ const headerNames = response.getHeaderNames(); ``` ### `response.getHeaders()` + @@ -1591,7 +1669,7 @@ are lowercase. The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others -are not defined and *will not work*. +are not defined and _will not work_. ```js response.setHeader('Foo', 'bar'); @@ -1602,6 +1680,7 @@ const headers = response.getHeaders(); ``` ### `response.hasHeader(name)` + @@ -1617,6 +1696,7 @@ const hasContentType = response.hasHeader('content-type'); ``` ### `response.headersSent` + @@ -1626,6 +1706,7 @@ added: v0.9.3 Boolean (read-only). True if headers were sent, false otherwise. ### `response.removeHeader(name)` + @@ -1639,6 +1720,7 @@ response.removeHeader('Content-Encoding'); ``` ### `response.req` + @@ -1648,6 +1730,7 @@ added: v15.7.0 A reference to the original HTTP `request` object. ### `response.sendDate` + @@ -1661,6 +1744,7 @@ This should only be disabled for testing; HTTP requires the Date header in responses. ### `response.setHeader(name, value)` + @@ -1714,6 +1798,7 @@ is desired with potential future retrieval and modification, use [`response.setHeader()`][] instead of [`response.writeHead()`][]. ### `response.setTimeout(msecs[, callback])` + @@ -1732,6 +1817,7 @@ assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. ### `response.socket` + @@ -1757,6 +1843,7 @@ a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `response.statusCode` + @@ -1775,6 +1862,7 @@ After response header was sent to the client, this property indicates the status code which was sent out. ### `response.statusMessage` + @@ -1794,6 +1882,7 @@ After response header was sent to the client, this property indicates the status message which was sent out. ### `response.uncork()` + @@ -1814,6 +1904,7 @@ does not indicate whether the data has been flushed, for this use [`response.writableFinished`][] instead. ### `response.writableFinished` + @@ -1824,6 +1915,7 @@ Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. ### `response.write(chunk[, encoding][, callback])` + @@ -1861,6 +1953,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. ### `response.writeContinue()` + @@ -1870,6 +1963,7 @@ the request body should be sent. See the [`'checkContinue'`][] event on `Server`. ### `response.writeHead(statusCode[, statusMessage][, headers])` + @@ -1961,6 +2056,7 @@ Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent. ## Class: `http.IncomingMessage` + @@ -2005,6 +2103,7 @@ added: v0.4.2 Indicates that the underlying connection was closed. ### `message.aborted` + @@ -2046,6 +2146,7 @@ const req = http.request({ ``` ### `message.connection` + @@ -2126,6 +2230,7 @@ Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. ### `message.method` + @@ -2137,15 +2242,16 @@ added: v0.1.1 The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. ### `message.rawHeaders` + -* {string[]} +* {string\[]} The raw request/response headers list exactly as they were received. -The keys and values are in the same list. It is *not* a +The keys and values are in the same list. It is _not_ a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. @@ -2166,16 +2272,18 @@ console.log(request.rawHeaders); ``` ### `message.rawTrailers` + -* {string[]} +* {string\[]} The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. ### `message.setTimeout(msecs[, callback])` + @@ -2187,6 +2295,7 @@ added: v0.5.9 Calls `message.socket.setTimeout(msecs, callback)`. ### `message.socket` + @@ -2203,6 +2312,7 @@ a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `message.statusCode` + @@ -2214,6 +2324,7 @@ added: v0.1.1 The 3-digit HTTP response status code. E.G. `404`. ### `message.statusMessage` + @@ -2226,6 +2337,7 @@ The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. ### `message.trailers` + @@ -2235,6 +2347,7 @@ added: v0.3.0 The request/response trailers object. Only populated at the `'end'` event. ### `message.url` + @@ -2280,6 +2393,7 @@ URL { ``` ## Class: `http.OutgoingMessage` + @@ -2291,6 +2405,7 @@ and [`http.ServerResponse`][]. It is an abstract of outgoing message from the perspective of the participants of HTTP transaction. ### Event: `drain` + @@ -2298,6 +2413,7 @@ added: v0.3.6 Emitted when the buffer of the message is free again. ### Event: `finish` + @@ -2305,6 +2421,7 @@ added: v0.1.17 Emitted when the transmission is finished successfully. ### Event: `prefinish` + @@ -2314,6 +2431,7 @@ When the event is emitted, all data has been processed but not necessarily completely flushed. ### `outgoingMessage.addTrailers(headers)` + @@ -2340,6 +2458,7 @@ Attempting to set a header field name or value that contains invalid characters will result in a `TypeError` being thrown. ### `outgoingMessage.connection` + @@ -2356,6 +2477,7 @@ added: v14.0.0 See [`writable.cork()`][]. ### `outgoingMessage.destroy([error])` + @@ -2367,6 +2489,7 @@ Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well. ### `outgoingMessage.end(chunk[, encoding][, callback])` + @@ -2407,6 +2531,7 @@ data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the request. ### `outgoingMessage.getHeader(name)` + @@ -2418,16 +2543,18 @@ Gets the value of HTTP header with the given name. If such a name doesn't exist in message, it will be `undefined`. ### `outgoingMessage.getHeaderNames()` + -* Returns {string[]} +* Returns {string\[]} Returns an array of names of headers of the outgoing outgoingMessage. All names are lowercase. ### `outgoingMessage.getHeaders()` + @@ -2454,6 +2581,7 @@ const headers = outgoingMessage.getHeaders(); ``` ### `outgoingMessage.hasHeader(name)` + @@ -2469,6 +2597,7 @@ const hasContentType = outgoingMessage.hasHeader('content-type'); ``` ### `outgoingMessage.headersSent` + @@ -2478,6 +2607,7 @@ added: v0.9.3 Read-only. `true` if the headers were sent, otherwise `false`. ### `outgoingMessage.pipe()` + @@ -2492,6 +2622,7 @@ it inherits from `Stream`. The User should not call this function directly. ### `outgoingMessage.removeHeader()` + @@ -2503,6 +2634,7 @@ outgoingMessage.removeHeader('Content-Encoding'); ``` ### `outgoingMessage.setHeader(name, value)` + @@ -2514,6 +2646,7 @@ added: v0.4.0 Sets a single header value for the header object. ### `outgoingMessage.setTimeout(msesc[, callback])` + @@ -2527,6 +2660,7 @@ Once a socket is associated with the message and is connected, [`socket.setTimeout()`][] will be called with `msecs` as the first parameter. ### `outgoingMessage.socket` + @@ -2539,6 +2673,7 @@ this property. After calling `outgoingMessage.end()`, this property will be nulled. ### `outgoingMessage.uncork()` + @@ -2546,6 +2681,7 @@ added: v14.0.0 See [`writable.uncork()`][] ### `outgoingMessage.writableCorked` + @@ -2556,6 +2692,7 @@ This `outgoingMessage.writableCorked` will return the time how many `outgoingMessage.cork()` have been called. ### `outgoingMessage.writableEnded` + @@ -2567,6 +2704,7 @@ this property does not reflect whether the data has been flush. For that purpose, use `message.writableFinished` instead. ### `outgoingMessage.writableFinished` + @@ -2576,6 +2714,7 @@ added: v13.0.0 Readonly. `true` if all data has been flushed to the underlying system. ### `outgoingMessage.writableHighWaterMark` + @@ -2590,6 +2729,7 @@ underlying socket if socket exists. Else, it would be the default buffered by the socket. ### `outgoingMessage.writableLength` + @@ -2600,6 +2740,7 @@ Readonly, This `outgoingMessage.writableLength` contains the number of bytes (or objects) in the buffer ready to send. ### `outgoingMessage.writableObjectMode` + @@ -2609,6 +2750,7 @@ added: v13.0.0 Readonly, always returns `false`. ### `outgoingMessage.write(chunk[, encoding][, callback])` + -* {string[]} +* {string\[]} A list of the HTTP methods that are supported by the parser. ## `http.STATUS_CODES` + @@ -2672,6 +2816,7 @@ short description of each. For example, `http.STATUS_CODES[404] === 'Not Found'`. ## `http.createServer([options][, requestListener])` + @@ -2837,6 +2986,7 @@ Global instance of `Agent` which is used as the default for all HTTP client requests. ## `http.maxHeaderSize` + @@ -3154,6 +3307,7 @@ or response. The HTTP module will automatically validate such headers. Examples: Example: + ```js const { validateHeaderName } = require('http'); @@ -3167,6 +3321,7 @@ try { ``` ## `http.validateHeaderValue(name, value)` + @@ -3178,6 +3333,7 @@ Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. Passing illegal value as `value` will result in a [`TypeError`][] being thrown. + * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. diff --git a/doc/api/http2.md b/doc/api/http2.md index bc03c14ef50ddd..51efb6c9dc886c 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -1,4 +1,5 @@ # HTTP/2 + + > Stability: 2 - Stable @@ -29,7 +31,7 @@ const http2 = require('http2'); ## Core API The Core API provides a low-level interface designed specifically around -support for HTTP/2 protocol features. It is specifically *not* designed for +support for HTTP/2 protocol features. It is specifically _not_ designed for compatibility with the existing [HTTP/1][] module API. However, the [Compatibility API][] is. @@ -105,6 +107,7 @@ req.end(); ``` ### Class: `Http2Session` + @@ -112,7 +115,7 @@ added: v8.4.0 * Extends: {EventEmitter} Instances of the `http2.Http2Session` class represent an active communications -session between an HTTP/2 client and server. Instances of this class are *not* +session between an HTTP/2 client and server. Instances of this class are _not_ intended to be constructed directly by user code. Each `Http2Session` instance will exhibit slightly different behaviors @@ -144,6 +147,7 @@ Once a `Socket` has been bound to an `Http2Session`, user code should rely solely on the API of the `Http2Session`. #### Event: `'close'` + @@ -152,6 +156,7 @@ The `'close'` event is emitted once the `Http2Session` has been destroyed. Its listener does not expect any arguments. #### Event: `'connect'` + @@ -165,6 +170,7 @@ connected to the remote peer and communication may begin. User code will typically not listen for this event directly. #### Event: `'error'` + @@ -175,6 +181,7 @@ The `'error'` event is emitted when an error occurs during the processing of an `Http2Session`. #### Event: `'frameError'` + @@ -195,6 +202,7 @@ event is not associated with a stream, the `Http2Session` will be shut down immediately following the `'frameError'` event. #### Event: `'goaway'` + @@ -211,6 +219,7 @@ The `Http2Session` instance will be shut down automatically when the `'goaway'` event is emitted. #### Event: `'localSettings'` + @@ -232,6 +241,7 @@ session.on('localSettings', (settings) => { ``` #### Event: `'ping'` + @@ -242,6 +252,7 @@ The `'ping'` event is emitted whenever a `PING` frame is received from the connected peer. #### Event: `'remoteSettings'` + @@ -258,6 +269,7 @@ session.on('remoteSettings', (settings) => { ``` #### Event: `'stream'` + @@ -313,6 +325,7 @@ a network error will destroy each individual stream and must be handled on the stream level, as shown above. #### Event: `'timeout'` + @@ -328,6 +341,7 @@ session.on('timeout', () => { /* .. */ }); ``` #### `http2session.alpnProtocol` + @@ -340,6 +354,7 @@ will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. #### `http2session.close([callback])` + @@ -348,13 +363,14 @@ added: v9.4.0 Gracefully closes the `Http2Session`, allowing any existing streams to complete on their own and preventing new `Http2Stream` instances from being -created. Once closed, `http2session.destroy()` *might* be called if there +created. Once closed, `http2session.destroy()` _might_ be called if there are no open `Http2Stream` instances. If specified, the `callback` function is registered as a handler for the `'close'` event. #### `http2session.closed` + @@ -365,6 +381,7 @@ Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. #### `http2session.connecting` + @@ -376,6 +393,7 @@ to `false` before emitting `connect` event and/or calling the `http2.connect` callback. #### `http2session.destroy([error][, code])` + @@ -397,6 +415,7 @@ If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. #### `http2session.destroyed` + @@ -407,6 +426,7 @@ Will be `true` if this `Http2Session` instance has been destroyed and must no longer be used, otherwise `false`. #### `http2session.encrypted` + @@ -419,6 +439,7 @@ and `false` if the `Http2Session` is connected to any other kind of socket or stream. #### `http2session.goaway([code[, lastStreamID[, opaqueData]]])` + @@ -428,10 +449,11 @@ added: v9.4.0 * `opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. -Transmits a `GOAWAY` frame to the connected peer *without* shutting down the +Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the `Http2Session`. #### `http2session.localSettings` + @@ -439,14 +461,15 @@ added: v8.4.0 * {HTTP/2 Settings Object} A prototype-less object describing the current local settings of this -`Http2Session`. The local settings are local to *this* `Http2Session` instance. +`Http2Session`. The local settings are local to _this_ `Http2Session` instance. #### `http2session.originSet` + -* {string[]|undefined} +* {string\[]|undefined} If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property will return an `Array` of origins for which the `Http2Session` may be @@ -455,6 +478,7 @@ considered authoritative. The `originSet` property is only available when using a secure TLS connection. #### `http2session.pendingSettingsAck` + @@ -467,6 +491,7 @@ a sent `SETTINGS` frame. Will be `true` after calling the frames have been acknowledged. #### `http2session.ping([payload, ]callback)` + @@ -505,6 +530,7 @@ If the `payload` argument is not specified, the default payload will be the 64-bit timestamp (little endian) marking the start of the `PING` duration. #### `http2session.ref()` + @@ -513,6 +539,7 @@ Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session` instance's underlying [`net.Socket`][]. #### `http2session.remoteSettings` + @@ -520,9 +547,10 @@ added: v8.4.0 * {HTTP/2 Settings Object} A prototype-less object describing the current remote settings of this -`Http2Session`. The remote settings are set by the *connected* HTTP/2 peer. +`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. #### `http2session.setLocalWindowSize(windowSize)` + @@ -546,6 +574,7 @@ server.on('connect', (session) => { ``` #### `http2session.setTimeout(msecs, callback)` + @@ -558,6 +587,7 @@ the `Http2Session` after `msecs` milliseconds. The given `callback` is registered as a listener on the `'timeout'` event. #### `http2session.socket` + @@ -576,6 +606,7 @@ an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See All other interactions will be routed directly to the socket. #### `http2session.state` + @@ -606,6 +637,7 @@ Provides miscellaneous information about the current state of the An object describing the current status of this `Http2Session`. #### `http2session.settings([settings][, callback])` + @@ -629,6 +661,7 @@ is received and the `'localSettings'` event is emitted. It is possible to send multiple `SETTINGS` frames while acknowledgment is still pending. #### `http2session.type` + @@ -641,6 +674,7 @@ server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a client. #### `http2session.unref()` + @@ -649,6 +683,7 @@ Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session` instance's underlying [`net.Socket`][]. ### Class: `ServerHttp2Session` + @@ -656,6 +691,7 @@ added: v8.4.0 * Extends: {Http2Session} #### `serverhttp2session.altsvc(alt, originOrStream)` + @@ -687,7 +723,7 @@ server.on('stream', (stream) => { Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate service is associated with the origin of the given `Http2Stream`. -The `alt` and origin string *must* contain only ASCII bytes and are +The `alt` and origin string _must_ contain only ASCII bytes and are strictly interpreted as a sequence of ASCII bytes. The special value `'clear'` may be passed to clear any previously set alternative service for a given domain. @@ -700,7 +736,7 @@ cannot be parsed as a URL or if a valid origin cannot be derived. A `URL` object, or any object with an `origin` property, may be passed as `originOrStream`, in which case the value of the `origin` property will be -used. The value of the `origin` property *must* be a properly serialized +used. The value of the `origin` property _must_ be a properly serialized ASCII origin. #### Specifying alternative services @@ -711,7 +747,7 @@ associated with a specific host and port. For example, the value `'h2="example.org:81"'` indicates that the HTTP/2 protocol is available on the host `'example.org'` on TCP/IP port 81. The -host and port *must* be contained within the quote (`"`) characters. +host and port _must_ be contained within the quote (`"`) characters. Multiple alternatives may be specified, for instance: `'h2="example.org:81", h2=":82"'`. @@ -723,6 +759,7 @@ The syntax of these values is not validated by the Node.js implementation and are passed through as provided by the user or received from the peer. #### `serverhttp2session.origin(...origins)` + @@ -755,7 +792,7 @@ cannot be parsed as a URL or if a valid origin cannot be derived. A `URL` object, or any object with an `origin` property, may be passed as an `origin`, in which case the value of the `origin` property will be -used. The value of the `origin` property *must* be a properly serialized +used. The value of the `origin` property _must_ be a properly serialized ASCII origin. Alternatively, the `origins` option may be used when creating a new HTTP/2 @@ -773,6 +810,7 @@ server.on('stream', (stream) => { ``` ### Class: `ClientHttp2Session` + @@ -780,6 +818,7 @@ added: v8.4.0 * Extends: {Http2Session} #### Event: `'altsvc'` + @@ -805,11 +844,12 @@ client.on('altsvc', (alt, origin, streamId) => { ``` #### Event: `'origin'` + -* `origins` {string[]} +* `origins` {string\[]} The `'origin'` event is emitted whenever an `ORIGIN` frame is received by the client. The event is emitted with an array of `origin` strings. The @@ -829,13 +869,15 @@ client.on('origin', (origins) => { The `'origin'` event is only emitted when using a secure TLS connection. #### `clienthttp2session.request(headers[, options])` + * `headers` {HTTP/2 Headers Object} + * `options` {Object} - * `endStream` {boolean} `true` if the `Http2Stream` *writable* side should + * `endStream` {boolean} `true` if the `Http2Stream` _writable_ side should be closed initially, such as when sending a `GET` request that should not expect a payload body. * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, @@ -898,6 +940,7 @@ they respectively default to: * `:path` = `/` ### Class: `Http2Stream` + @@ -983,6 +1026,7 @@ property will be `true` and the `http2stream.rstCode` property will specify the destroyed. #### Event: `'aborted'` + @@ -995,6 +1039,7 @@ The `'aborted'` event will only be emitted if the `Http2Stream` writable side has not been ended. #### Event: `'close'` + @@ -1007,6 +1052,7 @@ the `http2stream.rstCode` property. If the code is any value other than `NGHTTP2_NO_ERROR` (`0`), an `'error'` event will have also been emitted. #### Event: `'error'` + @@ -1017,6 +1063,7 @@ The `'error'` event is emitted when an error occurs during the processing of an `Http2Stream`. #### Event: `'frameError'` + @@ -1033,6 +1080,7 @@ error code. The `Http2Stream` instance will be destroyed immediately after the `'frameError'` event is emitted. #### Event: `'ready'` + @@ -1042,6 +1090,7 @@ been assigned an `id`, and can be used. The listener does not expect any arguments. #### Event: `'timeout'` + @@ -1052,6 +1101,7 @@ The `'timeout'` event is emitted after no activity is received for this Its listener does not expect any arguments. #### Event: `'trailers'` + @@ -1074,6 +1124,7 @@ stream.on('trailers', (headers, flags) => { ``` #### Event: `'wantTrailers'` + @@ -1084,6 +1135,7 @@ trailing headers. When initiating a request or response, the `waitForTrailers` option must be set for this event to be emitted. #### `http2stream.aborted` + @@ -1094,6 +1146,7 @@ Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, the `'aborted'` event will have been emitted. #### `http2stream.bufferSize` + @@ -1119,6 +1173,7 @@ Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the connected HTTP/2 peer. #### `http2stream.closed` + @@ -1128,6 +1183,7 @@ added: v9.4.0 Set to `true` if the `Http2Stream` instance has been closed. #### `http2stream.destroyed` + @@ -1138,6 +1194,7 @@ Set to `true` if the `Http2Stream` instance has been destroyed and is no longer usable. #### `http2stream.endAfterHeaders` + @@ -1149,6 +1206,7 @@ HEADERS frame received, indicating that no additional data should be received and the readable side of the `Http2Stream` will be closed. #### `http2stream.id` + @@ -1159,6 +1217,7 @@ The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. #### `http2stream.pending` + @@ -1169,6 +1228,7 @@ Set to `true` if the `Http2Stream` instance has not yet been assigned a numeric stream identifier. #### `http2stream.priority(options)` + @@ -1189,6 +1249,7 @@ added: v8.4.0 Updates the priority for this `Http2Stream` instance. #### `http2stream.rstCode` + @@ -1201,6 +1262,7 @@ calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. #### `http2stream.sentHeaders` + @@ -1210,16 +1272,18 @@ added: v9.5.0 An object containing the outbound headers sent for this `Http2Stream`. #### `http2stream.sentInfoHeaders` + -* {HTTP/2 Headers Object[]} +* {HTTP/2 Headers Object\[]} An array of objects containing the outbound informational (additional) headers sent for this `Http2Stream`. #### `http2stream.sentTrailers` + @@ -1229,6 +1293,7 @@ added: v9.5.0 An object containing the outbound trailers sent for this `HttpStream`. #### `http2stream.session` + @@ -1239,6 +1304,7 @@ A reference to the `Http2Session` instance that owns this `Http2Stream`. The value will be `undefined` after the `Http2Stream` instance is destroyed. #### `http2stream.setTimeout(msecs, callback)` + @@ -1257,9 +1323,11 @@ req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); ``` #### `http2stream.state` + + Provides miscellaneous information about the current state of the `Http2Stream`. @@ -1279,6 +1347,7 @@ Provides miscellaneous information about the current state of the A current state of this `Http2Stream`. #### `http2stream.sendTrailers(headers)` + @@ -1308,6 +1377,7 @@ The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header fields (e.g. `':method'`, `':path'`, etc). ### Class: `ClientHttp2Stream` + @@ -1320,6 +1390,7 @@ provide events such as `'response'` and `'push'` that are only relevant on the client. #### Event: `'continue'` + @@ -1329,6 +1400,7 @@ the request contained `Expect: 100-continue`. This is an instruction that the client should send the request body. #### Event: `'headers'` + @@ -1345,6 +1417,7 @@ stream.on('headers', (headers, flags) => { ``` #### Event: `'push'` + @@ -1360,6 +1433,7 @@ stream.on('push', (headers, flags) => { ``` #### Event: `'response'` + @@ -1379,6 +1453,7 @@ req.on('response', (headers, flags) => { ``` ### Class: `ServerHttp2Stream` + @@ -1391,6 +1466,7 @@ provide additional methods such as `http2stream.pushStream()` and `http2stream.respond()` that are only relevant on the server. #### `http2stream.additionalHeaders(headers)` + @@ -1400,6 +1476,7 @@ added: v8.4.0 Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. #### `http2stream.headersSent` + @@ -1409,6 +1486,7 @@ added: v8.4.0 True if headers were sent, false otherwise (read-only). #### `http2stream.pushAllowed` + @@ -1421,6 +1499,7 @@ accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. #### `http2stream.pushStream(headers[, options], callback)` + @@ -1466,6 +1545,7 @@ Calling `http2stream.pushStream()` from within a pushed stream is not permitted and will throw an error. #### `http2stream.respond([headers[, options]])` + @@ -1755,6 +1838,7 @@ function. The `Http2Server` class is not exported directly by the `http2` module. #### Event: `'checkContinue'` + @@ -1777,6 +1861,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. #### Event: `'connection'` + @@ -1791,6 +1876,7 @@ This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any [`Duplex`][] stream can be passed. #### Event: `'request'` + @@ -1802,6 +1888,7 @@ Emitted each time there is a request. There may be multiple requests per session. See the [Compatibility API][]. #### Event: `'session'` + @@ -1810,6 +1897,7 @@ The `'session'` event is emitted when a new `Http2Session` is created by the `Http2Server`. #### Event: `'sessionError'` + @@ -1818,6 +1906,7 @@ The `'sessionError'` event is emitted when an `'error'` event is emitted by an `Http2Session` object associated with the `Http2Server`. #### Event: `'stream'` + @@ -1857,6 +1946,7 @@ server.on('stream', (stream, headers, flags) => { ``` #### Event: `'timeout'` + @@ -1886,6 +1977,7 @@ closed, although the server has already stopped allowing new sessions. See [`net.Server.close()`][] for more details. #### `server.setTimeout([msecs][, callback])` + @@ -1940,6 +2034,7 @@ Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. ### Class: `Http2SecureServer` + @@ -1951,6 +2046,7 @@ Instances of `Http2SecureServer` are created using the exported directly by the `http2` module. #### Event: `'checkContinue'` + @@ -1973,6 +2069,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. #### Event: `'connection'` + @@ -1987,6 +2084,7 @@ This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any [`Duplex`][] stream can be passed. #### Event: `'request'` + @@ -1998,6 +2096,7 @@ Emitted each time there is a request. There may be multiple requests per session. See the [Compatibility API][]. #### Event: `'session'` + @@ -2006,6 +2105,7 @@ The `'session'` event is emitted when a new `Http2Session` is created by the `Http2SecureServer`. #### Event: `'sessionError'` + @@ -2014,6 +2114,7 @@ The `'sessionError'` event is emitted when an `'error'` event is emitted by an `Http2Session` object associated with the `Http2SecureServer`. #### Event: `'stream'` + @@ -2055,6 +2156,7 @@ server.on('stream', (stream, headers, flags) => { ``` #### Event: `'timeout'` + @@ -2064,6 +2166,7 @@ a given number of milliseconds set using `http2secureServer.setTimeout()`. **Default:** 2 minutes. #### Event: `'unknownProtocol'` + @@ -2076,6 +2179,7 @@ the connection is terminated. A timeout may be specified using the See the [Compatibility API][]. #### `server.close([callback])` + @@ -2092,6 +2196,7 @@ closed, although the server has already stopped allowing new sessions. See [`tls.Server.close()`][] for more details. #### `server.setTimeout([msecs][, callback])` + @@ -2110,6 +2215,7 @@ In case if `callback` is not a function, a new `ERR_INVALID_CALLBACK` error will be thrown. #### `server.timeout` + @@ -2142,6 +2249,7 @@ Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. ### `http2.createServer(options[, onRequestHandler])` + @@ -2555,7 +2666,7 @@ added: v8.4.0 #### Error codes for `RST_STREAM` and `GOAWAY` | Value | Name | Constant | -|--------|---------------------|-----------------------------------------------| +| ------ | ------------------- | --------------------------------------------- | | `0x00` | No Error | `http2.constants.NGHTTP2_NO_ERROR` | | `0x01` | Protocol Error | `http2.constants.NGHTTP2_PROTOCOL_ERROR` | | `0x02` | Internal Error | `http2.constants.NGHTTP2_INTERNAL_ERROR` | @@ -2575,6 +2686,7 @@ The `'timeout'` event is emitted when there is no activity on the Server for a given number of milliseconds set using `http2server.setTimeout()`. ### `http2.getDefaultSettings()` + @@ -2586,6 +2698,7 @@ instance. This method returns a new object instance every time it is called so instances returned may be safely modified for use. ### `http2.getPackedSettings([settings])` + @@ -2607,6 +2720,7 @@ console.log(packed.toString('base64')); ``` ### `http2.getUnpackedSettings(buf)` + @@ -2618,6 +2732,7 @@ Returns a [HTTP/2 Settings Object][] containing the deserialized settings from the given `Buffer` as generated by `http2.getPackedSettings()`. ### `http2.sensitiveHeaders` + @@ -2703,6 +2818,7 @@ This property is also set for received headers. It will contain the names of all headers marked as sensitive, including ones marked that way automatically. ### Settings object + + The `http2.getDefaultSettings()`, `http2.getPackedSettings()`, `http2.createServer()`, `http2.createSecureServer()`, `http2session.settings()`, `http2session.localSettings`, and @@ -2726,7 +2843,7 @@ properties. is 232-1. **Default:** `4096`. * `enablePush` {boolean} Specifies `true` if HTTP/2 Push Streams are to be permitted on the `Http2Session` instances. **Default:** `true`. -* `initialWindowSize` {number} Specifies the *sender's* initial window size in +* `initialWindowSize` {number} Specifies the _sender's_ initial window size in bytes for stream-level flow control. The minimum allowed value is 0. The maximum allowed value is 232-1. **Default:** `65535`. * `maxFrameSize` {number} Specifies the size in bytes of the largest frame @@ -2777,20 +2894,20 @@ on where and when the error occurs. The HTTP/2 implementation applies stricter handling of invalid characters in HTTP header names and values than the HTTP/1 implementation. -Header field names are *case-insensitive* and are transmitted over the wire +Header field names are _case-insensitive_ and are transmitted over the wire strictly as lower-case strings. The API provided by Node.js allows header names to be set as mixed-case strings (e.g. `Content-Type`) but will convert those to lower-case (e.g. `content-type`) upon transmission. -Header field-names *must only* contain one or more of the following ASCII +Header field-names _must only_ contain one or more of the following ASCII characters: `a`-`z`, `A`-`Z`, `0`-`9`, `!`, `#`, `$`, `%`, `&`, `'`, `*`, `+`, `-`, `.`, `^`, `_`, `` ` `` (backtick), `|`, and `~`. Using invalid characters within an HTTP header field name will cause the stream to be closed with a protocol error being reported. -Header field values are handled with more leniency but *should* not contain -new-line or carriage return characters and *should* be limited to US-ASCII +Header field values are handled with more leniency but _should_ not contain +new-line or carriage return characters and _should_ be limited to US-ASCII characters, per the requirements of the HTTP specification. ### Push streams on the client @@ -2989,6 +3106,7 @@ The `'request'` event works identically on both [HTTPS][] and HTTP/2. ### Class: `http2.Http2ServerRequest` + @@ -3001,6 +3119,7 @@ A `Http2ServerRequest` object is created by [`http2.Server`][] or data. #### Event: `'aborted'` + @@ -3012,6 +3131,7 @@ The `'aborted'` event will only be emitted if the `Http2ServerRequest` writable side has not been ended. #### Event: `'close'` + @@ -3020,6 +3140,7 @@ Indicates that the underlying [`Http2Stream`][] was closed. Just like `'end'`, this event occurs only once per response. #### `request.aborted` + @@ -3030,6 +3151,7 @@ The `request.aborted` property will be `true` if the request has been aborted. #### `request.authority` + @@ -3042,6 +3164,7 @@ to set either `:authority` or `host`, this value is derived from `req.headers['host']`. #### `request.complete` + @@ -3052,6 +3175,7 @@ The `request.complete` property will be `true` if the request has been completed, aborted, or destroyed. #### `request.connection` + @@ -3077,6 +3202,7 @@ is emitted and `error` is passed as an argument to any listeners on the event. It does nothing if the stream was already destroyed. #### `request.headers` + @@ -3110,6 +3236,7 @@ assert(request.url); // Fails because the :path header has been removed ``` #### `request.httpVersion` + @@ -3124,6 +3251,7 @@ Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. #### `request.method` + @@ -3133,15 +3261,16 @@ added: v8.4.0 The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. #### `request.rawHeaders` + -* {string[]} +* {string\[]} The raw request/response headers list exactly as they were received. -The keys and values are in the same list. It is *not* a +The keys and values are in the same list. It is _not_ a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. @@ -3162,16 +3291,18 @@ console.log(request.rawHeaders); ``` #### `request.rawTrailers` + -* {string[]} +* {string\[]} The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. #### `request.scheme` + @@ -3182,6 +3313,7 @@ The request scheme pseudo header field indicating the scheme portion of the target URL. #### `request.setTimeout(msecs, callback)` + @@ -3200,6 +3332,7 @@ handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. #### `request.socket` + @@ -3226,6 +3359,7 @@ use [`request.socket.getPeerCertificate()`][] to obtain the client's authentication details. #### `request.stream` + @@ -3235,6 +3369,7 @@ added: v8.4.0 The [`Http2Stream`][] object backing the request. #### `request.trailers` + @@ -3244,6 +3379,7 @@ added: v8.4.0 The request/response trailers object. Only populated at the `'end'` event. #### `request.url` + @@ -3261,6 +3397,7 @@ Accept: text/plain Then `request.url` will be: + ```js '/status?name=ryan' ``` @@ -3287,6 +3424,7 @@ URL { ``` ### Class: `http2.Http2ServerResponse` + @@ -3297,6 +3435,7 @@ This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. #### Event: `'close'` + @@ -3305,6 +3444,7 @@ Indicates that the underlying [`Http2Stream`][] was terminated before [`response.end()`][] was called or able to flush. #### Event: `'finish'` + @@ -3317,6 +3457,7 @@ does not imply that the client has received anything yet. After this event, no more events will be emitted on the response object. #### `response.addTrailers(headers)` + @@ -3330,6 +3471,7 @@ Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. #### `response.connection` + @@ -3361,6 +3504,7 @@ parameter if successful. When `Http2ServerRequest` is closed, the callback is called with an error `ERR_HTTP2_INVALID_STREAM`. #### `response.end([data[, encoding]][, callback])` + @@ -3415,11 +3561,12 @@ const contentType = response.getHeader('content-type'); ``` #### `response.getHeaderNames()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array containing the unique names of the current outgoing headers. All header names are lowercase. @@ -3433,6 +3580,7 @@ const headerNames = response.getHeaderNames(); ``` #### `response.getHeaders()` + @@ -3448,7 +3596,7 @@ are lowercase. The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others -are not defined and *will not work*. +are not defined and _will not work_. ```js response.setHeader('Foo', 'bar'); @@ -3459,6 +3607,7 @@ const headers = response.getHeaders(); ``` #### `response.hasHeader(name)` + @@ -3474,6 +3623,7 @@ const hasContentType = response.hasHeader('content-type'); ``` #### `response.headersSent` + @@ -3483,6 +3633,7 @@ added: v8.4.0 True if headers were sent, false otherwise (read-only). #### `response.removeHeader(name)` + @@ -3496,6 +3647,7 @@ response.removeHeader('Content-Encoding'); ``` ### `response.req` + @@ -3505,6 +3657,7 @@ added: v15.7.0 A reference to the original HTTP2 `request` object. #### `response.sendDate` + @@ -3518,12 +3671,13 @@ This should only be disabled for testing; HTTP requires the Date header in responses. #### `response.setHeader(name, value)` + * `name` {string} -* `value` {string|string[]} +* `value` {string|string\[]} Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings @@ -3557,6 +3711,7 @@ const server = http2.createServer((req, res) => { ``` #### `response.setTimeout(msecs[, callback])` + @@ -3575,6 +3730,7 @@ handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. #### `response.socket` + @@ -3608,6 +3764,7 @@ const server = http2.createServer((req, res) => { ``` #### `response.statusCode` + @@ -3626,6 +3783,7 @@ After response header was sent to the client, this property indicates the status code which was sent out. #### `response.statusMessage` + @@ -3636,6 +3794,7 @@ Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns an empty string. #### `response.stream` + @@ -3645,6 +3804,7 @@ added: v8.4.0 The [`Http2Stream`][] object backing the response. #### `response.writableEnded` + @@ -3656,6 +3816,7 @@ does not indicate whether the data has been flushed, for this use [`writable.writableFinished`][] instead. #### `response.write(chunk[, encoding][, callback])` + @@ -3694,6 +3855,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. #### `response.writeContinue()` + @@ -3703,6 +3865,7 @@ should be sent. See the [`'checkContinue'`][] event on `Http2Server` and `Http2SecureServer`. #### `response.writeHead(statusCode[, statusMessage][, headers])` + @@ -84,6 +88,7 @@ added: v0.3.4 See [`http.Server`][] for more information. ### `server.close([callback])` + @@ -94,6 +99,7 @@ added: v0.1.90 See [`server.close()`][`http.close()`] from the HTTP module for details. ### `server.headersTimeout` + @@ -114,6 +120,7 @@ This method is identical to [`server.listen()`][] from [`net.Server`][]. See [`http.Server#maxHeadersCount`][]. ### `server.requestTimeout` + @@ -123,6 +130,7 @@ added: v14.11.0 See [`http.Server#requestTimeout`][]. ### `server.setTimeout([msecs][, callback])` + @@ -134,6 +142,7 @@ added: v0.11.2 See [`http.Server#setTimeout()`][]. ### `server.timeout` + @@ -156,6 +166,7 @@ added: v8.0.0 See [`http.Server#keepAliveTimeout`][]. ## `https.createServer([options][, requestListener])` + @@ -199,7 +210,9 @@ https.createServer(options, (req, res) => { ``` ## `https.get(options[, callback])` + ## `https.get(url[, options][, callback])` + @@ -247,7 +261,9 @@ added: v0.5.9 Global instance of [`https.Agent`][] for all HTTPS client requests. ## `https.request(options[, callback])` + ## `https.request(url[, options][, callback])` + @@ -87,6 +88,7 @@ The `inspector.Session` is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. ### `new inspector.Session()` + @@ -96,6 +98,7 @@ needs to be connected through [`session.connect()`][] before the messages can be dispatched to the inspector backend. ### Event: `'inspectorNotification'` + @@ -113,6 +116,7 @@ session.on('inspectorNotification', (message) => console.log(message.method)); It is also possible to subscribe only to notifications with specific method: ### Event: ``; + @@ -134,6 +138,7 @@ session.on('Debugger.paused', ({ params }) => { ``` ### `session.connect()` + @@ -141,6 +146,7 @@ added: v8.0.0 Connects a session to the inspector back-end. ### `session.connectToMainThread()` + @@ -149,6 +155,7 @@ Connects a session to the main thread inspector back-end. An exception will be thrown if this API was not called on a Worker thread. ### `session.disconnect()` + @@ -159,6 +166,7 @@ messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. ### `session.post(method[, params][, callback])` + diff --git a/doc/api/intl.md b/doc/api/intl.md index 716047a7c39c9a..cf4a852035d4e1 100644 --- a/doc/api/intl.md +++ b/doc/api/intl.md @@ -45,7 +45,7 @@ An overview of available Node.js and JavaScript features for each `configure` option: | Feature | `none` | `system-icu` | `small-icu` | `full-icu` | -|-----------------------------------------|-----------------------------------|------------------------------|------------------------|------------| +| --------------------------------------- | --------------------------------- | ---------------------------- | ---------------------- | ---------- | | [`String.prototype.normalize()`][] | none (function is no-op) | full | full | full | | `String.prototype.to*Case()` | full | full | full | full | | [`Intl`][] | none (object does not exist) | partial/full (depends on OS) | partial (English-only) | full | @@ -80,7 +80,7 @@ OS. Functionalities that only require the ICU library itself, such as [`String.prototype.normalize()`][] and the [WHATWG URL parser][], are fully supported under `system-icu`. Features that require ICU locale data in -addition, such as [`Intl.DateTimeFormat`][] *may* be fully or partially +addition, such as [`Intl.DateTimeFormat`][] _may_ be fully or partially supported, depending on the completeness of the ICU data installed on the system. diff --git a/doc/api/module.md b/doc/api/module.md index 519240841a644f..749bd350ba9c42 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -15,6 +15,7 @@ Provides general utility methods when interacting with instances of via `import 'module'` or `require('module')`. ### `module.builtinModules` + -* {string[]} +* {string\[]} A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third party or not. @@ -43,6 +44,7 @@ const builtin = require('module').builtinModules; ``` ### `module.createRequire(filename)` + @@ -61,6 +63,7 @@ const siblingModule = require('./sibling-module'); ``` ### `module.syncBuiltinESMExports()` + @@ -99,6 +102,7 @@ import('fs').then((esmFS) => { ``` ## Source map v3 support + + + ### `module.findSourceMap(path)` @@ -547,6 +548,7 @@ console.log(path.dirname(__filename)); ``` ### `__filename` + @@ -585,6 +587,7 @@ References to `__filename` within `b.js` will return `a.js` will return `/Users/mjr/app/a.js`. ### `exports` + @@ -598,6 +601,7 @@ See the section about the [exports shortcut][] for details on when to use `exports` and when to use `module.exports`. ### `module` + @@ -611,6 +615,7 @@ A reference to the current module, see the section about the a module exports and makes available through `require()`. ### `require(id)` + @@ -641,6 +646,7 @@ const crypto = require('crypto'); ``` #### `require.cache` + @@ -658,6 +664,7 @@ only `node:`-prefixed require calls are going to receive the native module. Use with care! + ```js const assert = require('assert'); const realFs = require('fs'); @@ -670,6 +677,7 @@ assert.strictEqual(require('node:fs'), realFs); ``` #### `require.extensions` + @@ -717,6 +726,7 @@ node entry.js ``` + ```js Module { id: '.', @@ -733,6 +743,7 @@ Module { ``` #### `require.resolve(request[, options])` + * `request` {string} The module path whose lookup paths are being retrieved. -* Returns: {string[]|null} +* Returns: {string\[]|null} Returns an array containing the paths searched during resolution of `request` or `null` if the `request` string references a core module, for example `http` or `fs`. ## The `module` object + @@ -785,15 +798,17 @@ also accessible via the `exports` module-global. `module` is not actually a global but rather local to each module. ### `module.children` + -* {module[]} +* {module\[]} The module objects required for the first time by this one. ### `module.exports` + @@ -848,6 +863,7 @@ console.log(x.a); ``` #### `exports` shortcut + @@ -868,6 +884,7 @@ When the `module.exports` property is being completely replaced by a new object, it is common to also reassign `exports`: + ```js module.exports = exports = function Constructor() { // ... etc. @@ -895,6 +912,7 @@ function require(/* ... */) { ``` ### `module.filename` + @@ -904,6 +922,7 @@ added: v0.1.16 The fully resolved filename of the module. ### `module.id` + @@ -914,6 +933,7 @@ The identifier for the module. Typically this is the fully resolved filename. ### `module.isPreloading` + @@ -922,6 +942,7 @@ added: v15.4.0 phase. ### `module.loaded` + @@ -932,6 +953,7 @@ Whether or not the module is done loading, or is in the process of loading. ### `module.parent` + @@ -959,15 +982,17 @@ The directory name of the module. This is usually the same as the [`path.dirname()`][] of the [`module.id`][]. ### `module.paths` + -* {string[]} +* {string\[]} The search paths for the module. ### `module.require(id)` + @@ -980,7 +1005,7 @@ The `module.require()` method provides a way to load a module as if In order to do this, it is necessary to get a reference to the `module` object. Since `require()` returns the `module.exports`, and the `module` is typically -*only* available within a specific module's code, it must be explicitly exported +_only_ available within a specific module's code, it must be explicitly exported in order to be used. ## The `Module` object @@ -989,6 +1014,7 @@ This section was moved to [Modules: `module` core module](module.md#the-module-object). + * `module.builtinModules` * `module.createRequire(filename)` * `module.syncBuiltinESMExports()` @@ -999,6 +1025,7 @@ This section was moved to [Modules: `module` core module](module.md#source-map-v3-support). + * `module.findSourceMap(path)` * Class: `module.SourceMap` * `new SourceMap(payload)` diff --git a/doc/api/n-api.md b/doc/api/n-api.md index f4025ffdbf37f7..fac452651e0fa5 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -91,24 +91,24 @@ versions: * the Node.js C++ APIs available via any of - ```cpp - #include - #include - #include - #include - ``` + ```cpp + #include + #include + #include + #include + ``` * the libuv APIs which are also included with Node.js and available via - ```cpp - #include - ``` + ```cpp + #include + ``` * the V8 API available via - ```cpp - #include - ``` + ```cpp + #include + ``` Thus, for an addon to remain ABI-compatible across Node.js major versions, it must use Node-API exclusively by restricting itself to using @@ -126,7 +126,7 @@ Unlike modules written in JavaScript, developing and deploying Node.js native addons using Node-API requires an additional set of tools. Besides the basic tools required to develop for Node.js, the native addon developer requires a toolchain that can compile C and C++ code into a binary. In -addition, depending upon how the native addon is deployed, the *user* of +addition, depending upon how the native addon is deployed, the _user_ of the native addon will also need to have a C/C++ toolchain installed. For Linux developers, the necessary C/C++ toolchain packages are readily @@ -155,7 +155,7 @@ and deploying Node.js native addons. ### Build tools -Both the tools listed here require that *users* of the native +Both the tools listed here require that _users_ of the native addon have a C/C++ toolchain installed in order to successfully install the native addon. @@ -482,7 +482,8 @@ the addon. To this end, Node-API provides a way to allocate data such that its life cycle is tied to the life cycle of the Agent. -### napi_set_instance_data +### `napi_set_instance_data` + + Integral status code indicating the success or failure of a Node-API call. Currently, the following status codes are supported. @@ -580,7 +584,8 @@ typedef enum { If additional information is required upon an API returning a failed status, it can be obtained by calling `napi_get_last_error_info`. -### napi_extended_error_info +### `napi_extended_error_info` + + Escapable handle scopes are a special type of handle scope to return values created within a particular handle scope to a parent scope. -#### napi_ref +#### `napi_ref` + + This is the abstraction to use to reference a `napi_value`. This allows for users to manage the lifetimes of JavaScript values, including defining their minimum lifetimes explicitly. For more details, review the [Object lifetime management][]. -#### napi_type_tag +#### `napi_type_tag` + + Opaque datatype that is passed to a callback function. It can be used for getting additional information about the context in which the callback was invoked. -#### napi_callback +#### `napi_callback` + + Function pointer type for user-provided native functions which are to be exposed to JavaScript via Node-API. Callback functions should satisfy the following signature: @@ -769,11 +788,13 @@ typedef napi_value (*napi_callback)(napi_env, napi_callback_info); Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside a `napi_callback` is not necessary. -#### napi_finalize +#### `napi_finalize` + + Function pointer type for add-on provided functions that allow the user to be notified when externally-owned data is ready to be cleaned up because the object with which it was associated with, has been garbage-collected. The user @@ -790,11 +811,13 @@ typedef void (*napi_finalize)(napi_env env, Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside the function body is not necessary. -#### napi_async_execute_callback +#### `napi_async_execute_callback` + + Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature: @@ -807,11 +830,13 @@ JavaScript or interact with JavaScript objects. Node-API calls should be in the `napi_async_complete_callback` instead. Do not use the `napi_env` parameter as it will likely result in execution of JavaScript. -#### napi_async_complete_callback +#### `napi_async_complete_callback` + + Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature: @@ -824,7 +849,8 @@ typedef void (*napi_async_complete_callback)(napi_env env, Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside the function body is not necessary. -#### napi_threadsafe_function_call_js +#### `napi_threadsafe_function_call_js` + @@ -66,6 +67,7 @@ disabling inbound or outbound access to specific IP addresses, IP ranges, or IP subnets. ### `blockList.addAddress(address[, type])` + @@ -76,6 +78,7 @@ added: v15.0.0 Adds a rule to block the given IP address. ### `blockList.addRange(start, end[, type])` + @@ -89,6 +92,7 @@ Adds a rule to block a range of IP addresses from `start` (inclusive) to `end` (inclusive). ### `blockList.addSubnet(net, prefix[, type])` + @@ -102,6 +106,7 @@ added: v15.0.0 Adds a rule to block a range of IP addresses specified as a subnet mask. ### `blockList.check(address[, type])` + @@ -129,19 +134,23 @@ console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true ``` ### `blockList.rules` + -* Type: {string[]} +* Type: {string\[]} The list of rules added to the blocklist. ## Class: `net.SocketAddress` + + ### `new net.SocketAddress([options])` + @@ -150,11 +159,13 @@ added: v15.14.0 * `address` {string} The network address as either an IPv4 or IPv6 string. **Default**: `'127.0.0.1'` if `family` is `'ipv4'`; `'::'` if `family` is `'ipv6'`. - * `family` {string} One of either `'ipv4'` or 'ipv6'`. **Default**: `'ipv4'`. + * `family` {string} One of either `'ipv4'` or `'ipv6'`. + **Default**: `'ipv4'`. * `flowlabel` {number} An IPv6 flow-label used only if `family` is `'ipv6'`. * `port` {number} An IP port. ### `socketaddress.address` + @@ -162,6 +173,7 @@ added: v15.14.0 * Type {string} ### `socketaddress.family` + @@ -169,6 +181,7 @@ added: v15.14.0 * Type {string} Either `'ipv4'` or `'ipv6'`. ### `socketaddress.flowlabel` + @@ -176,6 +189,7 @@ added: v15.14.0 * Type {number} ### `socketaddress.port` + @@ -183,6 +197,7 @@ added: v15.14.0 * Type {number} ## Class: `net.Server` + @@ -202,6 +217,7 @@ This class is used to create a TCP or [IPC][] server. `net.Server` is an [`EventEmitter`][] with the following events: ### Event: `'close'` + @@ -210,6 +226,7 @@ Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended. ### Event: `'connection'` + @@ -220,6 +237,7 @@ Emitted when a new connection is made. `socket` is an instance of `net.Socket`. ### Event: `'error'` + @@ -232,6 +250,7 @@ event will **not** be emitted directly following this event unless [`server.listen()`][]. ### Event: `'listening'` + @@ -239,6 +258,7 @@ added: v0.1.90 Emitted when the server has been bound after calling [`server.listen()`][]. ### `server.address()` + @@ -271,6 +291,7 @@ server.listen(() => { emitted or after calling `server.close()`. ### `server.close([callback])` + @@ -286,6 +307,7 @@ that event, it will be called with an `Error` as its only argument if the server was not open when it was closed. ### `server.getConnections(callback)` + @@ -305,15 +327,12 @@ an [IPC][] server depending on what it listens to. Possible signatures: - * [`server.listen(handle[, backlog][, callback])`][`server.listen(handle)`] * [`server.listen(options[, callback])`][`server.listen(options)`] * [`server.listen(path[, backlog][, callback])`][`server.listen(path)`] for [IPC][] servers -* - server.listen([port[, host[, backlog]]][, callback]) +* [`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`] for TCP servers - This function is asynchronous. When the server starts listening, the [`'listening'`][] event will be emitted. The last parameter `callback` @@ -349,6 +368,7 @@ server.on('error', (e) => { ``` #### `server.listen(handle[, backlog][, callback])` + @@ -368,6 +388,7 @@ valid file descriptor. Listening on a file descriptor is not supported on Windows. #### `server.listen(options[, callback])` + If `port` is specified, it behaves the same as - -server.listen([port[, host[, backlog]]][, callback]). +[`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`]. Otherwise, if `path` is specified, it behaves the same as [`server.listen(path[, backlog][, callback])`][`server.listen(path)`]. If none of them is specified, an error will be thrown. - If `exclusive` is `false` (default), then cluster workers will use the same underlying handle, allowing connection handling duties to be shared. When @@ -441,6 +459,7 @@ controller.abort(); ``` #### `server.listen(path[, backlog][, callback])` + @@ -454,6 +473,7 @@ added: v0.1.90 Start an [IPC][] server listening for connections on the given `path`. #### `server.listen([port[, host[, backlog]]][, callback])` + @@ -479,6 +499,7 @@ may cause the `net.Server` to also listen on the [unspecified IPv4 address][] (`0.0.0.0`). ### `server.listening` + @@ -486,6 +507,7 @@ added: v5.7.0 * {boolean} Indicates whether or not the server is listening for connections. ### `server.maxConnections` + @@ -499,6 +521,7 @@ It is not recommended to use this option once a socket has been sent to a child with [`child_process.fork()`][]. ### `server.ref()` + @@ -506,10 +529,11 @@ added: v0.9.1 * Returns: {net.Server} Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will -*not* let the program exit if it's the only server left (the default behavior). +_not_ let the program exit if it's the only server left (the default behavior). If the server is `ref`ed calling `ref()` again will have no effect. ### `server.unref()` + @@ -521,6 +545,7 @@ active server in the event system. If the server is already `unref`ed calling `unref()` again will have no effect. ## Class: `net.Socket` + @@ -541,6 +566,7 @@ is received. For example, it is passed to the listeners of a it to interact with the client. ### `new net.Socket([options])` + @@ -580,6 +607,7 @@ Emitted once the socket is fully closed. The argument `hadError` is a boolean which says if the socket was closed due to a transmission error. ### Event: `'connect'` + @@ -588,6 +616,7 @@ Emitted when a socket connection is successfully established. See [`net.createConnection()`][]. ### Event: `'data'` + @@ -601,6 +630,7 @@ The data will be lost if there is no listener when a `Socket` emits a `'data'` event. ### Event: `'drain'` + @@ -610,6 +640,7 @@ Emitted when the write buffer becomes empty. Can be used to throttle uploads. See also: the return values of `socket.write()`. ### Event: `'end'` + @@ -626,6 +657,7 @@ allowing the user to write arbitrary amounts of data. The user must call FIN packet back). ### Event: `'error'` + @@ -636,6 +668,7 @@ Emitted when an error occurs. The `'close'` event will be called directly following this event. ### Event: `'lookup'` + @@ -662,6 +696,7 @@ Emitted when a socket is ready to be used. Triggered immediately after `'connect'`. ### Event: `'timeout'` + @@ -672,6 +707,7 @@ the socket has been idle. The user must manually close the connection. See also: [`socket.setTimeout()`][]. ### `socket.address()` + @@ -683,6 +719,7 @@ socket as reported by the operating system: `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` ### `socket.bufferSize` + @@ -718,6 +756,7 @@ added: v0.5.3 The amount of received bytes. ### `socket.bytesWritten` + @@ -751,6 +790,7 @@ This function should only be used for reconnecting a socket after behavior. #### `socket.connect(options[, connectListener])` + @@ -858,6 +899,7 @@ Alias to called with `{port: port, host: host}` as `options`. ### `socket.connecting` + @@ -873,6 +915,7 @@ that the callback is a listener for the `'connect'` event. ### `socket.destroy([error])` + @@ -893,6 +936,7 @@ See [`writable.destroy()`][] for further details. See [`writable.destroyed`][] for further details. ### `socket.end([data[, encoding]][, callback])` + @@ -908,6 +952,7 @@ server will still send some data. See [`writable.end()`][] for further details. ### `socket.localAddress` + @@ -920,6 +965,7 @@ connects on `'192.168.1.1'`, the value of `socket.localAddress` would be `'192.168.1.1'`. ### `socket.localPort` + @@ -936,6 +982,7 @@ Pauses the reading of data. That is, [`'data'`][] events will not be emitted. Useful to throttle back an upload. ### `socket.pending` + @@ -956,10 +1004,11 @@ added: v0.9.1 * Returns: {net.Socket} The socket itself. Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will -*not* let the program exit if it's the only socket left (the default behavior). +_not_ let the program exit if it's the only socket left (the default behavior). If the socket is `ref`ed calling `ref` again will have no effect. ### `socket.remoteAddress` + @@ -971,6 +1020,7 @@ The string representation of the remote IP address. For example, the socket is destroyed (for example, if the client disconnected). ### `socket.remoteFamily` + @@ -980,6 +1030,7 @@ added: v0.11.14 The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. ### `socket.remotePort` + @@ -995,6 +1046,7 @@ The numeric representation of the remote port. For example, `80` or `21`. Resumes reading after a call to [`socket.pause()`][]. ### `socket.setEncoding([encoding])` + @@ -1006,6 +1058,7 @@ Set the encoding for the socket as a [Readable Stream][]. See [`readable.setEncoding()`][] for more information. ### `socket.setKeepAlive([enable][, initialDelay])` + @@ -1054,6 +1109,7 @@ algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's algorithm. ### `socket.setTimeout(timeout[, callback])` + @@ -1083,6 +1139,7 @@ The optional `callback` parameter will be added as a one-time listener for the [`'timeout'`][] event. ### `socket.timeout` + @@ -1093,6 +1150,7 @@ The socket timeout in milliseconds as set by [`socket.setTimeout()`][]. It is `undefined` if a timeout has not been set. ### `socket.unref()` + @@ -1104,6 +1162,7 @@ active socket in the event system. If the socket is already `unref`ed calling `unref()` again will have no effect. ### `socket.write(data[, encoding][, callback])` + @@ -1127,6 +1186,7 @@ See `Writable` stream [`write()`][stream_writable_write] method for more information. ### `socket.readyState` + @@ -1154,6 +1214,7 @@ Possible signatures: for TCP connections. ### `net.connect(options[, connectListener])` + @@ -1166,6 +1227,7 @@ Alias to [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`]. ### `net.connect(path[, connectListener])` + @@ -1178,6 +1240,7 @@ Alias to [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`]. ### `net.connect(port[, host][, connectListener])` + @@ -1211,6 +1274,7 @@ Possible signatures: The [`net.connect()`][] function is an alias to this function. ### `net.createConnection(options[, connectListener])` + @@ -1260,6 +1324,7 @@ const client = net.createConnection({ path: '/tmp/echo.sock' }); ``` ### `net.createConnection(path[, connectListener])` + @@ -1281,6 +1346,7 @@ immediately initiates connection with then returns the `net.Socket` that starts the connection. ### `net.createConnection(port[, host][, connectListener])` + @@ -1289,7 +1355,7 @@ added: v0.1.90 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. * `host` {string} Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. - **Default:** `'localhost'`. + **Default:** `'localhost'`. * `connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions, an "once" listener for the `'connect'` event on the initiating socket. Will be passed to @@ -1304,6 +1370,7 @@ immediately initiates connection with then returns the `net.Socket` that starts the connection. ## `net.createServer([options][, connectionListener])` + @@ -1380,6 +1447,7 @@ $ nc -U /tmp/echo.sock ``` ## `net.isIP(input)` + @@ -1392,6 +1460,7 @@ returns `4` for IP version 4 addresses, and returns `6` for IP version 6 addresses. ## `net.isIPv4(input)` + @@ -1402,6 +1471,7 @@ added: v0.3.0 Returns `true` if input is a version 4 IP address, otherwise returns `false`. ## `net.isIPv6(input)` + @@ -1445,6 +1515,7 @@ Returns `true` if input is a version 6 IP address, otherwise returns `false`. [`server.listen(handle)`]: #serverlistenhandle-backlog-callback [`server.listen(options)`]: #serverlistenoptions-callback [`server.listen(path)`]: #serverlistenpath-backlog-callback +[`server.listen(port)`]: #serverlistenport-host-backlog-callback [`socket(7)`]: https://man7.org/linux/man-pages/man7/socket.7.html [`socket.connect()`]: #socketconnect [`socket.connect(options)`]: #socketconnectoptions-connectlistener diff --git a/doc/api/os.md b/doc/api/os.md index 85469a56293cc6..c8d4380bec40ea 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -14,6 +14,7 @@ const os = require('os'); ``` ## `os.EOL` + @@ -26,6 +27,7 @@ The operating system-specific end-of-line marker. * `\r\n` on Windows ## `os.arch()` + @@ -39,6 +41,7 @@ compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`, The return value is equivalent to [`process.arch`][]. ## `os.constants` + @@ -50,11 +53,12 @@ process signals, and so on. The specific constants defined are described in [OS constants](#os-constants). ## `os.cpus()` + -* Returns: {Object[]} +* Returns: {Object\[]} Returns an array of objects containing information about each logical CPU core. @@ -70,6 +74,7 @@ The properties included on each object include: * `irq` {number} The number of milliseconds the CPU has spent in irq mode. + ```js [ { @@ -123,6 +128,7 @@ The properties included on each object include: are always 0. ## `os.devNull` + @@ -135,6 +141,7 @@ The platform-specific file path of the null device. * `/dev/null` on POSIX ## `os.endianness()` + @@ -147,6 +154,7 @@ binary was compiled. Possible values are `'BE'` for big endian and `'LE'` for little endian. ## `os.freemem()` + @@ -156,6 +164,7 @@ added: v0.3.3 Returns the amount of free system memory in bytes as an integer. ## `os.getPriority([pid])` + @@ -168,6 +177,7 @@ Returns the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the priority of the current process is returned. ## `os.homedir()` + @@ -183,6 +193,7 @@ On Windows, it uses the `USERPROFILE` environment variable if defined. Otherwise it uses the path to the profile directory of the current user. ## `os.hostname()` + @@ -192,11 +203,12 @@ added: v0.3.3 Returns the host name of the operating system as a string. ## `os.loadavg()` + -* Returns: {number[]} +* Returns: {number\[]} Returns an array containing the 1, 5, and 15 minute load averages. @@ -207,6 +219,7 @@ The load average is a Unix-specific concept. On Windows, the return value is always `[0, 0, 0]`. ## `os.networkInterfaces()` + @@ -234,6 +247,7 @@ The properties available on the assigned network address object include: to `null`. + ```js { lo: [ @@ -278,6 +292,7 @@ The properties available on the assigned network address object include: ``` ## `os.platform()` + @@ -294,6 +309,7 @@ The value `'android'` may also be returned if Node.js is built on the Android operating system. [Android support is experimental][Android building]. ## `os.release()` + @@ -307,6 +323,7 @@ On POSIX systems, the operating system release is determined by calling for more information. ## `os.setPriority([pid, ]priority)` + @@ -330,6 +347,7 @@ privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. ## `os.tmpdir()` + @@ -354,6 +373,7 @@ added: v0.3.3 Returns the total amount of system memory in bytes as an integer. ## `os.type()` + @@ -367,6 +387,7 @@ See for additional information about the output of running [`uname(3)`][] on various operating systems. ## `os.uptime()` + @@ -404,6 +426,7 @@ operating system response. Throws a [`SystemError`][] if a user has no `username` or `homedir`. ## `os.version()` + diff --git a/doc/api/packages.md b/doc/api/packages.md index 3c14b9897c5856..4d38ee61881afe 100644 --- a/doc/api/packages.md +++ b/doc/api/packages.md @@ -140,6 +140,7 @@ package: `"commonjs"` package). ### `--input-type` flag + @@ -275,6 +276,7 @@ absolute subpath of the package such as `require('/path/to/node_modules/pkg/subpath.js')` will still load `subpath.js`. ### Subpath exports + @@ -308,6 +310,7 @@ import submodule from 'es-module-package/private-module.js'; ``` ### Subpath imports + @@ -494,6 +500,7 @@ can be written: ``` ### Conditional exports + @@ -1096,6 +1109,7 @@ When a package has an [`"exports"`][] field, this will take precedence over the `"main"` field when importing the package by name. ### `"packageManager"` + @@ -1120,6 +1134,7 @@ This field is currently experimental and needs to be opted-in; check the [Corepack][] page for details about the procedure. ### `"type"` + -* Type: {Object} | {string} | {string[]} +* Type: {Object} | {string} | {string\[]} ```json { @@ -1219,6 +1235,7 @@ All paths defined in the `"exports"` must be relative file URLs starting with `./`. ### `"imports"` + @@ -136,6 +138,7 @@ process.env.PATH.split(path.delimiter); ``` ## `path.dirname(path)` + @@ -263,6 +268,7 @@ path.format({ ``` ## `path.isAbsolute(path)` + @@ -298,6 +304,7 @@ path.isAbsolute('.'); // false A [`TypeError`][] is thrown if `path` is not a string. ## `path.join([...paths])` + @@ -323,6 +330,7 @@ path.join('foo', {}, 'bar'); A [`TypeError`][] is thrown if any of the path segments is not a string. ## `path.normalize(path)` + @@ -366,6 +374,7 @@ path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar'); A [`TypeError`][] is thrown if `path` is not a string. ## `path.parse(path)` + @@ -432,6 +441,7 @@ path.parse('C:\\path\\dir\\file.txt'); A [`TypeError`][] is thrown if `path` is not a string. ## `path.posix` + @@ -527,6 +539,7 @@ path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); A [`TypeError`][] is thrown if any of the arguments is not a string. ## `path.sep` + @@ -557,6 +570,7 @@ as path segment separators; however, the `path` methods only add backward slashes (`\`). ## `path.toNamespacedPath(path)` + @@ -572,6 +586,7 @@ This method is meaningful only on Windows systems. On POSIX systems, the method is non-operational and always returns `path` without modifications. ## `path.win32` + @@ -44,6 +45,7 @@ An object that can be used to collect performance metrics from the current Node.js instance. It is similar to [`window.performance`][] in browsers. ### `performance.clearMarks([name])` + @@ -54,6 +56,7 @@ If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. If `name` is provided, removes only the named mark. ### `performance.eventLoopUtilization([utilization1[, utilization2]])` + * `utilization1` {Object} The result of a previous call to - `eventLoopUtilization()`. + `eventLoopUtilization()`. * `utilization2` {Object} The result of a previous call to - `eventLoopUtilization()` prior to `utilization1`. + `eventLoopUtilization()` prior to `utilization1`. * Returns {Object} * `idle` {number} * `active` {number} @@ -116,6 +119,7 @@ Passing in a user-defined object instead of the result of a previous call to are not guaranteed to reflect any correct state of the event loop. ### `performance.mark([name[, options]])` + @@ -191,6 +197,7 @@ An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. ### `performance.now()` + @@ -201,6 +208,7 @@ Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. ### `performance.timeOrigin` + @@ -211,6 +219,7 @@ The [`timeOrigin`][] specifies the high resolution millisecond timestamp at which the current `node` process began, measured in Unix time. ### `performance.timerify(fn[, options])` + @@ -270,11 +280,13 @@ An object which is JSON representation of the `performance` object. It is similar to [`window.performance.toJSON`][] in browsers. ## Class: `PerformanceEntry` + ### `performanceEntry.detail` + @@ -284,6 +296,7 @@ added: v16.0.0 Additional detail specific to the `entryType`. ### `performanceEntry.duration` + @@ -294,6 +307,7 @@ The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types. ### `performanceEntry.entryType` + @@ -311,6 +325,7 @@ The type of the performance entry. It may be one of: * `'http'` (Node.js only) ### `performanceEntry.flags` + @@ -348,6 +364,7 @@ added: v8.5.0 The name of the performance entry. ### `performanceEntry.kind` + @@ -447,6 +465,7 @@ When `performanceEntry.type` is equal to `'function'`, the the input arguments to the timed function. ## Class: `PerformanceNodeTiming` + @@ -459,6 +478,7 @@ Provides timing details for Node.js itself. The constructor of this class is not exposed to users. ### `performanceNodeTiming.bootstrapComplete` + @@ -470,6 +490,7 @@ completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1. ### `performanceNodeTiming.environment` + @@ -480,6 +501,7 @@ The high resolution millisecond timestamp at which the Node.js environment was initialized. ### `performanceNodeTiming.idleTime` + @@ -506,6 +529,7 @@ exited. If the event loop has not yet exited, the property has the value of -1. It can only have a value of not -1 in a handler of the [`'exit'`][] event. ### `performanceNodeTiming.loopStart` + @@ -517,6 +541,7 @@ started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1. ### `performanceNodeTiming.nodeStart` + @@ -527,6 +552,7 @@ The high resolution millisecond timestamp at which the Node.js process was initialized. ### `performanceNodeTiming.v8Start` + @@ -539,6 +565,7 @@ initialized. ## Class: `perf_hooks.PerformanceObserver` ### `new PerformanceObserver(callback)` + @@ -576,12 +603,15 @@ notified about new `PerformanceEntry` instances. The callback receives a `PerformanceObserver`. ### `performanceObserver.disconnect()` + + Disconnects the `PerformanceObserver` instance from all notifications. ### `performanceObserver.observe(options)` + @@ -635,11 +666,12 @@ The `PerformanceObserverEntryList` class is used to provide access to the The constructor of this class is not exposed to users. ### `performanceObserverEntryList.getEntries()` + -* Returns: {PerformanceEntry[]} +* Returns: {PerformanceEntry\[]} Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. @@ -677,13 +709,14 @@ performance.mark('meow'); ``` ### `performanceObserverEntryList.getEntriesByName(name[, type])` + * `name` {string} * `type` {string} -* Returns: {PerformanceEntry[]} +* Returns: {PerformanceEntry\[]} Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` whose `performanceEntry.name` is @@ -731,12 +764,13 @@ performance.mark('meow'); ``` ### `performanceObserverEntryList.getEntriesByType(type)` + * `type` {string} -* Returns: {PerformanceEntry[]} +* Returns: {PerformanceEntry\[]} Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` @@ -775,6 +809,7 @@ performance.mark('meow'); ``` ## `perf_hooks.createHistogram([options])` + @@ -791,6 +826,7 @@ added: v15.9.0 Returns a {RecordableHistogram}. ## `perf_hooks.monitorEventLoopDelay([options])` + @@ -827,11 +863,13 @@ console.log(h.percentile(99)); ``` ## Class: `Histogram` + ### `histogram.exceeds` + @@ -842,6 +880,7 @@ The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. ### `histogram.max` + @@ -851,6 +890,7 @@ added: v11.10.0 The maximum recorded event loop delay. ### `histogram.mean` + @@ -860,6 +900,7 @@ added: v11.10.0 The mean of the recorded event loop delays. ### `histogram.min` + @@ -869,6 +910,7 @@ added: v11.10.0 The minimum recorded event loop delay. ### `histogram.percentile(percentile)` + @@ -879,6 +921,7 @@ added: v11.10.0 Returns the value at the given percentile. ### `histogram.percentiles` + @@ -888,6 +931,7 @@ added: v11.10.0 Returns a `Map` object detailing the accumulated percentile distribution. ### `histogram.reset()` + @@ -895,6 +939,7 @@ added: v11.10.0 Resets the collected histogram data. ### `histogram.stddev` + @@ -908,6 +953,7 @@ The standard deviation of the recorded event loop delays. A `Histogram` that is periodically updated on a given interval. ### `histogram.disable()` + @@ -918,6 +964,7 @@ Disables the update interval timer. Returns `true` if the timer was stopped, `false` if it was already stopped. ### `histogram.enable()` + @@ -934,11 +981,13 @@ end, the histogram is cloned as a plain {Histogram} object that does not implement the `enable()` and `disable()` methods. ## Class: `RecordableHistogram extends Histogram` + ### `histogram.record(val)` + @@ -946,6 +995,7 @@ added: v15.9.0 * `val` {number|bigint} The amount to record in the histogram. ### `histogram.recordDelta()` + @@ -1005,6 +1055,7 @@ The following example measures the duration of `require()` operations to load dependencies: + ```js 'use strict'; const { diff --git a/doc/api/process.md b/doc/api/process.md index db6f48eb25fe44..269efb72223ef3 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -23,6 +23,7 @@ const process = require('process'); The `process` object is an instance of [`EventEmitter`][]. ### Event: `'beforeExit'` + @@ -36,10 +37,10 @@ continue. The listener callback function is invoked with the value of [`process.exitCode`][] passed as the only argument. -The `'beforeExit'` event is *not* emitted for conditions causing explicit +The `'beforeExit'` event is _not_ emitted for conditions causing explicit termination, such as calling [`process.exit()`][] or uncaught exceptions. -The `'beforeExit'` should *not* be used as an alternative to the `'exit'` event +The `'beforeExit'` should _not_ be used as an alternative to the `'exit'` event unless the intention is to schedule additional work. ```mjs @@ -81,6 +82,7 @@ console.log('This message is displayed first.'); ``` ### Event: `'disconnect'` + @@ -90,6 +92,7 @@ and [Cluster][] documentation), the `'disconnect'` event will be emitted when the IPC channel is closed. ### Event: `'exit'` + @@ -151,6 +154,7 @@ process.on('exit', (code) => { ``` ### Event: `'message'` + @@ -174,6 +178,7 @@ to represent. See [Advanced serialization for `child_process`][] for more details. ### Event: `'multipleResolves'` + @@ -254,6 +259,7 @@ main().then(console.log); ``` ### Event: `'rejectionHandled'` + @@ -315,6 +321,7 @@ likely best for long-running application) or upon process exit (which is likely most convenient for scripts). ### Event: `'uncaughtException'` + @@ -627,6 +637,7 @@ The `*-deprecation` command-line flags only affect warnings that use the name `'DeprecationWarning'`. ### Event: `'worker'` + @@ -676,7 +687,7 @@ refer to signal(7) for a listing of standard POSIX signal names such as Signals are not available on [`Worker`][] threads. The signal handler will receive the signal's name (`'SIGINT'`, - `'SIGTERM'`, etc.) as the first argument. +`'SIGTERM'`, etc.) as the first argument. The name of each event will be the uppercase common name for the signal (e.g. `'SIGINT'` for `SIGINT` signals). @@ -735,8 +746,8 @@ process.on('SIGTERM', handle); * `'SIGTERM'` is not supported on Windows, it can be listened on. * `'SIGINT'` from the terminal is supported on all platforms, and can usually be generated with Ctrl+C (though this may be configurable). - It is not generated when [terminal raw mode][] is enabled and - Ctrl+C is used. + It is not generated when [terminal raw mode][] is enabled + and Ctrl+C is used. * `'SIGBREAK'` is delivered on Windows when Ctrl+Break is pressed. On non-Windows platforms, it can be listened on, but there is no way to send or generate it. @@ -747,15 +758,16 @@ process.on('SIGTERM', handle); terminate Node.js on all platforms. * `'SIGSTOP'` cannot have a listener installed. * `'SIGBUS'`, `'SIGFPE'`, `'SIGSEGV'` and `'SIGILL'`, when not raised - artificially using kill(2), inherently leave the process in a state from - which it is not safe to call JS listeners. Doing so might cause the process - to stop responding. + artificially using kill(2), inherently leave the process in a state from + which it is not safe to call JS listeners. Doing so might cause the process + to stop responding. * `0` can be sent to test for the existence of a process, it has no effect if - the process exists, but will throw an error if the process does not exist. + the process exists, but will throw an error if the process does not exist. Windows does not support signals so has no equivalent to termination by signal, but Node.js offers some emulation with [`process.kill()`][], and [`subprocess.kill()`][]: + * Sending `SIGINT`, `SIGTERM`, and `SIGKILL` will cause the unconditional termination of the target process, and afterwards, subprocess will report that the process was terminated by signal. @@ -763,6 +775,7 @@ but Node.js offers some emulation with [`process.kill()`][], and existence of a process. ## `process.abort()` + @@ -773,6 +786,7 @@ generate a core file. This feature is not available in [`Worker`][] threads. ## `process.allowedNodeEnvironmentFlags` + @@ -791,16 +805,16 @@ return `true` in the following cases: * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. * Flags passed through to V8 (as listed in `--v8-options`) may replace - one or more *non-leading* dashes for an underscore, or vice-versa; + one or more _non-leading_ dashes for an underscore, or vice-versa; e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, etc. * Flags may contain one or more equals (`=`) characters; all characters after and including the first equals will be ignored; e.g., `--stack-trace-limit=100`. -* Flags *must* be allowable within [`NODE_OPTIONS`][]. +* Flags _must_ be allowable within [`NODE_OPTIONS`][]. When iterating over `process.allowedNodeEnvironmentFlags`, flags will -appear only *once*; each will begin with one or more dashes. Flags +appear only _once_; each will begin with one or more dashes. Flags passed through to V8 will contain underscores instead of non-leading dashes: @@ -830,11 +844,12 @@ The methods `add()`, `clear()`, and `delete()` of `process.allowedNodeEnvironmentFlags` do nothing, and will fail silently. -If Node.js was compiled *without* [`NODE_OPTIONS`][] support (shown in +If Node.js was compiled _without_ [`NODE_OPTIONS`][] support (shown in [`process.config`][]), `process.allowedNodeEnvironmentFlags` will -contain what *would have* been allowable. +contain what _would have_ been allowable. ## `process.arch` + @@ -858,11 +873,12 @@ console.log(`This processor architecture is ${process.arch}`); ``` ## `process.argv` + -* {string[]} +* {string\[]} The `process.argv` property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will @@ -908,6 +924,7 @@ Would generate the output: ``` ## `process.argv0` + @@ -926,6 +943,7 @@ $ bash -c 'exec -a customArgv0 ./node' ``` ## `process.channel` + @@ -954,6 +973,7 @@ listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. ### `process.channel.unref()` + @@ -966,6 +986,7 @@ listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. ## `process.chdir(directory)` + @@ -1003,6 +1024,7 @@ try { This feature is not available in [`Worker`][] threads. ## `process.config` + + ```js { target_defaults: @@ -1058,6 +1081,7 @@ Modifying the `process.config` property, or any child-property of the read-only in a future release. ## `process.connected` + @@ -1073,6 +1097,7 @@ Once `process.connected` is `false`, it is no longer possible to send messages over the IPC channel using `process.send()`. ## `process.cpuUsage([previousValue])` + @@ -1121,6 +1146,7 @@ console.log(cpuUsage(startUsage)); ``` ## `process.cwd()` + @@ -1143,6 +1169,7 @@ console.log(`Current directory: ${cwd()}`); ``` ## `process.debugPort` + @@ -1164,6 +1191,7 @@ process.debugPort = 5858; ``` ## `process.disconnect()` + @@ -1180,6 +1208,7 @@ If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. ## `process.dlopen(module, filename[, flags])` + @@ -1239,7 +1269,7 @@ added: v8.0.0 * `warning` {string|Error} The warning to emit. * `options` {Object} * `type` {string} When `warning` is a `String`, `type` is the name to use - for the *type* of warning being emitted. **Default:** `'Warning'`. + for the _type_ of warning being emitted. **Default:** `'Warning'`. * `code` {string} A unique identifier for the warning instance being emitted. * `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** @@ -1307,13 +1337,14 @@ process.on('warning', (warning) => { If `warning` is passed as an `Error` object, the `options` argument is ignored. ## `process.emitWarning(warning[, type[, code]][, ctor])` + * `warning` {string|Error} The warning to emit. * `type` {string} When `warning` is a `String`, `type` is the name to use - for the *type* of warning being emitted. **Default:** `'Warning'`. + for the _type_ of warning being emitted. **Default:** `'Warning'`. * `code` {string} A unique identifier for the warning instance being emitted. * `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** @@ -1478,6 +1509,7 @@ emitMyWarning(); ``` ## `process.env` + + ```js { TERM: 'xterm-256color', @@ -1611,11 +1644,12 @@ across [`Worker`][] threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. ## `process.execArgv` + -* {string[]} +* {string\[]} The `process.execArgv` property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not @@ -1631,6 +1665,7 @@ $ node --harmony script.js --version Results in `process.execArgv`: + ```js ['--harmony'] ``` @@ -1638,6 +1673,7 @@ Results in `process.execArgv`: And `process.argv`: + ```js ['/usr/local/bin/node', 'script.js', '--version'] ``` @@ -1646,6 +1682,7 @@ Refer to [`Worker` constructor][] for the detailed behavior of worker threads with this property. ## `process.execPath` + @@ -1656,11 +1693,13 @@ The `process.execPath` property returns the absolute pathname of the executable that started the Node.js process. Symbolic links, if any, are resolved. + ```js '/usr/local/bin/node' ``` ## `process.exit([code])` + @@ -1695,11 +1734,11 @@ completed fully, including I/O operations to `process.stdout` and `process.stderr`. In most situations, it is not actually necessary to call `process.exit()` -explicitly. The Node.js process will exit on its own *if there is no additional -work pending* in the event loop. The `process.exitCode` property can be set to +explicitly. The Node.js process will exit on its own _if there is no additional +work pending_ in the event loop. The `process.exitCode` property can be set to tell the process which exit code to use when the process exits gracefully. -For instance, the following example illustrates a *misuse* of the +For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being truncated and lost: @@ -1724,11 +1763,11 @@ if (someConditionNotMet()) { ``` The reason this is problematic is because writes to `process.stdout` in Node.js -are sometimes *asynchronous* and may occur over multiple ticks of the Node.js +are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js event loop. Calling `process.exit()`, however, forces the process to exit -*before* those additional writes to `stdout` can be performed. +_before_ those additional writes to `stdout` can be performed. -Rather than calling `process.exit()` directly, the code *should* set the +Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding scheduling any additional work for the event loop: @@ -1755,13 +1794,14 @@ if (someConditionNotMet()) { ``` If it is necessary to terminate the Node.js process due to an error condition, -throwing an *uncaught* error and allowing the process to terminate accordingly +throwing an _uncaught_ error and allowing the process to terminate accordingly is safer than calling `process.exit()`. In [`Worker`][] threads, this function stops the current thread rather than the current process. ## `process.exitCode` + @@ -1776,6 +1816,7 @@ Specifying a code to [`process.exit(code)`][`process.exit()`] will override any previous setting of `process.exitCode`. ## `process.getegid()` + @@ -1803,6 +1844,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.geteuid()` + @@ -1832,6 +1874,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.getgid()` + @@ -1861,11 +1904,12 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.getgroups()` + -* Returns: {integer[]} +* Returns: {integer\[]} The `process.getgroups()` method returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but @@ -1891,6 +1935,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.getuid()` + @@ -1920,6 +1965,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.hasUncaughtExceptionCaptureCallback()` + @@ -1930,14 +1976,15 @@ Indicates whether a callback has been set using [`process.setUncaughtExceptionCaptureCallback()`][]. ## `process.hrtime([time])` + > Stability: 3 - Legacy. Use [`process.hrtime.bigint()`][] instead. -* `time` {integer[]} The result of a previous call to `process.hrtime()` -* Returns: {integer[]} +* `time` {integer\[]} The result of a previous call to `process.hrtime()` +* Returns: {integer\[]} This is the legacy version of [`process.hrtime.bigint()`][] before `bigint` was introduced in JavaScript. @@ -1989,6 +2036,7 @@ setTimeout(() => { ``` ## `process.hrtime.bigint()` + @@ -2033,6 +2081,7 @@ setTimeout(() => { ``` ## `process.initgroups(user, extraGroup)` + @@ -2072,6 +2121,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.kill(pid[, signal])` + @@ -2129,6 +2179,7 @@ When `SIGUSR1` is received by a Node.js process, Node.js will start the debugger. See [Signal Events][]. ## `process.mainModule` + @@ -2250,6 +2303,7 @@ console.log(memoryUsage.rss()); ``` ## `process.nextTick(callback[, ...args])` + @@ -2482,6 +2537,7 @@ the [`'warning'` event][process_warning] and the flag's behavior. ## `process.pid` + @@ -2503,6 +2559,7 @@ console.log(`This process is pid ${pid}`); ``` ## `process.platform` + @@ -2539,6 +2596,7 @@ Android operating system. However, Android support in Node.js [is experimental][Android building]. ## `process.ppid` + + ```js { name: 'node', @@ -2616,6 +2676,7 @@ In custom builds from non-release versions of the source tree, only the relied upon to exist. ## `process.report` + @@ -3007,6 +3079,7 @@ console.log(resourceUsage()); ``` ## `process.send(message[, sendHandle[, options]][, callback])` + @@ -3032,6 +3105,7 @@ The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. ## `process.setegid(id)` + @@ -3076,6 +3150,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.seteuid(id)` + @@ -3120,6 +3195,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setgid(id)` + @@ -3164,11 +3240,12 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setgroups(groups)` + -* `groups` {integer[]} +* `groups` {integer\[]} The `process.setgroups()` method sets the supplementary group IDs for the Node.js process. This is a privileged operation that requires the Node.js @@ -3207,6 +3284,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setuid(id)` + @@ -3251,6 +3329,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setSourceMapsEnabled(val)` + @@ -3269,6 +3348,7 @@ Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded. ## `process.setUncaughtExceptionCaptureCallback(fn)` + @@ -3383,9 +3463,9 @@ important ways: respectively. 2. Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX: - * Files: *synchronous* on Windows and POSIX - * TTYs (Terminals): *asynchronous* on Windows, *synchronous* on POSIX - * Pipes (and sockets): *synchronous* on Windows, *asynchronous* on POSIX + * Files: _synchronous_ on Windows and POSIX + * TTYs (Terminals): _asynchronous_ on Windows, _synchronous_ on POSIX + * Pipes (and sockets): _synchronous_ on Windows, _asynchronous_ on POSIX These behaviors are partly for historical reasons, as changing them would create backward incompatibility, but they are also expected by some users. @@ -3395,7 +3475,7 @@ Synchronous writes avoid problems such as output written with `console.log()` or `process.exit()` is called before an asynchronous write completes. See [`process.exit()`][] for more information. -***Warning***: Synchronous writes block the event loop until the write has +_**Warning**_: Synchronous writes block the event loop until the write has completed. This can be near instantaneous in the case of output to a file, but under high system load, pipes that are not being read at the receiving end, or with slow terminals or file systems, its possible for the event loop to be @@ -3423,6 +3503,7 @@ false See the [TTY][] documentation for more information. ## `process.throwDeprecation` + @@ -3453,6 +3534,7 @@ Thrown: ``` ## `process.title` + @@ -3477,6 +3559,7 @@ within process manager applications such as macOS Activity Monitor or Windows Services Manager. ## `process.traceDeprecation` + @@ -3490,6 +3573,7 @@ documentation for the [`'warning'` event][process_warning] and the flag's behavior. ## `process.umask()` + @@ -3542,6 +3627,7 @@ console.log( In [`Worker`][] threads, `process.umask(mask)` will throw an exception. ## `process.uptime()` + @@ -3555,6 +3641,7 @@ The return value includes fractions of a second. Use `Math.floor()` to get whole seconds. ## `process.version` + @@ -3581,6 +3668,7 @@ To get the version string without the prepended _v_, use `process.versions.node`. ## `process.versions` + @@ -39,6 +40,7 @@ made available to developers as a convenience. Fixes or other modifications to the module must be directed to the [Punycode.js][] project. ## `punycode.decode(string)` + @@ -54,6 +56,7 @@ punycode.decode('--dqo34k'); // '☃-⌘' ``` ## `punycode.encode(string)` + @@ -69,6 +72,7 @@ punycode.encode('☃-⌘'); // '--dqo34k' ``` ## `punycode.toASCII(domain)` + @@ -88,6 +92,7 @@ punycode.toASCII('example.com'); // 'example.com' ``` ## `punycode.toUnicode(domain)` + @@ -106,11 +111,13 @@ punycode.toUnicode('example.com'); // 'example.com' ``` ## `punycode.ucs2` + ### `punycode.ucs2.decode(string)` + @@ -127,11 +134,12 @@ punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306] ``` ### `punycode.ucs2.encode(codePoints)` + -* `codePoints` {integer[]} +* `codePoints` {integer\[]} The `punycode.ucs2.encode()` method returns a string based on an array of numeric code point values. @@ -142,6 +150,7 @@ punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06' ``` ## `punycode.version` + diff --git a/doc/api/querystring.md b/doc/api/querystring.md index 4b7db7afc3b948..32e9904553d568 100644 --- a/doc/api/querystring.md +++ b/doc/api/querystring.md @@ -19,6 +19,7 @@ The `querystring` API is considered Legacy. While it is still maintained, new code should use the {URLSearchParams} API instead. ## `querystring.decode()` + @@ -26,6 +27,7 @@ added: v0.1.99 The `querystring.decode()` function is an alias for `querystring.parse()`. ## `querystring.encode()` + @@ -33,6 +35,7 @@ added: v0.1.99 The `querystring.encode()` function is an alias for `querystring.stringify()`. ## `querystring.escape(str)` + @@ -49,6 +52,7 @@ application code to provide a replacement percent-encoding implementation if necessary by assigning `querystring.escape` to an alternative function. ## `querystring.parse(str[, sep[, eq[, options]]])` + + ```js { foo: 'bar', @@ -93,7 +98,7 @@ For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others -are not defined and *will not work*. +are not defined and _will not work_. By default, percent-encoded characters within the query string will be assumed to use UTF-8 encoding. If an alternative character encoding is used, then an @@ -107,6 +112,7 @@ querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, ``` ## `querystring.stringify(obj[, sep[, eq[, options]]])` + @@ -125,7 +131,7 @@ The `querystring.stringify()` method produces a URL query string from a given `obj` by iterating through the object's "own properties". It serializes the following types of values passed in `obj`: -{string|number|bigint|boolean|string[]|number[]|bigint[]|boolean[]} +{string|number|bigint|boolean|string\[]|number\[]|bigint\[]|boolean\[]} The numeric values must be finite. Any other input values will be coerced to empty strings. @@ -149,6 +155,7 @@ querystring.stringify({ w: '中文', foo: 'bar' }, null, null, ``` ## `querystring.unescape(str)` + diff --git a/doc/api/readline.md b/doc/api/readline.md index e2b2214ccd98a2..7111e92b4a7016 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -37,6 +37,7 @@ Once this code is invoked, the Node.js application will not terminate until the received on the `input` stream. ## Class: `Interface` + @@ -50,6 +51,7 @@ The `output` stream is used to print prompts for user input that arrives on, and is read from, the `input` stream. ### Event: `'close'` + @@ -71,6 +73,7 @@ The `readline.Interface` instance is finished once the `'close'` event is emitted. ### Event: `'line'` + @@ -89,6 +92,7 @@ rl.on('line', (input) => { ``` ### Event: `'history'` + @@ -111,6 +115,7 @@ rl.on('history', (history) => { ``` ### Event: `'pause'` + @@ -130,6 +135,7 @@ rl.on('pause', () => { ``` ### Event: `'resume'` + @@ -145,6 +151,7 @@ rl.on('resume', () => { ``` ### Event: `'SIGCONT'` + @@ -153,7 +160,7 @@ The `'SIGCONT'` event is emitted when a Node.js process previously moved into the background using Ctrl+Z (i.e. `SIGTSTP`) is then brought back to the foreground using fg(1p). -If the `input` stream was paused *before* the `SIGTSTP` request, this event will +If the `input` stream was paused _before_ the `SIGTSTP` request, this event will not be emitted. The listener function is invoked without passing any arguments. @@ -168,14 +175,15 @@ rl.on('SIGCONT', () => { The `'SIGCONT'` event is _not_ supported on Windows. ### Event: `'SIGINT'` + -The `'SIGINT'` event is emitted whenever the `input` stream receives a -Ctrl+C input, known typically as `SIGINT`. If there are no `'SIGINT'` -event listeners registered when the `input` stream receives a `SIGINT`, the -`'pause'` event will be emitted. +The `'SIGINT'` event is emitted whenever the `input` stream receives +a Ctrl+C input, known typically as `SIGINT`. If there are no +`'SIGINT'` event listeners registered when the `input` stream receives a +`SIGINT`, the `'pause'` event will be emitted. The listener function is invoked without passing any arguments. @@ -188,12 +196,13 @@ rl.on('SIGINT', () => { ``` ### Event: `'SIGTSTP'` + -The `'SIGTSTP'` event is emitted when the `input` stream receives a -Ctrl+Z input, typically known as `SIGTSTP`. If there are +The `'SIGTSTP'` event is emitted when the `input` stream receives +a Ctrl+Z input, typically known as `SIGTSTP`. If there are no `'SIGTSTP'` event listeners registered when the `input` stream receives a `SIGTSTP`, the Node.js process will be sent to the background. @@ -216,6 +225,7 @@ rl.on('SIGTSTP', () => { The `'SIGTSTP'` event is _not_ supported on Windows. ### `rl.close()` + @@ -228,6 +238,7 @@ Calling `rl.close()` does not immediately stop other events (including `'line'`) from being emitted by the `readline.Interface` instance. ### `rl.pause()` + @@ -239,6 +250,7 @@ Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `readline.Interface` instance. ### `rl.prompt([preserveCursor])` + @@ -257,6 +269,7 @@ If the `readline.Interface` was created with `output` set to `null` or `undefined` the prompt is not written. ### `rl.question(query[, options], callback)` + @@ -328,6 +341,7 @@ questionExample(); ``` ### `rl.resume()` + @@ -335,6 +349,7 @@ added: v0.3.4 The `rl.resume()` method resumes the `input` stream if it has been paused. ### `rl.setPrompt(prompt)` + @@ -345,6 +360,7 @@ The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. ### `rl.getPrompt()` + @@ -354,6 +370,7 @@ added: v15.3.0 The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. ### `rl.write(data[, key])` + @@ -385,9 +402,10 @@ rl.write(null, { ctrl: true, name: 'u' }); ``` The `rl.write()` method will write the data to the `readline` `Interface`'s -`input` *as if it were provided by the user*. +`input` _as if it were provided by the user_. ### `rl[Symbol.asyncIterator]()` + @@ -486,6 +506,7 @@ portion of the input string that will be modified as input is processed, as well as the column where the terminal caret will be rendered. ### `rl.getCursorPos()` + @@ -719,6 +745,7 @@ if (process.stdin.isTTY) ``` ## `readline.moveCursor(stream, dx, dy[, callback])` + The REPL supports bi-directional reverse-i-search similar to [ZSH][]. It is -triggered with Ctrl+R to search backward and -Ctrl+S to search -forwards. +triggered with Ctrl+R to search backward +and Ctrl+S to search forwards. Duplicated history entries will be skipped. Entries are accepted as soon as any key is pressed that doesn't correspond -with the reverse search. Cancelling is possible by pressing Esc or -Ctrl+C. +with the reverse search. Cancelling is possible by pressing Esc +or Ctrl+C. Changing the direction immediately searches for the next entry in the expected direction from the current position on. @@ -367,6 +369,7 @@ function myWriter(output) { ``` ## Class: `REPLServer` + @@ -387,6 +390,7 @@ const secondInstance = new repl.REPLServer(options); ``` ### Event: `'exit'` + @@ -406,12 +410,13 @@ replServer.on('exit', () => { ``` ### Event: `'reset'` + The `'reset'` event is emitted when the REPL's context is reset. This occurs -whenever the `.clear` command is received as input *unless* the REPL is using +whenever the `.clear` command is received as input _unless_ the REPL is using the default evaluator and the `repl.REPLServer` instance was created with the `useGlobal` option set to `true`. The listener callback will be called with a reference to the `context` object as the only argument. @@ -451,11 +456,12 @@ Clearing context... ``` ### `replServer.defineCommand(keyword, cmd)` + -* `keyword` {string} The command keyword (*without* a leading `.` character). +* `keyword` {string} The command keyword (_without_ a leading `.` character). * `cmd` {Object|Function} The function to invoke when the command is processed. The `replServer.defineCommand()` method is used to add new `.`-prefixed commands @@ -497,6 +503,7 @@ Goodbye! ``` ### `replServer.displayPrompt([preserveCursor])` + @@ -517,6 +524,7 @@ within the action function for commands registered using the `replServer.defineCommand()` method. ### `replServer.clearBufferedCommand()` + @@ -527,6 +535,7 @@ called from within the action function for commands registered using the `replServer.defineCommand()` method. ### `replServer.parseREPLKeyword(keyword[, rest])` + @@ -558,15 +568,17 @@ programmatically. Use this method to initialize a history log file when working with REPL instances programmatically. ## `repl.builtinModules` + -* {string[]} +* {string\[]} A list of the names of all Node.js modules, e.g., `'http'`. ## `repl.start([options])` + @@ -110,12 +111,12 @@ enforce a strict memory limitation in general. Specific stream implementations may choose to enforce stricter limits but doing so is optional. Because [`Duplex`][] and [`Transform`][] streams are both `Readable` and -`Writable`, each maintains *two* separate internal buffers used for reading and +`Writable`, each maintains _two_ separate internal buffers used for reading and writing, allowing each side to operate independently of the other while maintaining an appropriate and efficient flow of data. For example, [`net.Socket`][] instances are [`Duplex`][] streams whose `Readable` side allows -consumption of data received *from* the socket and whose `Writable` side allows -writing data *to* the socket. Because data may be written to the socket at a +consumption of data received _from_ the socket and whose `Writable` side allows +writing data _to_ the socket. Because data may be written to the socket at a faster or slower rate than data is received, each side should operate (and buffer) independently of the other. @@ -196,7 +197,7 @@ section [API for stream implementers][]. ### Writable streams -Writable streams are an abstraction for a *destination* to which data is +Writable streams are an abstraction for a _destination_ to which data is written. Examples of [`Writable`][] streams include: @@ -228,6 +229,7 @@ myStream.end('done writing data'); ``` #### Class: `stream.Writable` + @@ -235,6 +237,7 @@ added: v0.9.4 ##### Event: `'close'` + @@ -289,6 +293,7 @@ function writeOneMillionTimes(writer, data, encoding, callback) { ``` ##### Event: `'error'` + @@ -302,10 +307,11 @@ The stream is closed when the `'error'` event is emitted unless the [`autoDestroy`][writable-new] option was set to `false` when creating the stream. -After `'error'`, no further events other than `'close'` *should* be emitted +After `'error'`, no further events other than `'close'` _should_ be emitted (including `'error'` events). ##### Event: `'finish'` + @@ -325,6 +331,7 @@ writer.end('This is the end\n'); ``` ##### Event: `'pipe'` + @@ -345,6 +352,7 @@ reader.pipe(writer); ``` ##### Event: `'unpipe'` + @@ -371,6 +379,7 @@ reader.unpipe(writer); ``` ##### `writable.cork()` + @@ -391,6 +400,7 @@ to be processed. However, use of `writable.cork()` without implementing See also: [`writable.uncork()`][], [`writable._writev()`][stream-_writev]. ##### `writable.destroy([error])` + @@ -466,6 +477,7 @@ console.log(myStream.destroyed); // true ``` ##### `writable.end([chunk[, encoding]][, callback])` + @@ -562,6 +576,7 @@ process.nextTick(() => { See also: [`writable.cork()`][]. ##### `writable.writable` + @@ -572,6 +587,7 @@ Is `true` if it is safe to call [`writable.write()`][stream-write], which means the stream has not been destroyed, errored or ended. ##### `writable.writableEnded` + @@ -583,6 +599,7 @@ does not indicate whether the data has been flushed, for this use [`writable.writableFinished`][] instead. ##### `writable.writableCorked` + @@ -604,6 +622,7 @@ added: v12.6.0 Is set to `true` immediately before the [`'finish'`][] event is emitted. ##### `writable.writableHighWaterMark` + @@ -613,6 +632,7 @@ added: v9.3.0 Return the value of `highWaterMark` passed when creating this `Writable`. ##### `writable.writableLength` + @@ -624,6 +644,7 @@ ready to be written. The value provides introspection data regarding the status of the `highWaterMark`. ##### `writable.writableNeedDrain` + @@ -633,6 +654,7 @@ added: v15.2.0 Is `true` if the stream's buffer has been full and stream will emit `'drain'`. ##### `writable.writableObjectMode` + @@ -642,6 +664,7 @@ added: v12.3.0 Getter for the property `objectMode` of a given `Writable` stream. ##### `writable.write(chunk[, encoding][, callback])` + @@ -852,6 +876,7 @@ added: v0.9.4 ##### Event: `'close'` + @@ -902,6 +928,7 @@ readable.on('data', (chunk) => { ``` ##### Event: `'end'` + @@ -925,6 +952,7 @@ readable.on('end', () => { ``` ##### Event: `'error'` + @@ -939,6 +967,7 @@ to push an invalid chunk of data. The listener callback will be passed a single `Error` object. ##### Event: `'pause'` + @@ -947,6 +976,7 @@ The `'pause'` event is emitted when [`stream.pause()`][stream-pause] is called and `readableFlowing` is not `false`. ##### Event: `'readable'` + @@ -1024,6 +1055,7 @@ The `'resume'` event is emitted when [`stream.resume()`][stream-resume] is called and `readableFlowing` is not `true`. ##### `readable.destroy([error])` + @@ -1056,6 +1089,7 @@ added: v8.0.0 Is `true` after [`readable.destroy()`][readable-destroy] has been called. ##### `readable.isPaused()` + @@ -1078,6 +1112,7 @@ readable.isPaused(); // === false ``` ##### `readable.pause()` + @@ -1105,6 +1140,7 @@ The `readable.pause()` method has no effect if there is a `'readable'` event listener. ##### `readable.pipe(destination[, options])` + @@ -1112,7 +1148,7 @@ added: v0.9.4 * `destination` {stream.Writable} The destination for writing data * `options` {Object} Pipe options * `end` {boolean} End the writer when the reader ends. **Default:** `true`. -* Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if +* Returns: {stream.Writable} The _destination_, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream The `readable.pipe()` method attaches a [`Writable`][] stream to the `readable`, @@ -1135,7 +1171,7 @@ readable.pipe(writable); It is possible to attach multiple `Writable` streams to a single `Readable` stream. -The `readable.pipe()` method returns a reference to the *destination* stream +The `readable.pipe()` method returns a reference to the _destination_ stream making it possible to set up chains of piped streams: ```js @@ -1159,14 +1195,15 @@ reader.on('end', () => { ``` One important caveat is that if the `Readable` stream emits an error during -processing, the `Writable` destination *is not closed* automatically. If an -error occurs, it will be necessary to *manually* close each stream in order +processing, the `Writable` destination _is not closed_ automatically. If an +error occurs, it will be necessary to _manually_ close each stream in order to prevent memory leaks. The [`process.stderr`][] and [`process.stdout`][] `Writable` streams are never closed until the Node.js process exits, regardless of the specified options. ##### `readable.read([size])` + @@ -1181,7 +1218,7 @@ specified using the `readable.setEncoding()` method or the stream is operating in object mode. The optional `size` argument specifies a specific number of bytes to read. If -`size` bytes are not available to be read, `null` will be returned *unless* +`size` bytes are not available to be read, `null` will be returned _unless_ the stream has ended, in which case all of the data remaining in the internal buffer will be returned. @@ -1250,6 +1287,7 @@ Calling [`stream.read([size])`][stream-read] after the [`'end'`][] event has been emitted will return `null`. No runtime error will be raised. ##### `readable.readable` + @@ -1260,6 +1298,7 @@ Is `true` if it is safe to call [`readable.read()`][stream-read], which means the stream has not been destroyed or emitted `'error'` or `'end'`. ##### `readable.readableAborted` + @@ -1271,6 +1310,7 @@ added: v16.8.0 Returns whether the stream was destroyed or errored before emitting `'end'`. ##### `readable.readableDidRead` + @@ -1282,6 +1322,7 @@ added: v16.7.0 Returns whether `'data'` has been emitted. ##### `readable.readableEncoding` + @@ -1292,6 +1333,7 @@ Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the [`readable.setEncoding()`][] method. ##### `readable.readableEnded` + @@ -1301,6 +1343,7 @@ added: v12.9.0 Becomes `true` when [`'end'`][] event is emitted. ##### `readable.readableFlowing` + @@ -1311,6 +1354,7 @@ This property reflects the current state of a `Readable` stream as described in the [Three states][] section. ##### `readable.readableHighWaterMark` + @@ -1320,6 +1364,7 @@ added: v9.3.0 Returns the value of `highWaterMark` passed when creating this `Readable`. ##### `readable.readableLength` + @@ -1331,6 +1376,7 @@ ready to be read. The value provides introspection data regarding the status of the `highWaterMark`. ##### `readable.readableObjectMode` + @@ -1340,6 +1386,7 @@ added: v12.3.0 Getter for the property `objectMode` of a given `Readable` stream. ##### `readable.resume()` + @@ -1401,6 +1449,7 @@ readable.on('data', (chunk) => { ``` ##### `readable.unpipe([destination])` + @@ -1411,7 +1460,7 @@ added: v0.9.4 The `readable.unpipe()` method detaches a `Writable` stream previously attached using the [`stream.pipe()`][] method. -If the `destination` is not specified, then *all* pipes are detached. +If the `destination` is not specified, then _all_ pipes are detached. If the `destination` is specified, but no pipe is set up for it, then the method does nothing. @@ -1432,6 +1481,7 @@ setTimeout(() => { ``` ##### `readable.unshift(chunk[, encoding])` + @@ -1541,6 +1592,7 @@ myReader.on('readable', () => { ``` ##### `readable[Symbol.asyncIterator]()` + @@ -1632,6 +1685,7 @@ showBoth(); ### Duplex and transform streams #### Class: `stream.Duplex` + @@ -1668,6 +1723,7 @@ This can be changed manually to change the half-open behavior of an existing emitted. #### Class: `stream.Transform` + @@ -1684,6 +1740,7 @@ Examples of `Transform` streams include: * [crypto streams][crypto] ##### `transform.destroy([error])` + -* `streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]} +* `streams` {Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]} * `source` {Stream|Iterable|AsyncIterable|Function} * Returns: {Iterable|AsyncIterable} * `...transforms` {Stream|Function} @@ -1946,6 +2006,7 @@ run().catch(console.error); ``` `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * `Readable` streams which have emitted `'end'` or `'close'`. * `Writable` streams which have emitted `'finish'` or `'close'`. @@ -1954,13 +2015,14 @@ after the `callback` has been invoked. In the case of reuse of streams after failure, this can cause event listener leaks and swallowed errors. ### `stream.compose(...streams)` + > Stability: 1 - `stream.compose` is experimental. -* `streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]} +* `streams` {Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]} * Returns: {stream.Duplex} Combines two or more streams into a `Duplex` stream that writes to the @@ -2043,6 +2105,7 @@ console.log(res); // prints 'HELLOWORLD' ``` ### `stream.Readable.from(iterable[, options])` + @@ -2094,6 +2158,7 @@ added: v16.11.0 * Returns: {stream.Readable} ### `stream.Readable.isDisturbed(stream)` + @@ -2106,6 +2171,7 @@ added: v16.8.0 Returns whether the stream has been read from or cancelled. ### `stream.Duplex.from(src)` + @@ -2134,9 +2200,11 @@ A utility method for creating duplex streams. * Returns: {stream.Duplex} ### `stream.addAbortSignal(signal, stream)` + + * `signal` {AbortSignal} A signal representing possible cancellation * `stream` {Stream} a stream to attach a signal to @@ -2182,6 +2250,7 @@ const stream = addAbortSignal( } })(); ``` + ## API for stream implementers @@ -2195,6 +2264,7 @@ of the four basic stream classes (`stream.Writable`, `stream.Readable`, parent class constructor: + ```js const { Writable } = require('stream'); @@ -2216,14 +2286,14 @@ options are forwarded instead of implicitly forwarding all options. The new stream class must then implement one or more specific methods, depending on the type of stream being created, as detailed in the chart below: -| Use-case | Class | Method(s) to implement | -| -------- | ----- | ---------------------- | -| Reading only | [`Readable`][] | [`_read()`][stream-_read] | -| Writing only | [`Writable`][] | [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | -| Reading and writing | [`Duplex`][] | [`_read()`][stream-_read], [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | -| Operate on written data, then read the result | [`Transform`][] | [`_transform()`][stream-_transform], [`_flush()`][stream-_flush], [`_final()`][stream-_final] | +| Use-case | Class | Method(s) to implement | +| --------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------ | +| Reading only | [`Readable`][] | [`_read()`][stream-_read] | +| Writing only | [`Writable`][] | [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | +| Reading and writing | [`Duplex`][] | [`_read()`][stream-_read], [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | +| Operate on written data, then read the result | [`Transform`][] | [`_transform()`][stream-_transform], [`_flush()`][stream-_flush], [`_final()`][stream-_final] | -The implementation code for a stream should *never* call the "public" methods +The implementation code for a stream should _never_ call the "public" methods of a stream that are intended for use by consumers (as described in the [API for stream consumers][] section). Doing so may lead to adverse side effects in application code consuming the stream. @@ -2236,6 +2306,7 @@ and/or compatibility issues with other streams, stream utilities, and user expectations. ### Simplified construction + @@ -2265,11 +2336,12 @@ const myWritable = new Writable({ The `stream.Writable` class is extended to implement a [`Writable`][] stream. -Custom `Writable` streams *must* call the `new stream.Writable([options])` +Custom `Writable` streams _must_ call the `new stream.Writable([options])` constructor and implement the `writable._write()` and/or `writable._writev()` method. #### `new stream.Writable([options])` + + ```js const { Writable } = require('stream'); @@ -2386,7 +2459,9 @@ const myWritable = new Writable({ // Later, abort the operation closing the stream controller.abort(); ``` + #### `writable._construct(callback)` + @@ -2436,6 +2511,7 @@ class WriteStream extends Writable { ``` #### `writable._write(chunk, encoding, callback)` + @@ -2528,6 +2605,7 @@ The `_destroy()` method is called by [`writable.destroy()`][writable-destroy]. It can be overridden by child classes but it **must not** be called directly. #### `writable._final(callback)` + @@ -2633,10 +2711,11 @@ console.log(w.data); // currency: € The `stream.Readable` class is extended to implement a [`Readable`][] stream. -Custom `Readable` streams *must* call the `new stream.Readable([options])` +Custom `Readable` streams _must_ call the `new stream.Readable([options])` constructor and implement the [`readable._read()`][] method. #### `new stream.Readable([options])` + + ```js const { Readable } = require('stream'); @@ -2731,6 +2811,7 @@ controller.abort(); ``` #### `readable._construct(callback)` + @@ -2788,6 +2869,7 @@ class ReadStream extends Readable { ``` #### `readable._read(size)` + @@ -2826,6 +2908,7 @@ internal to the class that defines it, and should never be called directly by user programs. #### `readable._destroy(err, callback)` + @@ -2838,6 +2921,7 @@ The `_destroy()` method is called by [`readable.destroy()`][readable-destroy]. It can be overridden by child classes but it **must not** be called directly. #### `readable.push(chunk[, encoding])` + + ```js const { Duplex } = require('stream'); @@ -3185,8 +3271,8 @@ The `stream.Transform` class is extended to implement a [`Transform`][] stream. The `stream.Transform` class prototypically inherits from `stream.Duplex` and implements its own versions of the `writable._write()` and -[`readable._read()`][] methods. Custom `Transform` implementations *must* -implement the [`transform._transform()`][stream-_transform] method and *may* +[`readable._read()`][] methods. Custom `Transform` implementations _must_ +implement the [`transform._transform()`][stream-_transform] method and _may_ also implement the [`transform._flush()`][stream-_flush] method. Care must be taken when using `Transform` streams in that data written to the @@ -3203,6 +3289,7 @@ output on the `Readable` side is not consumed. method. + ```js const { Transform } = require('stream'); @@ -3269,7 +3356,7 @@ store an amount of internal state used to optimally compress the output. When the stream ends, however, that additional data needs to be flushed so that the compressed data will be complete. -Custom [`Transform`][] implementations *may* implement the `transform._flush()` +Custom [`Transform`][] implementations _may_ implement the `transform._flush()` method. This will be called when there is no more written data to be consumed, but before the [`'end'`][] event is emitted signaling the end of the [`Readable`][] stream. @@ -3452,7 +3539,7 @@ less powerful and less useful. were required to store read data into buffers so the data would not be lost. * The [`stream.pause()`][stream-pause] method was advisory, rather than guaranteed. This meant that it was still necessary to be prepared to receive - [`'data'`][] events *even when the stream was in a paused state*. + [`'data'`][] events _even when the stream was in a paused state_. In Node.js 0.10, the [`Readable`][] class was added. For backward compatibility with older Node.js programs, `Readable` streams switch into @@ -3526,7 +3613,7 @@ situations within Node.js where this is done, particularly in the Use of `readable.push('')` is not recommended. Pushing a zero-byte string, `Buffer` or `Uint8Array` to a stream that is not in -object mode has an interesting side effect. Because it *is* a call to +object mode has an interesting side effect. Because it _is_ a call to [`readable.push()`][stream-push], the call will end the reading process. However, because the argument is an empty string, no data is added to the readable buffer so there is nothing for a user to consume. diff --git a/doc/api/string_decoder.md b/doc/api/string_decoder.md index 42a288c7c832ed..a628a5a8a14cf4 100644 --- a/doc/api/string_decoder.md +++ b/doc/api/string_decoder.md @@ -47,6 +47,7 @@ console.log(decoder.end(Buffer.from([0xAC]))); ## Class: `StringDecoder` ### `new StringDecoder([encoding])` + @@ -57,6 +58,7 @@ added: v0.1.99 Creates a new `StringDecoder` instance. ### `stringDecoder.end([buffer])` + @@ -74,6 +76,7 @@ is performed before returning the remaining input. After `end()` is called, the `stringDecoder` object can be reused for new input. ### `stringDecoder.write(buffer)` + @@ -35,13 +36,14 @@ added: v11.0.0 If true, the `Immediate` object will keep the Node.js event loop active. ### `immediate.ref()` + * Returns: {Immediate} a reference to `immediate` -When called, requests that the Node.js event loop *not* exit so long as the +When called, requests that the Node.js event loop _not_ exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no effect. @@ -49,6 +51,7 @@ By default, all `Immediate` objects are "ref'ed", making it normally unnecessary to call `immediate.ref()` unless `immediate.unref()` had been called previously. ### `immediate.unref()` + @@ -73,6 +76,7 @@ export both `timeout.ref()` and `timeout.unref()` functions that can be used to control this default behavior. ### `timeout.close()` + @@ -84,6 +88,7 @@ added: v0.9.1 Cancels the timeout. ### `timeout.hasRef()` + @@ -93,19 +98,21 @@ added: v11.0.0 If true, the `Timeout` object will keep the Node.js event loop active. ### `timeout.ref()` + * Returns: {Timeout} a reference to `timeout` -When called, requests that the Node.js event loop *not* exit so long as the +When called, requests that the Node.js event loop _not_ exit so long as the `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. By default, all `Timeout` objects are "ref'ed", making it normally unnecessary to call `timeout.ref()` unless `timeout.unref()` had been called previously. ### `timeout.refresh()` + @@ -121,6 +128,7 @@ Using this on a timer that has already called its callback will reactivate the timer. ### `timeout.unref()` + @@ -137,6 +145,7 @@ event loop. Creating too many of these can adversely impact performance of the Node.js application. ### `timeout[Symbol.toPrimitive]()` + @@ -184,6 +194,7 @@ This method has a custom variant for promises that is available using [`timersPromises.setImmediate()`][]. ### `setInterval(callback[, delay[, ...args]])` + @@ -205,6 +216,7 @@ This method has a custom variant for promises that is available using [`timersPromises.setInterval()`][]. ### `setTimeout(callback[, delay[, ...args]])` + @@ -277,6 +289,7 @@ ac.abort(); ``` ### `clearImmediate(immediate)` + @@ -287,6 +300,7 @@ added: v0.9.1 Cancels an `Immediate` object created by [`setImmediate()`][]. ### `clearInterval(timeout)` + @@ -297,6 +311,7 @@ added: v0.0.1 Cancels a `Timeout` object created by [`setInterval()`][]. ### `clearTimeout(timeout)` + @@ -307,6 +322,7 @@ added: v0.0.1 Cancels a `Timeout` object created by [`setTimeout()`][]. ## Timers Promises API + @@ -371,6 +388,7 @@ setTimeout(100, 'result').then((res) => { ``` ### `timersPromises.setImmediate([value[, options]])` + @@ -404,6 +422,7 @@ setImmediate('result').then((res) => { ``` ### `timersPromises.setInterval([delay[, value[, options]]])` + @@ -411,7 +430,7 @@ added: v15.9.0 Returns an async iterator that generates values in an interval of `delay` ms. * `delay` {number} The number of milliseconds to wait between iterations. - **Default:** `1`. + **Default:** `1`. * `value` {any} A value with which the iterator returns. * `options` {Object} * `ref` {boolean} Set to `false` to indicate that the scheduled `Timeout` diff --git a/doc/api/tls.md b/doc/api/tls.md index 6926b7cda0c66b..ac582be4dd761d 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -17,7 +17,7 @@ const tls = require('tls'); ## TLS/SSL concepts The TLS/SSL is a public/private key infrastructure (PKI). For most common -cases, each client and server must have a *private key*. +cases, each client and server must have a _private key_. Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 2048-bit RSA private @@ -27,11 +27,11 @@ key: openssl genrsa -out ryans-key.pem 2048 ``` -With TLS/SSL, all servers (and some clients) must have a *certificate*. -Certificates are *public keys* that correspond to a private key, and that are +With TLS/SSL, all servers (and some clients) must have a _certificate_. +Certificates are _public keys_ that correspond to a private key, and that are digitally signed either by a Certificate Authority or by the owner of the private key (such certificates are referred to as "self-signed"). The first -step to obtaining a certificate is to create a *Certificate Signing Request* +step to obtaining a certificate is to create a _Certificate Signing Request_ (CSR) file. The OpenSSL command-line interface can be used to generate a CSR for a private @@ -64,7 +64,7 @@ Where: * `in`: is the signed certificate * `inkey`: is the associated private key * `certfile`: is a concatenation of all Certificate Authority (CA) certs into - a single file, e.g. `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem` + a single file, e.g. `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem` ### Perfect forward secrecy @@ -190,7 +190,7 @@ send it to the client. Clients and servers save the session state. When reconnecting, clients send the ID of their saved session state and if the server also has the state for that ID, it can agree to use it. Otherwise, the server will create a new session. See [RFC 2246][] for more information, page 23 and -30. +30\. Resumption using session identifiers is supported by most web browsers when making HTTPS requests. @@ -237,8 +237,8 @@ securely generate 48 bytes of secure random data and set them with the regenerated and server's keys can be reset with [`server.setTicketKeys()`][]. -Session ticket keys are cryptographic keys, and they ***must be stored -securely***. With TLS 1.2 and below, if they are compromised all sessions that +Session ticket keys are cryptographic keys, and they _**must be stored +securely**_. With TLS 1.2 and below, if they are compromised all sessions that used tickets encrypted with them can be decrypted. They should not be stored on disk, and they should be regenerated regularly. @@ -280,6 +280,7 @@ default cipher list can be configured when building Node.js to allow distributions to provide their own default list. The following command can be used to show the default cipher suite: + ```console node -p crypto.constants.defaultCoreCipherList | tr ':' '\n' TLS_AES_256_GCM_SHA384 @@ -329,7 +330,7 @@ The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones that start with `'TLS_'`, and specifications for TLSv1.2 and below cipher suites. The TLSv1.2 ciphers support a legacy specification format, consult the OpenSSL [cipher list format][] documentation for details, but those -specifications do *not* apply to TLSv1.3 ciphers. The TLSv1.3 suites can only +specifications do _not_ apply to TLSv1.3 ciphers. The TLSv1.3 suites can only be enabled by including their full name in the cipher list. They cannot, for example, be enabled or disabled by using the legacy TLSv1.2 `'EECDH'` or `'!EECDH'` specification. @@ -347,7 +348,7 @@ used only if absolutely necessary. The default cipher suite prefers GCM ciphers for [Chrome's 'modern cryptography' setting][] and also prefers ECDHE and DHE ciphers for perfect -forward secrecy, while offering *some* backward compatibility. +forward secrecy, while offering _some_ backward compatibility. 128 bit AES is preferred over 192 and 256 bit AES in light of [specific attacks affecting larger AES key sizes][]. @@ -380,6 +381,7 @@ has the property `code` which can take one of the following values: values are taken from src/crypto/crypto_common.cc description are taken from deps/openssl/openssl/crypto/x509/x509_txt.c --> + * `'UNABLE_TO_GET_ISSUER_CERT'`: Unable to get issuer certificate. * `'UNABLE_TO_GET_CRL'`: Unable to get certificate CRL. * `'UNABLE_TO_DECRYPT_CERT_SIGNATURE'`: Unable to decrypt certificate's @@ -413,6 +415,7 @@ description are taken from deps/openssl/openssl/crypto/x509/x509_txt.c * `'HOSTNAME_MISMATCH'`: Hostname mismatch. ## Class: `tls.CryptoStream` + The `cryptoStream.bytesWritten` property returns the total number of bytes -written to the underlying socket *including* the bytes required for the +written to the underlying socket _including_ the bytes required for the implementation of the TLS protocol. ## Class: `tls.SecurePair` + @@ -467,6 +474,7 @@ added: v0.3.2 Accepts encrypted connections using TLS or SSL. ### Event: `'connection'` + @@ -481,6 +489,7 @@ This event can also be explicitly emitted by users to inject connections into the TLS server. In that case, any [`Duplex`][] stream can be passed. ### Event: `'keylog'` + @@ -581,6 +592,7 @@ after the addition of the event listener. An npm module like [asn1.js][] may be used to parse the certificates. ### Event: `'resumeSession'` + @@ -620,6 +632,7 @@ server.on('resumeSession', (id, cb) => { ``` ### Event: `'secureConnection'` + @@ -644,6 +657,7 @@ The `tlsSocket.servername` property is a string containing the server name requested via SNI. ### Event: `'tlsClientError'` + @@ -657,6 +671,7 @@ called: error originated. ### `server.addContext(hostname, context)` + @@ -673,6 +688,7 @@ When there are multiple matching contexts, the most recently added one is used. ### `server.address()` + @@ -684,6 +700,7 @@ server as reported by the operating system. See [`net.Server.address()`][] for more information. ### `server.close([callback])` + @@ -698,6 +715,7 @@ This function operates asynchronously. The `'close'` event will be emitted when the server has no more open connections. ### `server.getTicketKeys()` + @@ -714,6 +732,7 @@ Starts the server listening for encrypted connections. This method is identical to [`server.listen()`][] from [`net.Server`][]. ### `server.setSecureContext(options)` + @@ -726,6 +745,7 @@ The `server.setSecureContext()` method replaces the secure context of an existing server. Existing connections to the server are not interrupted. ### `server.setTicketKeys(keys)` + @@ -741,6 +761,7 @@ Existing or currently pending server connections will use the previous keys. See [Session Resumption][] for more information. ## Class: `tls.TLSSocket` + @@ -757,6 +778,7 @@ Methods that return TLS connection metadata (e.g. connection is open. ### `new tls.TLSSocket(socket[, options])` + @@ -836,6 +860,7 @@ Typically, the `response` is a digitally signed object from the server's CA that contains information about server's certificate revocation status. ### Event: `'secureConnect'` + @@ -854,6 +879,7 @@ The `'secureConnect'` event is not emitted when a {tls.TLSSocket} is created using the `new tls.TLSSocket()` constructor. ### Event: `'session'` + @@ -893,6 +919,7 @@ tlsSocket.once('session', (session) => { ``` ### `tlsSocket.address()` + @@ -904,6 +931,7 @@ underlying socket as reported by the operating system: `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. ### `tlsSocket.authorizationError` + @@ -912,6 +940,7 @@ Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`. ### `tlsSocket.authorized` + @@ -922,6 +951,7 @@ Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`. ### `tlsSocket.disableRenegotiation()` + @@ -930,6 +960,7 @@ Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts to renegotiate will trigger an `'error'` event on the `TLSSocket`. ### `tlsSocket.enableTrace()` + @@ -937,12 +968,13 @@ added: v12.2.0 When enabled, TLS packet trace information is written to `stderr`. This can be used to debug TLS connection problems. -Note: The format of the output is identical to the output of `openssl s_client --trace` or `openssl s_server -trace`. While it is produced by OpenSSL's -`SSL_trace()` function, the format is undocumented, can change without notice, -and should not be relied on. +The format of the output is identical to the output of +`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by +OpenSSL's `SSL_trace()` function, the format is undocumented, can change +without notice, and should not be relied on. ### `tlsSocket.encrypted` + @@ -951,6 +983,7 @@ Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances. ### `tlsSocket.exportKeyingMaterial(length, label[, context])` + * `length` {number} number of bytes to retrieve from keying material + * `label` {string} an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * `context` {Buffer} Optionally provide a context. * Returns: {Buffer} requested bytes of the keying material @@ -982,10 +1017,12 @@ const keyingMaterial = tlsSocket.exportKeyingMaterial( 74 ef 2c ... 78 more bytes> */ ``` + See the OpenSSL [`SSL_export_keying_material`][] documentation for more information. ### `tlsSocket.getCertificate()` + @@ -1002,6 +1039,7 @@ If there is no local certificate, an empty object will be returned. If the socket has been destroyed, `null` will be returned. ### `tlsSocket.getCipher()` + @@ -1054,6 +1094,7 @@ if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. ### `tlsSocket.getFinished()` + @@ -1071,6 +1112,7 @@ Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used to implement the `tls-unique` channel binding from [RFC 5929][]. ### `tlsSocket.getPeerCertificate([detailed])` + @@ -1088,6 +1130,7 @@ If the full certificate chain was requested, each certificate will include an certificate. #### Certificate object + + ```js { subject: { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ], @@ -1178,6 +1222,7 @@ Example certificate: ``` ### `tlsSocket.getPeerFinished()` + @@ -1195,6 +1240,7 @@ Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used to implement the `tls-unique` channel binding from [RFC 5929][]. ### `tlsSocket.getPeerX509Certificate()` + @@ -1207,6 +1253,7 @@ If there is no peer certificate, or the socket has been destroyed, `undefined` will be returned. ### `tlsSocket.getProtocol()` + @@ -1229,6 +1276,7 @@ Protocol versions are: See the OpenSSL [`SSL_get_version`][] documentation for more information. ### `tlsSocket.getSession()` + @@ -1246,6 +1294,7 @@ Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications must use the [`'session'`][] event (it also works for TLSv1.2 and below). ### `tlsSocket.getSharedSigalgs()` + @@ -1254,10 +1303,11 @@ added: v12.11.0 the client in the order of decreasing preference. See -[SSL_get_shared_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) +[SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL\_get\_shared\_sigalgs.html) for more information. ### `tlsSocket.getTLSTicket()` + @@ -1272,6 +1322,7 @@ It may be useful for debugging. See [Session Resumption][] for more information. ### `tlsSocket.getX509Certificate()` + @@ -1284,6 +1335,7 @@ If there is no local certificate, or the socket has been destroyed, `undefined` will be returned. ### `tlsSocket.isSessionReused()` + @@ -1293,6 +1345,7 @@ added: v0.5.6 See [Session Resumption][] for more information. ### `tlsSocket.localAddress` + @@ -1302,6 +1355,7 @@ added: v0.11.4 Returns the string representation of the local IP address. ### `tlsSocket.localPort` + @@ -1311,6 +1365,7 @@ added: v0.11.4 Returns the numeric representation of the local port. ### `tlsSocket.remoteAddress` + @@ -1321,6 +1376,7 @@ Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. ### `tlsSocket.remoteFamily` + @@ -1330,6 +1386,7 @@ added: v0.11.4 Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. ### `tlsSocket.remotePort` + @@ -1339,6 +1396,7 @@ added: v0.11.4 Returns the numeric representation of the remote port. For example, `443`. ### `tlsSocket.renegotiate(options, callback)` + @@ -1349,11 +1407,12 @@ added: v0.11.8 verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`. * `requestCert` + * `callback` {Function} If `renegotiate()` returned `true`, callback is - attached once to the `'secure'` event. If `renegotiate()` returned `false`, - `callback` will be called in the next tick with an error, unless the - `tlsSocket` has been destroyed, in which case `callback` will not be called - at all. + attached once to the `'secure'` event. If `renegotiate()` returned `false`, + `callback` will be called in the next tick with an error, unless the + `tlsSocket` has been destroyed, in which case `callback` will not be called + at all. * Returns: {boolean} `true` if renegotiation was initiated, `false` otherwise. @@ -1371,6 +1430,7 @@ For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol. ### `tlsSocket.setMaxSendFragment(size)` + @@ -1390,6 +1450,7 @@ smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. ## `tls.checkServerIdentity(hostname, cert)` + @@ -1413,6 +1474,7 @@ This function is only called if the certificate passed all other checks, such as being issued by trusted CA (`options.ca`). ## `tls.connect(options[, callback])` + @@ -1605,6 +1669,7 @@ as an argument instead of an option. A path option, if specified, will take precedence over the path argument. ## `tls.connect(port[, host][, options][, callback])` + @@ -1622,6 +1687,7 @@ A port or host option, if specified, will take precedence over any port or host argument. ## `tls.createSecureContext([options])` + * `options` {Object} - * `ca` {string|string[]|Buffer|Buffer[]} Optionally override the trusted CA + * `ca` {string|string\[]|Buffer|Buffer\[]} Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or `Buffer`, or an `Array` of @@ -1686,20 +1752,20 @@ changes: For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE", "X509 CERTIFICATE", and "CERTIFICATE". See also [`tls.rootCertificates`][]. - * `cert` {string|string[]|Buffer|Buffer[]} Cert chains in PEM format. One cert - chain should be provided per private key. Each cert chain should consist of - the PEM formatted certificate for a provided private `key`, followed by the - PEM formatted intermediate certificates (if any), in order, and not - including the root CA (the root CA must be pre-known to the peer, see `ca`). - When providing multiple cert chains, they do not have to be in the same - order as their private keys in `key`. If the intermediate certificates are - not provided, the peer will not be able to validate the certificate, and the - handshake will fail. + * `cert` {string|string\[]|Buffer|Buffer\[]} Cert chains in PEM format. One + cert chain should be provided per private key. Each cert chain should + consist of the PEM formatted certificate for a provided private `key`, + followed by the PEM formatted intermediate certificates (if any), in order, + and not including the root CA (the root CA must be pre-known to the peer, + see `ca`). When providing multiple cert chains, they do not have to be in + the same order as their private keys in `key`. If the intermediate + certificates are not provided, the peer will not be able to validate the + certificate, and the handshake will fail. * `sigalgs` {string} Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). - See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) + See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL\_CTX\_set1\_sigalgs\_list.html) for more info. * `ciphers` {string} Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted @@ -1707,7 +1773,7 @@ changes: uppercased in order for OpenSSL to accept them. * `clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate. - * `crl` {string|string[]|Buffer|Buffer[]} PEM formatted CRLs (Certificate + * `crl` {string|string\[]|Buffer|Buffer\[]} PEM formatted CRLs (Certificate Revocation Lists). * `dhparam` {string|Buffer} Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. @@ -1726,11 +1792,11 @@ changes: preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information. - * `key` {string|string[]|Buffer|Buffer[]|Object[]} Private keys in PEM format. - PEM allows the option of private keys being encrypted. Encrypted keys will - be decrypted with `options.passphrase`. Multiple keys using different - algorithms can be provided either as an array of unencrypted key strings or - buffers, or an array of objects in the form + * `key` {string|string\[]|Buffer|Buffer\[]|Object\[]} Private keys in PEM + format. PEM allows the option of private keys being encrypted. Encrypted + keys will be decrypted with `options.passphrase`. Multiple keys using + different algorithms can be provided either as an array of unencrypted key + strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if @@ -1753,7 +1819,7 @@ changes: **Default:** [`tls.DEFAULT_MIN_VERSION`][]. * `passphrase` {string} Shared passphrase used for a single private key and/or a PFX. - * `pfx` {string|string[]|Buffer|Buffer[]|Object[]} PFX or PKCS12 encoded + * `pfx` {string|string\[]|Buffer|Buffer\[]|Object\[]} PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either @@ -1770,9 +1836,9 @@ changes: version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as - [SSL_METHODS][], use the function names as strings. For example, use - `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any - TLS protocol version up to TLSv1.3. It is not recommended to use TLS + [SSL\_METHODS][SSL_METHODS], use the function names as strings. For example, + use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow + any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. **Default:** none, see `minVersion`. * `sessionIdContext` {string} Opaque identifier used by servers to ensure @@ -1794,13 +1860,14 @@ The `tls.createSecureContext()` method creates a `SecureContext` object. It is usable as an argument to several `tls` APIs, such as [`tls.createServer()`][] and [`server.addContext()`][], but has no public methods. -A key is *required* for ciphers that use certificates. Either `key` or +A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of CAs][]. ## `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])` + * `options` {Object} - * `ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| + * `ALPNProtocols`: {string\[]|Buffer\[]|TypedArray\[]|DataView\[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN @@ -1923,6 +1991,7 @@ changes: * `ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudorandom data. See [Session Resumption][] for more information. * `pskCallback` {Function} + * socket: {tls.TLSSocket} the server [`tls.TLSSocket`][] instance for this connection. * identity: {string} identity parameter sent from the client. @@ -1933,10 +2002,10 @@ changes: When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an - "unknown_psk_identity" alert message will be sent to the other party. + "unknown\_psk\_identity" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection - fail with "decrypt_error" before negotiation is finished. + fail with "decrypt\_error" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][]. @@ -1990,11 +2059,12 @@ The server can be tested by connecting to it using the example client from [`tls.connect()`][]. ## `tls.getCiphers()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array with the names of the supported TLS ciphers. The names are lower-case for historical reasons, but must be uppercased to be used in @@ -2008,11 +2078,12 @@ console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] ``` ## `tls.rootCertificates` + -* {string[]} +* {string\[]} An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by current Node.js version. @@ -2021,6 +2092,7 @@ The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms. ## `tls.DEFAULT_ECDH_CURVE` + @@ -2047,6 +2120,7 @@ added: v11.4.0 highest maximum is used. ## `tls.DEFAULT_MIN_VERSION` + diff --git a/doc/api/tracing.md b/doc/api/tracing.md index 4b7a9bd8ff1913..d0b5ac4250e978 100644 --- a/doc/api/tracing.md +++ b/doc/api/tracing.md @@ -44,7 +44,7 @@ node --trace-event-categories v8,node,node.async_hooks server.js Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the -`--trace-events-enabled` flag *may* still be used and will enable the +`--trace-events-enabled` flag _may_ still be used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. ```bash @@ -88,11 +88,13 @@ unlike `process.hrtime()` which returns nanoseconds. The features from this module are not available in [`Worker`][] threads. ## The `trace_events` module + ### `Tracing` object + @@ -107,6 +109,7 @@ categories. Calling `tracing.disable()` will remove the categories from the set of enabled trace event categories. #### `tracing.categories` + @@ -117,14 +120,15 @@ A comma-separated list of the trace event categories covered by this `Tracing` object. #### `tracing.disable()` + Disables this `Tracing` object. -Only trace event categories *not* covered by other enabled `Tracing` objects -and *not* specified by the `--trace-event-categories` flag will be disabled. +Only trace event categories _not_ covered by other enabled `Tracing` objects +and _not_ specified by the `--trace-event-categories` flag will be disabled. ```js const trace_events = require('trace_events'); @@ -143,6 +147,7 @@ console.log(trace_events.getEnabledCategories()); ``` #### `tracing.enable()` + @@ -151,6 +156,7 @@ Enables this `Tracing` object for the set of categories covered by the `Tracing` object. #### `tracing.enabled` + @@ -158,12 +164,13 @@ added: v10.0.0 * {boolean} `true` only if the `Tracing` object has been enabled. ### `trace_events.createTracing(options)` + * `options` {Object} - * `categories` {string[]} An array of trace category names. Values included + * `categories` {string\[]} An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced. * Returns: {Tracing}. @@ -180,6 +187,7 @@ tracing.disable(); ``` ### `trace_events.getEnabledCategories()` + @@ -188,7 +196,7 @@ added: v10.0.0 Returns a comma-separated list of all currently-enabled trace event categories. The current set of enabled trace event categories is determined -by the *union* of all currently-enabled `Tracing` objects and any categories +by the _union_ of all currently-enabled `Tracing` objects and any categories enabled using the `--trace-event-categories` flag. Given the file `test.js` below, the command diff --git a/doc/api/tty.md b/doc/api/tty.md index 10eb874e561f8b..ea0640274f7e41 100644 --- a/doc/api/tty.md +++ b/doc/api/tty.md @@ -33,6 +33,7 @@ manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. ## Class: `tty.ReadStream` + @@ -44,6 +45,7 @@ Represents the readable side of a TTY. In normal circumstances process and there should be no reason to create additional instances. ### `readStream.isRaw` + @@ -52,6 +54,7 @@ A `boolean` that is `true` if the TTY is currently configured to operate as a raw device. Defaults to `false`. ### `readStream.isTTY` + @@ -59,6 +62,7 @@ added: v0.5.8 A `boolean` that is always `true` for `tty.ReadStream` instances. ### `readStream.setRawMode(mode)` + @@ -73,10 +77,12 @@ Allows configuration of `tty.ReadStream` so that it operates as a raw device. When in raw mode, input is always available character-by-character, not including modifiers. Additionally, all special processing of characters by the -terminal is disabled, including echoing input characters. -Ctrl+C will no longer cause a `SIGINT` when in this mode. +terminal is disabled, including echoing input +characters. Ctrl+C will no longer cause a `SIGINT` when +in this mode. ## Class: `tty.WriteStream` + @@ -89,6 +95,7 @@ Represents the writable side of a TTY. In normal circumstances, should be no reason to create additional instances. ### Event: `'resize'` + @@ -105,6 +112,7 @@ process.stdout.on('resize', () => { ``` ### `writeStream.clearLine(dir[, callback])` + @@ -151,6 +161,7 @@ A `number` specifying the number of columns the TTY currently has. This property is updated whenever the `'resize'` event is emitted. ### `writeStream.cursorTo(x[, y][, callback])` + @@ -204,11 +216,12 @@ Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. ### `writeStream.getWindowSize()` + -* Returns: {number[]} +* Returns: {number\[]} `writeStream.getWindowSize()` returns the size of the TTY corresponding to this `WriteStream`. The array is of the type @@ -216,6 +229,7 @@ corresponding to this `WriteStream`. The array is of the type of columns and rows in the corresponding TTY. ### `writeStream.hasColors([count][, env])` + @@ -254,6 +269,7 @@ added: v0.5.8 A `boolean` that is always `true`. ### `writeStream.moveCursor(dx, dy[, callback])` + @@ -281,6 +298,7 @@ A `number` specifying the number of rows the TTY currently has. This property is updated whenever the `'resize'` event is emitted. ## `tty.isatty(fd)` + diff --git a/doc/api/url.md b/doc/api/url.md index e42ccdd5f5ea1a..a7f68bfb564fd8 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -105,6 +105,7 @@ console.log(myURL.href); ## The WHATWG URL API ### Class: `URL` + @@ -644,6 +649,7 @@ Threads, `Blob` objects registered within one Worker will not be available to other workers or the main thread. #### `URL.revokeObjectURL(id)` + @@ -656,6 +662,7 @@ added: v16.7.0 Removes the stored {Blob} identified by the given ID. ### Class: `URLSearchParams` + @@ -1099,6 +1112,7 @@ fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) ``` ### `url.format(URL[, options])` + @@ -1153,6 +1167,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); ``` ### `url.pathToFileURL(path)` + @@ -1188,6 +1203,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI ``` ### `url.urlToHttpOptions(url)` + @@ -1251,6 +1267,7 @@ console.log(urlToHttpOptions(myUrl)); ``` ## Legacy URL API + @@ -71,6 +72,7 @@ callbackFunction((err, ret) => { ``` ## `util.debuglog(section[, callback])` + @@ -137,6 +139,7 @@ let debuglog = util.debuglog('internals', (debug) => { ``` ### `debuglog().enabled` + @@ -165,6 +168,7 @@ hello from foo [123] ``` ## `util.debug(section)` + @@ -173,6 +177,7 @@ Alias for `util.debuglog`. Usage allows for readability of that doesn't imply logging when only using `util.debuglog().enabled`. ## `util.deprecate(fn, msg[, code])` + @@ -358,6 +365,7 @@ util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); ``` ## `util.getSystemErrorName(err)` + @@ -377,6 +385,7 @@ fs.access('file/that/does/not/exist', (err) => { ``` ## `util.getSystemErrorMap()` + @@ -396,6 +405,7 @@ fs.access('file/that/does/not/exist', (err) => { ``` ## `util.inherits(constructor, superConstructor)` + @@ -951,6 +965,7 @@ console.log(arr); // logs the full array ``` ## `util.isDeepStrictEqual(val1, val2)` + @@ -966,6 +981,7 @@ See [`assert.deepStrictEqual()`][] for more information about deep strict equality. ## `util.promisify(original)` + @@ -1079,6 +1095,7 @@ If `promisify.custom` is defined but is not a function, `promisify()` will throw an error. ### `util.promisify.custom` + @@ -1125,6 +1143,7 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); ``` ## Class: `util.TextDecoder` + @@ -1152,47 +1171,47 @@ Different Node.js build configurations support different sets of encodings. #### Encodings supported by default (with full ICU data) -| Encoding | Aliases | -| ----------------- | -------------------------------- | -| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | -| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | -| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | -| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | -| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | -| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | -| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | -| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | -| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | -| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | -| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | -| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | -| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | -| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | -| `'koi8-u'` | `'koi8-ru'` | -| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | -| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | -| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | -| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | +| Encoding | Aliases | +| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | +| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | +| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | +| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | +| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | +| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | +| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | +| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | +| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | +| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | +| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | +| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | +| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | +| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | +| `'koi8-u'` | `'koi8-ru'` | +| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | +| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | +| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | +| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | | `'windows-1252'` | `'ansi_x3.4-1968'`, `'ascii'`, `'cp1252'`, `'cp819'`, `'csisolatin1'`, `'ibm819'`, `'iso-8859-1'`, `'iso-ir-100'`, `'iso8859-1'`, `'iso88591'`, `'iso_8859-1'`, `'iso_8859-1:1987'`, `'l1'`, `'latin1'`, `'us-ascii'`, `'x-cp1252'` | -| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | -| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | -| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | -| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | -| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | -| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | -| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | -| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | -| `'gb18030'` | | -| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | -| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | -| `'iso-2022-jp'` | `'csiso2022jp'` | -| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | -| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | +| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | +| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | +| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | +| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | +| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | +| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | +| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | +| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | +| `'gb18030'` | | +| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | +| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | +| `'iso-2022-jp'` | `'csiso2022jp'` | +| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | +| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | #### Encodings supported when Node.js is built with the `small-icu` option | Encoding | Aliases | -| ----------- | ------------------------------- | +| ------------ | ------------------------------- | | `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | | `'utf-16le'` | `'utf-16'` | | `'utf-16be'` | | @@ -1200,7 +1219,7 @@ Different Node.js build configurations support different sets of encodings. #### Encodings supported when ICU is disabled | Encoding | Aliases | -| ----------- | ------------------------------- | +| ------------ | ------------------------------- | | `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | | `'utf-16le'` | `'utf-16'` | @@ -1208,6 +1227,7 @@ The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] is not supported. ### `new TextDecoder([encoding[, options]])` + @@ -1331,6 +1353,7 @@ Returns the `string` after replacing any surrogate code points Unicode "replacement character" U+FFFD. ## `util.types` + @@ -1370,6 +1394,7 @@ util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true ``` ### `util.types.isArrayBufferView(value)` + @@ -1389,6 +1414,7 @@ util.types.isArrayBufferView(new ArrayBuffer()); // false ``` ### `util.types.isArgumentsObject(value)` + @@ -1399,6 +1425,7 @@ added: v10.0.0 Returns `true` if the value is an `arguments` object. + ```js function foo() { util.types.isArgumentsObject(arguments); // Returns true @@ -1406,6 +1433,7 @@ function foo() { ``` ### `util.types.isArrayBuffer(value)` + @@ -1414,7 +1442,7 @@ added: v10.0.0 * Returns: {boolean} Returns `true` if the value is a built-in [`ArrayBuffer`][] instance. -This does *not* include [`SharedArrayBuffer`][] instances. Usually, it is +This does _not_ include [`SharedArrayBuffer`][] instances. Usually, it is desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that. ```js @@ -1423,6 +1451,7 @@ util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false ``` ### `util.types.isAsyncFunction(value)` + @@ -1441,6 +1470,7 @@ util.types.isAsyncFunction(async function foo() {}); // Returns true ``` ### `util.types.isBigInt64Array(value)` + @@ -1456,6 +1486,7 @@ util.types.isBigInt64Array(new BigUint64Array()); // Returns false ``` ### `util.types.isBigUint64Array(value)` + @@ -1471,6 +1502,7 @@ util.types.isBigUint64Array(new BigUint64Array()); // Returns true ``` ### `util.types.isBooleanObject(value)` + @@ -1491,6 +1523,7 @@ util.types.isBooleanObject(Boolean(true)); // Returns false ``` ### `util.types.isBoxedPrimitive(value)` + @@ -1512,6 +1545,7 @@ util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true ``` ### `util.types.isCryptoKey(value)` + @@ -1522,6 +1556,7 @@ added: v16.2.0 Returns `true` if `value` is a {CryptoKey}, `false` otherwise. ### `util.types.isDataView(value)` + @@ -1540,6 +1575,7 @@ util.types.isDataView(new Float64Array()); // Returns false See also [`ArrayBuffer.isView()`][]. ### `util.types.isDate(value)` + @@ -1554,6 +1590,7 @@ util.types.isDate(new Date()); // Returns true ``` ### `util.types.isExternal(value)` + @@ -1599,6 +1636,7 @@ For further information on `napi_create_external`, refer to [`napi_create_external()`][]. ### `util.types.isFloat32Array(value)` + @@ -1615,6 +1653,7 @@ util.types.isFloat32Array(new Float64Array()); // Returns false ``` ### `util.types.isFloat64Array(value)` + @@ -1631,6 +1670,7 @@ util.types.isFloat64Array(new Float64Array()); // Returns true ``` ### `util.types.isGeneratorFunction(value)` + @@ -1649,6 +1689,7 @@ util.types.isGeneratorFunction(function* foo() {}); // Returns true ``` ### `util.types.isGeneratorObject(value)` + @@ -1669,6 +1710,7 @@ util.types.isGeneratorObject(generator); // Returns true ``` ### `util.types.isInt8Array(value)` + @@ -1685,6 +1727,7 @@ util.types.isInt8Array(new Float64Array()); // Returns false ``` ### `util.types.isInt16Array(value)` + @@ -1701,6 +1744,7 @@ util.types.isInt16Array(new Float64Array()); // Returns false ``` ### `util.types.isInt32Array(value)` + @@ -1717,6 +1761,7 @@ util.types.isInt32Array(new Float64Array()); // Returns false ``` ### `util.types.isKeyObject(value)` + @@ -1727,6 +1772,7 @@ added: v16.2.0 Returns `true` if `value` is a {KeyObject}, `false` otherwise. ### `util.types.isMap(value)` + @@ -1741,6 +1787,7 @@ util.types.isMap(new Map()); // Returns true ``` ### `util.types.isMapIterator(value)` + @@ -1760,6 +1807,7 @@ util.types.isMapIterator(map[Symbol.iterator]()); // Returns true ``` ### `util.types.isModuleNamespaceObject(value)` + @@ -1770,6 +1818,7 @@ added: v10.0.0 Returns `true` if the value is an instance of a [Module Namespace Object][]. + ```js import * as ns from './a.js'; @@ -1777,6 +1826,7 @@ util.types.isModuleNamespaceObject(ns); // Returns true ``` ### `util.types.isNativeError(value)` + @@ -1793,6 +1843,7 @@ util.types.isNativeError(new RangeError()); // Returns true ``` ### `util.types.isNumberObject(value)` + @@ -1809,6 +1860,7 @@ util.types.isNumberObject(new Number(0)); // Returns true ``` ### `util.types.isPromise(value)` + @@ -1823,6 +1875,7 @@ util.types.isPromise(Promise.resolve(42)); // Returns true ``` ### `util.types.isProxy(value)` + @@ -1840,6 +1893,7 @@ util.types.isProxy(proxy); // Returns true ``` ### `util.types.isRegExp(value)` + @@ -1855,6 +1909,7 @@ util.types.isRegExp(new RegExp('abc')); // Returns true ``` ### `util.types.isSet(value)` + @@ -1869,6 +1924,7 @@ util.types.isSet(new Set()); // Returns true ``` ### `util.types.isSetIterator(value)` + @@ -1888,6 +1944,7 @@ util.types.isSetIterator(set[Symbol.iterator]()); // Returns true ``` ### `util.types.isSharedArrayBuffer(value)` + @@ -1896,7 +1953,7 @@ added: v10.0.0 * Returns: {boolean} Returns `true` if the value is a built-in [`SharedArrayBuffer`][] instance. -This does *not* include [`ArrayBuffer`][] instances. Usually, it is +This does _not_ include [`ArrayBuffer`][] instances. Usually, it is desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that. ```js @@ -1905,6 +1962,7 @@ util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true ``` ### `util.types.isStringObject(value)` + @@ -1921,6 +1979,7 @@ util.types.isStringObject(new String('foo')); // Returns true ``` ### `util.types.isSymbolObject(value)` + @@ -1938,6 +1997,7 @@ util.types.isSymbolObject(Object(symbol)); // Returns true ``` ### `util.types.isTypedArray(value)` + @@ -1956,6 +2016,7 @@ util.types.isTypedArray(new Float64Array()); // Returns true See also [`ArrayBuffer.isView()`][]. ### `util.types.isUint8Array(value)` + @@ -1972,6 +2033,7 @@ util.types.isUint8Array(new Float64Array()); // Returns false ``` ### `util.types.isUint8ClampedArray(value)` + @@ -1988,6 +2050,7 @@ util.types.isUint8ClampedArray(new Float64Array()); // Returns false ``` ### `util.types.isUint16Array(value)` + @@ -2004,6 +2067,7 @@ util.types.isUint16Array(new Float64Array()); // Returns false ``` ### `util.types.isUint32Array(value)` + @@ -2020,6 +2084,7 @@ util.types.isUint32Array(new Float64Array()); // Returns false ``` ### `util.types.isWeakMap(value)` + @@ -2034,6 +2099,7 @@ util.types.isWeakMap(new WeakMap()); // Returns true ``` ### `util.types.isWeakSet(value)` + @@ -2048,6 +2114,7 @@ util.types.isWeakSet(new WeakSet()); // Returns true ``` ### `util.types.isWebAssemblyCompiledModule(value)` + @@ -33,6 +34,7 @@ console.log(v8.cachedDataVersionTag()); // 183726201 ``` ## `v8.getHeapCodeStatistics()` + @@ -46,6 +48,7 @@ Returns an object with the following properties: * `external_script_source_size` {number} + ```js { code_and_metadata_size: 212208, @@ -55,6 +58,7 @@ Returns an object with the following properties: ``` ## `v8.getHeapSnapshot()` + @@ -75,6 +79,7 @@ stream.pipe(process.stdout); ``` ## `v8.getHeapSpaceStatistics()` + -* Returns: {Object[]} +* Returns: {Object\[]} Returns statistics about the V8 heap spaces, i.e. the segments which make up the V8 heap. Neither the ordering of heap spaces, nor the availability of a @@ -140,6 +145,7 @@ The value returned is an array of objects containing the following properties: ``` ## `v8.getHeapStatistics()` + + ```js { total_heap_size: 7326976, @@ -200,6 +207,7 @@ being non-zero indicates a potential memory leak. ``` ## `v8.setFlagsFromString(flags)` + @@ -254,6 +262,7 @@ When the process is about to exit, one last coverage will still be written to disk unless [`v8.stopCoverage()`][] is invoked before the process exits. ## `v8.writeHeapSnapshot([filename])` + @@ -314,6 +323,7 @@ The format is backward-compatible (i.e. safe to store to disk). Equal JavaScript values may result in different serialized output. ### `v8.serialize(value)` + @@ -324,6 +334,7 @@ added: v8.0.0 Uses a [`DefaultSerializer`][] to serialize `value` into a buffer. ### `v8.deserialize(buffer)` + @@ -334,11 +345,13 @@ Uses a [`DefaultDeserializer`][] with default options to read a JS value from a buffer. ### Class: `v8.Serializer` + #### `new Serializer()` + Creates a new `Serializer` object. #### `serializer.writeHeader()` @@ -445,6 +458,7 @@ Indicate whether to treat `TypedArray` and `DataView` objects as host objects, i.e. pass them to [`serializer._writeHostObject()`][]. ### Class: `v8.Deserializer` + @@ -493,7 +507,7 @@ For use inside of a custom [`deserializer._readHostObject()`][]. #### `deserializer.readUint64()` -* Returns: {integer[]} +* Returns: {integer\[]} Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. @@ -526,6 +540,7 @@ This method is not present on the `Deserializer` class itself but can be provided by subclasses. ### Class: `v8.DefaultSerializer` + @@ -535,6 +550,7 @@ A subclass of [`Serializer`][] that serializes `TypedArray` stores the part of their underlying `ArrayBuffer`s that they are referring to. ### Class: `v8.DefaultDeserializer` + diff --git a/doc/api/vm.md b/doc/api/vm.md index a1451cdc059343..19ff922bcaf23d 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -43,6 +43,7 @@ console.log(x); // 1; y is not defined. ``` ## Class: `vm.Script` + @@ -51,6 +52,7 @@ Instances of the `vm.Script` class contain precompiled scripts that can be executed in specific contexts. ### `new vm.Script(code[, options])` + @@ -136,6 +139,7 @@ const cacheWithX = script.createCachedData(); ``` ### `script.runInContext(contextifiedObject[, options])` + @@ -560,6 +568,7 @@ The identifier of the current module, as set in the constructor. unsupported assertion is present. * `referencingModule` {vm.Module} The `Module` object `link()` is called on. + * Returns: {vm.Module|Promise} * Returns: {Promise} @@ -634,6 +643,7 @@ Other than `'errored'`, this status string corresponds to the specification's value that is not `undefined`. ## Class: `vm.SourceTextModule` + @@ -649,6 +659,7 @@ The `vm.SourceTextModule` class provides the [Source Text Module Record][] as defined in the ECMAScript specification. ### `new vm.SourceTextModule(code[, options])` + -* `exportNames` {string[]} Array of names that will be exported from the module. +* `exportNames` {string\[]} Array of names that will be exported from the + module. * `evaluateCallback` {Function} Called when the module is evaluated. * `options` * `identifier` {string} String used in stack traces. @@ -827,6 +842,7 @@ the module to access information outside the specified `context`. Use `vm.runInContext()` to create objects in a specific context. ### `syntheticModule.setExport(name, value)` + * `code` {string} The body of the function to compile. -* `params` {string[]} An array of strings containing all parameters for the +* `params` {string\[]} An array of strings containing all parameters for the function. * `options` {Object} * `filename` {string} Specifies the filename used in stack traces produced @@ -899,12 +916,12 @@ changes: is displayed in stack traces produced by this script. **Default:** `0`. * `cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied - source. + source. * `produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`. * `parsingContext` {Object} The [contextified][] object in which the said function should be compiled in. - * `contextExtensions` {Object[]} An array containing a collection of context + * `contextExtensions` {Object\[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`. * `importModuleDynamically` {Function} Called during evaluation of this module @@ -927,6 +944,7 @@ supplied, the current context is used), and returns it wrapped inside a function with the given `params`. ## `vm.createContext([contextObject[, options]])` + @@ -1089,6 +1108,7 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' }) ``` ## `vm.runInContext(code, contextifiedObject[, options])` + + ```js const vm = require('vm'); let localVar = 'initial value'; @@ -1364,7 +1387,7 @@ console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`); ``` Because `vm.runInThisContext()` does not have access to the local scope, -`localVar` is unchanged. In contrast, [`eval()`][] *does* have access to the +`localVar` is unchanged. In contrast, [`eval()`][] _does_ have access to the local scope, so the value `localVar` is changed. In this way `vm.runInThisContext()` is much like an [indirect `eval()` call][], e.g. `(0,eval)('code')`. diff --git a/doc/api/wasi.md b/doc/api/wasi.md index e0cd77a5a42c78..644daa217e900e 100644 --- a/doc/api/wasi.md +++ b/doc/api/wasi.md @@ -107,6 +107,7 @@ The `--experimental-wasi-unstable-preview1` CLI argument is needed for this example to run. ## Class: `WASI` + @@ -340,6 +341,7 @@ Calling `require('crypto').webcrypto` returns an instance of the `Crypto` class. `Crypto` is a singleton that provides access to the remainder of the crypto API. ### `crypto.subtle` + @@ -349,6 +351,7 @@ added: v15.0.0 Provides access to the `SubtleCrypto` API. ### `crypto.getRandomValues(typedArray)` + @@ -362,6 +365,7 @@ filled with random values, and a reference to `typedArray` is returned. An error will be thrown if the given `typedArray` is larger than 65,536 bytes. ### `crypto.randomUUID()` + @@ -372,17 +376,21 @@ Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator. ## Class: `CryptoKey` + ### `cryptoKey.algorithm` + + * Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams} + An object detailing the algorithm for which the key can be used along with @@ -391,6 +399,7 @@ additional algorithm-specific parameters. Read-only. ### `cryptoKey.extractable` + @@ -403,6 +412,7 @@ When `true`, the {CryptoKey} can be extracted using either Read-only. ### `cryptoKey.type` + @@ -413,11 +423,12 @@ A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. ### `cryptoKey.usages` + -* Type: {string[]} +* Type: {string\[]} An array of strings identifying the operations for which the key may be used. @@ -436,29 +447,30 @@ The possible usages are: Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). -| Key Type | `'encrypt'` | `'decrypt'` | `'sign'` | `'verify'` | `'deriveKey'` | `'deriveBits'` | `'wrapKey'` | `'unwrapKey'` | -| -------------------- | ----------- | ----------- | -------- | ---------- | ------------- | --------------- | ----------- | ------------- | -| `'AES-CBC'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'AES-CTR'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'AES-GCM'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'AES-KW'` | | | | | | | ✔ | ✔ | -| `'ECDH'` | | | | | ✔ | ✔ | | | -| `'ECDSA'` | | | ✔ | ✔ | | | | | -| `'HDKF'` | | | | | ✔ | ✔ | | | -| `'HMAC'` | | | ✔ | ✔ | | | | | -| `'PBKDF2'` | | | | | ✔ | ✔ | | | -| `'RSA-OAEP'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'RSA-PSS'` | | | ✔ | ✔ | | | | | -| `'RSASSA-PKCS1-v1_5'` | | | ✔ | ✔ | | | | | -| `'NODE-DSA'` 1 | | | ✔ | ✔ | | | | | -| `'NODE-DH'` 1 | | | | | ✔ | ✔ | | | -| `'NODE-SCRYPT'` 1 | | | | | ✔ | ✔ | | | -| `'NODE-ED25519'` 1 | | | ✔ | ✔ | | | | | -| `'NODE-ED448'` 1 | | | ✔ | ✔ | | | | | +| Key Type | `'encrypt'` | `'decrypt'` | `'sign'` | `'verify'` | `'deriveKey'` | `'deriveBits'` | `'wrapKey'` | `'unwrapKey'` | +| ----------------------------- | ----------- | ----------- | -------- | ---------- | ------------- | -------------- | ----------- | ------------- | +| `'AES-CBC'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'AES-CTR'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'AES-GCM'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'AES-KW'` | | | | | | | ✔ | ✔ | +| `'ECDH'` | | | | | ✔ | ✔ | | | +| `'ECDSA'` | | | ✔ | ✔ | | | | | +| `'HDKF'` | | | | | ✔ | ✔ | | | +| `'HMAC'` | | | ✔ | ✔ | | | | | +| `'PBKDF2'` | | | | | ✔ | ✔ | | | +| `'RSA-OAEP'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'RSA-PSS'` | | | ✔ | ✔ | | | | | +| `'RSASSA-PKCS1-v1_5'` | | | ✔ | ✔ | | | | | +| `'NODE-DSA'` 1 | | | ✔ | ✔ | | | | | +| `'NODE-DH'` 1 | | | | | ✔ | ✔ | | | +| `'NODE-SCRYPT'` 1 | | | | | ✔ | ✔ | | | +| `'NODE-ED25519'` 1 | | | ✔ | ✔ | | | | | +| `'NODE-ED448'` 1 | | | ✔ | ✔ | | | | | 1 Node.js-specific extension. ## Class: `CryptoKeyPair` + @@ -467,6 +479,7 @@ The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. ### `cryptoKeyPair.privateKey` + @@ -474,6 +487,7 @@ added: v15.0.0 * Type: {CryptoKey} A {CryptoKey} whose `type` will be `'private'`. ### `cryptoKeyPair.publicKey` + @@ -481,11 +495,13 @@ added: v15.0.0 * Type: {CryptoKey} A {CryptoKey} whose `type` will be `'public'`. ## Class: `SubtleCrypto` + ### `subtle.decrypt(algorithm, key, data)` + @@ -508,15 +524,18 @@ The algorithms currently supported include: * `'AES-GCM`' ### `subtle.deriveBits(algorithm, baseKey, length)` + + * `algorithm`: {EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} * `baseKey`: {CryptoKey} * `length`: {number} * Returns: {Promise} containing {ArrayBuffer} + Using the method and parameters specified in `algorithm` and the keying @@ -536,17 +555,20 @@ The algorithms currently supported include: 1 Node.js-specific extension ### `subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)` + + * `algorithm`: {EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} * `baseKey`: {CryptoKey} * `derivedKeyAlgorithm`: {HmacKeyGenParams|AesKeyGenParams} * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey} + Using the method and parameters specified in `algorithm`, and the keying @@ -569,6 +591,7 @@ The algorithms currently supported include: 1 Node.js-specific extension ### `subtle.digest(algorithm, data)` + @@ -592,6 +615,7 @@ If `algorithm` is provided as an {Object}, it must have a `name` property whose value is one of the above. ### `subtle.encrypt(algorithm, key, data)` + @@ -613,6 +637,7 @@ The algorithms currently supported include: * `'AES-GCM`' ### `subtle.exportKey(format, key)` + + * `algorithm`: {RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|AesKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams|NodeEdKeyGenParams} + + * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey|CryptoKeyPair} Using the method and parameters provided in `algorithm`, `subtle.generateKey()` @@ -704,6 +733,7 @@ The {CryptoKey} (secret key) generating algorithms supported include: 1 Non-standard Node.js extension ### `subtle.importKey(format, keyData, algorithm, extractable, keyUsages)` + + * `algorithm`: {RsaHashedImportParams|EcKeyImportParams|HmacImportParams|AesImportParams|Pbkdf2ImportParams|NodeDsaImportParams|NodeDhImportParams|NodeScryptImportParams|NodeEdKeyImportParams} + + * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey} The `subtle.importKey()` method attempts to interpret the provided `keyData` @@ -734,38 +768,41 @@ If importing a `'PBKDF2'` key, `extractable` must be `false`. The algorithms currently supported include: -| Key Type | `'spki'` | `'pkcs8'` | `'jwk'` | `'raw'` | -| --------------------- | -------- | --------- | ------- | ------- | -| `'AES-CBC'` | | | ✔ | ✔ | -| `'AES-CTR'` | | | ✔ | ✔ | -| `'AES-GCM'` | | | ✔ | ✔ | -| `'AES-KW'` | | | ✔ | ✔ | -| `'ECDH'` | ✔ | ✔ | ✔ | ✔ | -| `'ECDSA'` | ✔ | ✔ | ✔ | ✔ | -| `'HDKF'` | | | | ✔ | -| `'HMAC'` | | | ✔ | ✔ | -| `'PBKDF2'` | | | | ✔ | -| `'RSA-OAEP'` | ✔ | ✔ | ✔ | | -| `'RSA-PSS'` | ✔ | ✔ | ✔ | | -| `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | -| `'NODE-DSA'` 1 | ✔ | ✔ | | | -| `'NODE-DH'` 1 | ✔ | ✔ | | | -| `'NODE-SCRYPT'` 1 | | | | ✔ | -| `'NODE-ED25519'` 1 | ✔ | ✔ | ✔ | ✔ | -| `'NODE-ED448'` 1 | ✔ | ✔ | ✔ | ✔ | +| Key Type | `'spki'` | `'pkcs8'` | `'jwk'` | `'raw'` | +| ----------------------------- | -------- | --------- | ------- | ------- | +| `'AES-CBC'` | | | ✔ | ✔ | +| `'AES-CTR'` | | | ✔ | ✔ | +| `'AES-GCM'` | | | ✔ | ✔ | +| `'AES-KW'` | | | ✔ | ✔ | +| `'ECDH'` | ✔ | ✔ | ✔ | ✔ | +| `'ECDSA'` | ✔ | ✔ | ✔ | ✔ | +| `'HDKF'` | | | | ✔ | +| `'HMAC'` | | | ✔ | ✔ | +| `'PBKDF2'` | | | | ✔ | +| `'RSA-OAEP'` | ✔ | ✔ | ✔ | | +| `'RSA-PSS'` | ✔ | ✔ | ✔ | | +| `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | +| `'NODE-DSA'` 1 | ✔ | ✔ | | | +| `'NODE-DH'` 1 | ✔ | ✔ | | | +| `'NODE-SCRYPT'` 1 | | | | ✔ | +| `'NODE-ED25519'` 1 | ✔ | ✔ | ✔ | ✔ | +| `'NODE-ED448'` 1 | ✔ | ✔ | ✔ | ✔ | 1 Node.js-specific extension ### `subtle.sign(algorithm, key, data)` + + * `algorithm`: {RsaSignParams|RsaPssParams|EcdsaParams|HmacParams|NodeDsaSignParams} * `key`: {CryptoKey} * `data`: {ArrayBuffer|TypedArray|DataView|Buffer} * Returns: {Promise} containing {ArrayBuffer} + Using the method and parameters given by `algorithm` and the keying material @@ -786,6 +823,7 @@ The algorithms currently supported include: 1 Non-standard Node.js extension ### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)` + @@ -793,12 +831,16 @@ added: v15.0.0 * `format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `wrappedKey`: {ArrayBuffer|TypedArray|DataView|Buffer} * `unwrappingKey`: {CryptoKey} + + * `unwrapAlgo`: {RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams|AesKwParams} * `unwrappedKeyAlgo`: {RsaHashedImportParams|EcKeyImportParams|HmacImportParams|AesImportParams} + + * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey} In cryptography, "wrapping a key" refers to exporting and then encrypting the @@ -836,16 +878,19 @@ The unwrapped key algorithms supported include: 1 Non-standard Node.js extension ### `subtle.verify(algorithm, key, signature, data)` + + * `algorithm`: {RsaSignParams|RsaPssParams|EcdsaParams|HmacParams|NodeDsaSignParams} * `key`: {CryptoKey} * `signature`: {ArrayBuffer|TypedArray|DataView|Buffer} * `data`: {ArrayBuffer|TypedArray|DataView|Buffer} * Returns: {Promise} containing {boolean} + Using the method and parameters given in `algorithm` and the keying material @@ -866,6 +911,7 @@ The algorithms currently supported include: 1 Non-standard Node.js extension ### `subtle.wrapKey(format, key, wrappingKey, wrapAlgo)` + @@ -901,11 +947,13 @@ the various {SubtleCrypto} methods. While described here as "classes", they are simple JavaScript dictionary objects. ### Class: `AesCbcParams` + #### `aesCbcParams.iv` + @@ -916,6 +964,7 @@ Provides the initialization vector. It must be exactly 16-bytes in length and should be unpredictable and cryptographically random. #### `aesCbcParams.name` + @@ -923,11 +972,13 @@ added: v15.0.0 * Type: {string} Must be `'AES-CBC'`. ### Class: `AesCtrParams` + #### `aesCtrParams.counter` + @@ -940,6 +991,7 @@ The `AES-CTR` method uses the rightmost `length` bits of the block as the counter and the remaining bits as the nonce. #### `aesCtrParams.length` + @@ -948,6 +1000,7 @@ added: v15.0.0 to be used as the counter. #### `aesCtrParams.name` + @@ -955,11 +1008,13 @@ added: v15.0.0 * Type: {string} Must be `'AES-CTR'`. ### Class: `AesGcmParams` + #### `aesGcmParams.additionalData` + @@ -971,6 +1026,7 @@ encrypted but is included in the authentication of the data. The use of `additionalData` is optional. #### `aesGcmParams.iv` + @@ -982,6 +1038,7 @@ using a given key. It is recommended by the AES-GCM specification that this contain at least 12 random bytes. #### `aesGcmParams.name` + @@ -989,6 +1046,7 @@ added: v15.0.0 * Type: {string} Must be `'AES-GCM'`. #### `aesGcmParams.tagLength` + @@ -998,11 +1056,13 @@ added: v15.0.0 `128`. **Default:** `128`. ### Class: `AesImportParams` + #### `aesImportParams.name` + @@ -1011,11 +1071,13 @@ added: v15.0.0 `'AES-KW'`. ### Class: `AesKeyGenParams` + #### `aesKeyGenParams.length` + @@ -1026,6 +1088,7 @@ The length of the AES key to be generated. This must be either `128`, `192`, or `256`. #### `aesKeyGenParams.name` + @@ -1034,11 +1097,13 @@ added: v15.0.0 `'AES-KW'` ### Class: `AesKwParams` + #### `aesKwParams.name` + @@ -1046,11 +1111,13 @@ added: v15.0.0 * Type: {string} Must be `'AES-KW'`. ### Class: `EcdhKeyDeriveParams` + #### `ecdhKeyDeriveParams.name` + @@ -1058,6 +1125,7 @@ added: v15.0.0 * Type: {string} Must be `'ECDH'`. #### `ecdhKeyDeriveParams.public` + @@ -1070,11 +1138,13 @@ The `ecdhKeyDeriveParams.public` property is set to the other parties public key. ### Class: `EcdsaParams` + #### `ecdsaParams.hash` + @@ -1092,6 +1162,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `ecdsaParams.name` + @@ -1099,11 +1170,13 @@ added: v15.0.0 * Type: {string} Must be `'ECDSA'`. ### Class: `EcKeyGenParams` + #### `ecKeyGenParams.name` + @@ -1111,6 +1184,7 @@ added: v15.0.0 * Type: {string} Must be one of `'ECDSA'` or `'ECDH'`. #### `ecKeyGenParams.namedCurve` + @@ -1119,11 +1193,13 @@ added: v15.0.0 `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`. ### Class: `EcKeyImportParams` + #### `ecKeyImportParams.name` + @@ -1131,6 +1207,7 @@ added: v15.0.0 * Type: {string} Must be one of `'ECDSA'` or `'ECDH'`. #### `ecKeyImportParams.namedCurve` + @@ -1139,11 +1216,13 @@ added: v15.0.0 `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`. ### Class: `HkdfParams` + #### `hkdfParams.hash` + @@ -1161,6 +1240,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `hkdfParams.info` + @@ -1171,6 +1251,7 @@ Provides application-specific contextual input to the HKDF algorithm. This can be zero-length but must be provided. #### `hkdfParams.name` + @@ -1178,6 +1259,7 @@ added: v15.0.0 * Type: {string} Must be `'HKDF'`. #### `hkdfParams.salt` + @@ -1190,11 +1272,13 @@ output of the digest function (for instance, if using `'SHA-256'` as the digest, the salt should be 256-bits of random data). ### Class: `HmacImportParams` + #### `hmacImportParams.hash` + @@ -1212,6 +1296,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `hmacImportParams.length` + @@ -1222,6 +1307,7 @@ The optional number of bits in the HMAC key. This is optional and should be omitted for most cases. #### `hmacImportParams.name` + @@ -1229,11 +1315,13 @@ added: v15.0.0 * Type: {string} Must be `'HMAC'`. ### Class: `HmacKeyGenParams` + #### `hmacKeyGenParams.hash` + @@ -1251,6 +1339,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `hmacKeyGenParams.length` + @@ -1262,6 +1351,7 @@ the length will be determined by the hash algorithm used. This is optional and should be omitted for most cases. #### `hmacKeyGenParams.name` + @@ -1269,11 +1359,13 @@ added: v15.0.0 * Type: {string} Must be `'HMAC'`. ### Class: `HmacParams` + #### `hmacParams.name` + @@ -1281,11 +1373,13 @@ added: v15.0.0 * Type: {string} Must be `'HMAC'`. ### Class: `Pbkdf2ImportParams` + #### `pbkdf2ImportParams.name` + @@ -1293,11 +1387,13 @@ added: v15.0.0 * Type: {string} Must be `'PBKDF2'` ### Class: `Pbkdf2Params` + #### `pbkdb2Params.hash` + @@ -1315,6 +1411,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `pbkdf2Params.iterations` + @@ -1324,6 +1421,7 @@ added: v15.0.0 The number of iterations the PBKDF2 algorithm should make when deriving bits. #### `pbkdf2Params.name` + @@ -1331,6 +1429,7 @@ added: v15.0.0 * Type: {string} Must be `'PBKDF2'`. #### `pbkdf2Params.salt` + @@ -1340,11 +1439,13 @@ added: v15.0.0 Should be at least 16 random or pseudorandom bytes. ### Class: `RsaHashedImportParams` + #### `rsaHashedImportParams.hash` + @@ -1362,6 +1463,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `rsaHashedImportParams.name` + @@ -1370,11 +1472,13 @@ added: v15.0.0 `'RSA-OAEP'`. ### Class: `RsaHashedKeyGenParams` + #### `rsaHashedKeyGenParams.hash` + @@ -1392,6 +1496,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `rsaHashedKeyGenParams.modulusLength` + @@ -1402,6 +1507,7 @@ The length in bits of the RSA modulus. As a best practice, this should be at least `2048`. #### `rsaHashedKeyGenParams.name` + @@ -1410,6 +1516,7 @@ added: v15.0.0 `'RSA-OAEP'`. #### `rsaHashedKeyGenParams.publicExponent` + @@ -1423,11 +1530,13 @@ there is reason to use a different value, use `new Uint8Array([1, 0, 1])` (65537) as the public exponent. ### Class: `RsaOaepParams` + #### rsaOaepParams.label + @@ -1440,6 +1549,7 @@ to the generated ciphertext. The `rsaOaepParams.label` parameter is optional. #### rsaOaepParams.name + @@ -1447,11 +1557,13 @@ added: v15.0.0 * Type: {string} must be `'RSA-OAEP'`. ### Class: `RsaPssParams` + #### `rsaPssParams.name` + @@ -1459,6 +1571,7 @@ added: v15.0.0 * Type: {string} Must be `'RSA-PSS'`. #### `rsaPssParams.saltLength` + @@ -1468,11 +1581,13 @@ added: v15.0.0 The length (in bytes) of the random salt to use. ### Class: `RsaSignParams` + #### `rsaSignParams.name` + @@ -1492,6 +1607,7 @@ not supported by other WebCrypto implementations and reduce the portability of code to other environments. ### `NODE-DH` Algorithm + @@ -1500,11 +1616,13 @@ The `NODE-DH` algorithm is the common implementation of Diffie-Hellman key agreement. #### Class: `NodeDhImportParams` + ##### `nodeDhImportParams.name` + @@ -1512,11 +1630,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DH'`. #### Class: `NodeDhKeyGenParams` + ##### `nodeDhKeyGenParams.generator` + @@ -1524,6 +1644,7 @@ added: v15.0.0 * Type: {number} A custom generator. ##### `nodeDhKeyGenParams.group` + @@ -1531,6 +1652,7 @@ added: v15.0.0 * Type: {string} The Diffie-Hellman group name. ##### `nodeDhKeyGenParams.prime` + @@ -1538,6 +1660,7 @@ added: v15.0.0 * Type: {Buffer} The prime parameter. ##### `nodeDhKeyGenParams.primeLength` + @@ -1545,11 +1668,13 @@ added: v15.0.0 * Type: {number} The length in bits of the prime. #### Class: NodeDhDeriveBitsParams + ##### `nodeDhDeriveBitsParams.public` + @@ -1557,6 +1682,7 @@ added: v15.0.0 * Type: {CryptoKey} The other parties public key. ### `NODE-DSA` Algorithm + @@ -1565,11 +1691,13 @@ The `NODE-DSA` algorithm is the common implementation of the DSA digital signature algorithm. #### Class: `NodeDsaImportParams` + ##### `nodeDsaImportParams.hash` + @@ -1587,6 +1715,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. ##### `nodeDsaImportParams.name` + @@ -1594,11 +1723,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DSA'`. #### Class: `NodeDsaKeyGenParams` + ##### `nodeDsaKeyGenParams.divisorLength` + @@ -1608,6 +1739,7 @@ added: v15.0.0 The optional length in bits of the DSA divisor. ##### `nodeDsaKeyGenParams.hash` + @@ -1625,6 +1757,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. ##### `nodeDsaKeyGenParams.modulusLength` + @@ -1635,6 +1768,7 @@ The length in bits of the DSA modulus. As a best practice, this should be at least `2048`. ##### `nodeDsaKeyGenParams.name` + @@ -1642,11 +1776,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DSA'`. #### Class: `NodeDsaSignParams` + ##### `nodeDsaSignParams.name` + @@ -1654,16 +1790,19 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DSA'` ### `NODE-ED25519` and `NODE-ED448` Algorithms + #### Class: `NodeEdKeyGenParams` + ##### `nodeEdKeyGenParams.name` + @@ -1671,6 +1810,7 @@ added: v15.8.0 * Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'` or `'ECDH'`. ##### `nodeEdKeyGenParams.namedCurve` + @@ -1679,11 +1819,13 @@ added: v15.8.0 `'NODE-X25519'`, or `'NODE-X448'`. #### Class: `NodeEdKeyImportParams` + ##### `nodeEdKeyImportParams.name` + @@ -1693,6 +1835,7 @@ added: v15.8.0 an `X25519` or `X448` key. ##### `nodeEdKeyImportParams.namedCurve` + @@ -1701,6 +1844,7 @@ added: v15.8.0 `'NODE-X25519'`, or `'NODE-X448'`. ##### `nodeEdKeyImportParams.public` + @@ -1711,6 +1855,7 @@ The `public` parameter is used to specify that the `'raw'` format key is to be interpreted as a public key. **Default:** `false`. ### `NODE-SCRYPT` Algorithm + @@ -1719,11 +1864,13 @@ The `NODE-SCRYPT` algorithm is the common implementation of the scrypt key derivation algorithm. #### Class: `NodeScryptImportParams` + ##### `nodeScryptImportParams.name` + @@ -1731,11 +1878,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-SCRYPT'`. #### Class: `NodeScryptParams` + ##### `nodeScryptParams.encoding` + @@ -1743,6 +1892,7 @@ added: v15.0.0 * Type: {string} The string encoding when `salt` is a string. ##### `nodeScryptParams.maxmem` + @@ -1751,6 +1901,7 @@ added: v15.0.0 `127 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`. ##### `nodeScryptParams.N` + @@ -1759,6 +1910,7 @@ added: v15.0.0 greater than 1. **Default:** `16384`. ##### `nodeScryptParams.p` + @@ -1766,6 +1918,7 @@ added: v15.0.0 * Type: {number} Parallelization parameter. **Default:** `1`. ##### `nodeScryptParams.r` + @@ -1773,6 +1926,7 @@ added: v15.0.0 * Type: {number} Block size parameter. **Default:** `8`. ##### `nodeScryptParams.salt` + diff --git a/doc/api/webstreams.md b/doc/api/webstreams.md index fa10dcf4e2213b..14909704f384f1 100644 --- a/doc/api/webstreams.md +++ b/doc/api/webstreams.md @@ -98,16 +98,19 @@ const stream = new ReadableStream({ ## API ### Class: `ReadableStream` + #### `new ReadableStream([underlyingSource [, strategy]])` + + * `underlyingSource` {Object} * `start` {Function} A user-defined function that is invoked immediately when the `ReadableStream` is created. @@ -133,9 +136,11 @@ added: v16.5.0 chunk of data. * `chunk` {any} * Returns: {number} + #### `readableStream.locked` + @@ -148,6 +153,7 @@ switch to `true` while there is an active reader consuming the stream's data. #### `readableStream.cancel([reason])` + @@ -157,6 +163,7 @@ added: v16.5.0 been completed. #### `readableStream.getReader([options])` + @@ -188,6 +195,7 @@ reader.read().then(console.log); Causes the `readableStream.locked` to be `true`. #### `readableStream.pipeThrough(transform[, options])` + @@ -270,6 +278,7 @@ const transformedStream = stream.pipeThrough(transform); ``` #### `readableStream.pipeTo(destination, options)` + @@ -292,11 +301,12 @@ Causes the `readableStream.locked` to be `true` while the pipe operation is active. #### `readableStream.tee()` + -* Returns: {ReadableStream[]} +* Returns: {ReadableStream\[]} Returns a pair of new {ReadableStream} instances to which this `ReadableStream`'s data will be forwarded. Each will receive the @@ -305,6 +315,7 @@ same data. Causes the `readableStream.locked` to be `true`. #### `readableStream.values([options])` + @@ -373,6 +384,7 @@ port2.postMessage(stream, [stream]); ``` ### Class: `ReadableStreamDefaultReader` + @@ -384,6 +396,7 @@ values, which allows the {ReadableStream} to work with generally any JavaScript value. #### `new ReadableStreamDefaultReader(stream)` + @@ -394,6 +407,7 @@ Creates a new {ReadableStreamDefaultReader} that is locked to the given {ReadableStream}. #### `readableStreamDefaultReader.cancel([reason])` + @@ -405,6 +419,7 @@ Cancels the {ReadableStream} and returns a promise that is fulfilled when the underlying stream has been canceled. #### `readableStreamDefaultReader.closed` + @@ -413,6 +428,7 @@ added: v16.5.0 {ReadableStream} is closed or this reader's lock is released. #### `readableStreamDefaultReader.read()` + @@ -426,6 +442,7 @@ and returns a promise that is fulfilled with the data once it is available. #### `readableStreamDefaultReader.releaseLock()` + @@ -433,13 +450,14 @@ added: v16.5.0 Releases this reader's lock on the underlying {ReadableStream}. ### Class: `ReadableStreamBYOBReader` + The `ReadableStreamBYOBReader` is an alternative consumer for byte-oriented {ReadableStream}'s (those that are created with -`underlyingSource.type` set equal to `'bytes`` when the +`underlyingSource.type` set equal to `'bytes'` when the `ReadableStream` was created). The `BYOB` is short for "bring your own buffer". This is a @@ -505,6 +523,7 @@ console.log(Buffer.from(data).toString()); ``` #### `new ReadableStreamBYOBReader(stream)` + @@ -515,6 +534,7 @@ Creates a new `ReadableStreamBYOBReader` that is locked to the given {ReadableStream}. #### `readableStreamBYOBReader.cancel([reason])` + @@ -526,6 +546,7 @@ Cancels the {ReadableStream} and returns a promise that is fulfilled when the underlying stream has been canceled. #### `readableStreamBYOBReader.closed` + @@ -534,6 +555,7 @@ added: v16.5.0 {ReadableStream} is closed or this reader's lock is released. #### `readableStreamBYOBReader.read(view)` + @@ -554,11 +576,12 @@ callbacks. These types of `Buffer`s use a shared underlying {ArrayBuffer} object that contains all of the data from all of the pooled `Buffer` instances. When a `Buffer`, {TypedArray}, or {DataView} is passed in to `readableStreamBYOBReader.read()`, -the view's underlying `ArrayBuffer` is *detached*, invalidating +the view's underlying `ArrayBuffer` is _detached_, invalidating all existing views that may exist on that `ArrayBuffer`. This can have disastrous consequences for your application. #### `readableStreamBYOBReader.releaseLock()` + @@ -566,6 +589,7 @@ added: v16.5.0 Releases this reader's lock on the underlying {ReadableStream}. ### Class: `ReadableStreamDefaultController` + @@ -576,6 +600,7 @@ the internal state and management of the stream's queue. The implementation for `ReadableStream`s that are not byte-oriented. #### `readableStreamDefaultController.close()` + @@ -583,6 +608,7 @@ added: v16.5.0 Closes the {ReadableStream} to which this controller is associated. #### `readableStreamDefaultController.desiredSize` + @@ -593,6 +619,7 @@ Returns the amount of data remaining to fill the {ReadableStream}'s queue. #### `readableStreamDefaultController.enqueue(chunk)` + @@ -602,6 +629,7 @@ added: v16.5.0 Appends a new chunk of data to the {ReadableStream}'s queue. #### `readableStreamDefaultController.error(error)` + @@ -611,6 +639,7 @@ added: v16.5.0 Signals an error that causes the {ReadableStream} to error and close. ### Class: `ReadableByteStreamController` + @@ -620,6 +649,7 @@ the internal state and management of the stream's queue. The `ReadableByteStreamController` is for byte-oriented `ReadableStream`s. #### `readableByteStreamController.byobRequest` + @@ -627,6 +657,7 @@ added: v16.5.0 * Type: {ReadableStreamBYOBRequest} #### `readableByteStreamController.close()` + @@ -634,6 +665,7 @@ added: v16.5.0 Closes the {ReadableStream} to which this controller is associated. #### `readableByteStreamController.desiredSize` + @@ -644,6 +676,7 @@ Returns the amount of data remaining to fill the {ReadableStream}'s queue. #### `readableByteStreamController.enqueue(chunk)` + @@ -653,6 +686,7 @@ added: v16.5.0 Appends a new chunk of data to the {ReadableStream}'s queue. #### `readableByteStreamController.error(error)` + @@ -662,6 +696,7 @@ added: v16.5.0 Signals an error that causes the {ReadableStream} to error and close. ### Class: `ReadableStreamBYOBRequest` + @@ -677,6 +712,7 @@ and provides methods for signaling that the data has been provided. #### `readableStreamBYOBRequest.respond(bytesWritten)` + @@ -687,6 +723,7 @@ Signals that a `bytesWritten` number of bytes have been written to `readableStreamBYOBRequest.view`. #### `readableStreamBYOBRequest.respondWithNewView(view)` + @@ -697,6 +734,7 @@ Signals that the request has been fulfilled with bytes written to a new `Buffer`, `TypedArray`, or `DataView`. #### `readableStreamBYOBRequest.view` + @@ -704,6 +742,7 @@ added: v16.5.0 * Type: {Buffer|TypedArray|DataView} ### Class: `WritableStream` + @@ -725,6 +764,7 @@ await stream.getWriter().write('Hello World'); ``` #### `new WritableStream([underlyingSink[, strategy]])` + @@ -746,7 +786,7 @@ added: v16.5.0 the `WritableStream`. * `reason` {any} * Returns: A promise fulfilled with `undefined`. - * `type` {any} The `type` option is reserved for future use and *must* be + * `type` {any} The `type` option is reserved for future use and _must_ be undefined. * `strategy` {Object} * `highWaterMark` {number} The maximum internal queue size before backpressure @@ -757,6 +797,7 @@ added: v16.5.0 * Returns: {number} #### `writableStream.abort([reason])` + @@ -768,6 +809,7 @@ Abruptly terminates the `WritableStream`. All queued writes will be canceled with their associated promises rejected. #### `writableStream.close()` + @@ -777,6 +819,7 @@ added: v16.5.0 Closes the `WritableStream` when no additional writes are expected. #### `writableStream.getWriter()` + @@ -787,6 +830,7 @@ Creates and creates a new writer instance that can be used to write data into the `WritableStream`. #### `writableStream.locked` + @@ -814,11 +858,13 @@ port2.postMessage(stream, [stream]); ``` ### Class: `WritableStreamDefaultWriter` + #### `new WritableStreamDefaultWriter(stream)` + @@ -829,6 +875,7 @@ Creates a new `WritableStreamDefaultWriter` that is locked to the given `WritableStream`. #### `writableStreamDefaultWriter.abort([reason])` + @@ -840,6 +887,7 @@ Abruptly terminates the `WritableStream`. All queued writes will be canceled with their associated promises rejected. #### `writableStreamDefaultWriter.close()` + @@ -849,6 +897,7 @@ added: v16.5.0 Closes the `WritableStream` when no additional writes are expected. #### `writableStreamDefaultWriter.closed` + @@ -858,6 +907,7 @@ added: v16.5.0 released. #### `writableStreamDefaultWriter.desiredSize` + @@ -867,6 +917,7 @@ added: v16.5.0 The amount of data required to fill the {WritableStream}'s queue. #### `writableStreamDefaultWriter.ready` + @@ -875,6 +926,7 @@ added: v16.5.0 writer is ready to be used. #### `writableStreamDefaultWriter.releaseLock()` + @@ -882,6 +934,7 @@ added: v16.5.0 Releases this writer's lock on the underlying {ReadableStream}. #### `writableStreamDefaultWriter.write([chunk])` + @@ -892,6 +945,7 @@ added: v16.5.0 Appends a new chunk of data to the {WritableStream}'s queue. ### Class: `WritableStreamDefaultController` + @@ -904,6 +958,7 @@ internal state. * Type: {any} The `reason` value passed to `writableStream.abort()`. #### `writableStreamDefaultController.error(error)` + @@ -920,6 +975,7 @@ with currently pending writes canceled. write or close operations when a {WritableStream} is aborted. ### Class: `TransformStream` + @@ -947,6 +1003,7 @@ await Promise.all([ ``` #### `new TransformStream([transformer[, writableStrategy[, readableStrategy]]])` + @@ -968,9 +1025,9 @@ added: v16.5.0 * `controller` {TransformStreamDefaultController} * Returns: A promise fulfilled with `undefined`. * `readableType` {any} the `readableType` option is reserved for future use - and *must* be `undefined. + and _must_ be `undefined`. * `writableType` {any} the `writableType` option is reserved for future use - and *must* be `undefined. + and _must_ be `undefined`. * `writableStrategy` {Object} * `highWaterMark` {number} The maximum internal queue size before backpressure is applied. @@ -987,6 +1044,7 @@ added: v16.5.0 * Returns: {number} #### `transformStream.readable` + @@ -994,6 +1052,7 @@ added: v16.5.0 * Type: {ReadableStream} #### `transformStream.writable` + @@ -1018,6 +1077,7 @@ port2.postMessage(stream, [stream]); ``` ### Class: `TransformStreamDefaultController` + @@ -1026,6 +1086,7 @@ The `TransformStreamDefaultController` manages the internal state of the `TransformStream`. #### `transformStreamDefaultController.desiredSize` + @@ -1035,6 +1096,7 @@ added: v16.5.0 The amount of data required to fill the readable side's queue. #### `transformStreamDefaultController.enqueue([chunk])` + @@ -1044,6 +1106,7 @@ added: v16.5.0 Appends a chunk of data to the readable side's queue. #### `transformStreamDefaultController.error([reason])` + @@ -1055,6 +1118,7 @@ while processing the transform data, causing both sides to be abruptly closed. #### `transformStreamDefaultController.terminate()` + @@ -1063,11 +1127,13 @@ Closes the readable side of the transport and causes the writable side to be abruptly closed with an error. ### Class: `ByteLengthQueuingStrategy` + #### `new ByteLengthQueuingStrategy(options)` + @@ -1076,6 +1142,7 @@ added: v16.5.0 * `highWaterMark` {number} #### `byteLengthQueuingStrategy.highWaterMark` + @@ -1083,6 +1150,7 @@ added: v16.5.0 * Type: {number} #### `byteLengthQueuingStrategy.size` + @@ -1092,11 +1160,13 @@ added: v16.5.0 * Returns: {number} ### Class: `CountQueuingStrategy` + #### `new CountQueuingStrategy(options)` + @@ -1105,6 +1175,7 @@ added: v16.5.0 * `highWaterMark` {number} #### `countQueuingStrategy.highWaterMark` + @@ -1112,6 +1183,7 @@ added: v16.5.0 * Type: {number} #### `countQueuingStrategy.size` + @@ -1121,11 +1193,13 @@ added: v16.5.0 * Returns: {number} ### Class: `TextEncoderStream` + #### `new TextEncoderStream()` + @@ -1133,6 +1207,7 @@ added: v16.6.0 Creates a new `TextEncoderStream` instance. #### `textEncoderStream.encoding` + @@ -1142,6 +1217,7 @@ added: v16.6.0 The encoding supported by the `TextEncoderStream` instance. #### `textEncoderStream.readable` + @@ -1149,6 +1225,7 @@ added: v16.6.0 * Type: {ReadableStream} #### `textEncoderStream.writable` + @@ -1156,11 +1233,13 @@ added: v16.6.0 * Type: {WritableStream} ### Class: `TextDecoderStream` + #### `new TextDecoderStream([encoding[, options]])` + @@ -1177,6 +1256,7 @@ added: v16.6.0 Creates a new `TextDecoderStream` instance. #### `textDecoderStream.encoding` + @@ -1186,6 +1266,7 @@ added: v16.6.0 The encoding supported by the `TextDecoderStream` instance. #### `textDecoderStream.fatal` + @@ -1196,6 +1277,7 @@ The value will be `true` if decoding errors result in a `TypeError` being thrown. #### `textDecoderStream.ignoreBOM` + @@ -1206,6 +1288,7 @@ The value will be `true` if the decoding result will include the byte order mark. #### `textDecoderStream.readable` + @@ -1213,6 +1296,7 @@ added: v16.6.0 * Type: {ReadableStream} #### `textDecoderStream.writable` + @@ -1220,6 +1304,7 @@ added: v16.6.0 * Type: {WritableStream} ### Utility Consumers + @@ -1248,6 +1333,7 @@ const { ``` #### `streamConsumers.arrayBuffer(stream)` + @@ -1257,6 +1343,7 @@ added: v16.7.0 contents of the stream. #### `streamConsumers.blob(stream)` + @@ -1266,6 +1353,7 @@ added: v16.7.0 of the stream. #### `streamConsumers.buffer(stream)` + @@ -1275,6 +1363,7 @@ added: v16.7.0 contents of the stream. #### `streamConsumers.json(stream)` + @@ -1284,6 +1373,7 @@ added: v16.7.0 UTF-8 encoded string that is then passed through `JSON.parse()`. #### `streamConsumers.text(stream)` + diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index bfd8248b8482e5..73cd29538da91f 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -62,6 +62,7 @@ Worker threads inherit non-process-specific options by default. Refer to specifically `argv` and `execArgv` options. ## `worker.getEnvironmentData(key)` + @@ -94,6 +95,7 @@ if (isMainThread) { ``` ## `worker.isMainThread` + @@ -115,6 +117,7 @@ if (isMainThread) { ``` ## `worker.markAsUntransferable(object)` + * `port` {MessagePort} The message port to transfer. + * `contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method. @@ -178,6 +183,7 @@ However, the created `MessagePort` no longer inherits from events using it. ## `worker.parentPort` + @@ -209,6 +215,7 @@ if (isMainThread) { ``` ## `worker.receiveMessageOnPort(port)` + @@ -279,6 +288,7 @@ new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV }) ``` ## `worker.setEnvironmentData(key[, value])` + @@ -296,6 +306,7 @@ The `worker.setEnvironmentData()` API sets the content of instances spawned from the current context. ## `worker.threadId` + @@ -307,6 +318,7 @@ An integer identifier for the current thread. On the corresponding worker object This value is unique for each [`Worker`][] instance inside a single process. ## `worker.workerData` + @@ -328,6 +340,7 @@ if (isMainThread) { ``` ## Class: `BroadcastChannel extends EventTarget` + @@ -363,14 +376,16 @@ if (isMainThread) { ``` ### `new BroadcastChannel(name)` + * `name` {any} The name of the channel to connect to. Any JavaScript value - that can be converted to a string using ``${name}`` is permitted. + that can be converted to a string using `` `${name}` `` is permitted. ### `broadcastChannel.close()` + @@ -378,6 +393,7 @@ added: v15.4.0 Closes the `BroadcastChannel` connection. ### `broadcastChannel.onmessage` + @@ -386,6 +402,7 @@ added: v15.4.0 when a message is received. ### `broadcastChannel.onmessageerror` + @@ -394,6 +411,7 @@ added: v15.4.0 deserialized. ### `broadcastChannel.postMessage(message)` + @@ -401,16 +419,18 @@ added: v15.4.0 * `message` {any} Any cloneable JavaScript value. ### `broadcastChannel.ref()` + Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed -BroadcastChannel does *not* let the program exit if it's the only active handle +BroadcastChannel does _not_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect. ### `broadcastChannel.unref()` + @@ -420,6 +440,7 @@ is the only active handle in the event system. If the BroadcastChannel is already `unref()`ed calling `unref()` again has no effect. ## Class: `MessageChannel` + @@ -440,6 +461,7 @@ port2.postMessage({ foo: 'bar' }); ``` ## Class: `MessagePort` + @@ -482,6 +505,7 @@ port1.close(); ``` ### Event: `'message'` + @@ -495,6 +519,7 @@ Listeners on this event receive a clone of the `value` parameter as passed to `postMessage()` and no further arguments. ### Event: `'messageerror'` + @@ -524,6 +550,7 @@ The [`'close'` event][] is emitted on both `MessagePort` instances that are part of the channel. ### `port.postMessage(value[, transferList])` + * `value` {any} -* `transferList` {Object[]} +* `transferList` {Object\[]} Sends a JavaScript value to the receiving side of this channel. `value` is transferred in a way which is compatible with @@ -564,7 +591,7 @@ In particular, the significant differences to `JSON` are: * `value` may contain instances of builtin JS types such as `RegExp`s, `BigInt`s, `Map`s, `Set`s, etc. * `value` may contain typed arrays, both using `ArrayBuffer`s - and `SharedArrayBuffer`s. + and `SharedArrayBuffer`s. * `value` may contain [`WebAssembly.Module`][] instances. * `value` may not contain native (C++-backed) objects other than: * {CryptoKey}s, @@ -723,12 +750,13 @@ port2.postMessage(new URL('https://example.org')); ``` ### `port.ref()` + Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does -*not* let the program exit if it's the only active handle left (the default +_not_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect. If listeners are attached or removed using `.on('message')`, the port @@ -736,6 +764,7 @@ is `ref()`ed and `unref()`ed automatically depending on whether listeners for the event exist. ### `port.start()` + @@ -751,6 +780,7 @@ automatically calls `.start()`, but unsetting it lets messages queue up until a new handler is set or the port is discarded. ### `port.unref()` + @@ -764,6 +794,7 @@ If listeners are attached or removed using `.on('message')`, the port is listeners for the event exist. ## Class: `Worker` + @@ -839,6 +870,7 @@ if (isMainThread) { ``` ### `new Worker(filename[, options])` + @@ -949,6 +982,7 @@ The `'error'` event is emitted if the worker thread throws an uncaught exception. In that case, the worker is terminated. ### Event: `'exit'` + @@ -963,6 +997,7 @@ passed exit code. If the worker was terminated, the `exitCode` parameter is This is the final event emitted by any `Worker` instance. ### Event: `'message'` + @@ -977,6 +1012,7 @@ All messages sent from the worker thread are emitted before the [`'exit'` event][] is emitted on the `Worker` object. ### Event: `'messageerror'` + @@ -996,6 +1033,7 @@ The `'online'` event is emitted when the worker thread has started executing JavaScript code. ### `worker.getHeapSnapshot()` + * `utilization1` {Object} The result of a previous call to - `eventLoopUtilization()`. + `eventLoopUtilization()`. * `utilization2` {Object} The result of a previous call to - `eventLoopUtilization()` prior to `utilization1`. + `eventLoopUtilization()` prior to `utilization1`. * Returns {Object} * `idle` {number} * `active` {number} @@ -1076,28 +1116,31 @@ event][] emitted, and if called before this, or after the [`'exit'` event][], then all properties have the value of `0`. ### `worker.postMessage(value[, transferList])` + * `value` {any} -* `transferList` {Object[]} +* `transferList` {Object\[]} Send a message to the worker that is received via [`require('worker_threads').parentPort.on('message')`][]. See [`port.postMessage()`][] for more details. ### `worker.ref()` + Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does -*not* let the program exit if it's the only active handle left (the default +_not_ let the program exit if it's the only active handle left (the default behavior). If the worker is `ref()`ed, calling `ref()` again has no effect. ### `worker.resourceLimits` + @@ -1129,6 +1173,7 @@ inside the worker thread. If `stderr: true` was not passed to the [`process.stderr`][] stream. ### `worker.stdin` + @@ -1140,6 +1185,7 @@ writable stream. The data written to this stream will be made available in the worker thread as [`process.stdin`][]. ### `worker.stdout` + @@ -1152,6 +1198,7 @@ inside the worker thread. If `stdout: true` was not passed to the [`process.stdout`][] stream. ### `worker.terminate()` + @@ -1181,6 +1229,7 @@ it is available as [`require('worker_threads').threadId`][]. This value is unique for each `Worker` instance inside a single process. ### `worker.unref()` + diff --git a/doc/api/zlib.md b/doc/api/zlib.md index a2ce8fe682f976..85a0e02efb44e9 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -265,6 +265,7 @@ From `zlib/zconf.h`, modified for Node.js usage: The memory requirements for deflate are (in bytes): + ```js (1 << (windowBits + 2)) + (1 << (memLevel + 9)) ``` @@ -354,6 +355,7 @@ http.createServer((request, response) => { ``` ## Constants + @@ -412,6 +414,7 @@ Compression strategy. * `zlib.constants.Z_DEFAULT_STRATEGY` ### Brotli constants + @@ -588,6 +596,7 @@ added: v0.5.8 Compress data using deflate. ## Class: `zlib.DeflateRaw` + @@ -595,6 +604,7 @@ added: v0.5.8 Compress data using deflate, and do not append a `zlib` header. ## Class: `zlib.Gunzip` + @@ -620,6 +631,7 @@ added: v0.5.8 Compress data using gzip. ## Class: `zlib.Inflate` + @@ -653,6 +667,7 @@ Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header. ## Class: `zlib.ZlibBase` + @@ -696,6 +713,7 @@ the engine, before the bytes are processed (compressed or decompressed, as appropriate for the derived class). ### `zlib.close([callback])` + @@ -705,6 +723,7 @@ added: v0.9.4 Close the underlying handle. ### `zlib.flush([kind, ]callback)` + @@ -722,6 +741,7 @@ normal call to `.write()`, i.e. it will be queued up behind other pending writes and will only produce output when data is being read from the stream. ### `zlib.params(level, strategy, callback)` + @@ -736,6 +756,7 @@ Dynamically update the compression level and compression strategy. Only applicable to deflate algorithm. ### `zlib.reset()` + @@ -744,6 +765,7 @@ Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms. ## `zlib.constants` + @@ -751,6 +773,7 @@ added: v7.0.0 Provides an object enumerating Zlib-related constants. ## `zlib.createBrotliCompress([options])` + @@ -782,6 +807,7 @@ added: v0.5.8 Creates and returns a new [`Deflate`][] object. ## `zlib.createDeflateRaw([options])` + @@ -798,6 +824,7 @@ since passing `windowBits = 9` to zlib actually results in a compressed stream that effectively uses an 8-bit window only. ## `zlib.createGunzip([options])` + @@ -807,6 +834,7 @@ added: v0.5.8 Creates and returns a new [`Gunzip`][] object. ## `zlib.createGzip([options])` + @@ -817,6 +845,7 @@ Creates and returns a new [`Gzip`][] object. See [example][zlib.createGzip example]. ## `zlib.createInflate([options])` + @@ -826,6 +855,7 @@ added: v0.5.8 Creates and returns a new [`Inflate`][] object. ## `zlib.createInflateRaw([options])` + @@ -835,6 +865,7 @@ added: v0.5.8 Creates and returns a new [`InflateRaw`][] object. ## `zlib.createUnzip([options])` + @@ -856,6 +887,7 @@ Every method has a `*Sync` counterpart, which accept the same arguments, but without a callback. ### `zlib.brotliCompress(buffer[, options], callback)` + - -> Stability: 1 - Experimental - -* `readableStream` {ReadableStream} -* `options` {Object} - * `encoding` {string} - * `highWaterMark` {number} - * `objectMode` {boolean} - * `signal` {AbortSignal} -* Returns: {stream.Readable} - ### `stream.Readable.isDisturbed(stream)` +[^1]: Node.js 0.12 and older are intentionally omitted from this document + as their support has ended. -### Notes - -1Node.js 0.12 and older are intentionally omitted from this document -as their support has ended. - -2The V8 tests still require Python 2. To run these tests locally, -you can run `PYTHON2 ./configure.py` before running `make test-v8`, in the root -of this repository. On macOS, this also requires a full Xcode install, -not just the "command line tools" for Xcode. +[^2]: The V8 tests still require Python 2. To run these tests locally, you can + run `PYTHON2 ./configure.py` before running `make test-v8`, in the root + of this repository. On macOS, this also requires a full Xcode install, + not just the "command line tools" for Xcode. [ChromiumReleaseCalendar]: https://www.chromium.org/developers/calendar [Node.js CI]: https://ci.nodejs.org/job/node-test-pull-request/ From 91c3cf5d0a116c22647e132c8a02d3ee4607d9e9 Mon Sep 17 00:00:00 2001 From: Ray Wang Date: Thu, 14 Oct 2021 11:00:42 +0800 Subject: [PATCH 056/118] deps: V8: cherry-pick 422dc378a1da MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: [deserialization] Remove unnecessarily limit on buffer size 1. Now there is no serializer/deserializer-specific buffer size limit. 2. Update AUTHORS Ref: https://github.com/nodejs/node/issues/40059 Change-Id: Iad4c6d8f68a91ef21d3c404fb7945949e69ad9e2 Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/3170411 Reviewed-by: Jakob Kummerow Reviewed-by: Clemens Backes Commit-Queue: Jakob Kummerow Cr-Commit-Position: refs/heads/main@{#77084} Refs: https://github.com/v8/v8/commit/422dc378a1da528b97c9d69ae71ca4c9f318c970 PR-URL: https://github.com/nodejs/node/pull/40450 Fixes: https://github.com/nodejs/node/issues/40059 Reviewed-By: Michaël Zasso Reviewed-By: Colin Ihrig --- common.gypi | 2 +- deps/v8/AUTHORS | 27 +++++++++++++------------ deps/v8/src/api/api.cc | 26 ++---------------------- deps/v8/src/objects/value-serializer.cc | 2 +- 4 files changed, 18 insertions(+), 39 deletions(-) diff --git a/common.gypi b/common.gypi index 6862acc20b31c5..7bc2b3abf47019 100644 --- a/common.gypi +++ b/common.gypi @@ -36,7 +36,7 @@ # Reset this number to 0 on major V8 upgrades. # Increment by one for each non-official patch applied to deps/v8. - 'v8_embedder_string': '-node.13', + 'v8_embedder_string': '-node.14', ##### V8 defaults for Node.js ##### diff --git a/deps/v8/AUTHORS b/deps/v8/AUTHORS index ea786ddea4c085..35c49a01da884f 100644 --- a/deps/v8/AUTHORS +++ b/deps/v8/AUTHORS @@ -57,13 +57,12 @@ Alexis Campailla Allan Sandfeld Jensen Amos Lim Andreas Anyuru -Andrew Paprocki Andrei Kashcha +Andrew Paprocki Anna Henningsen Antoine du Hamel Anton Bikineev Bangfu Tao -Daniel Shelton Ben Coe Ben Newman Ben Noordhuis @@ -74,7 +73,6 @@ Brice Dobry Burcu Dogan Caitlin Potter Chao Wang -Craig Schlenter Charles Kerr Chengzhong Wu Choongwoo Han @@ -82,10 +80,12 @@ Chris Nardi Christopher A. Taylor Colin Ihrig Cong Zuo +Craig Schlenter Daniel Andersson Daniel Bevenius Daniel Dromboski Daniel James +Daniel Shelton Darshan Sen David Carlier David Manouchehri @@ -120,13 +120,13 @@ Ingvar Stepanyan Ioseb Dzmanashvili Isiah Meadows Jaime Bernardo -Jan de Mooij +James M Snell +James Pike Jan Krems +Jan de Mooij Janusz Majnert -Jay Freeman -James Pike -James M Snell Javad Amiri +Jay Freeman Jesper van den Ende Ji Qiu Jianghua Yang @@ -136,8 +136,8 @@ Joel Stanley Johan Bergström Jonathan Liu Julien Brianceau -Junha Park JunHo Seo +Junha Park Junming Huang Kang-Hao (Kenny) Lu Karl Skomski @@ -180,20 +180,21 @@ Oleksandr Chekhovskyi Oliver Dunk Paolo Giarrusso Patrick Gansterer +Paul Lind +Pavel Medvedev Peng Fei Peng Wu Peng-Yu Chen Peter Rybin Peter Varga Peter Wong -Paul Lind -Pavel Medvedev PhistucK Qingyan Li Qiuyi Zhang Rafal Krypa Raul Tambre Ray Glover +Ray Wang Refael Ackermann Rene Rebe Reza Yazdani @@ -218,11 +219,13 @@ Stefan Penner Stephan Hartmann Stephen Belanger Sylvestre Ledru +Takeshi Yoneda Taketoshi Aono Tao Liqiang Teddy Katz Thomas Young Tiancheng "Timothy" Gu +Tianping Yang Tobias Burnus Tobias Nießen Ujjwal Sharma @@ -246,13 +249,11 @@ Yi Wang Yong Wang Youfeng Hao Yu Yin -Yusif Khudhur Yuri Iozzelli +Yusif Khudhur Zac Hansen Zeynep Cankara Zhao Jiazhong Zheng Liu Zhongping Wang 柳荣一 -Tianping Yang -Takeshi Yoneda diff --git a/deps/v8/src/api/api.cc b/deps/v8/src/api/api.cc index 61e9ccfad5a071..1632be8f626d77 100644 --- a/deps/v8/src/api/api.cc +++ b/deps/v8/src/api/api.cc @@ -3283,7 +3283,6 @@ struct ValueDeserializer::PrivateData { : isolate(i), deserializer(i, data, delegate) {} i::Isolate* isolate; i::ValueDeserializer deserializer; - bool has_aborted = false; bool supports_legacy_wire_format = false; }; @@ -3293,16 +3292,8 @@ ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data, ValueDeserializer::ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size, Delegate* delegate) { - if (base::IsValueInRangeForNumericType(size)) { - private_ = new PrivateData( - reinterpret_cast(isolate), - base::Vector(data, static_cast(size)), delegate); - } else { - private_ = - new PrivateData(reinterpret_cast(isolate), - base::Vector(nullptr, 0), nullptr); - private_->has_aborted = true; - } + private_ = new PrivateData(reinterpret_cast(isolate), + base::Vector(data, size), delegate); } ValueDeserializer::~ValueDeserializer() { delete private_; } @@ -3312,15 +3303,6 @@ Maybe ValueDeserializer::ReadHeader(Local context) { ENTER_V8_NO_SCRIPT(isolate, context, ValueDeserializer, ReadHeader, Nothing(), i::HandleScope); - // We could have aborted during the constructor. - // If so, ReadHeader is where we report it. - if (private_->has_aborted) { - isolate->Throw(*isolate->factory()->NewError( - i::MessageTemplate::kDataCloneDeserializationError)); - has_pending_exception = true; - RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); - } - bool read_header = false; has_pending_exception = !private_->deserializer.ReadHeader().To(&read_header); RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool); @@ -3344,12 +3326,10 @@ void ValueDeserializer::SetSupportsLegacyWireFormat( } uint32_t ValueDeserializer::GetWireFormatVersion() const { - CHECK(!private_->has_aborted); return private_->deserializer.GetWireFormatVersion(); } MaybeLocal ValueDeserializer::ReadValue(Local context) { - CHECK(!private_->has_aborted); PREPARE_FOR_EXECUTION(context, ValueDeserializer, ReadValue, Value); i::MaybeHandle result; if (GetWireFormatVersion() > 0) { @@ -3366,14 +3346,12 @@ MaybeLocal ValueDeserializer::ReadValue(Local context) { void ValueDeserializer::TransferArrayBuffer(uint32_t transfer_id, Local array_buffer) { - CHECK(!private_->has_aborted); private_->deserializer.TransferArrayBuffer(transfer_id, Utils::OpenHandle(*array_buffer)); } void ValueDeserializer::TransferSharedArrayBuffer( uint32_t transfer_id, Local shared_array_buffer) { - CHECK(!private_->has_aborted); private_->deserializer.TransferArrayBuffer( transfer_id, Utils::OpenHandle(*shared_array_buffer)); } diff --git a/deps/v8/src/objects/value-serializer.cc b/deps/v8/src/objects/value-serializer.cc index 53bb0cf92736bf..8f0c587ae35a8a 100644 --- a/deps/v8/src/objects/value-serializer.cc +++ b/deps/v8/src/objects/value-serializer.cc @@ -1117,7 +1117,7 @@ ValueDeserializer::ValueDeserializer(Isolate* isolate, : isolate_(isolate), delegate_(delegate), position_(data.begin()), - end_(data.begin() + data.length()), + end_(data.end()), id_map_(isolate->global_handles()->Create( ReadOnlyRoots(isolate_).empty_fixed_array())) {} From 789fef1309db62694f04c4afdc0dde563e1c5e83 Mon Sep 17 00:00:00 2001 From: Ray Wang Date: Sun, 26 Sep 2021 17:22:25 +0800 Subject: [PATCH 057/118] src: throw error instead of assertion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40243 Fixes: https://github.com/nodejs/node/issues/40059 Reviewed-By: James M Snell Reviewed-By: Michaël Zasso --- src/node_buffer.cc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 0546e7a53fae90..48df1323ca7215 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -494,7 +494,12 @@ MaybeLocal New(Environment* env, size_t length) { if (length > 0) { CHECK_NOT_NULL(data); - CHECK(length <= kMaxLength); + // V8 currently only allows a maximum Typed Array index of max Smi. + if (length > kMaxLength) { + Isolate* isolate(env->isolate()); + isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate)); + return Local(); + } } auto free_callback = [](char* data, void* hint) { free(data); }; From 579f01c0a385f89e3c4cf9a20af868eba7c7cf22 Mon Sep 17 00:00:00 2001 From: Ray Wang Date: Tue, 5 Oct 2021 08:50:50 +0800 Subject: [PATCH 058/118] doc: describe buffer limit of v8.serialize MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40243 Fixes: https://github.com/nodejs/node/issues/40059 Reviewed-By: James M Snell Reviewed-By: Michaël Zasso --- doc/api/v8.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/doc/api/v8.md b/doc/api/v8.md index e94323e8a71712..ab46699158aba7 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -333,6 +333,10 @@ added: v8.0.0 Uses a [`DefaultSerializer`][] to serialize `value` into a buffer. +[`ERR_BUFFER_TOO_LARGE`][] will be thrown when trying to +serialize a huge object which requires buffer +larger than [`buffer.constants.MAX_LENGTH`][]. + ### `v8.deserialize(buffer)` @@ -18,11 +18,11 @@ The `AsyncLocalStorage` and `AsyncResource` classes are part of the `async_hooks` module: ```mjs -import async_hooks from 'async_hooks'; +import { AsyncLocalStorage, AsyncResource } from 'async_hooks'; ``` ```cjs -const async_hooks = require('async_hooks'); +const { AsyncLocalStorage, AsyncResource } = require('async_hooks'); ``` ## Class: `AsyncLocalStorage` diff --git a/doc/api/index.md b/doc/api/index.md index 0e7bf073d2843c..7aba47edcb35af 100644 --- a/doc/api/index.md +++ b/doc/api/index.md @@ -11,7 +11,7 @@
* [Assertion testing](assert.md) -* [Async\_context](async\_context.md) +* [Asynchronous context tracking](async\_context.md) * [Async hooks](async\_hooks.md) * [Buffer](buffer.md) * [C++ addons](addons.md) From 5593dd1b255f11205342e9c60537e3ff3ba95db0 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 21 Oct 2021 10:06:49 -0700 Subject: [PATCH 066/118] doc: fix macOS environment variables for ccache macOS requires `cc` and `c++` rather than `gcc` and `g++`. Closes: https://github.com/nodejs/node/issues/40542 PR-URL: https://github.com/nodejs/node/pull/40550 Fixes: https://github.com/nodejs/node/issues/40542 Reviewed-By: Geoffrey Booth Reviewed-By: Antoine du Hamel Reviewed-By: Luigi Pinca --- BUILDING.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/BUILDING.md b/BUILDING.md index c26cdfc9bec3dc..c12a45cfe30120 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -523,6 +523,8 @@ $ make test-only If you plan to frequently rebuild Node.js, especially if using several branches, installing `ccache` can help to greatly reduce build times. Set up with: +On GNU/Linux: + ```console $ sudo apt install ccache # for Debian/Ubuntu, included in most Linux distros $ ccache -o cache_dir= @@ -531,6 +533,16 @@ $ export CC="ccache gcc" # add to your .profile $ export CXX="ccache g++" # add to your .profile ``` +On macOS: + +```console +$ brew install ccache # see https://brew.sh +$ ccache -o cache_dir= +$ ccache -o max_size=5.0G +$ export CC="ccache cc" # add to ~/.zshrc or other shell config file +$ export CXX="ccache c++" # add to ~/.zshrc or other shell config file +``` + This will allow for near-instantaneous rebuilds even when switching branches. When modifying only the JS layer in `lib`, it is possible to externally load it From 0a7c4ff2488a3a555b8867ce1297f8ca97653f6a Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 21 Oct 2021 18:06:05 +0000 Subject: [PATCH 067/118] doc: simplify ccache instructions `ccache` has reasonable defaults for `max_size` and `cache_dir` so remove instructions to set those things explicitly. Change fenced code from `console` to `bash` for easier copy/paste. PR-URL: https://github.com/nodejs/node/pull/40550 Fixes: https://github.com/nodejs/node/issues/40542 Reviewed-By: Geoffrey Booth Reviewed-By: Antoine du Hamel Reviewed-By: Luigi Pinca --- BUILDING.md | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/BUILDING.md b/BUILDING.md index c12a45cfe30120..8a8c544d46f9ac 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -525,22 +525,18 @@ installing `ccache` can help to greatly reduce build times. Set up with: On GNU/Linux: -```console -$ sudo apt install ccache # for Debian/Ubuntu, included in most Linux distros -$ ccache -o cache_dir= -$ ccache -o max_size=5.0G -$ export CC="ccache gcc" # add to your .profile -$ export CXX="ccache g++" # add to your .profile +```bash +sudo apt install ccache # for Debian/Ubuntu, included in most Linux distros +export CC="ccache gcc" # add to your .profile +export CXX="ccache g++" # add to your .profile ``` On macOS: -```console -$ brew install ccache # see https://brew.sh -$ ccache -o cache_dir= -$ ccache -o max_size=5.0G -$ export CC="ccache cc" # add to ~/.zshrc or other shell config file -$ export CXX="ccache c++" # add to ~/.zshrc or other shell config file +```bash +brew install ccache # see https://brew.sh +export CC="ccache cc" # add to ~/.zshrc or other shell config file +export CXX="ccache c++" # add to ~/.zshrc or other shell config file ``` This will allow for near-instantaneous rebuilds even when switching branches. From 0003cb6b3bb25f0450c9b3a3d0cff3763fafbcea Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 22 Oct 2021 10:11:06 -0700 Subject: [PATCH 068/118] meta: consolidate AUTHORS entries for darai0512 PR-URL: https://github.com/nodejs/node/pull/40569 Reviewed-By: Luigi Pinca Reviewed-By: Zijian Liu Reviewed-By: James M Snell --- .mailmap | 1 + AUTHORS | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index a132f28d5091c9..e157a51b2f0256 100644 --- a/.mailmap +++ b/.mailmap @@ -88,6 +88,7 @@ Christopher Lenz Claudio Rodriguez Colin Ihrig Corey Martin +Daiki Arai Damien Simonin Feugas Dan Fabulich Dan Kaplun diff --git a/AUTHORS b/AUTHORS index 371630bff18433..0e2327f50f7ae9 100644 --- a/AUTHORS +++ b/AUTHORS @@ -2596,7 +2596,6 @@ DoiChris VeysonD susantruong Takahiro Nakamura -Daiki Arai horihiro grimrose timothy searcy From 7c7f8791c609af828211a3f2c0cb1d48616b8dab Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 22 Oct 2021 10:26:39 -0700 Subject: [PATCH 069/118] doc: update onboarding task Make starting Jenkins CI optional. PR-URL: https://github.com/nodejs/node/pull/40570 Reviewed-By: Voltrex Reviewed-By: Antoine du Hamel Reviewed-By: Gireesh Punathil Reviewed-By: James M Snell --- onboarding.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/onboarding.md b/onboarding.md index 73070bea6e1b51..8a176951517f9a 100644 --- a/onboarding.md +++ b/onboarding.md @@ -215,7 +215,9 @@ needs to be pointed out separately during the onboarding. labels. The `fast-track` label should cause the Node.js GitHub bot to post a comment in the pull request asking collaborators to approve the pull request by leaving a 👍 reaction on the comment. -* Run CI on the pull request. Use the `node-test-pull-request` CI task. +* Optional: Run CI on the pull request. Use the `node-test-pull-request` CI + task. As a convenience, you may apply the `request-ci` label to the pull + request to have a GitHub Actions workflow start the Jenkins CI task for you. * After two Collaborator approvals for the change and two Collaborator approvals for fast-tracking, land the PR. * If there are not enough approvals within a reasonable time, consider the From 27009092c85c263712e3715df6b1ca53a290f01a Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 22 Oct 2021 11:02:50 -0700 Subject: [PATCH 070/118] build: skip long-running Actions for README-only modifications MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If the only file modified is README.md do not run test-linux or build-windows tasks. This will help streamline onboarding sessions but may help some other cases too. PR-URL: https://github.com/nodejs/node/pull/40571 Reviewed-By: Voltrex Reviewed-By: Colin Ihrig Reviewed-By: Zijian Liu Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- .github/workflows/build-windows.yml | 4 ++++ .github/workflows/test-linux.yml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index e6fd0a4b92fe23..992319168b7e9c 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -2,6 +2,8 @@ name: build-windows on: pull_request: + paths-ignore: + - "README.md" types: [opened, synchronize, reopened, ready_for_review] push: branches: @@ -10,6 +12,8 @@ on: - canary - v[0-9]+.x-staging - v[0-9]+.x + paths-ignore: + - "README.md" env: PYTHON_VERSION: '3.10' diff --git a/.github/workflows/test-linux.yml b/.github/workflows/test-linux.yml index 01227a0ff92289..b7dce4dd8a9672 100644 --- a/.github/workflows/test-linux.yml +++ b/.github/workflows/test-linux.yml @@ -2,6 +2,8 @@ name: test-linux on: pull_request: + paths-ignore: + - "README.md" types: [opened, synchronize, reopened, ready_for_review] push: branches: @@ -10,6 +12,8 @@ on: - canary - v[0-9]+.x-staging - v[0-9]+.x + paths-ignore: + - "README.md" env: PYTHON_VERSION: '3.10' From dab574e93761c327d80d551da381f60b29d3436f Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 23 Oct 2021 05:37:17 +0000 Subject: [PATCH 071/118] policy: fix message for invalid manifest specifier Add test for invalid manifest specifier and fix the error message which is missing a space ("singletrailing" instead of "single trailing"). PR-URL: https://github.com/nodejs/node/pull/40574 Reviewed-By: Antoine du Hamel Reviewed-By: Colin Ihrig Reviewed-By: Zijian Liu Reviewed-By: Luigi Pinca Reviewed-By: Bradley Farias Reviewed-By: James M Snell Reviewed-By: Voltrex --- lib/internal/policy/manifest.js | 5 ++--- test/fixtures/policy-manifest/invalid.json | 9 ++++++++ test/parallel/test-policy-manifest.js | 25 ++++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 test/fixtures/policy-manifest/invalid.json create mode 100644 test/parallel/test-policy-manifest.js diff --git a/lib/internal/policy/manifest.js b/lib/internal/policy/manifest.js index 42ff63e87dc9cf..a601113182674e 100644 --- a/lib/internal/policy/manifest.js +++ b/lib/internal/policy/manifest.js @@ -136,9 +136,8 @@ class DependencyMapperInstance { if (!target) { throw new ERR_MANIFEST_INVALID_SPECIFIER( this.href, - target + - ', pattern needs to have a single' + - 'trailing "*" in target'); + `${target}, pattern needs to have a single trailing "*" in target` + ); } const prefix = target[1]; const suffix = target[2]; diff --git a/test/fixtures/policy-manifest/invalid.json b/test/fixtures/policy-manifest/invalid.json new file mode 100644 index 00000000000000..a8a0deb2cf7e07 --- /dev/null +++ b/test/fixtures/policy-manifest/invalid.json @@ -0,0 +1,9 @@ +{ + "resources": { + "./fhqwhgads.js": { + "dependencies": { + "**": true + } + } + } +} diff --git a/test/parallel/test-policy-manifest.js b/test/parallel/test-policy-manifest.js new file mode 100644 index 00000000000000..a8494175f3e68f --- /dev/null +++ b/test/parallel/test-policy-manifest.js @@ -0,0 +1,25 @@ +'use strict'; + +const common = require('../common'); + +if (!common.hasCrypto) + common.skip('missing crypto'); + +common.requireNoPackageJSONAbove(); + +const assert = require('assert'); +const { spawnSync } = require('child_process'); +const fixtures = require('../common/fixtures.js'); + +const policyFilepath = fixtures.path('policy-manifest', 'invalid.json'); + +const result = spawnSync(process.execPath, [ + '--experimental-policy', + policyFilepath, + './fhqwhgads.js', +]); + +assert.notStrictEqual(result.status, 0); +const stderr = result.stderr.toString(); +assert.match(stderr, /ERR_MANIFEST_INVALID_SPECIFIER/); +assert.match(stderr, /pattern needs to have a single trailing "\*"/); From 23d11a1dd9acac0d2f66a236c790e5debac47b25 Mon Sep 17 00:00:00 2001 From: Nitzan Uziely Date: Fri, 22 Oct 2021 20:00:45 +0300 Subject: [PATCH 072/118] dgram: fix send with out of bounds offset + length fix Socket.prototype.send sending garbage when the message is a string, or Buffer and offset+length is out of bounds. Fixes: https://github.com/nodejs/node/issues/40491 PR-URL: https://github.com/nodejs/node/pull/40568 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- lib/dgram.js | 8 ++++ .../parallel/test-dgram-send-bad-arguments.js | 41 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/lib/dgram.js b/lib/dgram.js index c515c551427d98..57d9289853ac7a 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -40,6 +40,7 @@ const { } = require('internal/dgram'); const { guessHandleType } = internalBinding('util'); const { + ERR_BUFFER_OUT_OF_BOUNDS, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_SOCKET_ALREADY_BOUND, @@ -487,6 +488,13 @@ function sliceBuffer(buffer, offset, length) { offset = offset >>> 0; length = length >>> 0; + if (offset > buffer.byteLength) { + throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); + } + + if (offset + length > buffer.byteLength) { + throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); + } return Buffer.from(buffer.buffer, buffer.byteOffset + offset, length); } diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js index 3e42f31b1af4b6..b30951d441cbd2 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -77,6 +77,47 @@ function checkArgs(connected) { message: 'Already connected' } ); + + const longArray = [1, 2, 3, 4, 5, 6, 7, 8]; + for (const input of ['hello', + Buffer.from('hello'), + Buffer.from('hello world').subarray(0, 5), + Buffer.from('hello world').subarray(4, 9), + Buffer.from('hello world').subarray(6), + new Uint8Array([1, 2, 3, 4, 5]), + new Uint8Array(longArray).subarray(0, 5), + new Uint8Array(longArray).subarray(2, 7), + new Uint8Array(longArray).subarray(3), + new DataView(new ArrayBuffer(5), 0), + new DataView(new ArrayBuffer(6), 1), + new DataView(new ArrayBuffer(7), 1, 5)]) { + assert.throws( + () => { sock.send(input, 6, 0); }, + { + code: 'ERR_BUFFER_OUT_OF_BOUNDS', + name: 'RangeError', + message: '"offset" is outside of buffer bounds', + } + ); + + assert.throws( + () => { sock.send(input, 0, 6); }, + { + code: 'ERR_BUFFER_OUT_OF_BOUNDS', + name: 'RangeError', + message: '"length" is outside of buffer bounds', + } + ); + + assert.throws( + () => { sock.send(input, 3, 4); }, + { + code: 'ERR_BUFFER_OUT_OF_BOUNDS', + name: 'RangeError', + message: '"length" is outside of buffer bounds', + } + ); + } } else { assert.throws(() => { sock.send(buf, 1, 1, -1, host); }, RangeError); assert.throws(() => { sock.send(buf, 1, 1, 0, host); }, RangeError); From d38077babe2e6f8b9ed326f86be0a9cf93b38b99 Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Sun, 24 Oct 2021 19:10:57 +0200 Subject: [PATCH 073/118] doc: fix typo in changelogs Fix typo in v12.22.7, v14.18.1, and v16.11.1 changelogs. PR-URL: https://github.com/nodejs/node/pull/40585 Reviewed-By: Rich Trott Reviewed-By: Voltrex --- doc/changelogs/CHANGELOG_V16.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/changelogs/CHANGELOG_V16.md b/doc/changelogs/CHANGELOG_V16.md index 10404385dcca74..9c8e089841b18e 100644 --- a/doc/changelogs/CHANGELOG_V16.md +++ b/doc/changelogs/CHANGELOG_V16.md @@ -158,7 +158,7 @@ This is a security release. * **CVE-2021-22959**: HTTP Request Smuggling due to spaced in headers (Medium) * The http parser accepts requests with a space (SP) right after the header name before the colon. This can lead to HTTP Request Smuggling (HRS). More details will be available at [CVE-2021-22959](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22959) after publication. * **CVE-2021-22960**: HTTP Request Smuggling when parsing the body (Medium) - * The parse ignores chunk extensions when parsing the body of chunked requests. This leads to HTTP Request Smuggling (HRS) under certain conditions. More details will be available at [CVE-2021-22960](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22960) after publication. + * The http parser ignores chunk extensions when parsing the body of chunked requests. This leads to HTTP Request Smuggling (HRS) under certain conditions. More details will be available at [CVE-2021-22960](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22960) after publication. ### Commits From 7b1c89f35773d6c132ebda3cd0c978264e4e42c2 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 24 Oct 2021 12:04:08 -0700 Subject: [PATCH 074/118] meta: consolidate AUTHORS entries for clakech PR-URL: https://github.com/nodejs/node/pull/40589 Reviewed-By: Voltrex Reviewed-By: Nitzan Uziely --- .mailmap | 1 + AUTHORS | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index e157a51b2f0256..eb72aa57cc2cc2 100644 --- a/.mailmap +++ b/.mailmap @@ -88,6 +88,7 @@ Christopher Lenz Claudio Rodriguez Colin Ihrig Corey Martin +Cyril Lakech <1169286+clakech@users.noreply.github.com> Daiki Arai Damien Simonin Feugas Dan Fabulich diff --git a/AUTHORS b/AUTHORS index 0e2327f50f7ae9..3e2f9f6fc82945 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1949,7 +1949,6 @@ Pawan Jangid Stephan Smith joelostrowski Javier Blanco -Cyril Lakech <1169286+clakech@users.noreply.github.com> Grant Gasparyan Klemen Kogovsek Gus Caplan From 97aa8e42b8cbeceb56097d5fe2327e8307b7a3ec Mon Sep 17 00:00:00 2001 From: Jeremiah Senkpiel Date: Mon, 25 Oct 2021 10:14:01 -0700 Subject: [PATCH 075/118] meta: move Fishrock123 to emeritus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I've moved on. I do not wish to be responsible for anything here and have been inactive for more than a year. PR-URL: https://github.com/nodejs/node/pull/40596 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Michaël Zasso Reviewed-By: Rich Trott Reviewed-By: Richard Lau Reviewed-By: Nitzan Uziely --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 200a7d007328ad..72f8596896331a 100644 --- a/README.md +++ b/README.md @@ -327,8 +327,6 @@ For information about the governance of the Node.js project, see **Evan Lucas** \ (he/him) * [fhinkel](https://github.com/fhinkel) - **Franziska Hinkelmann** \ (she/her) -* [Fishrock123](https://github.com/Fishrock123) - - **Jeremiah Senkpiel** \ (he/they) * [Flarna](https://github.com/Flarna) - **Gerhard Stöbich** \ (he/they) * [gabrielschulhof](https://github.com/gabrielschulhof) - @@ -501,6 +499,8 @@ For information about the governance of the Node.js project, see **Alexander Makarenko** \ * [firedfox](https://github.com/firedfox) - **Daniel Wang** \ +* [Fishrock123](https://github.com/Fishrock123) - + **Jeremiah Senkpiel** \ (he/they) * [gdams](https://github.com/gdams) - **George Adams** \ (he/him) * [geek](https://github.com/geek) - From e2114e21f4a901438c3a93ca3618384bdbf191cd Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Mon, 18 Oct 2021 17:18:29 -0400 Subject: [PATCH 076/118] doc: add info on project's usage of coverity Document project's used of coverity and how collaborators can get access. Signed-off-by: Michael Dawson PR-URL: https://github.com/nodejs/node/pull/40506 Reviewed-By: James M Snell Reviewed-By: Richard Lau --- doc/guides/offboarding.md | 3 +++ doc/guides/static-analysis.md | 16 ++++++++++++++++ onboarding.md | 3 +++ 3 files changed, 22 insertions(+) create mode 100644 doc/guides/static-analysis.md diff --git a/doc/guides/offboarding.md b/doc/guides/offboarding.md index 2c5ecfa9018f6c..87f21103540bef 100644 --- a/doc/guides/offboarding.md +++ b/doc/guides/offboarding.md @@ -12,3 +12,6 @@ emeritus or leaves the project. a team listing. For example, if someone is removed from @nodejs/build, they should also be removed from the Build WG README.md file in the repository. +* Open an issue in the [build](https://github.com/nodejs/build) repository + titled `Remove Collaborator from Coverity` asking that the collaborator + be removed from the Node.js coverity project if they had access. diff --git a/doc/guides/static-analysis.md b/doc/guides/static-analysis.md new file mode 100644 index 00000000000000..47047e9edcc18b --- /dev/null +++ b/doc/guides/static-analysis.md @@ -0,0 +1,16 @@ +# Static Analysis + +The project uses Coverity to scan Node.js source code and to report potential +issues in the C/C++ code base. + +Those who have been added to the Node.js coverity project can receive emails +when there are new issues reported as well as view all current issues +through [https://scan9.coverity.com/reports.htm](https://scan9.coverity.com/reports.htm). + +Any collaborator can ask to be added to the Node.js coverity project +by opening an issue in the [build](https://github.com/nodejs/build) repository +titled `Please add me to coverity`. A member of the build WG with admin +access will verify that the requestor is an existing collaborator as listed in +the [colloborators section](https://github.com/nodejs/node#collaborators) +on the nodejs/node project repo. Once validated the requestor will added +to to the coverity project. diff --git a/onboarding.md b/onboarding.md index 8a176951517f9a..76c7a3dcecd8ba 100644 --- a/onboarding.md +++ b/onboarding.md @@ -249,6 +249,8 @@ needs to be pointed out separately during the onboarding. project. The Foundation has travel funds to cover participants' expenses including accommodations, transportation, visa fees, etc. if needed. Check out the [summit](https://github.com/nodejs/summit) repository for details. +* If you are interested in helping to fix coverity reports consider requesting + access to the projects coverity project as outlined in [static-analysis][]. [Code of Conduct]: https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md [Labels]: doc/guides/collaborator-guide.md#labels @@ -259,6 +261,7 @@ needs to be pointed out separately during the onboarding. [`git-node`]: https://github.com/nodejs/node-core-utils/blob/HEAD/docs/git-node.md [`node-core-utils`]: https://github.com/nodejs/node-core-utils [set up the credentials]: https://github.com/nodejs/node-core-utils#setting-up-github-credentials +[static-analysis]: doc/guides/static-analysis.md [two-factor authentication]: https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/ [using a TOTP mobile app]: https://help.github.com/articles/configuring-two-factor-authentication-via-a-totp-mobile-app/ [who-to-cc]: doc/guides/collaborator-guide.md#who-to-cc-in-the-issue-tracker From 8648e5018397ab6d196fb9ffac987824cf0f0b9f Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 25 Oct 2021 14:15:48 -0700 Subject: [PATCH 077/118] tools: fix formatting of warning message in update-authors.js The email already has `<` and `>` surrounding it so adding it results in a misformatted message. PR-URL: https://github.com/nodejs/node/pull/40600 Reviewed-By: Colin Ihrig Reviewed-By: Voltrex Reviewed-By: Luigi Pinca --- tools/update-authors.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/update-authors.js b/tools/update-authors.js index 4ba73f28c9adc1..1eae7b61a83be4 100755 --- a/tools/update-authors.js +++ b/tools/update-authors.js @@ -121,7 +121,7 @@ rl.on('line', (line) => { const duplicate = previousAuthors.get(author); if (duplicate && !duplicate.includes(email)) { console.warn('Author name already in AUTHORS file. Possible duplicate:'); - console.warn(` ${author} <${email}>`); + console.warn(` ${author} ${email}`); } }); From 2a53995442839efeee83f0fbc109d1fe763de1ea Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Sun, 24 Oct 2021 08:21:34 +0200 Subject: [PATCH 078/118] tools: update ESLint to 8.1.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40582 Reviewed-By: Michaël Zasso Reviewed-By: Voltrex Reviewed-By: Rich Trott Reviewed-By: Tobias Nießen Reviewed-By: Colin Ihrig Reviewed-By: Trivikram Kamat --- tools/node_modules/eslint/README.md | 2 +- .../eslint/lib/cli-engine/cli-engine.js | 31 +-- .../node_modules/eslint/lib/eslint/eslint.js | 17 +- .../lib/linter/config-comment-parser.js | 2 +- .../node_modules/eslint/lib/linter/linter.js | 2 +- .../eslint/lib/linter/node-event-generator.js | 7 + .../eslint/lib/rule-tester/rule-tester.js | 7 +- tools/node_modules/eslint/lib/rules/index.js | 1 + .../eslint/lib/rules/keyword-spacing.js | 15 +- .../rules/no-unused-private-class-members.js | 194 ++++++++++++++++++ tools/node_modules/eslint/lib/shared/types.js | 2 +- .../@eslint/eslintrc/package.json | 5 +- .../@eslint/eslintrc/universal.js | 9 + tools/node_modules/eslint/package.json | 6 +- 14 files changed, 252 insertions(+), 48 deletions(-) create mode 100644 tools/node_modules/eslint/lib/rules/no-unused-private-class-members.js create mode 100644 tools/node_modules/eslint/node_modules/@eslint/eslintrc/universal.js diff --git a/tools/node_modules/eslint/README.md b/tools/node_modules/eslint/README.md index 43bcdaa3f29778..90eac6469998a5 100644 --- a/tools/node_modules/eslint/README.md +++ b/tools/node_modules/eslint/README.md @@ -242,7 +242,7 @@ Toru Nagashima
16Current16LTS 14LTS 12LTS
-16.12.0
+16.13.0
+16.12.0
16.11.1
16.11.0
16.10.0
From 134e8afc594e531b8e50ebbc155b698f9333f0e8 Mon Sep 17 00:00:00 2001 From: FrankQiu Date: Mon, 4 Oct 2021 16:33:37 +0800 Subject: [PATCH 002/118] build: update codeowners-validator to 0.6 PR-URL: https://github.com/nodejs/node/pull/40307 Reviewed-By: Mary Marchini --- .github/workflows/linters.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/linters.yml b/.github/workflows/linters.yml index 131d220562a5d9..ebd27575c4778b 100644 --- a/.github/workflows/linters.yml +++ b/.github/workflows/linters.yml @@ -120,7 +120,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - uses: mszostok/codeowners-validator@v0.4.0 + - uses: mszostok/codeowners-validator@v0.6.0 with: checks: "files,duppatterns" lint-pr-url: From a9990876f703e54e6905626f344cf4d0b198f7b3 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 10 Oct 2021 22:18:27 -0700 Subject: [PATCH 003/118] tools: update lint-md dependencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update lint-md dependencies and re-create lint-md.mjs. PR-URL: https://github.com/nodejs/node/pull/40404 Reviewed-By: Michaël Zasso Reviewed-By: Zijian Liu Reviewed-By: Antoine du Hamel --- tools/lint-md/lint-md.mjs | 241 +++++++++----------- tools/lint-md/package-lock.json | 380 ++++++++++++++++++++------------ tools/lint-md/package.json | 2 +- 3 files changed, 349 insertions(+), 274 deletions(-) diff --git a/tools/lint-md/lint-md.mjs b/tools/lint-md/lint-md.mjs index af678e476c23d2..bd893097132255 100644 --- a/tools/lint-md/lint-md.mjs +++ b/tools/lint-md/lint-md.mjs @@ -2379,7 +2379,7 @@ function initializeDocument(effects) { while (index--) { if ( // The token starts before the line ending… - childFlow.events[index][1].start.offset < lineStartOffset && + childFlow.events[index][1].start.offset < lineStartOffset && // …and either is not ended yet… (!childFlow.events[index][1].end || // …or ends after it. childFlow.events[index][1].end.offset > lineStartOffset) ) { @@ -6447,6 +6447,10 @@ function factoryLabel(effects, ok, nok, type, markerType, stringType) { code === null || code === 91 || (code === 93 && !data) || + /* To do: remove in the future once we’ve switched from + * `micromark-extension-footnote` to `micromark-extension-gfm-footnote`, + * which doesn’t need this */ + /* Hidden footnotes hook */ /* c8 ignore next 3 */ @@ -8468,6 +8472,10 @@ function tokenizeLabelStartImage(effects, ok, nok) { /** @type {State} */ function after(code) { + /* To do: remove in the future once we’ve switched from + * `micromark-extension-footnote` to `micromark-extension-gfm-footnote`, + * which doesn’t need this */ + /* Hidden footnotes hook */ /* c8 ignore next 3 */ @@ -8507,6 +8515,10 @@ function tokenizeLabelStartLink(effects, ok, nok) { /** @type {State} */ function after(code) { + /* To do: remove in the future once we’ve switched from + * `micromark-extension-footnote` to `micromark-extension-gfm-footnote`, + * which doesn’t need this */ + /* Hidden footnotes hook. */ /* c8 ignore next 3 */ @@ -10241,6 +10253,13 @@ const own$5 = {}.hasOwnProperty; */ const fromMarkdown = + /** + * @type {( + * ((value: Value, encoding: Encoding, options?: Options) => Root) & + * ((value: Value, options?: Options) => Root) + * )} + */ + /** * @param {Value} value * @param {Encoding} [encoding] @@ -10783,7 +10802,9 @@ function compiler(options = {}) { function onenterlistitemvalue(token) { if (getData('expectingFirstListItemValue')) { - const ancestor = this.stack[this.stack.length - 2]; + const ancestor = + /** @type {List} */ + this.stack[this.stack.length - 2]; ancestor.start = Number.parseInt(this.sliceSerialize(token), 10); setData('expectingFirstListItemValue'); } @@ -10792,14 +10813,18 @@ function compiler(options = {}) { function onexitcodefencedfenceinfo() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Code} */ + this.stack[this.stack.length - 1]; node.lang = data; } /** @type {Handle} */ function onexitcodefencedfencemeta() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Code} */ + this.stack[this.stack.length - 1]; node.meta = data; } /** @type {Handle} */ @@ -10814,7 +10839,9 @@ function compiler(options = {}) { function onexitcodefenced() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Code} */ + this.stack[this.stack.length - 1]; node.value = data.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, ''); setData('flowCodeInside'); } @@ -10822,7 +10849,9 @@ function compiler(options = {}) { function onexitcodeindented() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Code} */ + this.stack[this.stack.length - 1]; node.value = data.replace(/(\r?\n|\r)$/g, ''); } /** @type {Handle} */ @@ -10830,7 +10859,9 @@ function compiler(options = {}) { function onexitdefinitionlabelstring(token) { // Discard label, use the source content instead. const label = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Definition} */ + this.stack[this.stack.length - 1]; node.label = label; node.identifier = normalizeIdentifier( this.sliceSerialize(token) @@ -10840,20 +10871,26 @@ function compiler(options = {}) { function onexitdefinitiontitlestring() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Definition} */ + this.stack[this.stack.length - 1]; node.title = data; } /** @type {Handle} */ function onexitdefinitiondestinationstring() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Definition} */ + this.stack[this.stack.length - 1]; node.url = data; } /** @type {Handle} */ function onexitatxheadingsequence(token) { - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Heading} */ + this.stack[this.stack.length - 1]; if (!node.depth) { const depth = this.sliceSerialize(token).length; @@ -10868,7 +10905,9 @@ function compiler(options = {}) { /** @type {Handle} */ function onexitsetextheadinglinesequence(token) { - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Heading} */ + this.stack[this.stack.length - 1]; node.depth = this.sliceSerialize(token).charCodeAt(0) === 61 ? 1 : 2; } /** @type {Handle} */ @@ -10879,7 +10918,9 @@ function compiler(options = {}) { /** @type {Handle} */ function onenterdata(token) { - const parent = this.stack[this.stack.length - 1]; + const parent = + /** @type {Parent} */ + this.stack[this.stack.length - 1]; /** @type {Node} */ let tail = parent.children[parent.children.length - 1]; @@ -10934,27 +10975,35 @@ function compiler(options = {}) { function onexithtmlflow() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {HTML} */ + this.stack[this.stack.length - 1]; node.value = data; } /** @type {Handle} */ function onexithtmltext() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {HTML} */ + this.stack[this.stack.length - 1]; node.value = data; } /** @type {Handle} */ function onexitcodetext() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {InlineCode} */ + this.stack[this.stack.length - 1]; node.value = data; } /** @type {Handle} */ function onexitlink() { - const context = this.stack[this.stack.length - 1]; // To do: clean. + const context = + /** @type {Link & {identifier: string, label: string}} */ + this.stack[this.stack.length - 1]; // To do: clean. if (getData('inReference')) { context.type += 'Reference'; // @ts-expect-error: mutate. @@ -10975,7 +11024,9 @@ function compiler(options = {}) { /** @type {Handle} */ function onexitimage() { - const context = this.stack[this.stack.length - 1]; // To do: clean. + const context = + /** @type {Image & {identifier: string, label: string}} */ + this.stack[this.stack.length - 1]; // To do: clean. if (getData('inReference')) { context.type += 'Reference'; // @ts-expect-error: mutate. @@ -10996,7 +11047,9 @@ function compiler(options = {}) { /** @type {Handle} */ function onexitlabeltext(token) { - const ancestor = this.stack[this.stack.length - 2]; + const ancestor = + /** @type {(Link|Image) & {identifier: string, label: string}} */ + this.stack[this.stack.length - 2]; const string = this.sliceSerialize(token); ancestor.label = decodeString(string); ancestor.identifier = normalizeIdentifier(string).toLowerCase(); @@ -11004,9 +11057,13 @@ function compiler(options = {}) { /** @type {Handle} */ function onexitlabel() { - const fragment = this.stack[this.stack.length - 1]; + const fragment = + /** @type {Fragment} */ + this.stack[this.stack.length - 1]; const value = this.resume(); - const node = this.stack[this.stack.length - 1]; // Assume a reference. + const node = + /** @type {(Link|Image) & {identifier: string, label: string}} */ + this.stack[this.stack.length - 1]; // Assume a reference. setData('inReference', true); @@ -11021,14 +11078,18 @@ function compiler(options = {}) { function onexitresourcedestinationstring() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Link|Image} */ + this.stack[this.stack.length - 1]; node.url = data; } /** @type {Handle} */ function onexitresourcetitlestring() { const data = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Link|Image} */ + this.stack[this.stack.length - 1]; node.title = data; } /** @type {Handle} */ @@ -11045,7 +11106,9 @@ function compiler(options = {}) { function onexitreferencestring(token) { const label = this.resume(); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {LinkReference|ImageReference} */ + this.stack[this.stack.length - 1]; node.label = label; node.identifier = normalizeIdentifier( this.sliceSerialize(token) @@ -11086,14 +11149,18 @@ function compiler(options = {}) { function onexitautolinkprotocol(token) { onexitdata.call(this, token); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Link} */ + this.stack[this.stack.length - 1]; node.url = this.sliceSerialize(token); } /** @type {Handle} */ function onexitautolinkemail(token) { onexitdata.call(this, token); - const node = this.stack[this.stack.length - 1]; + const node = + /** @type {Link} */ + this.stack[this.stack.length - 1]; node.url = 'mailto:' + this.sliceSerialize(token); } // // Creaters. @@ -14650,19 +14717,7 @@ function gfmStrikethrough(options = {}) { */ function resolveAllStrikethrough(events, context) { - let index = -1; - /** @type {Token} */ - - let strikethrough; - /** @type {Token} */ - - let text; - /** @type {number} */ - - let open; - /** @type {Event[]} */ - - let nextEvents; // Walk through all events. + let index = -1; // Walk through all events. while (++index < events.length) { // Find a token that can close. @@ -14671,7 +14726,7 @@ function gfmStrikethrough(options = {}) { events[index][1].type === 'strikethroughSequenceTemporary' && events[index][1]._close ) { - open = index; // Now walk back to find an opener. + let open = index; // Now walk back to find an opener. while (open--) { // Find a token that can open the closer. @@ -14684,18 +14739,18 @@ function gfmStrikethrough(options = {}) { ) { events[index][1].type = 'strikethroughSequence'; events[open][1].type = 'strikethroughSequence'; - strikethrough = { + const strikethrough = { type: 'strikethrough', start: Object.assign({}, events[open][1].start), end: Object.assign({}, events[index][1].end) }; - text = { + const text = { type: 'strikethroughText', start: Object.assign({}, events[open][1].end), end: Object.assign({}, events[index][1].start) }; // Opening. - nextEvents = [ + const nextEvents = [ ['enter', strikethrough, context], ['enter', events[open][1], context], ['exit', events[open][1], context], @@ -14748,9 +14803,8 @@ function gfmStrikethrough(options = {}) { function start(code) { if ( - code !== 126 || - (previous === 126 && - events[events.length - 1][1].type !== 'characterEscape') + previous === 126 && + events[events.length - 1][1].type !== 'characterEscape' ) { return nok(code) } @@ -14960,9 +15014,6 @@ const nextPrefixedOrBlank = { function resolveTable(events, context) { let index = -1; - /** @type {Token} */ - - let token; /** @type {boolean|undefined} */ let inHead; @@ -14972,15 +15023,6 @@ function resolveTable(events, context) { /** @type {boolean|undefined} */ let inRow; - /** @type {Token} */ - - let cell; - /** @type {Token} */ - - let content; - /** @type {Token} */ - - let text; /** @type {number|undefined} */ let contentStart; @@ -14992,7 +15034,7 @@ function resolveTable(events, context) { let cellStart; while (++index < events.length) { - token = events[index][1]; + const token = events[index][1]; if (inRow) { if (token.type === 'temporaryTableCellContent') { @@ -15005,13 +15047,14 @@ function resolveTable(events, context) { (token.type === 'tableCellDivider' || token.type === 'tableRow') && contentEnd ) { - content = { + const content = { type: 'tableContent', - // @ts-expect-error `contentStart` is defined if `contentEnd` is too. start: events[contentStart][1].start, end: events[contentEnd][1].end }; - text = { + /** @type {Token} */ + + const text = { type: 'chunkText', start: content.start, end: content.end, @@ -15019,15 +15062,13 @@ function resolveTable(events, context) { contentType: 'text' }; events.splice( - // @ts-expect-error `contentStart` is defined if `contentEnd` is too. - contentStart, // @ts-expect-error `contentStart` is defined if `contentEnd` is too. + contentStart, contentEnd - contentStart + 1, ['enter', content, context], ['enter', text, context], ['exit', text, context], ['exit', content, context] - ); // @ts-expect-error `contentStart` is defined if `contentEnd` is too. - + ); index -= contentEnd - contentStart - 3; contentStart = undefined; contentEnd = undefined; @@ -15043,7 +15084,7 @@ function resolveTable(events, context) { (cellStart + 3 < index || events[cellStart][1].type !== 'whitespace'))) ) { - cell = { + const cell = { type: inDelimiterRow ? 'tableDelimiter' : inHead @@ -15205,7 +15246,6 @@ function tokenizeTable(effects, ok, nok) { /** @type {State} */ function atDelimiterLineStart(code) { - // To do: is the lazy setext thing still needed? return effects.check( setextUnderlineMini, nok, // Support an indent before the delimiter row. @@ -18880,71 +18920,6 @@ const remarkLintListItemIndent = lintRule( var remarkLintListItemIndent$1 = remarkLintListItemIndent; -/** - * @author Titus Wormer - * @copyright 2015 Titus Wormer - * @license MIT - * @module no-auto-link-without-protocol - * @fileoverview - * Warn for autolinks without protocol. - * Autolinks are URLs enclosed in `<` (less than) and `>` (greater than) - * characters. - * - * ## Fix - * - * [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify) - * adds a protocol where needed. - * - * See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown) - * on how to automatically fix warnings for this rule. - * - * @example - * {"name": "ok.md"} - * - * - * - * - * Most Markdown vendors don’t recognize the following as a link: - * - * - * @example - * {"name": "not-ok.md", "label": "input"} - * - * - * - * @example - * {"name": "not-ok.md", "label": "output"} - * - * 1:1-1:14: All automatic links must start with a protocol - */ - -// Protocol expression. -// See: . -const protocol = /^[a-z][a-z+.-]+:\/?/i; - -const remarkLintNoAutoLinkWithoutProtocol = lintRule( - { - origin: 'remark-lint:no-auto-link-without-protocol', - url: 'https://github.com/remarkjs/remark-lint/tree/main/packages/remark-lint-no-auto-link-without-protocol#readme' - }, - /** @type {import('unified-lint-rule').Rule} */ - (tree, file) => { - visit$1(tree, 'link', (node) => { - if ( - !generated(node) && - pointStart(node).column === pointStart(node.children[0]).column - 1 && - pointEnd(node).column === - pointEnd(node.children[node.children.length - 1]).column + 1 && - !protocol.test(toString(node)) - ) { - file.message('All automatic links must start with a protocol', node); - } - }); - } -); - -var remarkLintNoAutoLinkWithoutProtocol$1 = remarkLintNoAutoLinkWithoutProtocol; - /** * @author Titus Wormer * @copyright 2015 Titus Wormer @@ -20012,8 +19987,6 @@ const remarkPresetLintRecommended = { // Rendering across vendors differs greatly if using other styles. remarkLintListItemBulletIndent$1, [remarkLintListItemIndent$1, 'tab-size'], - // Differs or unsupported across vendors. - remarkLintNoAutoLinkWithoutProtocol$1, remarkLintNoBlockquoteWithoutMarker$1, remarkLintNoLiteralUrls$1, [remarkLintOrderedListMarkerStyle$1, '.'], diff --git a/tools/lint-md/package-lock.json b/tools/lint-md/package-lock.json index dfc8f3194bba14..4525157c8bf8af 100644 --- a/tools/lint-md/package-lock.json +++ b/tools/lint-md/package-lock.json @@ -16,15 +16,15 @@ "vfile-reporter": "^7.0.2" }, "devDependencies": { - "@rollup/plugin-commonjs": "^20.0.0", + "@rollup/plugin-commonjs": "^21.0.0", "@rollup/plugin-node-resolve": "^13.0.5", "rollup": "^2.58.0" } }, "node_modules/@rollup/plugin-commonjs": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-20.0.0.tgz", - "integrity": "sha512-5K0g5W2Ol8hAcTHqcTBHiA7M58tfmYi1o9KxeJuuRNpGaTa5iLjcyemBitCBcKXaHamOBBEH2dGom6v6Unmqjg==", + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-21.0.0.tgz", + "integrity": "sha512-XDQimjHl0kNotAV5lLo34XoygaI0teqiKGJ100B3iCU8+15YscJPeqk2KqkqD3NIe1H8ZTUo5lYjUFZyEgASTw==", "dev": true, "dependencies": { "@rollup/pluginutils": "^3.1.0", @@ -120,9 +120,9 @@ "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==" }, "node_modules/@types/node": { - "version": "16.10.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.10.2.tgz", - "integrity": "sha512-zCclL4/rx+W5SQTzFs9wyvvyCwoK9QtBpratqz2IYJ3O8Umrn0m3nsTv0wQBk9sRGpvUe9CwPDrQFB10f1FIjQ==", + "version": "16.10.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.10.3.tgz", + "integrity": "sha512-ho3Ruq+fFnBrZhUYI46n/bV2GjwzSkwuT4dTf0GkuNFmnb8nq4ny2z9JEVemFi6bdEJanHLlYfy9c6FN9B9McQ==", "dev": true }, "node_modules/@types/resolve": { @@ -275,6 +275,22 @@ "node": ">=0.10.0" } }, + "node_modules/dequal": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.2.tgz", + "integrity": "sha512-q9K8BlJVxK7hQYqa6XISGmBZbtQQWVXSrRrWreHC94rMt1QL/Impruc+7p2CYSYuVIUr+YCt6hjrs1kkdJRTug==", + "engines": { + "node": ">=6" + } + }, + "node_modules/diff": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", + "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/emoji-regex": { "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", @@ -509,6 +525,14 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/kleur": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.4.tgz", + "integrity": "sha512-8QADVssbrFjivHWQU7KkMgptGTl6WAcSdlbBPY4uNF+mWr6DGcKrvY2w4FQJoXch7+fKMjj0dRrL75vk3k23OA==", + "engines": { + "node": ">=6" + } + }, "node_modules/longest-streak": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.0.0.tgz", @@ -574,9 +598,9 @@ } }, "node_modules/mdast-util-from-markdown": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.2.tgz", - "integrity": "sha512-gXaxv/5fGdrr9TqSMlQK7FmshK8yR9DvW3+NapMBDm44inORxIZVJa1D3yjrUT9ISu8tB/jjblEkUzyzclquNg==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.4.tgz", + "integrity": "sha512-BlL42o885QO+6o43ceoc6KBdp/bi9oYyamj0hUbeu730yhP1WDC7m2XYSBfmQkOb0TdoHSAJ3de3SMqse69u+g==", "dependencies": { "@types/mdast": "^3.0.0", "@types/unist": "^2.0.0", @@ -588,7 +612,8 @@ "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0", "parse-entities": "^3.0.0", - "unist-util-stringify-position": "^3.0.0" + "unist-util-stringify-position": "^3.0.0", + "uvu": "^0.5.0" }, "funding": { "type": "opencollective", @@ -716,9 +741,9 @@ } }, "node_modules/micromark": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-3.0.5.tgz", - "integrity": "sha512-QfjERBnPw0G9mxhOCkkbRP0n8SX8lIBLrEKeEVceviUukqVMv3hWE4AgNTOK/W6GWqtPvvIHg2Apl3j1Dxm6aQ==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-3.0.7.tgz", + "integrity": "sha512-67ipZ2CzQVsDyH1kqNLh7dLwe5QMPJwjFBGppW7JCLByaSc6ZufV0ywPOxt13MIDAzzmj3wctDL6Ov5w0fOHXw==", "funding": [ { "type": "GitHub Sponsors", @@ -745,13 +770,14 @@ "micromark-util-subtokenize": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.1", - "parse-entities": "^3.0.0" + "parse-entities": "^3.0.0", + "uvu": "^0.5.0" } }, "node_modules/micromark-core-commonmark": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-1.0.1.tgz", - "integrity": "sha512-vEOw8hcQ3nwHkKKNIyP9wBi8M50zjNajtmI+cCUWcVfJS+v5/3WCh4PLKf7PPRZFUutjzl4ZjlHwBWUKfb/SkA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-1.0.3.tgz", + "integrity": "sha512-0E8aE27v0DYHPk40IxzhCdXnZWQuvZ6rbflrx1u8ZZAUJEB48o0fgLXA5+yMab28yXT+mi1Q4LXdsI4oGS6Vng==", "funding": [ { "type": "GitHub Sponsors", @@ -777,7 +803,8 @@ "micromark-util-subtokenize": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.1", - "parse-entities": "^3.0.0" + "parse-entities": "^3.0.0", + "uvu": "^0.5.0" } }, "node_modules/micromark-extension-gfm": { @@ -799,14 +826,15 @@ } }, "node_modules/micromark-extension-gfm-autolink-literal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-1.0.0.tgz", - "integrity": "sha512-t+K0aPK32mXypVTEKV+WRfoT/Rb7MERDgHZVRr56NXpyQQhgMk72QnK4NljYUlrgbuesH+MxiPQwThzqRDIwvA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-1.0.2.tgz", + "integrity": "sha512-z2Asd0v4iV/QoI1l23J1qB6G8IqVWTKmwdlP45YQfdGW47ZzpddyzSxZ78YmlucOLqIbS5H98ekKf9GunFfnLA==", "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-sanitize-uri": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" }, "funding": { "type": "opencollective", @@ -814,15 +842,16 @@ } }, "node_modules/micromark-extension-gfm-strikethrough": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-1.0.1.tgz", - "integrity": "sha512-fzGYXWz9HPWH1uHqYwdyR8XpEtuoYVHUjTdPQTnl3ETVZOQe1NXMwE3RA7AMqeON52hG+kO9g1/P1+pLONBSMQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-1.0.3.tgz", + "integrity": "sha512-PJKhBNyrNIo694ZQCE/FBBQOQSb6YC0Wi5Sv0OCah5XunnNaYbtak9CSv9/eq4YeFMMyd1jX84IRwUSE+7ioLA==", "dependencies": { "micromark-util-chunked": "^1.0.0", "micromark-util-classify-character": "^1.0.0", "micromark-util-resolve-all": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" }, "funding": { "type": "opencollective", @@ -830,14 +859,15 @@ } }, "node_modules/micromark-extension-gfm-table": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-1.0.0.tgz", - "integrity": "sha512-OATRuHDgEAT/aaJJRSdU12V+s01kNSnJ0jumdfLq5mPy0F5DkR3zbTSFLH4tjVYM0/kEG6umxIhHY62mFe4z5Q==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-1.0.2.tgz", + "integrity": "sha512-mRtt0S/jVT8IRWqIw2Wnl8dr/9yHh+b3NgiDQ4zdgheiAtkFYalng5CUQooFfQeSxQjfV+QKXqtPpjdIHu3AqQ==", "dependencies": { "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" }, "funding": { "type": "opencollective", @@ -857,14 +887,15 @@ } }, "node_modules/micromark-extension-gfm-task-list-item": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-1.0.0.tgz", - "integrity": "sha512-3tkHCq1NNwijtwpjYba9+rl1yvQ4xYg8iQpUAfTJRyq8MtIEsBUF/vW6B9Gh8Qwy1hE2FmpyHhP4jnFAt61zLg==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-1.0.2.tgz", + "integrity": "sha512-8AZib9xxPtppTKig/d00i9uKi96kVgoqin7+TRtGprDb8uTUrN1ZfJ38ga8yUdmu7EDQxr2xH8ltZdbCcmdshg==", "dependencies": { "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" }, "funding": { "type": "opencollective", @@ -892,9 +923,9 @@ } }, "node_modules/micromark-factory-label": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-1.0.0.tgz", - "integrity": "sha512-XWEucVZb+qBCe2jmlOnWr6sWSY6NHx+wtpgYFsm4G+dufOf6tTQRRo0bdO7XSlGPu5fyjpJenth6Ksnc5Mwfww==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-1.0.2.tgz", + "integrity": "sha512-CTIwxlOnU7dEshXDQ+dsr2n+yxpP0+fn271pu0bwDIS8uqfFcumXpj5mLn3hSC8iw2MUr6Gx8EcKng1dD7i6hg==", "funding": [ { "type": "GitHub Sponsors", @@ -908,7 +939,8 @@ "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "node_modules/micromark-factory-space": { @@ -931,9 +963,9 @@ } }, "node_modules/micromark-factory-title": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-1.0.0.tgz", - "integrity": "sha512-flvC7Gx0dWVWorXuBl09Cr3wB5FTuYec8pMGVySIp2ZlqTcIjN/lFohZcP0EG//krTptm34kozHk7aK/CleCfA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-1.0.2.tgz", + "integrity": "sha512-zily+Nr4yFqgMGRKLpTVsNl5L4PMu485fGFDOQJQBl2NFpjGte1e86zC0da93wf97jrc4+2G2GQudFMHn3IX+A==", "funding": [ { "type": "GitHub Sponsors", @@ -948,7 +980,8 @@ "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "node_modules/micromark-factory-whitespace": { @@ -1067,9 +1100,9 @@ } }, "node_modules/micromark-util-decode-string": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-1.0.0.tgz", - "integrity": "sha512-4g5UJ8P/J8wuRKUXCcB7udQuOBXpLyvBQSLSuznfBLCG+thKG6UTwFnXfHkrr/1wddprkUbPatCzxDjrJ+5zDg==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-1.0.1.tgz", + "integrity": "sha512-Wf3H6jLaO3iIlHEvblESXaKAr72nK7JtBbLLICPwuZc3eJkMcp4j8rJ5Xv1VbQWMCWWDvKUbVUbE2MfQNznwTA==", "funding": [ { "type": "GitHub Sponsors", @@ -1083,6 +1116,7 @@ "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-decode-numeric-character-reference": "^1.0.0", + "micromark-util-symbol": "^1.0.0", "parse-entities": "^3.0.0" } }, @@ -1173,9 +1207,9 @@ } }, "node_modules/micromark-util-subtokenize": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.0.tgz", - "integrity": "sha512-EsnG2qscmcN5XhkqQBZni/4oQbLFjz9yk3ZM/P8a3YUjwV6+6On2wehr1ALx0MxK3+XXXLTzuBKHDFeDFYRdgQ==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.2.tgz", + "integrity": "sha512-d90uqCnXp/cy4G881Ub4psE57Sf8YD0pim9QdjCRNjfas2M1u6Lbt+XZK9gnHL2XFhnozZiEdCa9CNfXSfQ6xA==", "funding": [ { "type": "GitHub Sponsors", @@ -1189,7 +1223,8 @@ "dependencies": { "micromark-util-chunked": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "node_modules/micromark-util-symbol": { @@ -1234,6 +1269,14 @@ "node": "*" } }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "engines": { + "node": ">=4" + } + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -1592,24 +1635,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/remark-lint-no-auto-link-without-protocol": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/remark-lint-no-auto-link-without-protocol/-/remark-lint-no-auto-link-without-protocol-3.1.0.tgz", - "integrity": "sha512-GqZXDu/xfajWCEPhS8UjO9dYMTlY5lD8ShoYIaouUgz3nNQvLwX33pTKqfRpd/R9EmV1uQw0PCJ6TYwhBrnOXQ==", - "dependencies": { - "@types/mdast": "^3.0.0", - "mdast-util-to-string": "^3.0.0", - "unified": "^10.0.0", - "unified-lint-rule": "^2.0.0", - "unist-util-generated": "^2.0.0", - "unist-util-position": "^4.0.0", - "unist-util-visit": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, "node_modules/remark-lint-no-blockquote-without-marker": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/remark-lint-no-blockquote-without-marker/-/remark-lint-no-blockquote-without-marker-5.1.0.tgz", @@ -2119,9 +2144,9 @@ } }, "node_modules/remark-preset-lint-recommended": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/remark-preset-lint-recommended/-/remark-preset-lint-recommended-6.1.0.tgz", - "integrity": "sha512-1jUbuzRAP5idWu9GZ5x7M96Z1TcTWwJu0C8ziz5RLezWL9rChhw9kV6s0beR0lrY5Kl5E5pjA6SKaP7NyGi2ug==", + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/remark-preset-lint-recommended/-/remark-preset-lint-recommended-6.1.1.tgz", + "integrity": "sha512-ez8/QTY8x/XKZcewXbWd+vQWWhNbgHCEq+NwY6sf9/QuwxBarG9cmSkP9yXi5glYKGVaEefVZmrZRB4jvZWcog==", "dependencies": { "@types/mdast": "^3.0.0", "remark-lint": "^9.0.0", @@ -2129,7 +2154,6 @@ "remark-lint-hard-break-spaces": "^3.0.0", "remark-lint-list-item-bullet-indent": "^4.0.0", "remark-lint-list-item-indent": "^3.0.0", - "remark-lint-no-auto-link-without-protocol": "^3.0.0", "remark-lint-no-blockquote-without-marker": "^5.0.0", "remark-lint-no-duplicate-definitions": "^3.0.0", "remark-lint-no-heading-content-indent": "^4.0.0", @@ -2189,6 +2213,17 @@ "fsevents": "~2.3.2" } }, + "node_modules/sade": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.7.4.tgz", + "integrity": "sha512-y5yauMD93rX840MwUJr7C1ysLFBgMspsdTo4UVrDg3fXDvtwOyIqykhVAAm6fk/3au77773itJStObgK+LKaiA==", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", @@ -2271,6 +2306,14 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/totalist": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-2.0.0.tgz", + "integrity": "sha512-+Y17F0YzxfACxTyjfhnJQEe7afPA0GSpYlFkl2VFMxYP7jshQf9gXV7cH47EfToBumFThfKBvfAcoUn6fdNeRQ==", + "engines": { + "node": ">=6" + } + }, "node_modules/trough": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/trough/-/trough-2.0.2.tgz", @@ -2423,6 +2466,24 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/uvu": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.2.tgz", + "integrity": "sha512-m2hLe7I2eROhh+tm3WE5cTo/Cv3WQA7Oc9f7JB6uWv+/zVKvfAm53bMyOoGOSZeQ7Ov2Fu9pLhFr7p07bnT20w==", + "dependencies": { + "dequal": "^2.0.0", + "diff": "^5.0.0", + "kleur": "^4.0.3", + "sade": "^1.7.3", + "totalist": "^2.0.0" + }, + "bin": { + "uvu": "bin.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/vfile": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/vfile/-/vfile-5.1.0.tgz", @@ -2537,9 +2598,9 @@ }, "dependencies": { "@rollup/plugin-commonjs": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-20.0.0.tgz", - "integrity": "sha512-5K0g5W2Ol8hAcTHqcTBHiA7M58tfmYi1o9KxeJuuRNpGaTa5iLjcyemBitCBcKXaHamOBBEH2dGom6v6Unmqjg==", + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-21.0.0.tgz", + "integrity": "sha512-XDQimjHl0kNotAV5lLo34XoygaI0teqiKGJ100B3iCU8+15YscJPeqk2KqkqD3NIe1H8ZTUo5lYjUFZyEgASTw==", "dev": true, "requires": { "@rollup/pluginutils": "^3.1.0", @@ -2619,9 +2680,9 @@ "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==" }, "@types/node": { - "version": "16.10.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.10.2.tgz", - "integrity": "sha512-zCclL4/rx+W5SQTzFs9wyvvyCwoK9QtBpratqz2IYJ3O8Umrn0m3nsTv0wQBk9sRGpvUe9CwPDrQFB10f1FIjQ==", + "version": "16.10.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.10.3.tgz", + "integrity": "sha512-ho3Ruq+fFnBrZhUYI46n/bV2GjwzSkwuT4dTf0GkuNFmnb8nq4ny2z9JEVemFi6bdEJanHLlYfy9c6FN9B9McQ==", "dev": true }, "@types/resolve": { @@ -2731,6 +2792,16 @@ "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", "dev": true }, + "dequal": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.2.tgz", + "integrity": "sha512-q9K8BlJVxK7hQYqa6XISGmBZbtQQWVXSrRrWreHC94rMt1QL/Impruc+7p2CYSYuVIUr+YCt6hjrs1kkdJRTug==" + }, + "diff": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", + "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==" + }, "emoji-regex": { "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", @@ -2886,6 +2957,11 @@ "argparse": "^2.0.1" } }, + "kleur": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.4.tgz", + "integrity": "sha512-8QADVssbrFjivHWQU7KkMgptGTl6WAcSdlbBPY4uNF+mWr6DGcKrvY2w4FQJoXch7+fKMjj0dRrL75vk3k23OA==" + }, "longest-streak": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.0.0.tgz", @@ -2932,9 +3008,9 @@ } }, "mdast-util-from-markdown": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.2.tgz", - "integrity": "sha512-gXaxv/5fGdrr9TqSMlQK7FmshK8yR9DvW3+NapMBDm44inORxIZVJa1D3yjrUT9ISu8tB/jjblEkUzyzclquNg==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.4.tgz", + "integrity": "sha512-BlL42o885QO+6o43ceoc6KBdp/bi9oYyamj0hUbeu730yhP1WDC7m2XYSBfmQkOb0TdoHSAJ3de3SMqse69u+g==", "requires": { "@types/mdast": "^3.0.0", "@types/unist": "^2.0.0", @@ -2946,7 +3022,8 @@ "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0", "parse-entities": "^3.0.0", - "unist-util-stringify-position": "^3.0.0" + "unist-util-stringify-position": "^3.0.0", + "uvu": "^0.5.0" } }, "mdast-util-gfm": { @@ -3034,9 +3111,9 @@ "integrity": "sha512-n4Vypz/DZgwo0iMHLQL49dJzlp7YtAJP+N07MZHpjPf/5XJuHUWstviF4Mn2jEiR/GNmtnRRqnwsXExk3igfFA==" }, "micromark": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-3.0.5.tgz", - "integrity": "sha512-QfjERBnPw0G9mxhOCkkbRP0n8SX8lIBLrEKeEVceviUukqVMv3hWE4AgNTOK/W6GWqtPvvIHg2Apl3j1Dxm6aQ==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-3.0.7.tgz", + "integrity": "sha512-67ipZ2CzQVsDyH1kqNLh7dLwe5QMPJwjFBGppW7JCLByaSc6ZufV0ywPOxt13MIDAzzmj3wctDL6Ov5w0fOHXw==", "requires": { "@types/debug": "^4.0.0", "debug": "^4.0.0", @@ -3053,13 +3130,14 @@ "micromark-util-subtokenize": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.1", - "parse-entities": "^3.0.0" + "parse-entities": "^3.0.0", + "uvu": "^0.5.0" } }, "micromark-core-commonmark": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-1.0.1.tgz", - "integrity": "sha512-vEOw8hcQ3nwHkKKNIyP9wBi8M50zjNajtmI+cCUWcVfJS+v5/3WCh4PLKf7PPRZFUutjzl4ZjlHwBWUKfb/SkA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-1.0.3.tgz", + "integrity": "sha512-0E8aE27v0DYHPk40IxzhCdXnZWQuvZ6rbflrx1u8ZZAUJEB48o0fgLXA5+yMab28yXT+mi1Q4LXdsI4oGS6Vng==", "requires": { "micromark-factory-destination": "^1.0.0", "micromark-factory-label": "^1.0.0", @@ -3075,7 +3153,8 @@ "micromark-util-subtokenize": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.1", - "parse-entities": "^3.0.0" + "parse-entities": "^3.0.0", + "uvu": "^0.5.0" } }, "micromark-extension-gfm": { @@ -3093,37 +3172,40 @@ } }, "micromark-extension-gfm-autolink-literal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-1.0.0.tgz", - "integrity": "sha512-t+K0aPK32mXypVTEKV+WRfoT/Rb7MERDgHZVRr56NXpyQQhgMk72QnK4NljYUlrgbuesH+MxiPQwThzqRDIwvA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-1.0.2.tgz", + "integrity": "sha512-z2Asd0v4iV/QoI1l23J1qB6G8IqVWTKmwdlP45YQfdGW47ZzpddyzSxZ78YmlucOLqIbS5H98ekKf9GunFfnLA==", "requires": { "micromark-util-character": "^1.0.0", "micromark-util-sanitize-uri": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "micromark-extension-gfm-strikethrough": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-1.0.1.tgz", - "integrity": "sha512-fzGYXWz9HPWH1uHqYwdyR8XpEtuoYVHUjTdPQTnl3ETVZOQe1NXMwE3RA7AMqeON52hG+kO9g1/P1+pLONBSMQ==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-1.0.3.tgz", + "integrity": "sha512-PJKhBNyrNIo694ZQCE/FBBQOQSb6YC0Wi5Sv0OCah5XunnNaYbtak9CSv9/eq4YeFMMyd1jX84IRwUSE+7ioLA==", "requires": { "micromark-util-chunked": "^1.0.0", "micromark-util-classify-character": "^1.0.0", "micromark-util-resolve-all": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "micromark-extension-gfm-table": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-1.0.0.tgz", - "integrity": "sha512-OATRuHDgEAT/aaJJRSdU12V+s01kNSnJ0jumdfLq5mPy0F5DkR3zbTSFLH4tjVYM0/kEG6umxIhHY62mFe4z5Q==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-1.0.2.tgz", + "integrity": "sha512-mRtt0S/jVT8IRWqIw2Wnl8dr/9yHh+b3NgiDQ4zdgheiAtkFYalng5CUQooFfQeSxQjfV+QKXqtPpjdIHu3AqQ==", "requires": { "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "micromark-extension-gfm-tagfilter": { @@ -3135,14 +3217,15 @@ } }, "micromark-extension-gfm-task-list-item": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-1.0.0.tgz", - "integrity": "sha512-3tkHCq1NNwijtwpjYba9+rl1yvQ4xYg8iQpUAfTJRyq8MtIEsBUF/vW6B9Gh8Qwy1hE2FmpyHhP4jnFAt61zLg==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-1.0.2.tgz", + "integrity": "sha512-8AZib9xxPtppTKig/d00i9uKi96kVgoqin7+TRtGprDb8uTUrN1ZfJ38ga8yUdmu7EDQxr2xH8ltZdbCcmdshg==", "requires": { "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "micromark-factory-destination": { @@ -3156,13 +3239,14 @@ } }, "micromark-factory-label": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-1.0.0.tgz", - "integrity": "sha512-XWEucVZb+qBCe2jmlOnWr6sWSY6NHx+wtpgYFsm4G+dufOf6tTQRRo0bdO7XSlGPu5fyjpJenth6Ksnc5Mwfww==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-1.0.2.tgz", + "integrity": "sha512-CTIwxlOnU7dEshXDQ+dsr2n+yxpP0+fn271pu0bwDIS8uqfFcumXpj5mLn3hSC8iw2MUr6Gx8EcKng1dD7i6hg==", "requires": { "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "micromark-factory-space": { @@ -3175,14 +3259,15 @@ } }, "micromark-factory-title": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-1.0.0.tgz", - "integrity": "sha512-flvC7Gx0dWVWorXuBl09Cr3wB5FTuYec8pMGVySIp2ZlqTcIjN/lFohZcP0EG//krTptm34kozHk7aK/CleCfA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-1.0.2.tgz", + "integrity": "sha512-zily+Nr4yFqgMGRKLpTVsNl5L4PMu485fGFDOQJQBl2NFpjGte1e86zC0da93wf97jrc4+2G2GQudFMHn3IX+A==", "requires": { "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "micromark-factory-whitespace": { @@ -3241,12 +3326,13 @@ } }, "micromark-util-decode-string": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-1.0.0.tgz", - "integrity": "sha512-4g5UJ8P/J8wuRKUXCcB7udQuOBXpLyvBQSLSuznfBLCG+thKG6UTwFnXfHkrr/1wddprkUbPatCzxDjrJ+5zDg==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-1.0.1.tgz", + "integrity": "sha512-Wf3H6jLaO3iIlHEvblESXaKAr72nK7JtBbLLICPwuZc3eJkMcp4j8rJ5Xv1VbQWMCWWDvKUbVUbE2MfQNznwTA==", "requires": { "micromark-util-character": "^1.0.0", "micromark-util-decode-numeric-character-reference": "^1.0.0", + "micromark-util-symbol": "^1.0.0", "parse-entities": "^3.0.0" } }, @@ -3287,13 +3373,14 @@ } }, "micromark-util-subtokenize": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.0.tgz", - "integrity": "sha512-EsnG2qscmcN5XhkqQBZni/4oQbLFjz9yk3ZM/P8a3YUjwV6+6On2wehr1ALx0MxK3+XXXLTzuBKHDFeDFYRdgQ==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.2.tgz", + "integrity": "sha512-d90uqCnXp/cy4G881Ub4psE57Sf8YD0pim9QdjCRNjfas2M1u6Lbt+XZK9gnHL2XFhnozZiEdCa9CNfXSfQ6xA==", "requires": { "micromark-util-chunked": "^1.0.0", "micromark-util-symbol": "^1.0.0", - "micromark-util-types": "^1.0.0" + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" } }, "micromark-util-symbol": { @@ -3315,6 +3402,11 @@ "brace-expansion": "^1.1.7" } }, + "mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==" + }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -3585,20 +3677,6 @@ "unist-util-visit": "^4.0.0" } }, - "remark-lint-no-auto-link-without-protocol": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/remark-lint-no-auto-link-without-protocol/-/remark-lint-no-auto-link-without-protocol-3.1.0.tgz", - "integrity": "sha512-GqZXDu/xfajWCEPhS8UjO9dYMTlY5lD8ShoYIaouUgz3nNQvLwX33pTKqfRpd/R9EmV1uQw0PCJ6TYwhBrnOXQ==", - "requires": { - "@types/mdast": "^3.0.0", - "mdast-util-to-string": "^3.0.0", - "unified": "^10.0.0", - "unified-lint-rule": "^2.0.0", - "unist-util-generated": "^2.0.0", - "unist-util-position": "^4.0.0", - "unist-util-visit": "^4.0.0" - } - }, "remark-lint-no-blockquote-without-marker": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/remark-lint-no-blockquote-without-marker/-/remark-lint-no-blockquote-without-marker-5.1.0.tgz", @@ -3999,9 +4077,9 @@ } }, "remark-preset-lint-recommended": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/remark-preset-lint-recommended/-/remark-preset-lint-recommended-6.1.0.tgz", - "integrity": "sha512-1jUbuzRAP5idWu9GZ5x7M96Z1TcTWwJu0C8ziz5RLezWL9rChhw9kV6s0beR0lrY5Kl5E5pjA6SKaP7NyGi2ug==", + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/remark-preset-lint-recommended/-/remark-preset-lint-recommended-6.1.1.tgz", + "integrity": "sha512-ez8/QTY8x/XKZcewXbWd+vQWWhNbgHCEq+NwY6sf9/QuwxBarG9cmSkP9yXi5glYKGVaEefVZmrZRB4jvZWcog==", "requires": { "@types/mdast": "^3.0.0", "remark-lint": "^9.0.0", @@ -4009,7 +4087,6 @@ "remark-lint-hard-break-spaces": "^3.0.0", "remark-lint-list-item-bullet-indent": "^4.0.0", "remark-lint-list-item-indent": "^3.0.0", - "remark-lint-no-auto-link-without-protocol": "^3.0.0", "remark-lint-no-blockquote-without-marker": "^5.0.0", "remark-lint-no-duplicate-definitions": "^3.0.0", "remark-lint-no-heading-content-indent": "^4.0.0", @@ -4052,6 +4129,14 @@ "fsevents": "~2.3.2" } }, + "sade": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.7.4.tgz", + "integrity": "sha512-y5yauMD93rX840MwUJr7C1ysLFBgMspsdTo4UVrDg3fXDvtwOyIqykhVAAm6fk/3au77773itJStObgK+LKaiA==", + "requires": { + "mri": "^1.1.0" + } + }, "semver": { "version": "7.3.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", @@ -4106,6 +4191,11 @@ "vfile": "^5.1.0" } }, + "totalist": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-2.0.0.tgz", + "integrity": "sha512-+Y17F0YzxfACxTyjfhnJQEe7afPA0GSpYlFkl2VFMxYP7jshQf9gXV7cH47EfToBumFThfKBvfAcoUn6fdNeRQ==" + }, "trough": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/trough/-/trough-2.0.2.tgz", @@ -4214,6 +4304,18 @@ "unist-util-is": "^5.0.0" } }, + "uvu": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.2.tgz", + "integrity": "sha512-m2hLe7I2eROhh+tm3WE5cTo/Cv3WQA7Oc9f7JB6uWv+/zVKvfAm53bMyOoGOSZeQ7Ov2Fu9pLhFr7p07bnT20w==", + "requires": { + "dequal": "^2.0.0", + "diff": "^5.0.0", + "kleur": "^4.0.3", + "sade": "^1.7.3", + "totalist": "^2.0.0" + } + }, "vfile": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/vfile/-/vfile-5.1.0.tgz", diff --git a/tools/lint-md/package.json b/tools/lint-md/package.json index ffa82b4b14f2fb..a6c883f9882c85 100644 --- a/tools/lint-md/package.json +++ b/tools/lint-md/package.json @@ -14,7 +14,7 @@ "vfile-reporter": "^7.0.2" }, "devDependencies": { - "@rollup/plugin-commonjs": "^20.0.0", + "@rollup/plugin-commonjs": "^21.0.0", "@rollup/plugin-node-resolve": "^13.0.5", "rollup": "^2.58.0" } From e2c9e1ccdd579f215b62668f1b4374e72bea8e06 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 12 Oct 2021 11:26:53 -0700 Subject: [PATCH 004/118] meta: consolidate AUTHORS entries for evantorrie MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a .mailmap entry for evantorrie to consolidate their two AUTHORS entries into one. PR-URL: https://github.com/nodejs/node/pull/40430 Reviewed-By: Luigi Pinca Reviewed-By: Juan José Arboleda --- .mailmap | 1 + AUTHORS | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index ea3fae1ae350f9..8a3d2aa6cc210d 100644 --- a/.mailmap +++ b/.mailmap @@ -132,6 +132,7 @@ EungJun Yi Evan Larkin Evan Lucas Evan Lucas +Evan Torrie FangDun Cai Fangshi He Farid Neshat diff --git a/AUTHORS b/AUTHORS index 98d3796f357e9d..892ed5cb90b13c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1332,7 +1332,6 @@ Benedikt Meurer Kai Cataldo Victor Felder Yann Pringault -Evan Torrie Michael Lefkowitz Viktor Karpov Lukasz Gasior From 4724e0747613caa3785a54ab9c719e91b88872ea Mon Sep 17 00:00:00 2001 From: Isaac Brodsky Date: Thu, 7 Oct 2021 17:59:56 -0700 Subject: [PATCH 005/118] doc: indicate n-api out params that may be NULL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is useful information to have for applications that don't need to read the other properties. The implementation checks for `nullptr`, see: https://github.com/nodejs/node/blob/master/src/js_native_api_v8.cc#L2879 PR-URL: https://github.com/nodejs/node/pull/40371 Reviewed-By: Chengzhong Wu Reviewed-By: Tobias Nießen Reviewed-By: Michael Dawson Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- doc/api/n-api.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 5fb8cc65859ff1..f4025ffdbf37f7 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -2821,6 +2821,8 @@ Returns `napi_ok` if the API succeeded. This API returns various properties of a typed array. +Any of the out parameters may be `NULL` if that property is unneeded. + *Warning*: Use caution while using this API since the underlying data buffer is managed by the VM. @@ -2851,6 +2853,8 @@ napi_status napi_get_dataview_info(napi_env env, Returns `napi_ok` if the API succeeded. +Any of the out parameters may be `NULL` if that property is unneeded. + This API returns various properties of a `DataView`. #### napi_get_date_value From 06706e8dd286b8c8ac554dabfe25031beb9fffb0 Mon Sep 17 00:00:00 2001 From: Mestery Date: Sun, 10 Oct 2021 21:36:08 +0200 Subject: [PATCH 006/118] meta: add `typings` to label-pr-config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40401 Reviewed-By: Antoine du Hamel Reviewed-By: Michaël Zasso Reviewed-By: Zijian Liu --- .github/label-pr-config.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/label-pr-config.yml b/.github/label-pr-config.yml index 313e928c4d3558..93aeaab0257369 100644 --- a/.github/label-pr-config.yml +++ b/.github/label-pr-config.yml @@ -71,6 +71,7 @@ subSystemLabels: # all other tool changes should be marked as such /^tools\//: tools /^\.eslint|\.remark|\.editorconfig/: tools + /^typings\//: typings ## Dependencies # libuv needs an explicit mapping, as the ordinary /deps/ mapping below would @@ -186,6 +187,7 @@ allJsSubSystems: - timers - tls - tty + - typings - url - util - v8 From 934dcc85c31d07b26ed443bf3048e6cbde1c2a2f Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Thu, 14 Oct 2021 15:10:36 +0200 Subject: [PATCH 007/118] doc: update Collaborator guide to reflect GitHub web UI update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40456 Reviewed-By: Darshan Sen Reviewed-By: Richard Lau Reviewed-By: Michaël Zasso Reviewed-By: Michael Dawson --- doc/guides/collaborator-guide.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/guides/collaborator-guide.md b/doc/guides/collaborator-guide.md index e3d48c09c5338a..50f2a1264001a2 100644 --- a/doc/guides/collaborator-guide.md +++ b/doc/guides/collaborator-guide.md @@ -242,8 +242,8 @@ files also qualify as affecting the `node` binary: If there are GitHub Actions CI failures unrelated to the change in the pull -request, try "Re-run all jobs". It's under the "🔄 Re-run jobs" button, on the -right-hand side of "Checks" tab. +request, try the "🔄 Re-run all jobs" button, on the right-hand side of the +"Checks" tab. If there are Jenkins CI failures unrelated to the change in the pull request, try "Resume Build". It is in the left navigation of the relevant From 618bbbf2f45184557176604cea4e49d973020f41 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 13 Oct 2021 12:00:14 -0700 Subject: [PATCH 008/118] meta: consolidate AUTHORS entries for ebickle PR-URL: https://github.com/nodejs/node/pull/40447 Reviewed-By: Zijian Liu Reviewed-By: Luigi Pinca --- .mailmap | 1 + AUTHORS | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index 8a3d2aa6cc210d..19c8811d513138 100644 --- a/.mailmap +++ b/.mailmap @@ -120,6 +120,7 @@ Doug Wade Eduard Burtescu Einar Otto Stangvik Elliott Cable +Eric Bickle Eric Phetteplace Ernesto Salazar Erwin W. Ramadhan diff --git a/AUTHORS b/AUTHORS index 892ed5cb90b13c..693878d20788f3 100644 --- a/AUTHORS +++ b/AUTHORS @@ -2987,7 +2987,6 @@ Andrew Neitsch RamanandPatil forfun414 David Gilbertson -Eric Bickle Joe Pea ExE Boss <3889017+ExE-Boss@users.noreply.github.com> Mateusz Krawczuk From ff3b7d228e5decb3f3bd885b3cd39dd2ac6a8850 Mon Sep 17 00:00:00 2001 From: Shelley Vohr Date: Mon, 11 Oct 2021 12:49:40 +0200 Subject: [PATCH 009/118] src: ensure V8 initialized before marking milestone PR-URL: https://github.com/nodejs/node/pull/40405 Refs: https://github.com/electron/electron/pull/31349 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Joyee Cheung --- src/env.cc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/env.cc b/src/env.cc index 1cc7da1ce15f43..2cb2dccdf32ba4 100644 --- a/src/env.cc +++ b/src/env.cc @@ -458,8 +458,11 @@ void Environment::InitializeMainContext(Local context, environment_start_time_); performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START, per_process::node_start_time); - performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START, - performance::performance_v8_start); + + if (per_process::v8_initialized) { + performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START, + performance::performance_v8_start); + } } Environment::~Environment() { From bfdd32fa6229e76b584dabe700d3017b6989286e Mon Sep 17 00:00:00 2001 From: Jiawen Geng Date: Fri, 15 Oct 2021 06:27:27 +0000 Subject: [PATCH 010/118] build: avoid run find inactive authors on forked repo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40465 Reviewed-By: Michaël Zasso Reviewed-By: Antoine du Hamel Reviewed-By: Tobias Nießen Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott --- .github/workflows/find-inactive-collaborators.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/find-inactive-collaborators.yml b/.github/workflows/find-inactive-collaborators.yml index ca582839fc8b7d..1d7d8304d1888a 100644 --- a/.github/workflows/find-inactive-collaborators.yml +++ b/.github/workflows/find-inactive-collaborators.yml @@ -13,7 +13,7 @@ env: jobs: find: - + if: github.repository == 'nodejs/node' runs-on: ubuntu-latest steps: From c15afda79f7e0f4318848649ef43c78fea46d0ba Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Thu, 7 Oct 2021 12:03:10 +0800 Subject: [PATCH 011/118] src: get embedder options on-demand Only query embedder options when they are needed so that the bootstrap remains as stateless as possible so that the bootstrap snapshot is controlled solely by configure options, and subsequent runtime changes should be done in pre-execution. PR-URL: https://github.com/nodejs/node/pull/40357 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Shelley Vohr --- lib/internal/bootstrap/pre_execution.js | 7 ++--- lib/internal/options.js | 28 ++++++++++------- src/node_options.cc | 41 ++++++++++++++++--------- src/node_options.h | 2 +- 4 files changed, 48 insertions(+), 30 deletions(-) diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js index a4c73cba5481b3..f2a10641906e31 100644 --- a/lib/internal/bootstrap/pre_execution.js +++ b/lib/internal/bootstrap/pre_execution.js @@ -11,8 +11,7 @@ const { const { getOptionValue, - noGlobalSearchPaths, - shouldNotRegisterESMLoader, + getEmbedderOptions, } = require('internal/options'); const { reconnectZeroFillToggle } = require('internal/buffer'); @@ -421,7 +420,7 @@ function initializeWASI() { function initializeCJSLoader() { const CJSLoader = require('internal/modules/cjs/loader'); - if (!noGlobalSearchPaths) { + if (!getEmbedderOptions().noGlobalSearchPaths) { CJSLoader.Module._initPaths(); } // TODO(joyeecheung): deprecate this in favor of a proper hook? @@ -433,7 +432,7 @@ function initializeESMLoader() { // Create this WeakMap in js-land because V8 has no C++ API for WeakMap. internalBinding('module_wrap').callbackMap = new SafeWeakMap(); - if (shouldNotRegisterESMLoader) return; + if (getEmbedderOptions().shouldNotRegisterESMLoader) return; const { setImportModuleDynamicallyCallback, diff --git a/lib/internal/options.js b/lib/internal/options.js index cb694c7dfdd576..01b334d4ec5614 100644 --- a/lib/internal/options.js +++ b/lib/internal/options.js @@ -1,36 +1,43 @@ 'use strict'; const { - getOptions, - noGlobalSearchPaths, - shouldNotRegisterESMLoader, + getCLIOptions, + getEmbedderOptions: getEmbedderOptionsFromBinding, } = internalBinding('options'); let warnOnAllowUnauthorized = true; let optionsMap; let aliasesMap; +let embedderOptions; -// getOptions() would serialize the option values from C++ land. +// getCLIOptions() would serialize the option values from C++ land. // It would error if the values are queried before bootstrap is // complete so that we don't accidentally include runtime-dependent // states into a runtime-independent snapshot. -function getOptionsFromBinding() { +function getCLIOptionsFromBinding() { if (!optionsMap) { - ({ options: optionsMap } = getOptions()); + ({ options: optionsMap } = getCLIOptions()); } return optionsMap; } function getAliasesFromBinding() { if (!aliasesMap) { - ({ aliases: aliasesMap } = getOptions()); + ({ aliases: aliasesMap } = getCLIOptions()); } return aliasesMap; } +function getEmbedderOptions() { + if (!embedderOptions) { + embedderOptions = getEmbedderOptionsFromBinding(); + } + return embedderOptions; +} + function getOptionValue(optionName) { - const options = getOptionsFromBinding(); + const options = getCLIOptionsFromBinding(); if (optionName.startsWith('--no-')) { const option = options.get('--' + optionName.slice(5)); return option && !option.value; @@ -54,13 +61,12 @@ function getAllowUnauthorized() { module.exports = { get options() { - return getOptionsFromBinding(); + return getCLIOptionsFromBinding(); }, get aliases() { return getAliasesFromBinding(); }, getOptionValue, getAllowUnauthorized, - noGlobalSearchPaths, - shouldNotRegisterESMLoader, + getEmbedderOptions }; diff --git a/src/node_options.cc b/src/node_options.cc index c7f153f1d87817..acec2d72515d1d 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -915,7 +915,7 @@ std::string GetBashCompletion() { // Return a map containing all the options and their metadata as well // as the aliases -void GetOptions(const FunctionCallbackInfo& args) { +void GetCLIOptions(const FunctionCallbackInfo& args) { Mutex::ScopedLock lock(per_process::cli_options_mutex); Environment* env = Environment::GetCurrent(args); if (!env->has_run_bootstrapping_code()) { @@ -1056,13 +1056,38 @@ void GetOptions(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ret); } +void GetEmbedderOptions(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + if (!env->has_run_bootstrapping_code()) { + // No code because this is an assertion. + return env->ThrowError( + "Should not query options before bootstrapping is done"); + } + Isolate* isolate = args.GetIsolate(); + Local context = env->context(); + Local ret = Object::New(isolate); + + if (ret->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"), + Boolean::New(isolate, env->should_not_register_esm_loader())) + .IsNothing()) return; + + if (ret->Set(context, + FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"), + Boolean::New(isolate, env->no_global_search_paths())) + .IsNothing()) return; + + args.GetReturnValue().Set(ret); +} + void Initialize(Local target, Local unused, Local context, void* priv) { Environment* env = Environment::GetCurrent(context); Isolate* isolate = env->isolate(); - env->SetMethodNoSideEffect(target, "getOptions", GetOptions); + env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions); + env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions); Local env_settings = Object::New(isolate); NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment); @@ -1072,18 +1097,6 @@ void Initialize(Local target, context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings) .Check(); - target - ->Set(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"), - Boolean::New(isolate, env->should_not_register_esm_loader())) - .Check(); - - target - ->Set(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"), - Boolean::New(isolate, env->no_global_search_paths())) - .Check(); - Local types = Object::New(isolate); NODE_DEFINE_CONSTANT(types, kNoOp); NODE_DEFINE_CONSTANT(types, kV8Option); diff --git a/src/node_options.h b/src/node_options.h index e5744333140a02..5cf2bb442fad40 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -461,7 +461,7 @@ class OptionsParser { template friend class OptionsParser; - friend void GetOptions(const v8::FunctionCallbackInfo& args); + friend void GetCLIOptions(const v8::FunctionCallbackInfo& args); friend std::string GetBashCompletion(); }; From 04c2cbecb9283c41556e316c9919c1c2f07546c7 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 13 Oct 2021 11:51:19 -0700 Subject: [PATCH 012/118] tools: update tools/lint-md dependencies to support GFM footnotes PR-URL: https://github.com/nodejs/node/pull/40445 Reviewed-By: Antoine du Hamel Reviewed-By: Luigi Pinca --- tools/lint-md/lint-md.mjs | 1020 +++++++++++++++++-------------- tools/lint-md/package-lock.json | 154 +++-- tools/lint-md/package.json | 4 +- 3 files changed, 684 insertions(+), 494 deletions(-) diff --git a/tools/lint-md/lint-md.mjs b/tools/lint-md/lint-md.mjs index bd893097132255..9d3903a1d4b478 100644 --- a/tools/lint-md/lint-md.mjs +++ b/tools/lint-md/lint-md.mjs @@ -1738,50 +1738,6 @@ function constructs(existing, list) { splice(existing, 0, 0, before); } -/** - * Combine several HTML extensions into one. - * - * @param {HtmlExtension[]} htmlExtensions List of HTML extensions. - * @returns {HtmlExtension} A single combined extension. - */ -function combineHtmlExtensions(htmlExtensions) { - /** @type {HtmlExtension} */ - const handlers = {}; - let index = -1; - - while (++index < htmlExtensions.length) { - htmlExtension(handlers, htmlExtensions[index]); - } - - return handlers -} - -/** - * Merge `extension` into `all`. - * - * @param {HtmlExtension} all Extension to merge into. - * @param {HtmlExtension} extension Extension to merge. - * @returns {void} - */ -function htmlExtension(all, extension) { - /** @type {string} */ - let hook; - - for (hook in extension) { - const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined; - const left = maybe || (all[hook] = {}); - const right = extension[hook]; - /** @type {string} */ - let type; - - if (right) { - for (type in right) { - left[type] = right[type]; - } - } - } -} - // This module is generated by `script/`. // // CommonMark handles attention (emphasis, strong) markers based on what comes @@ -8640,7 +8596,7 @@ const listItemPrefixWhitespaceConstruct = { /** @type {Construct} */ const indentConstruct = { - tokenize: tokenizeIndent, + tokenize: tokenizeIndent$1, partial: true }; /** @@ -8820,7 +8776,7 @@ function tokenizeListContinuation(effects, ok, nok) { * @this {TokenizeContextWithState} */ -function tokenizeIndent(effects, ok, nok) { +function tokenizeIndent$1(effects, ok, nok) { const self = this; return factorySpace( effects, @@ -13827,7 +13783,8 @@ function joinDefinition(left, right) { /** * @typedef {import('mdast').Root|import('mdast').Content} Node - * @typedef {import('mdast-util-to-markdown').Options} Options + * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownOptions + * @typedef {Omit} Options */ /** @type {import('unified').Plugin<[Options]|void[], Node, string>} */ @@ -13843,7 +13800,10 @@ function remarkStringify(options) { // Note: this option is not in the readme. // The goal is for it to be set by plugins on `data` instead of being // passed by users. - extensions: this.data('toMarkdownExtensions') || [] + extensions: + /** @type {ToMarkdownOptions['extensions']} */ ( + this.data('toMarkdownExtensions') + ) || [] }) ) }; @@ -14479,201 +14439,419 @@ function previousUnbalanced(events) { return result } -const characterReferences = {'"': 'quot', '&': 'amp', '<': 'lt', '>': 'gt'}; - /** - * Encode only the dangerous HTML characters. - * - * This ensures that certain characters which have special meaning in HTML are - * dealt with. - * Technically, we can skip `>` and `"` in many cases, but CM includes them. - * - * @param {string} value - * @returns {string} + * @typedef {import('micromark-util-types').Extension} Extension + * @typedef {import('micromark-util-types').Resolver} Resolver + * @typedef {import('micromark-util-types').Token} Token + * @typedef {import('micromark-util-types').Tokenizer} Tokenizer + * @typedef {import('micromark-util-types').Exiter} Exiter + * @typedef {import('micromark-util-types').State} State + * @typedef {import('micromark-util-types').Event} Event + */ +const indent = { + tokenize: tokenizeIndent, + partial: true +}; +/** + * @returns {Extension} */ -function encode(value) { - return value.replace(/["&<>]/g, replace) - /** - * @param {string} value - * @returns {string} - */ - function replace(value) { - // @ts-expect-error Hush, it’s fine. - return '&' + characterReferences[value] + ';' +function gfmFootnote() { + /** @type {Extension} */ + return { + document: { + [91]: { + tokenize: tokenizeDefinitionStart, + continuation: { + tokenize: tokenizeDefinitionContinuation + }, + exit: gfmFootnoteDefinitionEnd + } + }, + text: { + [91]: { + tokenize: tokenizeGfmFootnoteCall + }, + [93]: { + add: 'after', + tokenize: tokenizePotentialGfmFootnoteCall, + resolveTo: resolveToPotentialGfmFootnoteCall + } + } } } +/** @type {Tokenizer} */ -/** - * Make a value safe for injection as a URL. - * - * This encodes unsafe characters with percent-encoding and skips already - * encoded sequences (see `normalizeUri` below). - * Further unsafe characters are encoded as character references (see - * `micromark-util-encode`). - * - * Then, a regex of allowed protocols can be given, in which case the URL is - * sanitized. - * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, - * or `/^https?$/i` for `img[src]`. - * If the URL includes an unknown protocol (one not matched by `protocol`, such - * as a dangerous example, `javascript:`), the value is ignored. - * - * @param {string|undefined} url - * @param {RegExp} [protocol] - * @returns {string} - */ -function sanitizeUri(url, protocol) { - const value = encode(normalizeUri(url || '')); +function tokenizePotentialGfmFootnoteCall(effects, ok, nok) { + const self = this; + let index = self.events.length; + /** @type {string[]} */ + // @ts-expect-error It’s fine! - if (!protocol) { - return value + const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []); + /** @type {Token} */ + + let labelStart; // Find an opening. + + while (index--) { + const token = self.events[index][1]; + + if (token.type === 'labelImage') { + labelStart = token; + break + } // Exit if we’ve walked far enough. + + if ( + token.type === 'gfmFootnoteCall' || + token.type === 'labelLink' || + token.type === 'label' || + token.type === 'image' || + token.type === 'link' + ) { + break + } } - const colon = value.indexOf(':'); - const questionMark = value.indexOf('?'); - const numberSign = value.indexOf('#'); - const slash = value.indexOf('/'); + return start + /** @type {State} */ - if ( - // If there is no protocol, it’s relative. - colon < 0 || // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol. - (slash > -1 && colon > slash) || - (questionMark > -1 && colon > questionMark) || - (numberSign > -1 && colon > numberSign) || // It is a protocol, it should be allowed. - protocol.test(value.slice(0, colon)) - ) { - return value + function start(code) { + if (!labelStart || !labelStart._balanced) { + return nok(code) + } + + const id = normalizeIdentifier( + self.sliceSerialize({ + start: labelStart.end, + end: self.now() + }) + ); + + if (id.charCodeAt(0) !== 94 || !defined.includes(id.slice(1))) { + return nok(code) + } + + effects.enter('gfmFootnoteCallLabelMarker'); + effects.consume(code); + effects.exit('gfmFootnoteCallLabelMarker'); + return ok(code) } +} +/** @type {Resolver} */ - return '' +function resolveToPotentialGfmFootnoteCall(events, context) { + let index = events.length; + + while (index--) { + if ( + events[index][1].type === 'labelImage' && + events[index][0] === 'enter' + ) { + events[index][1]; + break + } + } + + // Change the `labelImageMarker` to a `data`. + events[index + 1][1].type = 'data'; + events[index + 3][1].type = 'gfmFootnoteCallLabelMarker'; // The whole (without `!`): + + const call = { + type: 'gfmFootnoteCall', + start: Object.assign({}, events[index + 3][1].start), + end: Object.assign({}, events[events.length - 1][1].end) + }; // The `^` marker + + const marker = { + type: 'gfmFootnoteCallMarker', + start: Object.assign({}, events[index + 3][1].end), + end: Object.assign({}, events[index + 3][1].end) + }; // Increment the end 1 character. + + marker.end.column++; + marker.end.offset++; + marker.end._bufferIndex++; + const string = { + type: 'gfmFootnoteCallString', + start: Object.assign({}, marker.end), + end: Object.assign({}, events[events.length - 1][1].start) + }; + const chunk = { + type: 'chunkString', + contentType: 'string', + start: Object.assign({}, string.start), + end: Object.assign({}, string.end) + }; + /** @type {Event[]} */ + + const replacement = [ + // Take the `labelImageMarker` (now `data`, the `!`) + events[index + 1], + events[index + 2], + ['enter', call, context], // The `[` + events[index + 3], + events[index + 4], // The `^`. + ['enter', marker, context], + ['exit', marker, context], // Everything in between. + ['enter', string, context], + ['enter', chunk, context], + ['exit', chunk, context], + ['exit', string, context], // The ending (`]`, properly parsed and labelled). + events[events.length - 2], + events[events.length - 1], + ['exit', call, context] + ]; + events.splice(index, events.length - index + 1, ...replacement); + return events } -/** - * Normalize a URL (such as used in definitions). - * - * Encode unsafe characters with percent-encoding, skipping already encoded - * sequences. - * - * @param {string} value - * @returns {string} - */ +/** @type {Tokenizer} */ -function normalizeUri(value) { +function tokenizeGfmFootnoteCall(effects, ok, nok) { + const self = this; /** @type {string[]} */ - const result = []; - let index = -1; - let start = 0; - let skip = 0; + // @ts-expect-error It’s fine! - while (++index < value.length) { - const code = value.charCodeAt(index); - /** @type {string} */ + const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []); + let size = 0; + /** @type {boolean} */ + + let data; + return start + /** @type {State} */ + + function start(code) { + effects.enter('gfmFootnoteCall'); + effects.enter('gfmFootnoteCallLabelMarker'); + effects.consume(code); + effects.exit('gfmFootnoteCallLabelMarker'); + return callStart + } + /** @type {State} */ + + function callStart(code) { + if (code !== 94) return nok(code) + effects.enter('gfmFootnoteCallMarker'); + effects.consume(code); + effects.exit('gfmFootnoteCallMarker'); + effects.enter('gfmFootnoteCallString'); + effects.enter('chunkString').contentType = 'string'; + return callData + } + /** @type {State} */ + + function callData(code) { + /** @type {Token} */ + let token; + + if (code === null || code === 91 || size++ > 999) { + return nok(code) + } + + if (code === 93) { + if (!data) { + return nok(code) + } + + effects.exit('chunkString'); + token = effects.exit('gfmFootnoteCallString'); + return defined.includes(normalizeIdentifier(self.sliceSerialize(token))) + ? end(code) + : nok(code) + } + + effects.consume(code); + + if (!markdownLineEndingOrSpace(code)) { + data = true; + } + + return code === 92 ? callEscape : callData + } + /** @type {State} */ + + function callEscape(code) { + if (code === 91 || code === 92 || code === 93) { + effects.consume(code); + size++; + return callData + } + + return callData(code) + } + /** @type {State} */ + + function end(code) { + effects.enter('gfmFootnoteCallLabelMarker'); + effects.consume(code); + effects.exit('gfmFootnoteCallLabelMarker'); + effects.exit('gfmFootnoteCall'); + return ok + } +} +/** @type {Tokenizer} */ + +function tokenizeDefinitionStart(effects, ok, nok) { + const self = this; + /** @type {string[]} */ + // @ts-expect-error It’s fine! + + const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []); + /** @type {string} */ + + let identifier; + let size = 0; + /** @type {boolean|undefined} */ + + let data; + return start + /** @type {State} */ + + function start(code) { + effects.enter('gfmFootnoteDefinition')._container = true; + effects.enter('gfmFootnoteDefinitionLabel'); + effects.enter('gfmFootnoteDefinitionLabelMarker'); + effects.consume(code); + effects.exit('gfmFootnoteDefinitionLabelMarker'); + return labelStart + } + /** @type {State} */ + + function labelStart(code) { + if (code === 94) { + effects.enter('gfmFootnoteDefinitionMarker'); + effects.consume(code); + effects.exit('gfmFootnoteDefinitionMarker'); + effects.enter('gfmFootnoteDefinitionLabelString'); + return atBreak + } + + return nok(code) + } + /** @type {State} */ + + function atBreak(code) { + /** @type {Token} */ + let token; + + if (code === null || code === 91 || size > 999) { + return nok(code) + } + + if (code === 93) { + if (!data) { + return nok(code) + } - let replace = ''; // A correct percent encoded value. + token = effects.exit('gfmFootnoteDefinitionLabelString'); + identifier = normalizeIdentifier(self.sliceSerialize(token)); + effects.enter('gfmFootnoteDefinitionLabelMarker'); + effects.consume(code); + effects.exit('gfmFootnoteDefinitionLabelMarker'); + effects.exit('gfmFootnoteDefinitionLabel'); + return labelAfter + } + if (markdownLineEnding(code)) { + effects.enter('lineEnding'); + effects.consume(code); + effects.exit('lineEnding'); + size++; + return atBreak + } + + effects.enter('chunkString').contentType = 'string'; + return label(code) + } + /** @type {State} */ + + function label(code) { if ( - code === 37 && - asciiAlphanumeric(value.charCodeAt(index + 1)) && - asciiAlphanumeric(value.charCodeAt(index + 2)) + code === null || + markdownLineEnding(code) || + code === 91 || + code === 93 || + size > 999 ) { - skip = 2; - } // ASCII. - else if (code < 128) { - if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code))) { - replace = String.fromCharCode(code); - } - } // Astral. - else if (code > 55295 && code < 57344) { - const next = value.charCodeAt(index + 1); // A correct surrogate pair. - - if (code < 56320 && next > 56319 && next < 57344) { - replace = String.fromCharCode(code, next); - skip = 1; - } // Lone surrogate. - else { - replace = '\uFFFD'; - } - } // Unicode. - else { - replace = String.fromCharCode(code); + effects.exit('chunkString'); + return atBreak(code) } - if (replace) { - result.push(value.slice(start, index), encodeURIComponent(replace)); - start = index + skip + 1; - replace = ''; + if (!markdownLineEndingOrSpace(code)) { + data = true; } - if (skip) { - index += skip; - skip = 0; + size++; + effects.consume(code); + return code === 92 ? labelEscape : label + } + /** @type {State} */ + + function labelEscape(code) { + if (code === 91 || code === 92 || code === 93) { + effects.consume(code); + size++; + return label } + + return label(code) } + /** @type {State} */ - return result.join('') + value.slice(start) -} + function labelAfter(code) { + if (code === 58) { + effects.enter('definitionMarker'); + effects.consume(code); + effects.exit('definitionMarker'); // Any whitespace after the marker is eaten, forming indented code + // is not possible. + // No space is also fine, just like a block quote marker. -/** - * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension - * @typedef {import('micromark-util-types').Handle} Handle - * @typedef {import('micromark-util-types').CompileContext} CompileContext - * @typedef {import('micromark-util-types').Token} Token - */ -/** @type {HtmlExtension} */ + return factorySpace(effects, done, 'gfmFootnoteDefinitionWhitespace') + } -const gfmAutolinkLiteralHtml = { - exit: { - literalAutolinkEmail, - literalAutolinkHttp, - literalAutolinkWww + return nok(code) } -}; -/** @type {Handle} */ + /** @type {State} */ -function literalAutolinkWww(token) { - anchorFromToken.call(this, token, 'http://'); -} -/** @type {Handle} */ + function done(code) { + if (!defined.includes(identifier)) { + defined.push(identifier); + } -function literalAutolinkEmail(token) { - anchorFromToken.call(this, token, 'mailto:'); + return ok(code) + } } -/** @type {Handle} */ +/** @type {Tokenizer} */ -function literalAutolinkHttp(token) { - anchorFromToken.call(this, token); +function tokenizeDefinitionContinuation(effects, ok, nok) { + // Either a blank line, which is okay, or an indented thing. + return effects.check(blankLine, ok, effects.attempt(indent, ok, nok)) } -/** - * @this CompileContext - * @param {Token} token - * @param {string} [protocol] - * @returns {void} - */ +/** @type {Exiter} */ -function anchorFromToken(token, protocol) { - const url = this.sliceSerialize(token); - this.tag(''); - this.raw(this.encode(url)); - this.tag(''); +function gfmFootnoteDefinitionEnd(effects) { + effects.exit('gfmFootnoteDefinition'); } +/** @type {Tokenizer} */ -/** - * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension - */ +function tokenizeIndent(effects, ok, nok) { + const self = this; + return factorySpace( + effects, + afterPrefix, + 'gfmFootnoteDefinitionIndent', + 4 + 1 + ) + /** @type {State} */ -/** @type {HtmlExtension} */ -const gfmStrikethroughHtml = { - enter: { - strikethrough() { - this.tag(''); - } - }, - exit: { - strikethrough() { - this.tag(''); - } + function afterPrefix(code) { + const tail = self.events[self.events.length - 1]; + return tail && + tail[1].type === 'gfmFootnoteDefinitionIndent' && + tail[2].sliceSerialize(tail[1], true).length === 4 + ? ok(code) + : nok(code) } -}; +} /** * @typedef {import('micromark-util-types').Extension} Extension @@ -14835,156 +15013,6 @@ function gfmStrikethrough(options = {}) { } } -/** - * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension - */ - -/** - * @typedef {import('./syntax.js').Align} Align - */ -const alignment = { - null: '', - left: ' align="left"', - right: ' align="right"', - center: ' align="center"' -}; -/** @type {HtmlExtension} */ - -const gfmTableHtml = { - enter: { - table(token) { - this.lineEndingIfNeeded(); - this.tag(''); // @ts-expect-error Custom. - - this.setData('tableAlign', token._align); - }, - - tableBody() { - // Clear slurping line ending from the delimiter row. - this.setData('slurpOneLineEnding'); - this.tag(''); - }, - - tableData() { - /** @type {string|undefined} */ - const align = // @ts-expect-error Custom. - alignment[this.getData('tableAlign')[this.getData('tableColumn')]]; - - if (align === undefined) { - // Capture results to ignore them. - this.buffer(); - } else { - this.lineEndingIfNeeded(); - this.tag(''); - } - }, - - tableHead() { - this.lineEndingIfNeeded(); - this.tag(''); - }, - - tableHeader() { - this.lineEndingIfNeeded(); - this.tag( - '' - ); - }, - - tableRow() { - this.setData('tableColumn', 0); - this.lineEndingIfNeeded(); - this.tag(''); - } - }, - exit: { - // Overwrite the default code text data handler to unescape escaped pipes when - // they are in tables. - codeTextData(token) { - let value = this.sliceSerialize(token); - - if (this.getData('tableAlign')) { - value = value.replace(/\\([\\|])/g, replace$1); - } - - this.raw(this.encode(value)); - }, - - table() { - this.setData('tableAlign'); // If there was no table body, make sure the slurping from the delimiter row - // is cleared. - - this.setData('slurpAllLineEndings'); - this.lineEndingIfNeeded(); - this.tag('
'); - }, - - tableBody() { - this.lineEndingIfNeeded(); - this.tag('

-薛定谔的猫 +唯然
diff --git a/tools/node_modules/eslint/lib/cli-engine/cli-engine.js b/tools/node_modules/eslint/lib/cli-engine/cli-engine.js index aae71607d2c89a..e3647018d26fa3 100644 --- a/tools/node_modules/eslint/lib/cli-engine/cli-engine.js +++ b/tools/node_modules/eslint/lib/cli-engine/cli-engine.js @@ -570,8 +570,10 @@ class CLIEngine { /** * Creates a new instance of the core CLI engine. * @param {CLIEngineOptions} providedOptions The options for this instance. + * @param {Object} [additionalData] Additional settings that are not CLIEngineOptions. + * @param {Record|null} [additionalData.preloadedPlugins] Preloaded plugins. */ - constructor(providedOptions) { + constructor(providedOptions, { preloadedPlugins } = {}) { const options = Object.assign( Object.create(null), defaultOptions, @@ -584,6 +586,13 @@ class CLIEngine { } const additionalPluginPool = new Map(); + + if (preloadedPlugins) { + for (const [id, plugin] of Object.entries(preloadedPlugins)) { + additionalPluginPool.set(id, plugin); + } + } + const cacheFilePath = getCacheFile( options.cacheLocation || options.cacheFile, options.cwd @@ -698,26 +707,6 @@ class CLIEngine { }); } - - /** - * Add a plugin by passing its configuration - * @param {string} name Name of the plugin. - * @param {Plugin} pluginObject Plugin configuration object. - * @returns {void} - */ - addPlugin(name, pluginObject) { - const { - additionalPluginPool, - configArrayFactory, - lastConfigArrays - } = internalSlotsMap.get(this); - - additionalPluginPool.set(name, pluginObject); - configArrayFactory.clearCache(); - lastConfigArrays.length = 1; - lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile(); - } - /** * Resolves the patterns passed into executeOnFiles() into glob-based patterns * for easier handling. diff --git a/tools/node_modules/eslint/lib/eslint/eslint.js b/tools/node_modules/eslint/lib/eslint/eslint.js index b4a1d028db9d15..8886d45ab43480 100644 --- a/tools/node_modules/eslint/lib/eslint/eslint.js +++ b/tools/node_modules/eslint/lib/eslint/eslint.js @@ -54,7 +54,7 @@ const { version } = require("../../package.json"); * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance * @property {string} [overrideConfigFile] The configuration file to use. - * @property {Record} [plugins] An array of plugin implementations. + * @property {Record|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation. * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives. * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD. * @property {string[]} [rulePaths] An array of directories to load custom rules from. @@ -433,26 +433,13 @@ class ESLint { */ constructor(options = {}) { const processedOptions = processOptions(options); - const cliEngine = new CLIEngine(processedOptions); + const cliEngine = new CLIEngine(processedOptions, { preloadedPlugins: options.plugins }); const { - additionalPluginPool, configArrayFactory, lastConfigArrays } = getCLIEngineInternalSlots(cliEngine); let updated = false; - /* - * Address `plugins` to add plugin implementations. - * Operate the `additionalPluginPool` internal slot directly to avoid - * using `addPlugin(id, plugin)` method that resets cache everytime. - */ - if (options.plugins) { - for (const [id, plugin] of Object.entries(options.plugins)) { - additionalPluginPool.set(id, plugin); - updated = true; - } - } - /* * Address `overrideConfig` to set override config. * Operate the `configArrayFactory` internal slot directly because this diff --git a/tools/node_modules/eslint/lib/linter/config-comment-parser.js b/tools/node_modules/eslint/lib/linter/config-comment-parser.js index 34675a76b55987..b88c5e6c850929 100644 --- a/tools/node_modules/eslint/lib/linter/config-comment-parser.js +++ b/tools/node_modules/eslint/lib/linter/config-comment-parser.js @@ -15,7 +15,7 @@ const levn = require("levn"), Legacy: { ConfigOps } - } = require("@eslint/eslintrc/universal"); // eslint-disable-line node/no-missing-require -- false positive + } = require("@eslint/eslintrc/universal"); const debug = require("debug")("eslint:config-comment-parser"); diff --git a/tools/node_modules/eslint/lib/linter/linter.js b/tools/node_modules/eslint/lib/linter/linter.js index fab6c26113f4e4..410c07fee519e9 100644 --- a/tools/node_modules/eslint/lib/linter/linter.js +++ b/tools/node_modules/eslint/lib/linter/linter.js @@ -24,7 +24,7 @@ const ConfigValidator, environments: BuiltInEnvironments } - } = require("@eslint/eslintrc/universal"), // eslint-disable-line node/no-missing-require -- false positive + } = require("@eslint/eslintrc/universal"), Traverser = require("../shared/traverser"), { SourceCode } = require("../source-code"), CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"), diff --git a/tools/node_modules/eslint/lib/linter/node-event-generator.js b/tools/node_modules/eslint/lib/linter/node-event-generator.js index 89ebd281048ffd..d56bef2fa9defd 100644 --- a/tools/node_modules/eslint/lib/linter/node-event-generator.js +++ b/tools/node_modules/eslint/lib/linter/node-event-generator.js @@ -98,6 +98,13 @@ function getPossibleTypes(parsedSelector) { case "adjacent": return getPossibleTypes(parsedSelector.right); + case "class": + if (parsedSelector.name === "function") { + return ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]; + } + + return null; + default: return null; diff --git a/tools/node_modules/eslint/lib/rule-tester/rule-tester.js b/tools/node_modules/eslint/lib/rule-tester/rule-tester.js index 324af7b2caea32..7f590a5ea70995 100644 --- a/tools/node_modules/eslint/lib/rule-tester/rule-tester.js +++ b/tools/node_modules/eslint/lib/rule-tester/rule-tester.js @@ -67,6 +67,7 @@ const { SourceCode } = require("../source-code"); /** * A test case that is expected to pass lint. * @typedef {Object} ValidTestCase + * @property {string} [name] Name for the test case. * @property {string} code Code for the test case. * @property {any[]} [options] Options for the test case. * @property {{ [name: string]: any }} [settings] Settings for the test case. @@ -81,6 +82,7 @@ const { SourceCode } = require("../source-code"); /** * A test case that is expected to fail lint. * @typedef {Object} InvalidTestCase + * @property {string} [name] Name for the test case. * @property {string} code Code for the test case. * @property {number | Array} errors Expected errors. * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested. @@ -124,6 +126,7 @@ let defaultConfig = { rules: {} }; * configuration */ const RuleTesterParameters = [ + "name", "code", "filename", "options", @@ -964,7 +967,7 @@ class RuleTester { RuleTester.describe("valid", () => { test.valid.forEach(valid => { RuleTester[valid.only ? "itOnly" : "it"]( - sanitize(typeof valid === "object" ? valid.code : valid), + sanitize(typeof valid === "object" ? valid.name || valid.code : valid), () => { testValidTemplate(valid); } @@ -975,7 +978,7 @@ class RuleTester { RuleTester.describe("invalid", () => { test.invalid.forEach(invalid => { RuleTester[invalid.only ? "itOnly" : "it"]( - sanitize(invalid.code), + sanitize(invalid.name || invalid.code), () => { testInvalidTemplate(invalid); } diff --git a/tools/node_modules/eslint/lib/rules/index.js b/tools/node_modules/eslint/lib/rules/index.js index c88febd85b9f22..ed322a4120af13 100644 --- a/tools/node_modules/eslint/lib/rules/index.js +++ b/tools/node_modules/eslint/lib/rules/index.js @@ -221,6 +221,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({ "no-unsafe-optional-chaining": () => require("./no-unsafe-optional-chaining"), "no-unused-expressions": () => require("./no-unused-expressions"), "no-unused-labels": () => require("./no-unused-labels"), + "no-unused-private-class-members": () => require("./no-unused-private-class-members"), "no-unused-vars": () => require("./no-unused-vars"), "no-use-before-define": () => require("./no-use-before-define"), "no-useless-backreference": () => require("./no-useless-backreference"), diff --git a/tools/node_modules/eslint/lib/rules/keyword-spacing.js b/tools/node_modules/eslint/lib/rules/keyword-spacing.js index e9441ad1708fda..d860ae0f04bbeb 100644 --- a/tools/node_modules/eslint/lib/rules/keyword-spacing.js +++ b/tools/node_modules/eslint/lib/rules/keyword-spacing.js @@ -109,6 +109,8 @@ module.exports = { create(context) { const sourceCode = context.getSourceCode(); + const tokensToIgnore = new WeakSet(); + /** * Reports a given token if there are not space(s) before the token. * @param {Token} token A token to report. @@ -121,6 +123,7 @@ module.exports = { if (prevToken && (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && astUtils.isTokenOnSameLine(prevToken, token) && !sourceCode.isSpaceBetweenTokens(prevToken, token) ) { @@ -147,6 +150,7 @@ module.exports = { if (prevToken && (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && astUtils.isTokenOnSameLine(prevToken, token) && sourceCode.isSpaceBetweenTokens(prevToken, token) ) { @@ -173,6 +177,7 @@ module.exports = { if (nextToken && (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && astUtils.isTokenOnSameLine(token, nextToken) && !sourceCode.isSpaceBetweenTokens(token, nextToken) ) { @@ -199,6 +204,7 @@ module.exports = { if (nextToken && (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && astUtils.isTokenOnSameLine(token, nextToken) && sourceCode.isSpaceBetweenTokens(token, nextToken) ) { @@ -584,7 +590,14 @@ module.exports = { ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier, MethodDefinition: checkSpacingForProperty, PropertyDefinition: checkSpacingForProperty, - Property: checkSpacingForProperty + Property: checkSpacingForProperty, + + // To avoid conflicts with `space-infix-ops`, e.g. `a > this.b` + "BinaryExpression[operator='>']"(node) { + const operatorToken = sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken); + + tokensToIgnore.add(operatorToken); + } }; } }; diff --git a/tools/node_modules/eslint/lib/rules/no-unused-private-class-members.js b/tools/node_modules/eslint/lib/rules/no-unused-private-class-members.js new file mode 100644 index 00000000000000..74cf6ab694a460 --- /dev/null +++ b/tools/node_modules/eslint/lib/rules/no-unused-private-class-members.js @@ -0,0 +1,194 @@ +/** + * @fileoverview Rule to flag declared but unused private class members + * @author Tim van der Lippe + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + type: "problem", + + docs: { + description: "disallow unused private class members", + recommended: false, + url: "https://eslint.org/docs/rules/no-unused-private-class-members" + }, + + schema: [], + + messages: { + unusedPrivateClassMember: "'{{classMemberName}}' is defined but never used." + } + }, + + create(context) { + const trackedClasses = []; + + /** + * Check whether the current node is in a write only assignment. + * @param {ASTNode} privateIdentifierNode Node referring to a private identifier + * @returns {boolean} Whether the node is in a write only assignment + * @private + */ + function isWriteOnlyAssignment(privateIdentifierNode) { + const parentStatement = privateIdentifierNode.parent.parent; + const isAssignmentExpression = parentStatement.type === "AssignmentExpression"; + + if (!isAssignmentExpression && + parentStatement.type !== "ForInStatement" && + parentStatement.type !== "ForOfStatement" && + parentStatement.type !== "AssignmentPattern") { + return false; + } + + // It is a write-only usage, since we still allow usages on the right for reads + if (parentStatement.left !== privateIdentifierNode.parent) { + return false; + } + + // For any other operator (such as '+=') we still consider it a read operation + if (isAssignmentExpression && parentStatement.operator !== "=") { + + /* + * However, if the read operation is "discarded" in an empty statement, then + * we consider it write only. + */ + return parentStatement.parent.type === "ExpressionStatement"; + } + + return true; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + // Collect all declared members up front and assume they are all unused + ClassBody(classBodyNode) { + const privateMembers = new Map(); + + trackedClasses.unshift(privateMembers); + for (const bodyMember of classBodyNode.body) { + if (bodyMember.type === "PropertyDefinition" || bodyMember.type === "MethodDefinition") { + if (bodyMember.key.type === "PrivateIdentifier") { + privateMembers.set(bodyMember.key.name, { + declaredNode: bodyMember, + isAccessor: bodyMember.type === "MethodDefinition" && + (bodyMember.kind === "set" || bodyMember.kind === "get") + }); + } + } + } + }, + + /* + * Process all usages of the private identifier and remove a member from + * `declaredAndUnusedPrivateMembers` if we deem it used. + */ + PrivateIdentifier(privateIdentifierNode) { + const classBody = trackedClasses.find(classProperties => classProperties.has(privateIdentifierNode.name)); + + // Can't happen, as it is a parser to have a missing class body, but let's code defensively here. + if (!classBody) { + return; + } + + // In case any other usage was already detected, we can short circuit the logic here. + const memberDefinition = classBody.get(privateIdentifierNode.name); + + if (memberDefinition.isUsed) { + return; + } + + // The definition of the class member itself + if (privateIdentifierNode.parent.type === "PropertyDefinition" || + privateIdentifierNode.parent.type === "MethodDefinition") { + return; + } + + /* + * Any usage of an accessor is considered a read, as the getter/setter can have + * side-effects in its definition. + */ + if (memberDefinition.isAccessor) { + memberDefinition.isUsed = true; + return; + } + + // Any assignments to this member, except for assignments that also read + if (isWriteOnlyAssignment(privateIdentifierNode)) { + return; + } + + const wrappingExpressionType = privateIdentifierNode.parent.parent.type; + const parentOfWrappingExpressionType = privateIdentifierNode.parent.parent.parent.type; + + // A statement which only increments (`this.#x++;`) + if (wrappingExpressionType === "UpdateExpression" && + parentOfWrappingExpressionType === "ExpressionStatement") { + return; + } + + /* + * ({ x: this.#usedInDestructuring } = bar); + * + * But should treat the following as a read: + * ({ [this.#x]: a } = foo); + */ + if (wrappingExpressionType === "Property" && + parentOfWrappingExpressionType === "ObjectPattern" && + privateIdentifierNode.parent.parent.value === privateIdentifierNode.parent) { + return; + } + + // [...this.#unusedInRestPattern] = bar; + if (wrappingExpressionType === "RestElement") { + return; + } + + // [this.#unusedInAssignmentPattern] = bar; + if (wrappingExpressionType === "ArrayPattern") { + return; + } + + /* + * We can't delete the memberDefinition, as we need to keep track of which member we are marking as used. + * In the case of nested classes, we only mark the first member we encounter as used. If you were to delete + * the member, then any subsequent usage could incorrectly mark the member of an encapsulating parent class + * as used, which is incorrect. + */ + memberDefinition.isUsed = true; + }, + + /* + * Post-process the class members and report any remaining members. + * Since private members can only be accessed in the current class context, + * we can safely assume that all usages are within the current class body. + */ + "ClassBody:exit"() { + const unusedPrivateMembers = trackedClasses.shift(); + + for (const [classMemberName, { declaredNode, isUsed }] of unusedPrivateMembers.entries()) { + if (isUsed) { + continue; + } + context.report({ + node: declaredNode, + loc: declaredNode.key.loc, + messageId: "unusedPrivateClassMember", + data: { + classMemberName: `#${classMemberName}` + } + }); + } + } + }; + } +}; diff --git a/tools/node_modules/eslint/lib/shared/types.js b/tools/node_modules/eslint/lib/shared/types.js index bbfd2ed9a99a98..c497f783be5c46 100644 --- a/tools/node_modules/eslint/lib/shared/types.js +++ b/tools/node_modules/eslint/lib/shared/types.js @@ -21,7 +21,7 @@ module.exports = {}; /** * @typedef {Object} ParserOptions * @property {EcmaFeatures} [ecmaFeatures] The optional features. - * @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number). + * @property {3|5|6|7|8|9|10|11|12|13|2015|2016|2017|2018|2019|2020|2021|2022} [ecmaVersion] The ECMAScript version (or revision number). * @property {"script"|"module"} [sourceType] The source code type. */ diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json index 593e8aeb1db413..ae56ceeac196a3 100644 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json +++ b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json @@ -1,6 +1,6 @@ { "name": "@eslint/eslintrc", - "version": "1.0.2", + "version": "1.0.3", "description": "The legacy ESLintRC config file format for ESLint", "type": "module", "main": "./dist/eslintrc.cjs", @@ -19,7 +19,8 @@ "lib", "conf", "LICENSE", - "dist" + "dist", + "universal.js" ], "publishConfig": { "access": "public" diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/universal.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/universal.js new file mode 100644 index 00000000000000..4e1846ee6e0106 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/universal.js @@ -0,0 +1,9 @@ +// Jest (and probably some other runtimes with custom implementations of +// `require`) doesn't support `exports` in `package.json`, so this file is here +// to help them load this module. Note that it is also `.js` and not `.cjs` for +// the same reason - `cjs` files requires to be loaded with an extension, but +// since Jest doesn't respect `module` outside of ESM mode it still works in +// this case (and the `require` in _this_ file does specify the extension). + +// eslint-disable-next-line no-undef +module.exports = require("./dist/eslintrc-universal.cjs"); diff --git a/tools/node_modules/eslint/package.json b/tools/node_modules/eslint/package.json index 89b02acd4cba1b..f214112c74cc63 100644 --- a/tools/node_modules/eslint/package.json +++ b/tools/node_modules/eslint/package.json @@ -1,6 +1,6 @@ { "name": "eslint", - "version": "8.0.0", + "version": "8.1.0", "author": "Nicholas C. Zakas ", "description": "An AST-based pattern checker for JavaScript.", "bin": { @@ -47,7 +47,7 @@ "homepage": "https://eslint.org", "bugs": "https://github.com/eslint/eslint/issues/", "dependencies": { - "@eslint/eslintrc": "^1.0.2", + "@eslint/eslintrc": "^1.0.3", "@humanwhocodes/config-array": "^0.6.0", "ajv": "^6.10.0", "chalk": "^4.0.0", @@ -99,7 +99,7 @@ "eslint": "file:.", "eslint-config-eslint": "file:packages/eslint-config-eslint", "eslint-plugin-eslint-comments": "^3.2.0", - "eslint-plugin-eslint-plugin": "^3.5.3", + "eslint-plugin-eslint-plugin": "^4.0.1", "eslint-plugin-internal-rules": "file:tools/internal-rules", "eslint-plugin-jsdoc": "^36.0.6", "eslint-plugin-node": "^11.1.0", From d732ff4614ee1f390070acf6d42d3ffc3ae93ddd Mon Sep 17 00:00:00 2001 From: Daniel Nalborczyk Date: Fri, 22 Oct 2021 21:01:09 -0400 Subject: [PATCH 079/118] doc: remove unused imports PR-URL: https://github.com/nodejs/node/pull/40573 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Voltrex --- doc/api/esm.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index 46750050ee90d6..ebece69b38b9b3 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -887,8 +887,6 @@ purposes. ```js // coffeescript-loader.mjs import { readFile } from 'fs/promises'; -import { readFileSync } from 'fs'; -import { createRequire } from 'module'; import { dirname, extname, resolve as resolvePath } from 'path'; import { cwd } from 'process'; import { fileURLToPath, pathToFileURL } from 'url'; From d72fb7df4a5f0117dce1fd0097440444bbd73495 Mon Sep 17 00:00:00 2001 From: Daniel Nalborczyk Date: Fri, 22 Oct 2021 21:02:34 -0400 Subject: [PATCH 080/118] doc: call cwd function PR-URL: https://github.com/nodejs/node/pull/40573 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Voltrex --- doc/api/esm.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index ebece69b38b9b3..a69addbb072fb2 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -893,7 +893,7 @@ import { fileURLToPath, pathToFileURL } from 'url'; import CoffeeScript from 'coffeescript'; -const baseURL = pathToFileURL(`${cwd}/`).href; +const baseURL = pathToFileURL(`${cwd()}/`).href; // CoffeeScript files end in .coffee, .litcoffee or .coffee.md. const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/; From 7a6e8336773c706e0c75ddf87494021fcd92ca7e Mon Sep 17 00:00:00 2001 From: Daniel Nalborczyk Date: Fri, 22 Oct 2021 21:04:12 -0400 Subject: [PATCH 081/118] doc: add node: url scheme PR-URL: https://github.com/nodejs/node/pull/40573 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Voltrex --- doc/api/esm.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index a69addbb072fb2..6d8022a3fbf9c5 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -886,11 +886,10 @@ purposes. ```js // coffeescript-loader.mjs -import { readFile } from 'fs/promises'; -import { dirname, extname, resolve as resolvePath } from 'path'; -import { cwd } from 'process'; -import { fileURLToPath, pathToFileURL } from 'url'; - +import { readFile } from 'node:fs/promises'; +import { dirname, extname, resolve as resolvePath } from 'node:path'; +import { cwd } from 'node:process'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import CoffeeScript from 'coffeescript'; const baseURL = pathToFileURL(`${cwd()}/`).href; From eea061f8f10b06fd4b886dcb41ea6a1220692bdd Mon Sep 17 00:00:00 2001 From: Mestery Date: Sun, 24 Oct 2021 19:26:09 +0200 Subject: [PATCH 082/118] doc: use 'GitHub Actions workflow' instead MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40586 Reviewed-By: Luigi Pinca Reviewed-By: Voltrex Reviewed-By: Tobias Nießen --- doc/guides/collaborator-guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/guides/collaborator-guide.md b/doc/guides/collaborator-guide.md index 50f2a1264001a2..b737ee85fbb9fa 100644 --- a/doc/guides/collaborator-guide.md +++ b/doc/guides/collaborator-guide.md @@ -185,7 +185,7 @@ delay. For example: * Regressions that happen right before a release, or reported soon after. To propose fast-tracking a pull request, apply the `fast-track` label. Then a -GitHub Action will add a comment that collaborators can upvote. +GitHub Actions workflow will add a comment that collaborators can upvote. If someone disagrees with the fast-tracking request, remove the label. Do not fast-track the pull request in that case. From fbe0323ebfc6247ec1726836e2ba195dd830d001 Mon Sep 17 00:00:00 2001 From: Mestery Date: Mon, 11 Oct 2021 18:08:34 +0200 Subject: [PATCH 083/118] typings: improve internal bindings typings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40411 Reviewed-By: Michaël Zasso Reviewed-By: James M Snell --- typings/globals.d.ts | 13 +- typings/internalBinding/config.d.ts | 22 +- typings/internalBinding/constants.d.ts | 784 +++++++++++------------ typings/internalBinding/fs.d.ts | 20 +- typings/internalBinding/http_parser.d.ts | 5 +- typings/internalBinding/os.d.ts | 18 +- typings/internalBinding/serdes.d.ts | 2 + typings/internalBinding/symbols.d.ts | 28 +- typings/internalBinding/types.d.ts | 46 +- typings/internalBinding/util.d.ts | 2 +- typings/internalBinding/worker.d.ts | 3 +- 11 files changed, 501 insertions(+), 442 deletions(-) diff --git a/typings/globals.d.ts b/typings/globals.d.ts index 5d849b28b66ba0..182284aa342718 100644 --- a/typings/globals.d.ts +++ b/typings/globals.d.ts @@ -1 +1,12 @@ -declare type TypedArray = Uint16Array | Uint32Array | Uint8Array | Uint8ClampedArray | Int16Array | Int32Array | Int8Array | BigInt64Array | Float32Array | Float64Array | BigUint64Array; +declare type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | Float32Array + | Float64Array + | BigUint64Array + | BigInt64Array; diff --git a/typings/internalBinding/config.d.ts b/typings/internalBinding/config.d.ts index 3fccf4007f145b..d9f34e1131ced5 100644 --- a/typings/internalBinding/config.d.ts +++ b/typings/internalBinding/config.d.ts @@ -1,12 +1,12 @@ declare function InternalBinding(binding: 'config'): { - isDebugBuild: boolean, - hasOpenSSL: boolean, - fipsMode: boolean, - hasIntl: boolean, - hasTracing: boolean, - hasNodeOptions: boolean, - hasInspector: boolean, - noBrowserGlobals: boolean, - bits: number, - hasDtrace: boolean -} + isDebugBuild: boolean; + hasOpenSSL: boolean; + fipsMode: boolean; + hasIntl: boolean; + hasTracing: boolean; + hasNodeOptions: boolean; + hasInspector: boolean; + noBrowserGlobals: boolean; + bits: number; + hasDtrace: boolean; +}; diff --git a/typings/internalBinding/constants.d.ts b/typings/internalBinding/constants.d.ts index 802a0c019f6096..8baaebbfef8ea0 100644 --- a/typings/internalBinding/constants.d.ts +++ b/typings/internalBinding/constants.d.ts @@ -1,402 +1,402 @@ declare function InternalBinding(binding: 'constants'): { os: { - UV_UDP_REUSEADDR: 4, + UV_UDP_REUSEADDR: 4; dlopen: { - RTLD_LAZY: 1, - RTLD_NOW: 2, - RTLD_GLOBAL: 8, - RTLD_LOCAL: 4 - }, - errno:{ - E2BIG: 7, - EACCES: 13, - EADDRINUSE: 48, - EADDRNOTAVAIL: 49, - EAFNOSUPPORT: 47, - EAGAIN: 35, - EALREADY: 37, - EBADF: 9, - EBADMSG: 94, - EBUSY: 16, - ECANCELED: 89, - ECHILD: 10, - ECONNABORTED: 53, - ECONNREFUSED: 61, - ECONNRESET: 54, - EDEADLK: 11, - EDESTADDRREQ: 39, - EDOM: 33, - EDQUOT: 69, - EEXIST: 17, - EFAULT: 14, - EFBIG: 27, - EHOSTUNREACH: 65, - EIDRM: 90, - EILSEQ: 92, - EINPROGRESS: 36, - EINTR: 4, - EINVAL: 22, - EIO: 5, - EISCONN: 56, - EISDIR: 21, - ELOOP: 62, - EMFILE: 24, - EMLINK: 31, - EMSGSIZE: 40, - EMULTIHOP: 95, - ENAMETOOLONG: 63, - ENETDOWN: 50, - ENETRESET: 52, - ENETUNREACH: 51, - ENFILE: 23, - ENOBUFS: 55, - ENODATA: 96, - ENODEV: 19, - ENOENT: 2, - ENOEXEC: 8, - ENOLCK: 77, - ENOLINK: 97, - ENOMEM: 12, - ENOMSG: 91, - ENOPROTOOPT: 42, - ENOSPC: 28, - ENOSR: 98, - ENOSTR: 99, - ENOSYS: 78, - ENOTCONN: 57, - ENOTDIR: 20, - ENOTEMPTY: 66, - ENOTSOCK: 38, - ENOTSUP: 45, - ENOTTY: 25, - ENXIO: 6, - EOPNOTSUPP: 102, - EOVERFLOW: 84, - EPERM: 1, - EPIPE: 32, - EPROTO: 100, - EPROTONOSUPPORT: 43, - EPROTOTYPE: 41, - ERANGE: 34, - EROFS: 30, - ESPIPE: 29, - ESRCH: 3, - ESTALE: 70, - ETIME: 101, - ETIMEDOUT: 60, - ETXTBSY: 26, - EWOULDBLOCK: 35, - EXDEV: 18 - }, + RTLD_LAZY: 1; + RTLD_NOW: 2; + RTLD_GLOBAL: 8; + RTLD_LOCAL: 4; + }; + errno: { + E2BIG: 7; + EACCES: 13; + EADDRINUSE: 48; + EADDRNOTAVAIL: 49; + EAFNOSUPPORT: 47; + EAGAIN: 35; + EALREADY: 37; + EBADF: 9; + EBADMSG: 94; + EBUSY: 16; + ECANCELED: 89; + ECHILD: 10; + ECONNABORTED: 53; + ECONNREFUSED: 61; + ECONNRESET: 54; + EDEADLK: 11; + EDESTADDRREQ: 39; + EDOM: 33; + EDQUOT: 69; + EEXIST: 17; + EFAULT: 14; + EFBIG: 27; + EHOSTUNREACH: 65; + EIDRM: 90; + EILSEQ: 92; + EINPROGRESS: 36; + EINTR: 4; + EINVAL: 22; + EIO: 5; + EISCONN: 56; + EISDIR: 21; + ELOOP: 62; + EMFILE: 24; + EMLINK: 31; + EMSGSIZE: 40; + EMULTIHOP: 95; + ENAMETOOLONG: 63; + ENETDOWN: 50; + ENETRESET: 52; + ENETUNREACH: 51; + ENFILE: 23; + ENOBUFS: 55; + ENODATA: 96; + ENODEV: 19; + ENOENT: 2; + ENOEXEC: 8; + ENOLCK: 77; + ENOLINK: 97; + ENOMEM: 12; + ENOMSG: 91; + ENOPROTOOPT: 42; + ENOSPC: 28; + ENOSR: 98; + ENOSTR: 99; + ENOSYS: 78; + ENOTCONN: 57; + ENOTDIR: 20; + ENOTEMPTY: 66; + ENOTSOCK: 38; + ENOTSUP: 45; + ENOTTY: 25; + ENXIO: 6; + EOPNOTSUPP: 102; + EOVERFLOW: 84; + EPERM: 1; + EPIPE: 32; + EPROTO: 100; + EPROTONOSUPPORT: 43; + EPROTOTYPE: 41; + ERANGE: 34; + EROFS: 30; + ESPIPE: 29; + ESRCH: 3; + ESTALE: 70; + ETIME: 101; + ETIMEDOUT: 60; + ETXTBSY: 26; + EWOULDBLOCK: 35; + EXDEV: 18; + }; signals: { - SIGHUP: 1, - SIGINT: 2, - SIGQUIT: 3, - SIGILL: 4, - SIGTRAP: 5, - SIGABRT: 6, - SIGIOT: 6, - SIGBUS: 10, - SIGFPE: 8, - SIGKILL: 9, - SIGUSR1: 30, - SIGSEGV: 11, - SIGUSR2: 31, - SIGPIPE: 13, - SIGALRM: 14, - SIGTERM: 15, - SIGCHLD: 20, - SIGCONT: 19, - SIGSTOP: 17, - SIGTSTP: 18, - SIGTTIN: 21, - SIGTTOU: 22, - SIGURG: 16, - SIGXCPU: 24, - SIGXFSZ: 25, - SIGVTALRM: 26, - SIGPROF: 27, - SIGWINCH: 28, - SIGIO: 23, - SIGINFO: 29, - SIGSYS: 12 - }, + SIGHUP: 1; + SIGINT: 2; + SIGQUIT: 3; + SIGILL: 4; + SIGTRAP: 5; + SIGABRT: 6; + SIGIOT: 6; + SIGBUS: 10; + SIGFPE: 8; + SIGKILL: 9; + SIGUSR1: 30; + SIGSEGV: 11; + SIGUSR2: 31; + SIGPIPE: 13; + SIGALRM: 14; + SIGTERM: 15; + SIGCHLD: 20; + SIGCONT: 19; + SIGSTOP: 17; + SIGTSTP: 18; + SIGTTIN: 21; + SIGTTOU: 22; + SIGURG: 16; + SIGXCPU: 24; + SIGXFSZ: 25; + SIGVTALRM: 26; + SIGPROF: 27; + SIGWINCH: 28; + SIGIO: 23; + SIGINFO: 29; + SIGSYS: 12; + }; priority: { - PRIORITY_LOW: 19, - PRIORITY_BELOW_NORMAL: 10, - PRIORITY_NORMAL: 0, - PRIORITY_ABOVE_NORMAL: -7, - PRIORITY_HIGH: -14, - PRIORITY_HIGHEST: -20 - } - }, + PRIORITY_LOW: 19; + PRIORITY_BELOW_NORMAL: 10; + PRIORITY_NORMAL: 0; + PRIORITY_ABOVE_NORMAL: -7; + PRIORITY_HIGH: -14; + PRIORITY_HIGHEST: -20; + }; + }; fs: { - UV_FS_SYMLINK_DIR: 1, - UV_FS_SYMLINK_JUNCTION: 2, - O_RDONLY: 0, - O_WRONLY: 1, - O_RDWR: 2, - UV_DIRENT_UNKNOWN: 0, - UV_DIRENT_FILE: 1, - UV_DIRENT_DIR: 2, - UV_DIRENT_LINK: 3, - UV_DIRENT_FIFO: 4, - UV_DIRENT_SOCKET: 5, - UV_DIRENT_CHAR: 6, - UV_DIRENT_BLOCK: 7, - S_IFMT: 61440, - S_IFREG: 32768, - S_IFDIR: 16384, - S_IFCHR: 8192, - S_IFBLK: 24576, - S_IFIFO: 4096, - S_IFLNK: 40960, - S_IFSOCK: 49152, - O_CREAT: 512, - O_EXCL: 2048, - UV_FS_O_FILEMAP: 0, - O_NOCTTY: 131072, - O_TRUNC: 1024, - O_APPEND: 8, - O_DIRECTORY: 1048576, - O_NOFOLLOW: 256, - O_SYNC: 128, - O_DSYNC: 4194304, - O_SYMLINK: 2097152, - O_NONBLOCK: 4, - S_IRWXU: 448, - S_IRUSR: 256, - S_IWUSR: 128, - S_IXUSR: 64, - S_IRWXG: 56, - S_IRGRP: 32, - S_IWGRP: 16, - S_IXGRP: 8, - S_IRWXO: 7, - S_IROTH: 4, - S_IWOTH: 2, - S_IXOTH: 1, - F_OK: 0, - R_OK: 4, - W_OK: 2, - X_OK: 1, - UV_FS_COPYFILE_EXCL: 1, - COPYFILE_EXCL: 1, - UV_FS_COPYFILE_FICLONE: 2, - COPYFILE_FICLONE: 2, - UV_FS_COPYFILE_FICLONE_FORCE: 4, - COPYFILE_FICLONE_FORCE: 4 - }, + UV_FS_SYMLINK_DIR: 1; + UV_FS_SYMLINK_JUNCTION: 2; + O_RDONLY: 0; + O_WRONLY: 1; + O_RDWR: 2; + UV_DIRENT_UNKNOWN: 0; + UV_DIRENT_FILE: 1; + UV_DIRENT_DIR: 2; + UV_DIRENT_LINK: 3; + UV_DIRENT_FIFO: 4; + UV_DIRENT_SOCKET: 5; + UV_DIRENT_CHAR: 6; + UV_DIRENT_BLOCK: 7; + S_IFMT: 61440; + S_IFREG: 32768; + S_IFDIR: 16384; + S_IFCHR: 8192; + S_IFBLK: 24576; + S_IFIFO: 4096; + S_IFLNK: 40960; + S_IFSOCK: 49152; + O_CREAT: 512; + O_EXCL: 2048; + UV_FS_O_FILEMAP: 0; + O_NOCTTY: 131072; + O_TRUNC: 1024; + O_APPEND: 8; + O_DIRECTORY: 1048576; + O_NOFOLLOW: 256; + O_SYNC: 128; + O_DSYNC: 4194304; + O_SYMLINK: 2097152; + O_NONBLOCK: 4; + S_IRWXU: 448; + S_IRUSR: 256; + S_IWUSR: 128; + S_IXUSR: 64; + S_IRWXG: 56; + S_IRGRP: 32; + S_IWGRP: 16; + S_IXGRP: 8; + S_IRWXO: 7; + S_IROTH: 4; + S_IWOTH: 2; + S_IXOTH: 1; + F_OK: 0; + R_OK: 4; + W_OK: 2; + X_OK: 1; + UV_FS_COPYFILE_EXCL: 1; + COPYFILE_EXCL: 1; + UV_FS_COPYFILE_FICLONE: 2; + COPYFILE_FICLONE: 2; + UV_FS_COPYFILE_FICLONE_FORCE: 4; + COPYFILE_FICLONE_FORCE: 4; + }; crypto: { - OPENSSL_VERSION_NUMBER: 269488319, - SSL_OP_ALL: 2147485780, - SSL_OP_ALLOW_NO_DHE_KEX: 1024, - SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: 262144, - SSL_OP_CIPHER_SERVER_PREFERENCE: 4194304, - SSL_OP_CISCO_ANYCONNECT: 32768, - SSL_OP_COOKIE_EXCHANGE: 8192, - SSL_OP_CRYPTOPRO_TLSEXT_BUG: 2147483648, - SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: 2048, - SSL_OP_EPHEMERAL_RSA: 0, - SSL_OP_LEGACY_SERVER_CONNECT: 4, - SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: 0, - SSL_OP_MICROSOFT_SESS_ID_BUG: 0, - SSL_OP_MSIE_SSLV2_RSA_PADDING: 0, - SSL_OP_NETSCAPE_CA_DN_BUG: 0, - SSL_OP_NETSCAPE_CHALLENGE_BUG: 0, - SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: 0, - SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: 0, - SSL_OP_NO_COMPRESSION: 131072, - SSL_OP_NO_ENCRYPT_THEN_MAC: 524288, - SSL_OP_NO_QUERY_MTU: 4096, - SSL_OP_NO_RENEGOTIATION: 1073741824, - SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: 65536, - SSL_OP_NO_SSLv2: 0, - SSL_OP_NO_SSLv3: 33554432, - SSL_OP_NO_TICKET: 16384, - SSL_OP_NO_TLSv1: 67108864, - SSL_OP_NO_TLSv1_1: 268435456, - SSL_OP_NO_TLSv1_2: 134217728, - SSL_OP_NO_TLSv1_3: 536870912, - SSL_OP_PKCS1_CHECK_1: 0, - SSL_OP_PKCS1_CHECK_2: 0, - SSL_OP_PRIORITIZE_CHACHA: 2097152, - SSL_OP_SINGLE_DH_USE: 0, - SSL_OP_SINGLE_ECDH_USE: 0, - SSL_OP_SSLEAY_080_CLIENT_DH_BUG: 0, - SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: 0, - SSL_OP_TLS_BLOCK_PADDING_BUG: 0, - SSL_OP_TLS_D5_BUG: 0, - SSL_OP_TLS_ROLLBACK_BUG: 8388608, - ENGINE_METHOD_RSA: 1, - ENGINE_METHOD_DSA: 2, - ENGINE_METHOD_DH: 4, - ENGINE_METHOD_RAND: 8, - ENGINE_METHOD_EC: 2048, - ENGINE_METHOD_CIPHERS: 64, - ENGINE_METHOD_DIGESTS: 128, - ENGINE_METHOD_PKEY_METHS: 512, - ENGINE_METHOD_PKEY_ASN1_METHS: 1024, - ENGINE_METHOD_ALL: 65535, - ENGINE_METHOD_NONE: 0, - DH_CHECK_P_NOT_SAFE_PRIME: 2, - DH_CHECK_P_NOT_PRIME: 1, - DH_UNABLE_TO_CHECK_GENERATOR: 4, - DH_NOT_SUITABLE_GENERATOR: 8, - ALPN_ENABLED: 1, - RSA_PKCS1_PADDING: 1, - RSA_SSLV23_PADDING: 2, - RSA_NO_PADDING: 3, - RSA_PKCS1_OAEP_PADDING: 4, - RSA_X931_PADDING: 5, - RSA_PKCS1_PSS_PADDING: 6, - RSA_PSS_SALTLEN_DIGEST: -1, - RSA_PSS_SALTLEN_MAX_SIGN: -2, - RSA_PSS_SALTLEN_AUTO: -2, - defaultCoreCipherList: 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA', - TLS1_VERSION: 769, - TLS1_1_VERSION: 770, - TLS1_2_VERSION: 771, - TLS1_3_VERSION: 772, - POINT_CONVERSION_COMPRESSED: 2, - POINT_CONVERSION_UNCOMPRESSED: 4, - POINT_CONVERSION_HYBRID: 6 - }, + OPENSSL_VERSION_NUMBER: 269488319; + SSL_OP_ALL: 2147485780; + SSL_OP_ALLOW_NO_DHE_KEX: 1024; + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: 262144; + SSL_OP_CIPHER_SERVER_PREFERENCE: 4194304; + SSL_OP_CISCO_ANYCONNECT: 32768; + SSL_OP_COOKIE_EXCHANGE: 8192; + SSL_OP_CRYPTOPRO_TLSEXT_BUG: 2147483648; + SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: 2048; + SSL_OP_EPHEMERAL_RSA: 0; + SSL_OP_LEGACY_SERVER_CONNECT: 4; + SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: 0; + SSL_OP_MICROSOFT_SESS_ID_BUG: 0; + SSL_OP_MSIE_SSLV2_RSA_PADDING: 0; + SSL_OP_NETSCAPE_CA_DN_BUG: 0; + SSL_OP_NETSCAPE_CHALLENGE_BUG: 0; + SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: 0; + SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: 0; + SSL_OP_NO_COMPRESSION: 131072; + SSL_OP_NO_ENCRYPT_THEN_MAC: 524288; + SSL_OP_NO_QUERY_MTU: 4096; + SSL_OP_NO_RENEGOTIATION: 1073741824; + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: 65536; + SSL_OP_NO_SSLv2: 0; + SSL_OP_NO_SSLv3: 33554432; + SSL_OP_NO_TICKET: 16384; + SSL_OP_NO_TLSv1: 67108864; + SSL_OP_NO_TLSv1_1: 268435456; + SSL_OP_NO_TLSv1_2: 134217728; + SSL_OP_NO_TLSv1_3: 536870912; + SSL_OP_PKCS1_CHECK_1: 0; + SSL_OP_PKCS1_CHECK_2: 0; + SSL_OP_PRIORITIZE_CHACHA: 2097152; + SSL_OP_SINGLE_DH_USE: 0; + SSL_OP_SINGLE_ECDH_USE: 0; + SSL_OP_SSLEAY_080_CLIENT_DH_BUG: 0; + SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: 0; + SSL_OP_TLS_BLOCK_PADDING_BUG: 0; + SSL_OP_TLS_D5_BUG: 0; + SSL_OP_TLS_ROLLBACK_BUG: 8388608; + ENGINE_METHOD_RSA: 1; + ENGINE_METHOD_DSA: 2; + ENGINE_METHOD_DH: 4; + ENGINE_METHOD_RAND: 8; + ENGINE_METHOD_EC: 2048; + ENGINE_METHOD_CIPHERS: 64; + ENGINE_METHOD_DIGESTS: 128; + ENGINE_METHOD_PKEY_METHS: 512; + ENGINE_METHOD_PKEY_ASN1_METHS: 1024; + ENGINE_METHOD_ALL: 65535; + ENGINE_METHOD_NONE: 0; + DH_CHECK_P_NOT_SAFE_PRIME: 2; + DH_CHECK_P_NOT_PRIME: 1; + DH_UNABLE_TO_CHECK_GENERATOR: 4; + DH_NOT_SUITABLE_GENERATOR: 8; + ALPN_ENABLED: 1; + RSA_PKCS1_PADDING: 1; + RSA_SSLV23_PADDING: 2; + RSA_NO_PADDING: 3; + RSA_PKCS1_OAEP_PADDING: 4; + RSA_X931_PADDING: 5; + RSA_PKCS1_PSS_PADDING: 6; + RSA_PSS_SALTLEN_DIGEST: -1; + RSA_PSS_SALTLEN_MAX_SIGN: -2; + RSA_PSS_SALTLEN_AUTO: -2; + defaultCoreCipherList: 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA'; + TLS1_VERSION: 769; + TLS1_1_VERSION: 770; + TLS1_2_VERSION: 771; + TLS1_3_VERSION: 772; + POINT_CONVERSION_COMPRESSED: 2; + POINT_CONVERSION_UNCOMPRESSED: 4; + POINT_CONVERSION_HYBRID: 6; + }; zlib: { - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - Z_VERSION_ERROR: -6, - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - ZLIB_VERNUM: 4784, - DEFLATE: 1, - INFLATE: 2, - GZIP: 3, - GUNZIP: 4, - DEFLATERAW: 5, - INFLATERAW: 6, - UNZIP: 7, - BROTLI_DECODE: 8, - BROTLI_ENCODE: 9, - Z_MIN_WINDOWBITS: 8, - Z_MAX_WINDOWBITS: 15, - Z_DEFAULT_WINDOWBITS: 15, - Z_MIN_CHUNK: 64, - Z_MAX_CHUNK: number, - Z_DEFAULT_CHUNK: 16384, - Z_MIN_MEMLEVEL: 1, - Z_MAX_MEMLEVEL: 9, - Z_DEFAULT_MEMLEVEL: 8, - Z_MIN_LEVEL: -1, - Z_MAX_LEVEL: 9, - Z_DEFAULT_LEVEL: -1, - BROTLI_OPERATION_PROCESS: 0, - BROTLI_OPERATION_FLUSH: 1, - BROTLI_OPERATION_FINISH: 2, - BROTLI_OPERATION_EMIT_METADATA: 3, - BROTLI_PARAM_MODE: 0, - BROTLI_MODE_GENERIC: 0, - BROTLI_MODE_TEXT: 1, - BROTLI_MODE_FONT: 2, - BROTLI_DEFAULT_MODE: 0, - BROTLI_PARAM_QUALITY: 1, - BROTLI_MIN_QUALITY: 0, - BROTLI_MAX_QUALITY: 11, - BROTLI_DEFAULT_QUALITY: 11, - BROTLI_PARAM_LGWIN: 2, - BROTLI_MIN_WINDOW_BITS: 10, - BROTLI_MAX_WINDOW_BITS: 24, - BROTLI_LARGE_MAX_WINDOW_BITS: 30, - BROTLI_DEFAULT_WINDOW: 22, - BROTLI_PARAM_LGBLOCK: 3, - BROTLI_MIN_INPUT_BLOCK_BITS: 16, - BROTLI_MAX_INPUT_BLOCK_BITS: 24, - BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, - BROTLI_PARAM_SIZE_HINT: 5, - BROTLI_PARAM_LARGE_WINDOW: 6, - BROTLI_PARAM_NPOSTFIX: 7, - BROTLI_PARAM_NDIRECT: 8, - BROTLI_DECODER_RESULT_ERROR: 0, - BROTLI_DECODER_RESULT_SUCCESS: 1, - BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, - BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, - BROTLI_DECODER_NO_ERROR: 0, - BROTLI_DECODER_SUCCESS: 1, - BROTLI_DECODER_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, - BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, - BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, - BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, - BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, - BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, - BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, - BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, - BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, - BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, - BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, - BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, - BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, - BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, - BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, - BROTLI_DECODER_ERROR_UNREACHABLE: -31 - }, + Z_NO_FLUSH: 0; + Z_PARTIAL_FLUSH: 1; + Z_SYNC_FLUSH: 2; + Z_FULL_FLUSH: 3; + Z_FINISH: 4; + Z_BLOCK: 5; + Z_OK: 0; + Z_STREAM_END: 1; + Z_NEED_DICT: 2; + Z_ERRNO: -1; + Z_STREAM_ERROR: -2; + Z_DATA_ERROR: -3; + Z_MEM_ERROR: -4; + Z_BUF_ERROR: -5; + Z_VERSION_ERROR: -6; + Z_NO_COMPRESSION: 0; + Z_BEST_SPEED: 1; + Z_BEST_COMPRESSION: 9; + Z_DEFAULT_COMPRESSION: -1; + Z_FILTERED: 1; + Z_HUFFMAN_ONLY: 2; + Z_RLE: 3; + Z_FIXED: 4; + Z_DEFAULT_STRATEGY: 0; + ZLIB_VERNUM: 4784; + DEFLATE: 1; + INFLATE: 2; + GZIP: 3; + GUNZIP: 4; + DEFLATERAW: 5; + INFLATERAW: 6; + UNZIP: 7; + BROTLI_DECODE: 8; + BROTLI_ENCODE: 9; + Z_MIN_WINDOWBITS: 8; + Z_MAX_WINDOWBITS: 15; + Z_DEFAULT_WINDOWBITS: 15; + Z_MIN_CHUNK: 64; + Z_MAX_CHUNK: number; + Z_DEFAULT_CHUNK: 16384; + Z_MIN_MEMLEVEL: 1; + Z_MAX_MEMLEVEL: 9; + Z_DEFAULT_MEMLEVEL: 8; + Z_MIN_LEVEL: -1; + Z_MAX_LEVEL: 9; + Z_DEFAULT_LEVEL: -1; + BROTLI_OPERATION_PROCESS: 0; + BROTLI_OPERATION_FLUSH: 1; + BROTLI_OPERATION_FINISH: 2; + BROTLI_OPERATION_EMIT_METADATA: 3; + BROTLI_PARAM_MODE: 0; + BROTLI_MODE_GENERIC: 0; + BROTLI_MODE_TEXT: 1; + BROTLI_MODE_FONT: 2; + BROTLI_DEFAULT_MODE: 0; + BROTLI_PARAM_QUALITY: 1; + BROTLI_MIN_QUALITY: 0; + BROTLI_MAX_QUALITY: 11; + BROTLI_DEFAULT_QUALITY: 11; + BROTLI_PARAM_LGWIN: 2; + BROTLI_MIN_WINDOW_BITS: 10; + BROTLI_MAX_WINDOW_BITS: 24; + BROTLI_LARGE_MAX_WINDOW_BITS: 30; + BROTLI_DEFAULT_WINDOW: 22; + BROTLI_PARAM_LGBLOCK: 3; + BROTLI_MIN_INPUT_BLOCK_BITS: 16; + BROTLI_MAX_INPUT_BLOCK_BITS: 24; + BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4; + BROTLI_PARAM_SIZE_HINT: 5; + BROTLI_PARAM_LARGE_WINDOW: 6; + BROTLI_PARAM_NPOSTFIX: 7; + BROTLI_PARAM_NDIRECT: 8; + BROTLI_DECODER_RESULT_ERROR: 0; + BROTLI_DECODER_RESULT_SUCCESS: 1; + BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2; + BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3; + BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0; + BROTLI_DECODER_PARAM_LARGE_WINDOW: 1; + BROTLI_DECODER_NO_ERROR: 0; + BROTLI_DECODER_SUCCESS: 1; + BROTLI_DECODER_NEEDS_MORE_INPUT: 2; + BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3; + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1; + BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2; + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3; + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4; + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5; + BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6; + BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7; + BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8; + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9; + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10; + BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11; + BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12; + BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13; + BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14; + BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15; + BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16; + BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19; + BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20; + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21; + BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22; + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25; + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26; + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27; + BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30; + BROTLI_DECODER_ERROR_UNREACHABLE: -31; + }; trace: { - TRACE_EVENT_PHASE_BEGIN: 66, - TRACE_EVENT_PHASE_END: 69, - TRACE_EVENT_PHASE_COMPLETE: 88, - TRACE_EVENT_PHASE_INSTANT: 73, - TRACE_EVENT_PHASE_ASYNC_BEGIN: 83, - TRACE_EVENT_PHASE_ASYNC_STEP_INTO: 84, - TRACE_EVENT_PHASE_ASYNC_STEP_PAST: 112, - TRACE_EVENT_PHASE_ASYNC_END: 70, - TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN: 98, - TRACE_EVENT_PHASE_NESTABLE_ASYNC_END: 101, - TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT: 110, - TRACE_EVENT_PHASE_FLOW_BEGIN: 115, - TRACE_EVENT_PHASE_FLOW_STEP: 116, - TRACE_EVENT_PHASE_FLOW_END: 102, - TRACE_EVENT_PHASE_METADATA: 77, - TRACE_EVENT_PHASE_COUNTER: 67, - TRACE_EVENT_PHASE_SAMPLE: 80, - TRACE_EVENT_PHASE_CREATE_OBJECT: 78, - TRACE_EVENT_PHASE_SNAPSHOT_OBJECT: 79, - TRACE_EVENT_PHASE_DELETE_OBJECT: 68, - TRACE_EVENT_PHASE_MEMORY_DUMP: 118, - TRACE_EVENT_PHASE_MARK: 82, - TRACE_EVENT_PHASE_CLOCK_SYNC: 99, - TRACE_EVENT_PHASE_ENTER_CONTEXT: 40, - TRACE_EVENT_PHASE_LEAVE_CONTEXT: 41, - TRACE_EVENT_PHASE_LINK_IDS: 61 - } + TRACE_EVENT_PHASE_BEGIN: 66; + TRACE_EVENT_PHASE_END: 69; + TRACE_EVENT_PHASE_COMPLETE: 88; + TRACE_EVENT_PHASE_INSTANT: 73; + TRACE_EVENT_PHASE_ASYNC_BEGIN: 83; + TRACE_EVENT_PHASE_ASYNC_STEP_INTO: 84; + TRACE_EVENT_PHASE_ASYNC_STEP_PAST: 112; + TRACE_EVENT_PHASE_ASYNC_END: 70; + TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN: 98; + TRACE_EVENT_PHASE_NESTABLE_ASYNC_END: 101; + TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT: 110; + TRACE_EVENT_PHASE_FLOW_BEGIN: 115; + TRACE_EVENT_PHASE_FLOW_STEP: 116; + TRACE_EVENT_PHASE_FLOW_END: 102; + TRACE_EVENT_PHASE_METADATA: 77; + TRACE_EVENT_PHASE_COUNTER: 67; + TRACE_EVENT_PHASE_SAMPLE: 80; + TRACE_EVENT_PHASE_CREATE_OBJECT: 78; + TRACE_EVENT_PHASE_SNAPSHOT_OBJECT: 79; + TRACE_EVENT_PHASE_DELETE_OBJECT: 68; + TRACE_EVENT_PHASE_MEMORY_DUMP: 118; + TRACE_EVENT_PHASE_MARK: 82; + TRACE_EVENT_PHASE_CLOCK_SYNC: 99; + TRACE_EVENT_PHASE_ENTER_CONTEXT: 40; + TRACE_EVENT_PHASE_LEAVE_CONTEXT: 41; + TRACE_EVENT_PHASE_LINK_IDS: 61; + }; }; diff --git a/typings/internalBinding/fs.d.ts b/typings/internalBinding/fs.d.ts index a7f086c258d6da..4576913bf1366b 100644 --- a/typings/internalBinding/fs.d.ts +++ b/typings/internalBinding/fs.d.ts @@ -2,7 +2,20 @@ declare namespace InternalFSBinding { class FSReqCallback { constructor(bigint?: boolean); oncomplete: ((error: Error) => void) | ((error: null, result: ResultType) => void); - context: any; + context: ReadFileContext; + } + + interface ReadFileContext { + fd: number | undefined; + isUserFd: boolean | undefined; + size: number; + callback: (err?: Error, data?: string | Buffer) => unknown; + buffers: Buffer[]; + buffer: Buffer; + pos: number; + encoding: string; + err: Error | null; + signal: unknown /* AbortSignal | undefined */; } interface FSSyncContext { @@ -16,9 +29,10 @@ declare namespace InternalFSBinding { } type Buffer = Uint8Array; + type Stream = object; type StringOrBuffer = string | Buffer; - const kUsePromises: symbol; + const kUsePromises: unique symbol; class FileHandle { constructor(fd: number, offset: number, length: number); @@ -26,7 +40,7 @@ declare namespace InternalFSBinding { getAsyncId(): number; close(): Promise; onread: () => void; - stream: unknown; + stream: Stream; } class StatWatcher { diff --git a/typings/internalBinding/http_parser.d.ts b/typings/internalBinding/http_parser.d.ts index 260c6e802b0808..bd9a22e55b12e5 100644 --- a/typings/internalBinding/http_parser.d.ts +++ b/typings/internalBinding/http_parser.d.ts @@ -1,4 +1,7 @@ declare namespace InternalHttpParserBinding { + type Buffer = Uint8Array; + type Stream = object; + class HTTPParser { static REQUEST: 1; static RESPONSE: 2; @@ -30,7 +33,7 @@ declare namespace InternalHttpParserBinding { ): void; pause(): void; resume(): void; - consume(stream: object): void; + consume(stream: Stream): void; unconsume(): void; getCurrentBuffer(): Buffer; } diff --git a/typings/internalBinding/os.d.ts b/typings/internalBinding/os.d.ts index cdddc330151a3e..161d9fd4b46836 100644 --- a/typings/internalBinding/os.d.ts +++ b/typings/internalBinding/os.d.ts @@ -1,21 +1,25 @@ +declare namespace InternalOSBinding { + type OSContext = {}; +} + declare function InternalBinding(binding: 'os'): { - getHostname(ctx: {}): string | undefined; + getHostname(ctx: InternalOSBinding.OSContext): string | undefined; getLoadAvg(array: Float64Array): void; getUptime(): number; getTotalMem(): number; getFreeMem(): number; getCPUs(): Array; - getInterfaceAddresses(ctx: {}): Array | undefined; - getHomeDirectory(ctx: {}): string | undefined; - getUserInfo(options: { encoding?: string } | undefined, ctx: {}): { + getInterfaceAddresses(ctx: InternalOSBinding.OSContext): Array | undefined; + getHomeDirectory(ctx: InternalOSBinding.OSContext): string | undefined; + getUserInfo(options: { encoding?: string } | undefined, ctx: InternalOSBinding.OSContext): { uid: number; gid: number; username: string; homedir: string; shell: string | null; } | undefined; - setPriority(pid: number, priority: number, ctx: {}): number; - getPriority(pid: number, ctx: {}): number | undefined; - getOSInformation(ctx: {}): [sysname: string, version: string, release: string]; + setPriority(pid: number, priority: number, ctx: InternalOSBinding.OSContext): number; + getPriority(pid: number, ctx: InternalOSBinding.OSContext): number | undefined; + getOSInformation(ctx: InternalOSBinding.OSContext): [sysname: string, version: string, release: string]; isBigEndian: boolean; }; diff --git a/typings/internalBinding/serdes.d.ts b/typings/internalBinding/serdes.d.ts index d328123e25ade4..b3577c658d2a9f 100644 --- a/typings/internalBinding/serdes.d.ts +++ b/typings/internalBinding/serdes.d.ts @@ -1,4 +1,6 @@ declare namespace InternalSerdesBinding { + type Buffer = Uint8Array; + class Serializer { _getDataCloneError: typeof Error; constructor(); diff --git a/typings/internalBinding/symbols.d.ts b/typings/internalBinding/symbols.d.ts index af49504f84b329..03c9c8f40474de 100644 --- a/typings/internalBinding/symbols.d.ts +++ b/typings/internalBinding/symbols.d.ts @@ -1,3 +1,27 @@ -declare function InternalBinding(binding: 'symbols'): { - [name: string]: symbol; +declare namespace InternalSymbolsBinding { + const async_id_symbol: unique symbol; + const handle_onclose_symbol: unique symbol; + const no_message_symbol: unique symbol; + const messaging_deserialize_symbol: unique symbol; + const messaging_transfer_symbol: unique symbol; + const messaging_clone_symbol: unique symbol; + const messaging_transfer_list_symbol: unique symbol; + const oninit_symbol: unique symbol; + const owner_symbol: unique symbol; + const onpskexchange_symbol: unique symbol; + const trigger_async_id_symbol: unique symbol; } + +declare function InternalBinding(binding: 'symbols'): { + async_id_symbol: typeof InternalSymbolsBinding.async_id_symbol; + handle_onclose_symbol: typeof InternalSymbolsBinding.handle_onclose_symbol; + no_message_symbol: typeof InternalSymbolsBinding.no_message_symbol; + messaging_deserialize_symbol: typeof InternalSymbolsBinding.messaging_deserialize_symbol; + messaging_transfer_symbol: typeof InternalSymbolsBinding.messaging_transfer_symbol; + messaging_clone_symbol: typeof InternalSymbolsBinding.messaging_clone_symbol; + messaging_transfer_list_symbol: typeof InternalSymbolsBinding.messaging_transfer_list_symbol; + oninit_symbol: typeof InternalSymbolsBinding.oninit_symbol; + owner_symbol: typeof InternalSymbolsBinding.owner_symbol; + onpskexchange_symbol: typeof InternalSymbolsBinding.onpskexchange_symbol; + trigger_async_id_symbol: typeof InternalSymbolsBinding.trigger_async_id_symbol; +}; diff --git a/typings/internalBinding/types.d.ts b/typings/internalBinding/types.d.ts index 6d01da4b535ed4..c8efea84b69e9d 100644 --- a/typings/internalBinding/types.d.ts +++ b/typings/internalBinding/types.d.ts @@ -1,26 +1,26 @@ declare function InternalBinding(binding: 'types'): { - isAsyncFunction(value: unknown): value is (...args: unknown[]) => Promise, - isGeneratorFunction(value: unknown): value is GeneratorFunction, - isAnyArrayBuffer(value: unknown): value is (ArrayBuffer | SharedArrayBuffer), - isArrayBuffer(value: unknown): value is ArrayBuffer, - isArgumentsObject(value: unknown): value is ArrayLike, - isBoxedPrimitive(value: unknown): value is (BigInt | Boolean | Number | String | Symbol), - isDataView(value: unknown): value is DataView, - isExternal(value: unknown): value is Object, - isMap(value: unknown): value is Map, - isMapIterator: (value: unknown) => value is IterableIterator, - isModuleNamespaceObject: (value: unknown) => value is {[Symbol.toStringTag]: 'Module', [key: string]: any}, - isNativeError: (value: unknown) => Error, - isPromise: (value: unknown) => value is Promise, - isSet: (value: unknown) => value is Set, - isSetIterator: (value: unknown) => value is IterableIterator, - isWeakMap: (value: unknown) => value is WeakMap, - isWeakSet: (value: unknown) => value is WeakSet, - isRegExp: (value: unknown) => RegExp, - isDate: (value: unknown) => Date, - isTypedArray: (value: unknown) => value is TypedArray, - isStringObject: (value: unknown) => value is String, - isNumberObject: (value: unknown) => value is Number, + isAsyncFunction(value: unknown): value is (...args: unknown[]) => Promise; + isGeneratorFunction(value: unknown): value is GeneratorFunction; + isAnyArrayBuffer(value: unknown): value is (ArrayBuffer | SharedArrayBuffer); + isArrayBuffer(value: unknown): value is ArrayBuffer; + isArgumentsObject(value: unknown): value is ArrayLike; + isBoxedPrimitive(value: unknown): value is (BigInt | Boolean | Number | String | Symbol); + isDataView(value: unknown): value is DataView; + isExternal(value: unknown): value is Object; + isMap(value: unknown): value is Map; + isMapIterator: (value: unknown) => value is IterableIterator; + isModuleNamespaceObject: (value: unknown) => value is { [Symbol.toStringTag]: 'Module' }; + isNativeError: (value: unknown) => Error; + isPromise: (value: unknown) => value is Promise; + isSet: (value: unknown) => value is Set; + isSetIterator: (value: unknown) => value is IterableIterator; + isWeakMap: (value: unknown) => value is WeakMap; + isWeakSet: (value: unknown) => value is WeakSet; + isRegExp: (value: unknown) => RegExp; + isDate: (value: unknown) => Date; + isTypedArray: (value: unknown) => value is TypedArray; + isStringObject: (value: unknown) => value is String; + isNumberObject: (value: unknown) => value is Number; isBooleanObject: (value: unknown) => value is Boolean, - isBigIntObject: (value: unknown) => value is BigInt, + isBigIntObject: (value: unknown) => value is BigInt; }; diff --git a/typings/internalBinding/util.d.ts b/typings/internalBinding/util.d.ts index 3d89796662f74a..40def32d570d55 100644 --- a/typings/internalBinding/util.d.ts +++ b/typings/internalBinding/util.d.ts @@ -1,5 +1,5 @@ declare namespace InternalUtilBinding { - class WeakReference { + class WeakReference { constructor(value: T); get(): undefined | T; incRef(): void; diff --git a/typings/internalBinding/worker.d.ts b/typings/internalBinding/worker.d.ts index 2fc7f9272d9f64..52bfc53c29dc0a 100644 --- a/typings/internalBinding/worker.d.ts +++ b/typings/internalBinding/worker.d.ts @@ -5,7 +5,8 @@ declare namespace InternalWorkerBinding { env: object | null | undefined, execArgv: string[] | null | undefined, resourceLimits: Float64Array, - trackUnmanagedFds: boolean); + trackUnmanagedFds: boolean, + ); startThread(): void; stopThread(): void; ref(): void; From 9e12ed4f6856824c202eec74626296b6962b06b8 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 26 Oct 2021 19:34:08 -0700 Subject: [PATCH 084/118] meta: consolidate AUTHORS entries for Azard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40619 Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- .mailmap | 1 + AUTHORS | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.mailmap b/.mailmap index eb72aa57cc2cc2..bd7ce4197cb2dc 100644 --- a/.mailmap +++ b/.mailmap @@ -45,6 +45,7 @@ Ashley Maceli Ashok Suthar Ashutosh Kumar Singh Atsuo Fukaya +Azard <330815461@qq.com> Ben Lugavere Ben Noordhuis Ben Noordhuis diff --git a/AUTHORS b/AUTHORS index 3e2f9f6fc82945..e436826aa18c79 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1535,7 +1535,7 @@ sallen450 OriLev Zongmin Lei lena -Azard <330815461@qq.com> +Azard Ezequiel Garcia Kyle Farnung Weijia Wang @@ -1607,7 +1607,6 @@ Greg Alexander dcharbonnier Jared Kantrowitz Guy Margalit -Azard nishijayaraj Nick Stanish Mandeep Singh From 7230b6d33dba6a6c258822c42a98e0a7358735b3 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 26 Oct 2021 19:42:43 -0700 Subject: [PATCH 085/118] meta: consolidate AUTHORS entries for alexzherdev MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40620 Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- .mailmap | 1 + AUTHORS | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.mailmap b/.mailmap index bd7ce4197cb2dc..67b3aa21823a43 100644 --- a/.mailmap +++ b/.mailmap @@ -12,6 +12,7 @@ Alex Hultman Alex Jordan Alex Kocharin Alex Kocharin +Alex Zherdev Alexander Marchenko Alexey Kupershtokh Alexis Campailla diff --git a/AUTHORS b/AUTHORS index e436826aa18c79..75980374258f63 100644 --- a/AUTHORS +++ b/AUTHORS @@ -2833,7 +2833,7 @@ akitsu-sanae Minuk Park Jim Schlight Theotime Poisseau -Alex Zherdev +Alex Zherdev dev-313 Michael Perrotte Alexandre Ferrando @@ -2914,7 +2914,6 @@ jens-cappelle bruce-one Jason Macgowan Vincent Dhennin -Alex Zherdev Jeny Tchoupinax Sebastien Ahkrin From b9533c592abcca6a228f5fc264b4b8d87b9345c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Sun, 24 Oct 2021 21:47:17 +0000 Subject: [PATCH 086/118] test: use conventional argument order in assertion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40591 Reviewed-By: Colin Ihrig Reviewed-By: Voltrex Reviewed-By: Rich Trott Reviewed-By: Michaël Zasso Reviewed-By: Luigi Pinca Reviewed-By: Trivikram Kamat Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell --- test/parallel/test-buffer-fill.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 00e65c82e91849..e91492a59e81b3 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -315,7 +315,7 @@ Buffer.alloc(8, ''); buf.fill('h'); for (let i = 0; i < buf.length; i++) - assert.strictEqual('h'.charCodeAt(0), buf[i]); + assert.strictEqual(buf[i], 'h'.charCodeAt(0)); buf.fill(0); for (let i = 0; i < buf.length; i++) From 59c26a2b2c3748ff6bc4fc47f58e5ed2b0587c34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Wed, 27 Oct 2021 22:34:17 +0000 Subject: [PATCH 087/118] src: fix #endif description in crypto_keygen.h PR-URL: https://github.com/nodejs/node/pull/40639 Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Voltrex Reviewed-By: James M Snell --- src/crypto/crypto_keygen.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/crypto/crypto_keygen.h b/src/crypto/crypto_keygen.h index d4790097419044..f8d863a2d93990 100644 --- a/src/crypto/crypto_keygen.h +++ b/src/crypto/crypto_keygen.h @@ -301,6 +301,6 @@ using SecretKeyGenJob = KeyGenJob; } // namespace crypto } // namespace node -#endif // !defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #endif // SRC_CRYPTO_CRYPTO_KEYGEN_H_ From 3cb74d72f86721f45a3c9fa309515824a9c07a47 Mon Sep 17 00:00:00 2001 From: ryan Date: Tue, 26 Oct 2021 19:02:53 +0800 Subject: [PATCH 088/118] doc: fix markdown syntax and HTML tag misses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40608 Reviewed-By: Antoine du Hamel Reviewed-By: Tobias Nießen Reviewed-By: Richard Lau Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca Reviewed-By: Voltrex --- doc/api/cli.md | 2 +- doc/api/crypto.md | 2 ++ doc/api/dns.md | 6 +++--- doc/api/os.md | 2 +- doc/api/tls.md | 2 +- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/doc/api/cli.md b/doc/api/cli.md index 725184d163cdec..60200a7e0e26f6 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -830,7 +830,7 @@ warning will be written to stderr instead. The `file` name may be an absolute path. If it is not, the default directory it will be written to is controlled by the -[`--diagnostic-dir`]() command-line option. +[`--diagnostic-dir`][] command-line option. ### `--report-compact` diff --git a/doc/api/crypto.md b/doc/api/crypto.md index b23bee42e95bc6..669eb4373d65d2 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -5637,6 +5637,7 @@ See the [list of SSL OP Flags][] for details. SSL_OP_NO_TLSv1_3 Instructs OpenSSL to turn off TLS v1.3 + SSL_OP_PKCS1_CHECK_1 @@ -5662,6 +5663,7 @@ See the [list of SSL OP Flags][] for details. Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. + SSL_OP_SSLEAY_080_CLIENT_DH_BUG diff --git a/doc/api/dns.md b/doc/api/dns.md index 48796f9c846f30..705c654d9e2656 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -338,7 +338,7 @@ records. The type and structure of individual results varies based on `rrtype`: | `'TXT'` | text records | {string\[]} | [`dns.resolveTxt()`][] | On error, `err` is an [`Error`][] object, where `err.code` is one of the -[DNS error codes](). +[DNS error codes][]. ## `dns.resolve4(hostname[, options], callback)` @@ -942,7 +942,7 @@ based on `rrtype`: | `'TXT'` | text records | {string\[]} | [`dnsPromises.resolveTxt()`][] | On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` -is one of the [DNS error codes](). +is one of the [DNS error codes][]. ### `dnsPromises.resolve4(hostname[, options])` @@ -1210,7 +1210,7 @@ Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names. On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` -is one of the [DNS error codes](). +is one of the [DNS error codes][]. ### `dnsPromises.setDefaultResultOrder(order)` diff --git a/doc/api/os.md b/doc/api/os.md index c8d4380bec40ea..3a5d98264348b3 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -952,7 +952,7 @@ The following error constants are exported by `os.constants.errno`. EXDEV - Indicates an improper link. + Indicates an improper link. diff --git a/doc/api/tls.md b/doc/api/tls.md index ac582be4dd761d..e83a34ecf67ce9 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -459,7 +459,7 @@ The `'secure'` event is emitted by the `SecurePair` object once a secure connection has been established. As with checking for the server -[`'secureConnection'`]() +[`'secureConnection'`][] event, `pair.cleartext.authorized` should be inspected to confirm whether the certificate used is properly authorized. From befac5ddd9a209a62dc552623035f38ec684eed6 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 27 Oct 2021 23:17:30 +0800 Subject: [PATCH 089/118] doc: update tracking issues of startup performance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The issues listed in the doc have been closed, and a new one is currently being used to track snapshot integration. PR-URL: https://github.com/nodejs/node/pull/40629 Reviewed-By: Rich Trott Reviewed-By: Michaël Zasso Reviewed-By: Luigi Pinca Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell --- doc/guides/strategic-initiatives.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/guides/strategic-initiatives.md b/doc/guides/strategic-initiatives.md index 2bb7b0d4c51878..8bcd8800b7ee2b 100644 --- a/doc/guides/strategic-initiatives.md +++ b/doc/guides/strategic-initiatives.md @@ -11,7 +11,7 @@ agenda to ensure they are active and have the support they need. | Core Promise APIs | [Antoine du Hamel][aduh95] | | | Future of Build Toolchain | [Mary Marchini][mmarchini] | , | | QUIC / HTTP3 | [James M Snell][jasnell] | | -| Startup performance | [Joyee Cheung][joyeecheung] | | +| Startup performance | [Joyee Cheung][joyeecheung] | | | V8 Currency | [Michaël Zasso][targos] | |
From ef46cb428decfffe103afecfe7d4f3a4a0d48b11 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 25 Oct 2021 14:11:27 -0700 Subject: [PATCH 090/118] meta: consolidate AUTHORS entries for brettkiefer PR-URL: https://github.com/nodejs/node/pull/40599 Reviewed-By: James M Snell Reviewed-By: Myles Borins --- .mailmap | 1 + AUTHORS | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index 67b3aa21823a43..d78783b34f7465 100644 --- a/.mailmap +++ b/.mailmap @@ -70,6 +70,7 @@ Brandon Benvie Brandon Kobel Brendan Ashworth Brent Pendergraft +Brett Kiefer Brian White Brian White Caleb Boyd diff --git a/AUTHORS b/AUTHORS index 75980374258f63..8b6045de4dfc5d 100644 --- a/AUTHORS +++ b/AUTHORS @@ -2218,7 +2218,6 @@ Misty De Meo James Kylstra Shelley Vohr Deepjyoti Mondal -Brett Kiefer Kevin Thomas ZaneHannanAU Fernando Doglio From f778fa230ba544d2605d2fbb6ef94ed8bf887770 Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Sat, 16 Oct 2021 14:46:48 +0530 Subject: [PATCH 091/118] test: test `crypto.setEngine()` using an actual engine Signed-off-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/40481 Reviewed-By: James M Snell --- Makefile | 1 + node.gyp | 26 +++++++++ test/fixtures/test_crypto_engine.c | 20 +++++++ test/parallel/test-crypto-engine.js | 91 +++++++++++++++++------------ tools/run-worker.js | 4 +- 5 files changed, 103 insertions(+), 39 deletions(-) create mode 100644 test/fixtures/test_crypto_engine.c diff --git a/Makefile b/Makefile index e55bd8d70242ac..7671bb804fa6a4 100644 --- a/Makefile +++ b/Makefile @@ -1327,6 +1327,7 @@ LINT_CPP_FILES = $(filter-out $(LINT_CPP_EXCLUDE), $(wildcard \ test/cctest/*.h \ test/embedding/*.cc \ test/embedding/*.h \ + test/fixtures/*.c \ test/js-native-api/*/*.cc \ test/js-native-api/*/*.h \ test/node-api/*/*.cc \ diff --git a/node.gyp b/node.gyp index faf50d86bcad64..2052917d7ee338 100644 --- a/node.gyp +++ b/node.gyp @@ -1391,5 +1391,31 @@ }, ] }], # end aix section + # TODO(RaisinTen): Enable this to build on other platforms as well. + ['(OS=="mac" or (OS=="linux" and target_arch=="x64")) and \ + node_use_openssl=="true"', { + 'targets': [ + { + 'target_name': 'test_crypto_engine', + 'type': 'shared_library', + 'include_dirs': ['deps/openssl/openssl/include'], + 'sources': ['test/fixtures/test_crypto_engine.c'], + 'conditions': [ + ['OS=="mac"', { + 'dependencies': ['deps/openssl/openssl.gyp:openssl'], + 'xcode_settings': { + 'OTHER_CFLAGS': ['-Wno-deprecated-declarations'], + }, + }], + ['OS=="linux" and target_arch=="x64"', { + 'cflags': [ + '-Wno-deprecated-declarations', + '-fPIC', + ], + }], + ], + }, # test_crypto_engine + ], # end targets + }], # end node_use_openssl section ], # end conditions block } diff --git a/test/fixtures/test_crypto_engine.c b/test/fixtures/test_crypto_engine.c new file mode 100644 index 00000000000000..1715196bf5bb03 --- /dev/null +++ b/test/fixtures/test_crypto_engine.c @@ -0,0 +1,20 @@ +#include + +#include + +int bind(ENGINE* e, const char* id) { + if (ENGINE_set_id(e, "libtest_crypto_engine") == 0) { + fprintf(stderr, "ENGINE_set_id() failed.\n"); + return 0; + } + + if (ENGINE_set_name(e, "A test crypto engine") == 0) { + fprintf(stderr, "ENGINE_set_name() failed.\n"); + return 0; + } + + return 1; +} + +IMPLEMENT_DYNAMIC_BIND_FN(bind) +IMPLEMENT_DYNAMIC_CHECK_FN() diff --git a/test/parallel/test-crypto-engine.js b/test/parallel/test-crypto-engine.js index 8b33285b454eef..399745f0f6463e 100644 --- a/test/parallel/test-crypto-engine.js +++ b/test/parallel/test-crypto-engine.js @@ -1,43 +1,60 @@ 'use strict'; const common = require('../common'); +if (!common.hasCrypto) common.skip('missing crypto'); -if (!common.hasCrypto) - common.skip('missing crypto'); +// This tests crypto.setEngine(). const assert = require('assert'); const crypto = require('crypto'); -const invalidEngineName = 'xxx'; - -assert.throws( - () => crypto.setEngine(true), - { - code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError', - message: 'The "id" argument must be of type string. Received type boolean' + - ' (true)' - }); - -assert.throws( - () => crypto.setEngine('/path/to/engine', 'notANumber'), - { - code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError', - message: 'The "flags" argument must be of type number. Received type' + - " string ('notANumber')" - }); - -assert.throws( - () => crypto.setEngine(invalidEngineName), - { - code: 'ERR_CRYPTO_ENGINE_UNKNOWN', - name: 'Error', - message: `Engine "${invalidEngineName}" was not found` - }); - -assert.throws( - () => crypto.setEngine(invalidEngineName, crypto.constants.ENGINE_METHOD_RSA), - { - code: 'ERR_CRYPTO_ENGINE_UNKNOWN', - name: 'Error', - message: `Engine "${invalidEngineName}" was not found` - }); +const fs = require('fs'); +const path = require('path'); + +assert.throws(() => crypto.setEngine(true), /ERR_INVALID_ARG_TYPE/); +assert.throws(() => crypto.setEngine('/path/to/engine', 'notANumber'), + /ERR_INVALID_ARG_TYPE/); + +{ + const invalidEngineName = 'xxx'; + assert.throws(() => crypto.setEngine(invalidEngineName), + /ERR_CRYPTO_ENGINE_UNKNOWN/); + assert.throws(() => crypto.setEngine(invalidEngineName, + crypto.constants.ENGINE_METHOD_RSA), + /ERR_CRYPTO_ENGINE_UNKNOWN/); +} + +crypto.setEngine('dynamic'); +crypto.setEngine('dynamic'); + +crypto.setEngine('dynamic', crypto.constants.ENGINE_METHOD_RSA); +crypto.setEngine('dynamic', crypto.constants.ENGINE_METHOD_RSA); + +{ + const engineName = 'test_crypto_engine'; + let engineLib; + if (common.isOSX) + engineLib = `lib${engineName}.dylib`; + else if (common.isLinux && process.arch === 'x64') + engineLib = `lib${engineName}.so`; + + if (engineLib !== undefined) { + const execDir = path.dirname(process.execPath); + const enginePath = path.join(execDir, engineLib); + const engineId = path.parse(engineLib).name; + + fs.accessSync(enginePath); + + crypto.setEngine(enginePath); + crypto.setEngine(enginePath); + + crypto.setEngine(enginePath, crypto.constants.ENGINE_METHOD_RSA); + crypto.setEngine(enginePath, crypto.constants.ENGINE_METHOD_RSA); + + process.env.OPENSSL_ENGINES = execDir; + + crypto.setEngine(engineId); + crypto.setEngine(engineId); + + crypto.setEngine(engineId, crypto.constants.ENGINE_METHOD_RSA); + crypto.setEngine(engineId, crypto.constants.ENGINE_METHOD_RSA); + } +} diff --git a/tools/run-worker.js b/tools/run-worker.js index 7590e460a404ae..bfacc48320136e 100644 --- a/tools/run-worker.js +++ b/tools/run-worker.js @@ -5,7 +5,7 @@ if (typeof require === 'undefined') { } const path = require('path'); -const { Worker } = require('worker_threads'); +const { Worker, SHARE_ENV } = require('worker_threads'); -new Worker(path.resolve(process.cwd(), process.argv[2])) +new Worker(path.resolve(process.cwd(), process.argv[2]), { env: SHARE_ENV }) .on('exit', (code) => process.exitCode = code); From 2c8a6ec28e12577150d344305b4fd5e17410c45d Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Sun, 24 Oct 2021 14:20:15 +0530 Subject: [PATCH 092/118] src: remove usage of `AllocatedBuffer` from `node_http2` Signed-off-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/40584 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen --- src/node_http2.cc | 92 +++++++++++++++++++++++++++++------------------ src/node_http2.h | 7 ++-- 2 files changed, 60 insertions(+), 39 deletions(-) diff --git a/src/node_http2.cc b/src/node_http2.cc index c01fa4d5255077..f5a1db0d022a18 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -21,9 +21,11 @@ namespace node { using v8::Array; using v8::ArrayBuffer; using v8::ArrayBufferView; +using v8::BackingStore; using v8::Boolean; using v8::Context; using v8::EscapableHandleScope; +using v8::False; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; @@ -37,6 +39,7 @@ using v8::Number; using v8::Object; using v8::ObjectTemplate; using v8::String; +using v8::True; using v8::Uint8Array; using v8::Undefined; using v8::Value; @@ -267,17 +270,20 @@ Local Http2Settings::Pack( size_t count, const nghttp2_settings_entry* entries) { EscapableHandleScope scope(env->isolate()); - const size_t size = count * 6; - AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size); - ssize_t ret = - nghttp2_pack_settings_payload( - reinterpret_cast(buffer.data()), - size, - entries, - count); - Local buf = Undefined(env->isolate()); - if (ret >= 0) buf = buffer.ToBuffer().ToLocalChecked(); - return scope.Escape(buf); + std::unique_ptr bs; + { + NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data()); + bs = ArrayBuffer::NewBackingStore(env->isolate(), count * 6); + } + if (nghttp2_pack_settings_payload(static_cast(bs->Data()), + bs->ByteLength(), + entries, + count) < 0) { + return scope.Escape(Undefined(env->isolate())); + } + Local ab = ArrayBuffer::New(env->isolate(), std::move(bs)); + return scope.Escape(Buffer::New(env, ab, 0, ab->ByteLength()) + .FromMaybe(Local())); } // Updates the shared TypedArray with the current remote or local settings for @@ -323,7 +329,7 @@ void Http2Settings::Done(bool ack) { double duration = (end - startTime_) / 1e6; Local argv[] = { - ack ? v8::True(env()->isolate()) : v8::False(env()->isolate()), + ack ? True(env()->isolate()) : False(env()->isolate()), Number::New(env()->isolate(), duration) }; MakeCallback(callback(), arraysize(argv), argv); @@ -368,19 +374,23 @@ Origins::Origins( return; } - buf_ = AllocatedBuffer::AllocateManaged( - env, - (alignof(nghttp2_origin_entry) - 1) + - count_ * sizeof(nghttp2_origin_entry) + - origin_string_len); + { + NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data()); + bs_ = ArrayBuffer::NewBackingStore(env->isolate(), + alignof(nghttp2_origin_entry) - 1 + + count_ * sizeof(nghttp2_origin_entry) + + origin_string_len); + } // Make sure the start address is aligned appropriately for an nghttp2_nv*. - char* start = AlignUp(buf_.data(), alignof(nghttp2_origin_entry)); + char* start = AlignUp(static_cast(bs_->Data()), + alignof(nghttp2_origin_entry)); char* origin_contents = start + (count_ * sizeof(nghttp2_origin_entry)); nghttp2_origin_entry* const nva = reinterpret_cast(start); - CHECK_LE(origin_contents + origin_string_len, buf_.data() + buf_.size()); + CHECK_LE(origin_contents + origin_string_len, + static_cast(bs_->Data()) + bs_->ByteLength()); CHECK_EQ(origin_string->WriteOneByte( env->isolate(), reinterpret_cast(origin_contents), @@ -819,7 +829,7 @@ void Http2Session::ConsumeHTTP2Data() { DecrementCurrentSessionMemory(stream_buf_.len); stream_buf_offset_ = 0; stream_buf_ab_.Reset(); - stream_buf_allocation_.clear(); + stream_buf_allocation_.reset(); stream_buf_ = uv_buf_init(nullptr, 0); // Send any data that was queued up while processing the received data. @@ -1247,7 +1257,8 @@ void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { Local ab; if (session->stream_buf_ab_.IsEmpty()) { - ab = session->stream_buf_allocation_.ToArrayBuffer(); + ab = ArrayBuffer::New(env->isolate(), + std::move(session->stream_buf_allocation_)); session->stream_buf_ab_.Reset(env->isolate(), ab); } else { ab = PersistentToLocal::Strong(session->stream_buf_ab_); @@ -1823,7 +1834,7 @@ Http2Stream* Http2Session::SubmitRequest( } uv_buf_t Http2Session::OnStreamAlloc(size_t suggested_size) { - return AllocatedBuffer::AllocateManaged(env(), suggested_size).release(); + return env()->allocate_managed_buffer(suggested_size); } // Callback used to receive inbound data from the i/o stream @@ -1833,7 +1844,7 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) { Http2Scope h2scope(this); CHECK_NOT_NULL(stream_); Debug(this, "receiving %d bytes, offset %d", nread, stream_buf_offset_); - AllocatedBuffer buf(env(), buf_); + std::unique_ptr bs = env()->release_managed_buffer(buf_); // Only pass data on if nread > 0 if (nread <= 0) { @@ -1843,24 +1854,34 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) { return; } + CHECK_LE(static_cast(nread), bs->ByteLength()); + statistics_.data_received += nread; if (LIKELY(stream_buf_offset_ == 0)) { // Shrink to the actual amount of used data. - buf.Resize(nread); + bs = BackingStore::Reallocate(env()->isolate(), std::move(bs), nread); } else { // This is a very unlikely case, and should only happen if the ReadStart() // call in OnStreamAfterWrite() immediately provides data. If that does // happen, we concatenate the data we received with the already-stored // pending input data, slicing off the already processed part. size_t pending_len = stream_buf_.len - stream_buf_offset_; - AllocatedBuffer new_buf = - AllocatedBuffer::AllocateManaged(env(), pending_len + nread); - memcpy(new_buf.data(), stream_buf_.base + stream_buf_offset_, pending_len); - memcpy(new_buf.data() + pending_len, buf.data(), nread); - - buf = std::move(new_buf); - nread = buf.size(); + std::unique_ptr new_bs; + { + NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data()); + new_bs = ArrayBuffer::NewBackingStore(env()->isolate(), + pending_len + nread); + } + memcpy(static_cast(new_bs->Data()), + stream_buf_.base + stream_buf_offset_, + pending_len); + memcpy(static_cast(new_bs->Data()) + pending_len, + bs->Data(), + nread); + + bs = std::move(new_bs); + nread = bs->ByteLength(); stream_buf_offset_ = 0; stream_buf_ab_.Reset(); @@ -1873,12 +1894,13 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) { // Remember the current buffer, so that OnDataChunkReceived knows the // offset of a DATA frame's data into the socket read buffer. - stream_buf_ = uv_buf_init(buf.data(), static_cast(nread)); + stream_buf_ = uv_buf_init(static_cast(bs->Data()), + static_cast(nread)); // Store this so we can create an ArrayBuffer for read data from it. // DATA frames will be emitted as slices of that ArrayBuffer to avoid having // to copy memory. - stream_buf_allocation_ = std::move(buf); + stream_buf_allocation_ = std::move(bs); ConsumeHTTP2Data(); @@ -2023,7 +2045,7 @@ void Http2Stream::Close(int32_t code) { Debug(this, "closed with code %d", code); } -ShutdownWrap* Http2Stream::CreateShutdownWrap(v8::Local object) { +ShutdownWrap* Http2Stream::CreateShutdownWrap(Local object) { // DoShutdown() always finishes synchronously, so there's no need to create // a structure to store asynchronous context. return nullptr; @@ -3049,7 +3071,7 @@ void Http2Ping::Done(bool ack, const uint8_t* payload) { } Local argv[] = { - ack ? v8::True(isolate) : v8::False(isolate), + ack ? True(isolate) : False(isolate), Number::New(isolate, duration_ms), buf }; diff --git a/src/node_http2.h b/src/node_http2.h index 4d267e647d3494..e3d4d70b2d1fd5 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -8,7 +8,6 @@ #include "nghttp2/nghttp2.h" #include "env.h" -#include "allocated_buffer.h" #include "aliased_struct.h" #include "node_http2_state.h" #include "node_http_common.h" @@ -897,7 +896,7 @@ class Http2Session : public AsyncWrap, // When processing input data, either stream_buf_ab_ or stream_buf_allocation_ // will be set. stream_buf_ab_ is lazily created from stream_buf_allocation_. v8::Global stream_buf_ab_; - AllocatedBuffer stream_buf_allocation_; + std::unique_ptr stream_buf_allocation_; size_t stream_buf_offset_ = 0; // Custom error code for errors that originated inside one of the callbacks // called by nghttp2_session_mem_recv. @@ -1040,7 +1039,7 @@ class Origins { ~Origins() = default; const nghttp2_origin_entry* operator*() const { - return reinterpret_cast(buf_.data()); + return static_cast(bs_->Data()); } size_t length() const { @@ -1049,7 +1048,7 @@ class Origins { private: size_t count_; - AllocatedBuffer buf_; + std::unique_ptr bs_; }; #define HTTP2_HIDDEN_CONSTANTS(V) \ From b4a80dba79fb42171c37297f2f6acd61e3cba1fa Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Sat, 30 Oct 2021 17:45:25 +0200 Subject: [PATCH 093/118] tools: avoid fetch extra commits when validating commit messages PR-URL: https://github.com/nodejs/node/pull/39128 Reviewed-By: Mary Marchini --- .github/workflows/commit-lint.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/commit-lint.yml b/.github/workflows/commit-lint.yml index 0f6fd639523cb0..42e9dc05283730 100644 --- a/.github/workflows/commit-lint.yml +++ b/.github/workflows/commit-lint.yml @@ -9,10 +9,12 @@ jobs: lint-commit-message: runs-on: ubuntu-latest steps: + - name: Compute number of commits in the PR + id: nb-of-commits + run: echo "::set-output name=nb::$((${{ github.event.pull_request.commits }} + 1))" - uses: actions/checkout@v2 with: - # Last 100 commits should be enough for a PR - fetch-depth: 100 + fetch-depth: ${{ steps.nb-of-commits.outputs.nb }} - name: Install Node.js uses: actions/setup-node@v2 with: From 67c7d11f1a1fd40518e5e84abd4ace8e5a37e098 Mon Sep 17 00:00:00 2001 From: Voltrex <62040526+VoltrexMaster@users.noreply.github.com> Date: Sun, 25 Apr 2021 03:39:46 +0430 Subject: [PATCH 094/118] typings: add JSDoc typings for inspector MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added JSDoc typings for the `inspector` lib module. PR-URL: https://github.com/nodejs/node/pull/38390 Reviewed-By: James M Snell Reviewed-By: Adrian Estrada Reviewed-By: Rich Trott Reviewed-By: Michaël Zasso --- lib/inspector.js | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/inspector.js b/lib/inspector.js index d7518eff261f3a..46779a0ec21dac 100644 --- a/lib/inspector.js +++ b/lib/inspector.js @@ -53,6 +53,10 @@ class Session extends EventEmitter { this[messageCallbacksSymbol] = new SafeMap(); } + /** + * Connects the session to the inspector back-end. + * @returns {void} + */ connect() { if (this[connectionSymbol]) throw new ERR_INSPECTOR_ALREADY_CONNECTED('The inspector session'); @@ -60,6 +64,11 @@ class Session extends EventEmitter { new Connection((message) => this[onMessageSymbol](message)); } + /** + * Connects the session to the main thread + * inspector back-end. + * @returns {void} + */ connectToMainThread() { if (isMainThread) throw new ERR_INSPECTOR_NOT_WORKER(); @@ -93,6 +102,13 @@ class Session extends EventEmitter { } } + /** + * Posts a message to the inspector back-end. + * @param {string} method + * @param {Record} [params] + * @param {Function} [callback] + * @returns {void} + */ post(method, params, callback) { validateString(method, 'method'); if (!callback && typeof params === 'function') { @@ -120,6 +136,12 @@ class Session extends EventEmitter { this[connectionSymbol].dispatch(JSONStringify(message)); } + /** + * Immediately closes the session, all pending + * message callbacks will be called with an + * error. + * @returns {void} + */ disconnect() { if (!this[connectionSymbol]) return; @@ -134,6 +156,13 @@ class Session extends EventEmitter { } } +/** + * Activates inspector on host and port. + * @param {number} [port] + * @param {string} [host] + * @param {boolean} [wait] + * @returns {void} + */ function inspectorOpen(port, host, wait) { if (isEnabled()) { throw new ERR_INSPECTOR_ALREADY_ACTIVATED(); @@ -143,6 +172,12 @@ function inspectorOpen(port, host, wait) { waitForDebugger(); } +/** + * Blocks until a client (existing or connected later) + * has sent the `Runtime.runIfWaitingForDebugger` + * command. + * @returns {void} + */ function inspectorWaitForDebugger() { if (!waitForDebugger()) throw new ERR_INSPECTOR_NOT_ACTIVE(); @@ -151,7 +186,7 @@ function inspectorWaitForDebugger() { module.exports = { open: inspectorOpen, close: process._debugEnd, - url: url, + url, waitForDebugger: inspectorWaitForDebugger, // This is dynamically added during bootstrap, // where the console from the VM is still available From de5c5c8509901a5fb3db38068b5fab4b6d52a693 Mon Sep 17 00:00:00 2001 From: FrankQiu Date: Wed, 27 Oct 2021 21:59:08 +0800 Subject: [PATCH 095/118] doc: remove `--experimental-modules` documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/38974 Reviewed-By: Michaël Zasso Reviewed-By: Anna Henningsen Reviewed-By: Jan Krems Reviewed-By: Myles Borins Reviewed-By: Geoffrey Booth Reviewed-By: James M Snell --- doc/api/cli.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/doc/api/cli.md b/doc/api/cli.md index 60200a7e0e26f6..2762d24c409702 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -285,14 +285,6 @@ added: v9.0.0 Specify the `module` of a custom experimental [ECMAScript Module loader][]. `module` may be either a path to a file, or an ECMAScript Module name. -### `--experimental-modules` - - - -Enable latest experimental modules features (deprecated). - ### `--experimental-policy` ## Technology Sponsors diff --git a/tools/node_modules/eslint/lib/rules/key-spacing.js b/tools/node_modules/eslint/lib/rules/key-spacing.js index cb176dd00d8abd..c09cebb513ae3d 100644 --- a/tools/node_modules/eslint/lib/rules/key-spacing.js +++ b/tools/node_modules/eslint/lib/rules/key-spacing.js @@ -427,19 +427,7 @@ module.exports = { * @returns {void} */ function report(property, side, whitespace, expected, mode) { - const diff = whitespace.length - expected, - nextColon = getNextColon(property.key), - tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }), - tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }), - isKeySide = side === "key", - isExtra = diff > 0, - diffAbs = Math.abs(diff), - spaces = Array(diffAbs + 1).join(" "); - - const locStart = isKeySide ? tokenBeforeColon.loc.end : nextColon.loc.start; - const locEnd = isKeySide ? nextColon.loc.start : tokenAfterColon.loc.start; - const missingLoc = isKeySide ? tokenBeforeColon.loc : tokenAfterColon.loc; - const loc = isExtra ? { start: locStart, end: locEnd } : missingLoc; + const diff = whitespace.length - expected; if (( diff && mode === "strict" || @@ -447,6 +435,19 @@ module.exports = { diff > 0 && !expected && mode === "minimum") && !(expected && containsLineTerminator(whitespace)) ) { + const nextColon = getNextColon(property.key), + tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }), + tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }), + isKeySide = side === "key", + isExtra = diff > 0, + diffAbs = Math.abs(diff), + spaces = Array(diffAbs + 1).join(" "); + + const locStart = isKeySide ? tokenBeforeColon.loc.end : nextColon.loc.start; + const locEnd = isKeySide ? nextColon.loc.start : tokenAfterColon.loc.start; + const missingLoc = isKeySide ? tokenBeforeColon.loc : tokenAfterColon.loc; + const loc = isExtra ? { start: locStart, end: locEnd } : missingLoc; + let fix; if (isExtra) { diff --git a/tools/node_modules/eslint/lib/rules/no-use-before-define.js b/tools/node_modules/eslint/lib/rules/no-use-before-define.js index fd8864e5fa5fa1..80ce3513af79df 100644 --- a/tools/node_modules/eslint/lib/rules/no-use-before-define.js +++ b/tools/node_modules/eslint/lib/rules/no-use-before-define.js @@ -34,52 +34,91 @@ function parseOptions(options) { } /** - * Checks whether or not a given variable is a function declaration. - * @param {eslint-scope.Variable} variable A variable to check. - * @returns {boolean} `true` if the variable is a function declaration. + * Checks whether or not a given location is inside of the range of a given node. + * @param {ASTNode} node An node to check. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of the range of the node. */ -function isFunction(variable) { - return variable.defs[0].type === "FunctionName"; +function isInRange(node, location) { + return node && node.range[0] <= location && location <= node.range[1]; } /** - * Checks whether or not a given variable is a class declaration in an upper function scope. - * @param {eslint-scope.Variable} variable A variable to check. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the variable is a class declaration. + * Checks whether or not a given location is inside of the range of a class static initializer. + * @param {ASTNode} node `ClassBody` node to check static initializers. + * @param {number} location A location to check. + * @returns {boolean} `true` if the location is inside of a class static initializer. */ -function isOuterClass(variable, reference) { - return ( - variable.defs[0].type === "ClassName" && - variable.scope.variableScope !== reference.from.variableScope - ); +function isInClassStaticInitializerRange(node, location) { + return node.body.some(classMember => ( + classMember.type === "PropertyDefinition" && + classMember.static && + classMember.value && + isInRange(classMember.value, location) + )); } /** - * Checks whether or not a given variable is a variable declaration in an upper function scope. - * @param {eslint-scope.Variable} variable A variable to check. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the variable is a variable declaration. + * Checks whether a given scope is the scope of a static class field initializer. + * @param {eslint-scope.Scope} scope A scope to check. + * @returns {boolean} `true` if the scope is a class static initializer scope. */ -function isOuterVariable(variable, reference) { - return ( - variable.defs[0].type === "Variable" && - variable.scope.variableScope !== reference.from.variableScope - ); +function isClassStaticInitializerScope(scope) { + if (scope.type === "class-field-initializer") { + + // `scope.block` is PropertyDefinition#value node + const propertyDefinition = scope.block.parent; + + return propertyDefinition.static; + } + + return false; } /** - * Checks whether or not a given location is inside of the range of a given node. - * @param {ASTNode} node An node to check. - * @param {number} location A location to check. - * @returns {boolean} `true` if the location is inside of the range of the node. + * Checks whether a given reference is evaluated in an execution context + * that isn't the one where the variable it refers to is defined. + * Execution contexts are: + * - top-level + * - functions + * - class field initializers (implicit functions) + * Static class field initializers are automatically run during the class definition evaluation, + * and therefore we'll consider them as a part of the parent execution context. + * Example: + * + * const x = 1; + * + * x; // returns `false` + * () => x; // returns `true` + * class C { + * field = x; // returns `true` + * static field = x; // returns `false` + * + * method() { + * x; // returns `true` + * } + * } + * @param {eslint-scope.Reference} reference A reference to check. + * @returns {boolean} `true` if the reference is from a separate execution context. */ -function isInRange(node, location) { - return node && node.range[0] <= location && location <= node.range[1]; +function isFromSeparateExecutionContext(reference) { + const variable = reference.resolved; + let scope = reference.from; + + // Scope#variableScope represents execution context + while (variable.scope.variableScope !== scope.variableScope) { + if (isClassStaticInitializerScope(scope.variableScope)) { + scope = scope.variableScope.upper; + } else { + return true; + } + } + + return false; } /** - * Checks whether or not a given reference is inside of the initializers of a given variable. + * Checks whether or not a given reference is evaluated during the initialization of its variable. * * This returns `true` in the following cases: * @@ -88,17 +127,44 @@ function isInRange(node, location) { * var {a = a} = obj * for (var a in a) {} * for (var a of a) {} - * @param {Variable} variable A variable to check. + * var C = class { [C]; } + * var C = class { static foo = C; } + * class C extends C {} + * class C extends (class { static foo = C; }) {} + * class C { [C]; } * @param {Reference} reference A reference to check. - * @returns {boolean} `true` if the reference is inside of the initializers. + * @returns {boolean} `true` if the reference is evaluated during the initialization. */ -function isInInitializer(variable, reference) { - if (variable.scope !== reference.from) { +function isEvaluatedDuringInitialization(reference) { + if (isFromSeparateExecutionContext(reference)) { + + /* + * Even if the reference appears in the initializer, it isn't evaluated during the initialization. + * For example, `const x = () => x;` is valid. + */ return false; } - let node = variable.identifiers[0].parent; const location = reference.identifier.range[1]; + const definition = reference.resolved.defs[0]; + + if (definition.type === "ClassName") { + + // `ClassDeclaration` or `ClassExpression` + const classDefinition = definition.node; + + return ( + isInRange(classDefinition, location) && + + /* + * Class binding is initialized before running static initializers. + * For example, `class C { static foo = C; }` is valid. + */ + !isInClassStaticInitializerRange(classDefinition.body, location) + ); + } + + let node = definition.name.parent; while (node) { if (node.type === "VariableDeclarator") { @@ -167,65 +233,77 @@ module.exports = { const options = parseOptions(context.options[0]); /** - * Determines whether a given use-before-define case should be reported according to the options. - * @param {eslint-scope.Variable} variable The variable that gets used before being defined - * @param {eslint-scope.Reference} reference The reference to the variable - * @returns {boolean} `true` if the usage should be reported + * Determines whether a given reference should be checked. + * + * Returns `false` if the reference is: + * - initialization's (e.g., `let a = 1`). + * - referring to an undefined variable (i.e., if it's an unresolved reference). + * - referring to a variable that is defined, but not in the given source code + * (e.g., global environment variable or `arguments` in functions). + * - allowed by options. + * @param {eslint-scope.Reference} reference The reference + * @returns {boolean} `true` if the reference should be checked */ - function isForbidden(variable, reference) { - if (isFunction(variable)) { - return options.functions; + function shouldCheck(reference) { + if (reference.init) { + return false; + } + + const variable = reference.resolved; + + if (!variable || variable.defs.length === 0) { + return false; } - if (isOuterClass(variable, reference)) { - return options.classes; + + const definitionType = variable.defs[0].type; + + if (!options.functions && definitionType === "FunctionName") { + return false; } - if (isOuterVariable(variable, reference)) { - return options.variables; + + if ( + ( + !options.variables && definitionType === "Variable" || + !options.classes && definitionType === "ClassName" + ) && + + // don't skip checking the reference if it's in the same execution context, because of TDZ + isFromSeparateExecutionContext(reference) + ) { + return false; } + return true; } /** - * Finds and validates all variables in a given scope. - * @param {Scope} scope The scope object. + * Finds and validates all references in a given scope and its child scopes. + * @param {eslint-scope.Scope} scope The scope object. * @returns {void} - * @private */ - function findVariablesInScope(scope) { - scope.references.forEach(reference => { + function checkReferencesInScope(scope) { + scope.references.filter(shouldCheck).forEach(reference => { const variable = reference.resolved; + const definitionIdentifier = variable.defs[0].name; - /* - * Skips when the reference is: - * - initialization's. - * - referring to an undefined variable. - * - referring to a global environment variable (there're no identifiers). - * - located preceded by the variable (except in initializers). - * - allowed by options. - */ - if (reference.init || - !variable || - variable.identifiers.length === 0 || - (variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) || - !isForbidden(variable, reference) + if ( + reference.identifier.range[1] < definitionIdentifier.range[1] || + isEvaluatedDuringInitialization(reference) ) { - return; + context.report({ + node: reference.identifier, + messageId: "usedBeforeDefined", + data: reference.identifier + }); } - - // Reports. - context.report({ - node: reference.identifier, - messageId: "usedBeforeDefined", - data: reference.identifier - }); }); - scope.childScopes.forEach(findVariablesInScope); + scope.childScopes.forEach(checkReferencesInScope); } return { Program() { - findVariablesInScope(context.getScope()); + checkReferencesInScope(context.getScope()); } }; } diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs index e1e5c3971fc741..b1b40391df324a 100644 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs +++ b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs @@ -2464,7 +2464,7 @@ function loadYAMLConfigFile(filePath) { try { // empty YAML file can be null, so always use - return yaml.safeLoad(readFile(filePath)) || {}; + return yaml.load(readFile(filePath)) || {}; } catch (e) { debug$2(`Error reading YAML file: ${filePath}`); e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; @@ -2510,7 +2510,7 @@ function loadLegacyConfigFile(filePath) { const yaml = require$1("js-yaml"); try { - return yaml.safeLoad(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {}; + return yaml.load(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {}; } catch (e) { debug$2("Error reading YAML file: %s\n%o", filePath, e); e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/lib/config-array-factory.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/lib/config-array-factory.js index 82abffa90cd799..b571e2f7f459e7 100644 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/lib/config-array-factory.js +++ b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/lib/config-array-factory.js @@ -162,7 +162,7 @@ function loadYAMLConfigFile(filePath) { try { // empty YAML file can be null, so always use - return yaml.safeLoad(readFile(filePath)) || {}; + return yaml.load(readFile(filePath)) || {}; } catch (e) { debug(`Error reading YAML file: ${filePath}`); e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; @@ -208,7 +208,7 @@ function loadLegacyConfigFile(filePath) { const yaml = require("js-yaml"); try { - return yaml.safeLoad(stripComments(readFile(filePath))) || /* istanbul ignore next */ {}; + return yaml.load(stripComments(readFile(filePath))) || /* istanbul ignore next */ {}; } catch (e) { debug("Error reading YAML file: %s\n%o", filePath, e); e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/LICENSE b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/LICENSE deleted file mode 100644 index 1afdae5584056a..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -(The MIT License) - -Copyright (C) 2012 by Vitaly Puzrin - -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: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -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. diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/README.md b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/README.md deleted file mode 100644 index 7fa6c40503e56a..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/README.md +++ /dev/null @@ -1,257 +0,0 @@ -argparse -======== - -[![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) -[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) - -CLI arguments parser for node.js. Javascript port of python's -[argparse](http://docs.python.org/dev/library/argparse.html) module -(original version 3.2). That's a full port, except some very rare options, -recorded in issue tracker. - -**NB. Difference with original.** - -- Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). -- Use `defaultValue` instead of `default`. -- Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and - similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` - (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and - `SUPPRESS`. - - -Example -======= - -test.js file: - -```javascript -#!/usr/bin/env node -'use strict'; - -var ArgumentParser = require('../lib/argparse').ArgumentParser; -var parser = new ArgumentParser({ - version: '0.0.1', - addHelp:true, - description: 'Argparse example' -}); -parser.addArgument( - [ '-f', '--foo' ], - { - help: 'foo bar' - } -); -parser.addArgument( - [ '-b', '--bar' ], - { - help: 'bar foo' - } -); -parser.addArgument( - '--baz', - { - help: 'baz bar' - } -); -var args = parser.parseArgs(); -console.dir(args); -``` - -Display help: - -``` -$ ./test.js -h -usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] - -Argparse example - -Optional arguments: - -h, --help Show this help message and exit. - -v, --version Show program's version number and exit. - -f FOO, --foo FOO foo bar - -b BAR, --bar BAR bar foo - --baz BAZ baz bar -``` - -Parse arguments: - -``` -$ ./test.js -f=3 --bar=4 --baz 5 -{ foo: '3', bar: '4', baz: '5' } -``` - -More [examples](https://github.com/nodeca/argparse/tree/master/examples). - - -ArgumentParser objects -====================== - -``` -new ArgumentParser({parameters hash}); -``` - -Creates a new ArgumentParser object. - -**Supported params:** - -- ```description``` - Text to display before the argument help. -- ```epilog``` - Text to display after the argument help. -- ```addHelp``` - Add a -h/–help option to the parser. (default: true) -- ```argumentDefault``` - Set the global default value for arguments. (default: null) -- ```parents``` - A list of ArgumentParser objects whose arguments should also be included. -- ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) -- ```formatterClass``` - A class for customizing the help output. -- ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) -- ```usage``` - The string describing the program usage (default: generated) -- ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. - -**Not supported yet** - -- ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. - - -Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) - - -addArgument() method -==================== - -``` -ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) -``` - -Defines how a single command-line argument should be parsed. - -- ```name or flag or [name] or [flags...]``` - Either a positional name - (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array - of a single positional name (e.g., `['foo']`), or an array of options - (e.g., `['-f', '--foo']`). - -Options: - -- ```action``` - The basic type of action to be taken when this argument is encountered at the command line. -- ```nargs```- The number of command-line arguments that should be consumed. -- ```constant``` - A constant value required by some action and nargs selections. -- ```defaultValue``` - The value produced if the argument is absent from the command line. -- ```type``` - The type to which the command-line argument should be converted. -- ```choices``` - A container of the allowable values for the argument. -- ```required``` - Whether or not the command-line option may be omitted (optionals only). -- ```help``` - A brief description of what the argument does. -- ```metavar``` - A name for the argument in usage messages. -- ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). - -Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) - - -Action (some details) -================ - -ArgumentParser objects associate command-line arguments with actions. -These actions can do just about anything with the command-line arguments associated -with them, though most actions simply add an attribute to the object returned by -parseArgs(). The action keyword argument specifies how the command-line arguments -should be handled. The supported actions are: - -- ```store``` - Just stores the argument’s value. This is the default action. -- ```storeConst``` - Stores value, specified by the const keyword argument. - (Note that the const keyword argument defaults to the rather unhelpful None.) - The 'storeConst' action is most commonly used with optional arguments, that - specify some sort of flag. -- ```storeTrue``` and ```storeFalse``` - Stores values True and False - respectively. These are special cases of 'storeConst'. -- ```append``` - Stores a list, and appends each argument value to the list. - This is useful to allow an option to be specified multiple times. -- ```appendConst``` - Stores a list, and appends value, specified by the - const keyword argument to the list. (Note, that the const keyword argument defaults - is None.) The 'appendConst' action is typically used when multiple arguments need - to store constants to the same list. -- ```count``` - Counts the number of times a keyword argument occurs. For example, - used for increasing verbosity levels. -- ```help``` - Prints a complete help message for all the options in the current - parser and then exits. By default a help action is automatically added to the parser. - See ArgumentParser for details of how the output is created. -- ```version``` - Prints version information and exit. Expects a `version=` - keyword argument in the addArgument() call. - -Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) - - -Sub-commands -============ - -ArgumentParser.addSubparsers() - -Many programs split their functionality into a number of sub-commands, for -example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, -and `svn commit`. Splitting up functionality this way can be a particularly good -idea when a program performs several different functions which require different -kinds of command-line arguments. `ArgumentParser` supports creation of such -sub-commands with `addSubparsers()` method. The `addSubparsers()` method is -normally called with no arguments and returns an special action object. -This object has a single method `addParser()`, which takes a command name and -any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object -that can be modified as usual. - -Example: - -sub_commands.js -```javascript -#!/usr/bin/env node -'use strict'; - -var ArgumentParser = require('../lib/argparse').ArgumentParser; -var parser = new ArgumentParser({ - version: '0.0.1', - addHelp:true, - description: 'Argparse examples: sub-commands', -}); - -var subparsers = parser.addSubparsers({ - title:'subcommands', - dest:"subcommand_name" -}); - -var bar = subparsers.addParser('c1', {addHelp:true}); -bar.addArgument( - [ '-f', '--foo' ], - { - action: 'store', - help: 'foo3 bar3' - } -); -var bar = subparsers.addParser( - 'c2', - {aliases:['co'], addHelp:true} -); -bar.addArgument( - [ '-b', '--bar' ], - { - action: 'store', - type: 'int', - help: 'foo3 bar3' - } -); - -var args = parser.parseArgs(); -console.dir(args); - -``` - -Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) - - -Contributors -============ - -- [Eugene Shkuropat](https://github.com/shkuropat) -- [Paul Jacobson](https://github.com/hpaulj) - -[others](https://github.com/nodeca/argparse/graphs/contributors) - -License -======= - -Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). -Released under the MIT license. See -[LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. - - diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/index.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/index.js deleted file mode 100644 index 3bbc143200483c..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./lib/argparse'); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action.js deleted file mode 100644 index 1483c79ffa53d6..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * class Action - * - * Base class for all actions - * Do not call in your code, use this class only for inherits your own action - * - * Information about how to convert command line strings to Javascript objects. - * Action objects are used by an ArgumentParser to represent the information - * needed to parse a single argument from one or more strings from the command - * line. The keyword arguments to the Action constructor are also all attributes - * of Action instances. - * - * ##### Allowed keywords: - * - * - `store` - * - `storeConstant` - * - `storeTrue` - * - `storeFalse` - * - `append` - * - `appendConstant` - * - `count` - * - `help` - * - `version` - * - * Information about action options see [[Action.new]] - * - * See also [original guide](http://docs.python.org/dev/library/argparse.html#action) - * - **/ - -'use strict'; - - -// Constants -var c = require('./const'); - - -/** - * new Action(options) - * - * Base class for all actions. Used only for inherits - * - * - * ##### Options: - * - * - `optionStrings` A list of command-line option strings for the action. - * - `dest` Attribute to hold the created object(s) - * - `nargs` The number of command-line arguments that should be consumed. - * By default, one argument will be consumed and a single value will be - * produced. - * - `constant` Default value for an action with no value. - * - `defaultValue` The value to be produced if the option is not specified. - * - `type` Cast to 'string'|'int'|'float'|'complex'|function (string). If - * None, 'string'. - * - `choices` The choices available. - * - `required` True if the action must always be specified at the command - * line. - * - `help` The help describing the argument. - * - `metavar` The name to be used for the option's argument with the help - * string. If None, the 'dest' value will be used as the name. - * - * ##### nargs supported values: - * - * - `N` (an integer) consumes N arguments (and produces a list) - * - `?` consumes zero or one arguments - * - `*` consumes zero or more arguments (and produces a list) - * - `+` consumes one or more arguments (and produces a list) - * - * Note: that the difference between the default and nargs=1 is that with the - * default, a single value will be produced, while with nargs=1, a list - * containing a single value will be produced. - **/ -var Action = module.exports = function Action(options) { - options = options || {}; - this.optionStrings = options.optionStrings || []; - this.dest = options.dest; - this.nargs = typeof options.nargs !== 'undefined' ? options.nargs : null; - this.constant = typeof options.constant !== 'undefined' ? options.constant : null; - this.defaultValue = options.defaultValue; - this.type = typeof options.type !== 'undefined' ? options.type : null; - this.choices = typeof options.choices !== 'undefined' ? options.choices : null; - this.required = typeof options.required !== 'undefined' ? options.required : false; - this.help = typeof options.help !== 'undefined' ? options.help : null; - this.metavar = typeof options.metavar !== 'undefined' ? options.metavar : null; - - if (!(this.optionStrings instanceof Array)) { - throw new Error('optionStrings should be an array'); - } - if (typeof this.required !== 'undefined' && typeof this.required !== 'boolean') { - throw new Error('required should be a boolean'); - } -}; - -/** - * Action#getName -> String - * - * Tells action name - **/ -Action.prototype.getName = function () { - if (this.optionStrings.length > 0) { - return this.optionStrings.join('/'); - } else if (this.metavar !== null && this.metavar !== c.SUPPRESS) { - return this.metavar; - } else if (typeof this.dest !== 'undefined' && this.dest !== c.SUPPRESS) { - return this.dest; - } - return null; -}; - -/** - * Action#isOptional -> Boolean - * - * Return true if optional - **/ -Action.prototype.isOptional = function () { - return !this.isPositional(); -}; - -/** - * Action#isPositional -> Boolean - * - * Return true if positional - **/ -Action.prototype.isPositional = function () { - return (this.optionStrings.length === 0); -}; - -/** - * Action#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Should be implemented in inherited classes - * - * ##### Example - * - * ActionCount.prototype.call = function (parser, namespace, values, optionString) { - * namespace.set(this.dest, (namespace[this.dest] || 0) + 1); - * }; - * - **/ -Action.prototype.call = function () { - throw new Error('.call() not defined');// Not Implemented error -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/append.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/append.js deleted file mode 100644 index b5da0de2327504..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/append.js +++ /dev/null @@ -1,53 +0,0 @@ -/*:nodoc:* - * class ActionAppend - * - * This action stores a list, and appends each argument value to the list. - * This is useful to allow an option to be specified multiple times. - * This class inherided from [[Action]] - * - **/ - -'use strict'; - -var util = require('util'); - -var Action = require('../action'); - -// Constants -var c = require('../const'); - -/*:nodoc:* - * new ActionAppend(options) - * - options (object): options hash see [[Action.new]] - * - * Note: options.nargs should be optional for constants - * and more then zero for other - **/ -var ActionAppend = module.exports = function ActionAppend(options) { - options = options || {}; - if (this.nargs <= 0) { - throw new Error('nargs for append actions must be > 0; if arg ' + - 'strings are not supplying the value to append, ' + - 'the append const action may be more appropriate'); - } - if (!!this.constant && this.nargs !== c.OPTIONAL) { - throw new Error('nargs must be OPTIONAL to supply const'); - } - Action.call(this, options); -}; -util.inherits(ActionAppend, Action); - -/*:nodoc:* - * ActionAppend#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionAppend.prototype.call = function (parser, namespace, values) { - var items = (namespace[this.dest] || []).slice(); - items.push(values); - namespace.set(this.dest, items); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/append/constant.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/append/constant.js deleted file mode 100644 index 313f5d2efcb03f..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/append/constant.js +++ /dev/null @@ -1,47 +0,0 @@ -/*:nodoc:* - * class ActionAppendConstant - * - * This stores a list, and appends the value specified by - * the const keyword argument to the list. - * (Note that the const keyword argument defaults to null.) - * The 'appendConst' action is typically useful when multiple - * arguments need to store constants to the same list. - * - * This class inherited from [[Action]] - **/ - -'use strict'; - -var util = require('util'); - -var Action = require('../../action'); - -/*:nodoc:* - * new ActionAppendConstant(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionAppendConstant = module.exports = function ActionAppendConstant(options) { - options = options || {}; - options.nargs = 0; - if (typeof options.constant === 'undefined') { - throw new Error('constant option is required for appendAction'); - } - Action.call(this, options); -}; -util.inherits(ActionAppendConstant, Action); - -/*:nodoc:* - * ActionAppendConstant#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionAppendConstant.prototype.call = function (parser, namespace) { - var items = [].concat(namespace[this.dest] || []); - items.push(this.constant); - namespace.set(this.dest, items); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/count.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/count.js deleted file mode 100644 index d6a5899d07ef24..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/count.js +++ /dev/null @@ -1,40 +0,0 @@ -/*:nodoc:* - * class ActionCount - * - * This counts the number of times a keyword argument occurs. - * For example, this is useful for increasing verbosity levels - * - * This class inherided from [[Action]] - * - **/ -'use strict'; - -var util = require('util'); - -var Action = require('../action'); - -/*:nodoc:* - * new ActionCount(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionCount = module.exports = function ActionCount(options) { - options = options || {}; - options.nargs = 0; - - Action.call(this, options); -}; -util.inherits(ActionCount, Action); - -/*:nodoc:* - * ActionCount#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionCount.prototype.call = function (parser, namespace) { - namespace.set(this.dest, (namespace[this.dest] || 0) + 1); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/help.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/help.js deleted file mode 100644 index b40e05a6f0b3eb..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/help.js +++ /dev/null @@ -1,47 +0,0 @@ -/*:nodoc:* - * class ActionHelp - * - * Support action for printing help - * This class inherided from [[Action]] - **/ -'use strict'; - -var util = require('util'); - -var Action = require('../action'); - -// Constants -var c = require('../const'); - -/*:nodoc:* - * new ActionHelp(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionHelp = module.exports = function ActionHelp(options) { - options = options || {}; - if (options.defaultValue !== null) { - options.defaultValue = options.defaultValue; - } else { - options.defaultValue = c.SUPPRESS; - } - options.dest = (options.dest !== null ? options.dest : c.SUPPRESS); - options.nargs = 0; - Action.call(this, options); - -}; -util.inherits(ActionHelp, Action); - -/*:nodoc:* - * ActionHelp#call(parser, namespace, values, optionString) - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Print help and exit - **/ -ActionHelp.prototype.call = function (parser) { - parser.printHelp(); - parser.exit(); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store.js deleted file mode 100644 index 283b8609217561..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store.js +++ /dev/null @@ -1,50 +0,0 @@ -/*:nodoc:* - * class ActionStore - * - * This action just stores the argument’s value. This is the default action. - * - * This class inherited from [[Action]] - * - **/ -'use strict'; - -var util = require('util'); - -var Action = require('../action'); - -// Constants -var c = require('../const'); - - -/*:nodoc:* - * new ActionStore(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionStore = module.exports = function ActionStore(options) { - options = options || {}; - if (this.nargs <= 0) { - throw new Error('nargs for store actions must be > 0; if you ' + - 'have nothing to store, actions such as store ' + - 'true or store const may be more appropriate'); - - } - if (typeof this.constant !== 'undefined' && this.nargs !== c.OPTIONAL) { - throw new Error('nargs must be OPTIONAL to supply const'); - } - Action.call(this, options); -}; -util.inherits(ActionStore, Action); - -/*:nodoc:* - * ActionStore#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionStore.prototype.call = function (parser, namespace, values) { - namespace.set(this.dest, values); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/constant.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/constant.js deleted file mode 100644 index 23caa897b375d4..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/constant.js +++ /dev/null @@ -1,43 +0,0 @@ -/*:nodoc:* - * class ActionStoreConstant - * - * This action stores the value specified by the const keyword argument. - * (Note that the const keyword argument defaults to the rather unhelpful null.) - * The 'store_const' action is most commonly used with optional - * arguments that specify some sort of flag. - * - * This class inherited from [[Action]] - **/ -'use strict'; - -var util = require('util'); - -var Action = require('../../action'); - -/*:nodoc:* - * new ActionStoreConstant(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionStoreConstant = module.exports = function ActionStoreConstant(options) { - options = options || {}; - options.nargs = 0; - if (typeof options.constant === 'undefined') { - throw new Error('constant option is required for storeAction'); - } - Action.call(this, options); -}; -util.inherits(ActionStoreConstant, Action); - -/*:nodoc:* - * ActionStoreConstant#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Save result in namespace object - **/ -ActionStoreConstant.prototype.call = function (parser, namespace) { - namespace.set(this.dest, this.constant); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/false.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/false.js deleted file mode 100644 index 9924f461dadfe6..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/false.js +++ /dev/null @@ -1,27 +0,0 @@ -/*:nodoc:* - * class ActionStoreFalse - * - * This action store the values False respectively. - * This is special cases of 'storeConst' - * - * This class inherited from [[Action]] - **/ - -'use strict'; - -var util = require('util'); - -var ActionStoreConstant = require('./constant'); - -/*:nodoc:* - * new ActionStoreFalse(options) - * - options (object): hash of options see [[Action.new]] - * - **/ -var ActionStoreFalse = module.exports = function ActionStoreFalse(options) { - options = options || {}; - options.constant = false; - options.defaultValue = options.defaultValue !== null ? options.defaultValue : true; - ActionStoreConstant.call(this, options); -}; -util.inherits(ActionStoreFalse, ActionStoreConstant); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/true.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/true.js deleted file mode 100644 index 9e22f7d4419eea..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/store/true.js +++ /dev/null @@ -1,26 +0,0 @@ -/*:nodoc:* - * class ActionStoreTrue - * - * This action store the values True respectively. - * This isspecial cases of 'storeConst' - * - * This class inherited from [[Action]] - **/ -'use strict'; - -var util = require('util'); - -var ActionStoreConstant = require('./constant'); - -/*:nodoc:* - * new ActionStoreTrue(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionStoreTrue = module.exports = function ActionStoreTrue(options) { - options = options || {}; - options.constant = true; - options.defaultValue = options.defaultValue !== null ? options.defaultValue : false; - ActionStoreConstant.call(this, options); -}; -util.inherits(ActionStoreTrue, ActionStoreConstant); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/subparsers.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/subparsers.js deleted file mode 100644 index 99dfedd0f1aa02..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/subparsers.js +++ /dev/null @@ -1,149 +0,0 @@ -/** internal - * class ActionSubparsers - * - * Support the creation of such sub-commands with the addSubparsers() - * - * This class inherited from [[Action]] - **/ -'use strict'; - -var util = require('util'); -var format = require('util').format; - - -var Action = require('../action'); - -// Constants -var c = require('../const'); - -// Errors -var argumentErrorHelper = require('../argument/error'); - - -/*:nodoc:* - * new ChoicesPseudoAction(name, help) - * - * Create pseudo action for correct help text - * - **/ -function ChoicesPseudoAction(name, help) { - var options = { - optionStrings: [], - dest: name, - help: help - }; - - Action.call(this, options); -} - -util.inherits(ChoicesPseudoAction, Action); - -/** - * new ActionSubparsers(options) - * - options (object): options hash see [[Action.new]] - * - **/ -function ActionSubparsers(options) { - options = options || {}; - options.dest = options.dest || c.SUPPRESS; - options.nargs = c.PARSER; - - this.debug = (options.debug === true); - - this._progPrefix = options.prog; - this._parserClass = options.parserClass; - this._nameParserMap = {}; - this._choicesActions = []; - - options.choices = this._nameParserMap; - Action.call(this, options); -} - -util.inherits(ActionSubparsers, Action); - -/*:nodoc:* - * ActionSubparsers#addParser(name, options) -> ArgumentParser - * - name (string): sub-command name - * - options (object): see [[ArgumentParser.new]] - * - * Note: - * addParser supports an additional aliases option, - * which allows multiple strings to refer to the same subparser. - * This example, like svn, aliases co as a shorthand for checkout - * - **/ -ActionSubparsers.prototype.addParser = function (name, options) { - var parser; - - var self = this; - - options = options || {}; - - options.debug = (this.debug === true); - - // set program from the existing prefix - if (!options.prog) { - options.prog = this._progPrefix + ' ' + name; - } - - var aliases = options.aliases || []; - - // create a pseudo-action to hold the choice help - if (!!options.help || typeof options.help === 'string') { - var help = options.help; - delete options.help; - - var choiceAction = new ChoicesPseudoAction(name, help); - this._choicesActions.push(choiceAction); - } - - // create the parser and add it to the map - parser = new this._parserClass(options); - this._nameParserMap[name] = parser; - - // make parser available under aliases also - aliases.forEach(function (alias) { - self._nameParserMap[alias] = parser; - }); - - return parser; -}; - -ActionSubparsers.prototype._getSubactions = function () { - return this._choicesActions; -}; - -/*:nodoc:* - * ActionSubparsers#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Call the action. Parse input aguments - **/ -ActionSubparsers.prototype.call = function (parser, namespace, values) { - var parserName = values[0]; - var argStrings = values.slice(1); - - // set the parser name if requested - if (this.dest !== c.SUPPRESS) { - namespace[this.dest] = parserName; - } - - // select the parser - if (this._nameParserMap[parserName]) { - parser = this._nameParserMap[parserName]; - } else { - throw argumentErrorHelper(format( - 'Unknown parser "%s" (choices: [%s]).', - parserName, - Object.keys(this._nameParserMap).join(', ') - )); - } - - // parse all the remaining options into the namespace - parser.parseArgs(argStrings, namespace); -}; - -module.exports = ActionSubparsers; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/version.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/version.js deleted file mode 100644 index 8053328cdef446..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action/version.js +++ /dev/null @@ -1,47 +0,0 @@ -/*:nodoc:* - * class ActionVersion - * - * Support action for printing program version - * This class inherited from [[Action]] - **/ -'use strict'; - -var util = require('util'); - -var Action = require('../action'); - -// -// Constants -// -var c = require('../const'); - -/*:nodoc:* - * new ActionVersion(options) - * - options (object): options hash see [[Action.new]] - * - **/ -var ActionVersion = module.exports = function ActionVersion(options) { - options = options || {}; - options.defaultValue = (options.defaultValue ? options.defaultValue : c.SUPPRESS); - options.dest = (options.dest || c.SUPPRESS); - options.nargs = 0; - this.version = options.version; - Action.call(this, options); -}; -util.inherits(ActionVersion, Action); - -/*:nodoc:* - * ActionVersion#call(parser, namespace, values, optionString) -> Void - * - parser (ArgumentParser): current parser - * - namespace (Namespace): namespace for output data - * - values (Array): parsed values - * - optionString (Array): input option string(not parsed) - * - * Print version and exit - **/ -ActionVersion.prototype.call = function (parser) { - var version = this.version || parser.version; - var formatter = parser._getFormatter(); - formatter.addText(version); - parser.exit(0, formatter.formatHelp()); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action_container.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action_container.js deleted file mode 100644 index 6f1237bea23d59..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/action_container.js +++ /dev/null @@ -1,482 +0,0 @@ -/** internal - * class ActionContainer - * - * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] - **/ - -'use strict'; - -var format = require('util').format; - -// Constants -var c = require('./const'); - -var $$ = require('./utils'); - -//Actions -var ActionHelp = require('./action/help'); -var ActionAppend = require('./action/append'); -var ActionAppendConstant = require('./action/append/constant'); -var ActionCount = require('./action/count'); -var ActionStore = require('./action/store'); -var ActionStoreConstant = require('./action/store/constant'); -var ActionStoreTrue = require('./action/store/true'); -var ActionStoreFalse = require('./action/store/false'); -var ActionVersion = require('./action/version'); -var ActionSubparsers = require('./action/subparsers'); - -// Errors -var argumentErrorHelper = require('./argument/error'); - -/** - * new ActionContainer(options) - * - * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] - * - * ##### Options: - * - * - `description` -- A description of what the program does - * - `prefixChars` -- Characters that prefix optional arguments - * - `argumentDefault` -- The default value for all arguments - * - `conflictHandler` -- The conflict handler to use for duplicate arguments - **/ -var ActionContainer = module.exports = function ActionContainer(options) { - options = options || {}; - - this.description = options.description; - this.argumentDefault = options.argumentDefault; - this.prefixChars = options.prefixChars || ''; - this.conflictHandler = options.conflictHandler; - - // set up registries - this._registries = {}; - - // register actions - this.register('action', null, ActionStore); - this.register('action', 'store', ActionStore); - this.register('action', 'storeConst', ActionStoreConstant); - this.register('action', 'storeTrue', ActionStoreTrue); - this.register('action', 'storeFalse', ActionStoreFalse); - this.register('action', 'append', ActionAppend); - this.register('action', 'appendConst', ActionAppendConstant); - this.register('action', 'count', ActionCount); - this.register('action', 'help', ActionHelp); - this.register('action', 'version', ActionVersion); - this.register('action', 'parsers', ActionSubparsers); - - // raise an exception if the conflict handler is invalid - this._getHandler(); - - // action storage - this._actions = []; - this._optionStringActions = {}; - - // groups - this._actionGroups = []; - this._mutuallyExclusiveGroups = []; - - // defaults storage - this._defaults = {}; - - // determines whether an "option" looks like a negative number - // -1, -1.5 -5e+4 - this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'); - - // whether or not there are any optionals that look like negative - // numbers -- uses a list so it can be shared and edited - this._hasNegativeNumberOptionals = []; -}; - -// Groups must be required, then ActionContainer already defined -var ArgumentGroup = require('./argument/group'); -var MutuallyExclusiveGroup = require('./argument/exclusive'); - -// -// Registration methods -// - -/** - * ActionContainer#register(registryName, value, object) -> Void - * - registryName (String) : object type action|type - * - value (string) : keyword - * - object (Object|Function) : handler - * - * Register handlers - **/ -ActionContainer.prototype.register = function (registryName, value, object) { - this._registries[registryName] = this._registries[registryName] || {}; - this._registries[registryName][value] = object; -}; - -ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) { - if (arguments.length < 3) { - defaultValue = null; - } - return this._registries[registryName][value] || defaultValue; -}; - -// -// Namespace default accessor methods -// - -/** - * ActionContainer#setDefaults(options) -> Void - * - options (object):hash of options see [[Action.new]] - * - * Set defaults - **/ -ActionContainer.prototype.setDefaults = function (options) { - options = options || {}; - for (var property in options) { - if ($$.has(options, property)) { - this._defaults[property] = options[property]; - } - } - - // if these defaults match any existing arguments, replace the previous - // default on the object with the new one - this._actions.forEach(function (action) { - if ($$.has(options, action.dest)) { - action.defaultValue = options[action.dest]; - } - }); -}; - -/** - * ActionContainer#getDefault(dest) -> Mixed - * - dest (string): action destination - * - * Return action default value - **/ -ActionContainer.prototype.getDefault = function (dest) { - var result = $$.has(this._defaults, dest) ? this._defaults[dest] : null; - - this._actions.forEach(function (action) { - if (action.dest === dest && $$.has(action, 'defaultValue')) { - result = action.defaultValue; - } - }); - - return result; -}; -// -// Adding argument actions -// - -/** - * ActionContainer#addArgument(args, options) -> Object - * - args (String|Array): argument key, or array of argument keys - * - options (Object): action objects see [[Action.new]] - * - * #### Examples - * - addArgument([ '-f', '--foo' ], { action: 'store', defaultValue: 1, ... }) - * - addArgument([ 'bar' ], { action: 'store', nargs: 1, ... }) - * - addArgument('--baz', { action: 'store', nargs: 1, ... }) - **/ -ActionContainer.prototype.addArgument = function (args, options) { - args = args; - options = options || {}; - - if (typeof args === 'string') { - args = [ args ]; - } - if (!Array.isArray(args)) { - throw new TypeError('addArgument first argument should be a string or an array'); - } - if (typeof options !== 'object' || Array.isArray(options)) { - throw new TypeError('addArgument second argument should be a hash'); - } - - // if no positional args are supplied or only one is supplied and - // it doesn't look like an option string, parse a positional argument - if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) { - if (args && !!options.dest) { - throw new Error('dest supplied twice for positional argument'); - } - options = this._getPositional(args, options); - - // otherwise, we're adding an optional argument - } else { - options = this._getOptional(args, options); - } - - // if no default was supplied, use the parser-level default - if (typeof options.defaultValue === 'undefined') { - var dest = options.dest; - if ($$.has(this._defaults, dest)) { - options.defaultValue = this._defaults[dest]; - } else if (typeof this.argumentDefault !== 'undefined') { - options.defaultValue = this.argumentDefault; - } - } - - // create the action object, and add it to the parser - var ActionClass = this._popActionClass(options); - if (typeof ActionClass !== 'function') { - throw new Error(format('Unknown action "%s".', ActionClass)); - } - var action = new ActionClass(options); - - // throw an error if the action type is not callable - var typeFunction = this._registryGet('type', action.type, action.type); - if (typeof typeFunction !== 'function') { - throw new Error(format('"%s" is not callable', typeFunction)); - } - - return this._addAction(action); -}; - -/** - * ActionContainer#addArgumentGroup(options) -> ArgumentGroup - * - options (Object): hash of options see [[ArgumentGroup.new]] - * - * Create new arguments groups - **/ -ActionContainer.prototype.addArgumentGroup = function (options) { - var group = new ArgumentGroup(this, options); - this._actionGroups.push(group); - return group; -}; - -/** - * ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup - * - options (Object): {required: false} - * - * Create new mutual exclusive groups - **/ -ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) { - var group = new MutuallyExclusiveGroup(this, options); - this._mutuallyExclusiveGroups.push(group); - return group; -}; - -ActionContainer.prototype._addAction = function (action) { - var self = this; - - // resolve any conflicts - this._checkConflict(action); - - // add to actions list - this._actions.push(action); - action.container = this; - - // index the action by any option strings it has - action.optionStrings.forEach(function (optionString) { - self._optionStringActions[optionString] = action; - }); - - // set the flag if any option strings look like negative numbers - action.optionStrings.forEach(function (optionString) { - if (optionString.match(self._regexpNegativeNumber)) { - if (!self._hasNegativeNumberOptionals.some(Boolean)) { - self._hasNegativeNumberOptionals.push(true); - } - } - }); - - // return the created action - return action; -}; - -ActionContainer.prototype._removeAction = function (action) { - var actionIndex = this._actions.indexOf(action); - if (actionIndex >= 0) { - this._actions.splice(actionIndex, 1); - } -}; - -ActionContainer.prototype._addContainerActions = function (container) { - // collect groups by titles - var titleGroupMap = {}; - this._actionGroups.forEach(function (group) { - if (titleGroupMap[group.title]) { - throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title)); - } - titleGroupMap[group.title] = group; - }); - - // map each action to its group - var groupMap = {}; - function actionHash(action) { - // unique (hopefully?) string suitable as dictionary key - return action.getName(); - } - container._actionGroups.forEach(function (group) { - // if a group with the title exists, use that, otherwise - // create a new group matching the container's group - if (!titleGroupMap[group.title]) { - titleGroupMap[group.title] = this.addArgumentGroup({ - title: group.title, - description: group.description - }); - } - - // map the actions to their new group - group._groupActions.forEach(function (action) { - groupMap[actionHash(action)] = titleGroupMap[group.title]; - }); - }, this); - - // add container's mutually exclusive groups - // NOTE: if add_mutually_exclusive_group ever gains title= and - // description= then this code will need to be expanded as above - var mutexGroup; - container._mutuallyExclusiveGroups.forEach(function (group) { - mutexGroup = this.addMutuallyExclusiveGroup({ - required: group.required - }); - // map the actions to their new mutex group - group._groupActions.forEach(function (action) { - groupMap[actionHash(action)] = mutexGroup; - }); - }, this); // forEach takes a 'this' argument - - // add all actions to this container or their group - container._actions.forEach(function (action) { - var key = actionHash(action); - if (groupMap[key]) { - groupMap[key]._addAction(action); - } else { - this._addAction(action); - } - }); -}; - -ActionContainer.prototype._getPositional = function (dest, options) { - if (Array.isArray(dest)) { - dest = dest[0]; - } - // make sure required is not specified - if (options.required) { - throw new Error('"required" is an invalid argument for positionals.'); - } - - // mark positional arguments as required if at least one is - // always required - if (options.nargs !== c.OPTIONAL && options.nargs !== c.ZERO_OR_MORE) { - options.required = true; - } - if (options.nargs === c.ZERO_OR_MORE && typeof options.defaultValue === 'undefined') { - options.required = true; - } - - // return the keyword arguments with no option strings - options.dest = dest; - options.optionStrings = []; - return options; -}; - -ActionContainer.prototype._getOptional = function (args, options) { - var prefixChars = this.prefixChars; - var optionStrings = []; - var optionStringsLong = []; - - // determine short and long option strings - args.forEach(function (optionString) { - // error on strings that don't start with an appropriate prefix - if (prefixChars.indexOf(optionString[0]) < 0) { - throw new Error(format('Invalid option string "%s": must start with a "%s".', - optionString, - prefixChars - )); - } - - // strings starting with two prefix characters are long options - optionStrings.push(optionString); - if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) { - optionStringsLong.push(optionString); - } - }); - - // infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' - var dest = options.dest || null; - delete options.dest; - - if (!dest) { - var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0]; - dest = $$.trimChars(optionStringDest, this.prefixChars); - - if (dest.length === 0) { - throw new Error( - format('dest= is required for options like "%s"', optionStrings.join(', ')) - ); - } - dest = dest.replace(/-/g, '_'); - } - - // return the updated keyword arguments - options.dest = dest; - options.optionStrings = optionStrings; - - return options; -}; - -ActionContainer.prototype._popActionClass = function (options, defaultValue) { - defaultValue = defaultValue || null; - - var action = (options.action || defaultValue); - delete options.action; - - var actionClass = this._registryGet('action', action, action); - return actionClass; -}; - -ActionContainer.prototype._getHandler = function () { - var handlerString = this.conflictHandler; - var handlerFuncName = '_handleConflict' + $$.capitalize(handlerString); - var func = this[handlerFuncName]; - if (typeof func === 'undefined') { - var msg = 'invalid conflict resolution value: ' + handlerString; - throw new Error(msg); - } else { - return func; - } -}; - -ActionContainer.prototype._checkConflict = function (action) { - var optionStringActions = this._optionStringActions; - var conflictOptionals = []; - - // find all options that conflict with this option - // collect pairs, the string, and an existing action that it conflicts with - action.optionStrings.forEach(function (optionString) { - var conflOptional = optionStringActions[optionString]; - if (typeof conflOptional !== 'undefined') { - conflictOptionals.push([ optionString, conflOptional ]); - } - }); - - if (conflictOptionals.length > 0) { - var conflictHandler = this._getHandler(); - conflictHandler.call(this, action, conflictOptionals); - } -}; - -ActionContainer.prototype._handleConflictError = function (action, conflOptionals) { - var conflicts = conflOptionals.map(function (pair) { return pair[0]; }); - conflicts = conflicts.join(', '); - throw argumentErrorHelper( - action, - format('Conflicting option string(s): %s', conflicts) - ); -}; - -ActionContainer.prototype._handleConflictResolve = function (action, conflOptionals) { - // remove all conflicting options - var self = this; - conflOptionals.forEach(function (pair) { - var optionString = pair[0]; - var conflictingAction = pair[1]; - // remove the conflicting option string - var i = conflictingAction.optionStrings.indexOf(optionString); - if (i >= 0) { - conflictingAction.optionStrings.splice(i, 1); - } - delete self._optionStringActions[optionString]; - // if the option now has no option string, remove it from the - // container holding it - if (conflictingAction.optionStrings.length === 0) { - conflictingAction.container._removeAction(conflictingAction); - } - }); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argparse.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argparse.js deleted file mode 100644 index f2a2c51d9a8917..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argparse.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -module.exports.ArgumentParser = require('./argument_parser.js'); -module.exports.Namespace = require('./namespace'); -module.exports.Action = require('./action'); -module.exports.HelpFormatter = require('./help/formatter.js'); -module.exports.Const = require('./const.js'); - -module.exports.ArgumentDefaultsHelpFormatter = - require('./help/added_formatters.js').ArgumentDefaultsHelpFormatter; -module.exports.RawDescriptionHelpFormatter = - require('./help/added_formatters.js').RawDescriptionHelpFormatter; -module.exports.RawTextHelpFormatter = - require('./help/added_formatters.js').RawTextHelpFormatter; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/error.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/error.js deleted file mode 100644 index c8a02a08b8fbaf..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/error.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - - -var format = require('util').format; - - -var ERR_CODE = 'ARGError'; - -/*:nodoc:* - * argumentError(argument, message) -> TypeError - * - argument (Object): action with broken argument - * - message (String): error message - * - * Error format helper. An error from creating or using an argument - * (optional or positional). The string value of this exception - * is the message, augmented with information - * about the argument that caused it. - * - * #####Example - * - * var argumentErrorHelper = require('./argument/error'); - * if (conflictOptionals.length > 0) { - * throw argumentErrorHelper( - * action, - * format('Conflicting option string(s): %s', conflictOptionals.join(', ')) - * ); - * } - * - **/ -module.exports = function (argument, message) { - var argumentName = null; - var errMessage; - var err; - - if (argument.getName) { - argumentName = argument.getName(); - } else { - argumentName = '' + argument; - } - - if (!argumentName) { - errMessage = message; - } else { - errMessage = format('argument "%s": %s', argumentName, message); - } - - err = new TypeError(errMessage); - err.code = ERR_CODE; - return err; -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/exclusive.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/exclusive.js deleted file mode 100644 index 8287e00d0464f3..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/exclusive.js +++ /dev/null @@ -1,54 +0,0 @@ -/** internal - * class MutuallyExclusiveGroup - * - * Group arguments. - * By default, ArgumentParser groups command-line arguments - * into “positional arguments” and “optional arguments” - * when displaying help messages. When there is a better - * conceptual grouping of arguments than this default one, - * appropriate groups can be created using the addArgumentGroup() method - * - * This class inherited from [[ArgumentContainer]] - **/ -'use strict'; - -var util = require('util'); - -var ArgumentGroup = require('./group'); - -/** - * new MutuallyExclusiveGroup(container, options) - * - container (object): main container - * - options (object): options.required -> true/false - * - * `required` could be an argument itself, but making it a property of - * the options argument is more consistent with the JS adaptation of the Python) - **/ -var MutuallyExclusiveGroup = module.exports = function MutuallyExclusiveGroup(container, options) { - var required; - options = options || {}; - required = options.required || false; - ArgumentGroup.call(this, container); - this.required = required; - -}; -util.inherits(MutuallyExclusiveGroup, ArgumentGroup); - - -MutuallyExclusiveGroup.prototype._addAction = function (action) { - var msg; - if (action.required) { - msg = 'mutually exclusive arguments must be optional'; - throw new Error(msg); - } - action = this._container._addAction(action); - this._groupActions.push(action); - return action; -}; - - -MutuallyExclusiveGroup.prototype._removeAction = function (action) { - this._container._removeAction(action); - this._groupActions.remove(action); -}; - diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/group.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/group.js deleted file mode 100644 index 58b271f2fec8d0..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument/group.js +++ /dev/null @@ -1,75 +0,0 @@ -/** internal - * class ArgumentGroup - * - * Group arguments. - * By default, ArgumentParser groups command-line arguments - * into “positional arguments” and “optional arguments” - * when displaying help messages. When there is a better - * conceptual grouping of arguments than this default one, - * appropriate groups can be created using the addArgumentGroup() method - * - * This class inherited from [[ArgumentContainer]] - **/ -'use strict'; - -var util = require('util'); - -var ActionContainer = require('../action_container'); - - -/** - * new ArgumentGroup(container, options) - * - container (object): main container - * - options (object): hash of group options - * - * #### options - * - **prefixChars** group name prefix - * - **argumentDefault** default argument value - * - **title** group title - * - **description** group description - * - **/ -var ArgumentGroup = module.exports = function ArgumentGroup(container, options) { - - options = options || {}; - - // add any missing keyword arguments by checking the container - options.conflictHandler = (options.conflictHandler || container.conflictHandler); - options.prefixChars = (options.prefixChars || container.prefixChars); - options.argumentDefault = (options.argumentDefault || container.argumentDefault); - - ActionContainer.call(this, options); - - // group attributes - this.title = options.title; - this._groupActions = []; - - // share most attributes with the container - this._container = container; - this._registries = container._registries; - this._actions = container._actions; - this._optionStringActions = container._optionStringActions; - this._defaults = container._defaults; - this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals; - this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups; -}; -util.inherits(ArgumentGroup, ActionContainer); - - -ArgumentGroup.prototype._addAction = function (action) { - // Parent add action - action = ActionContainer.prototype._addAction.call(this, action); - this._groupActions.push(action); - return action; -}; - - -ArgumentGroup.prototype._removeAction = function (action) { - // Parent remove action - ActionContainer.prototype._removeAction.call(this, action); - var actionIndex = this._groupActions.indexOf(action); - if (actionIndex >= 0) { - this._groupActions.splice(actionIndex, 1); - } -}; - diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument_parser.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument_parser.js deleted file mode 100644 index bd9a59a453c946..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/argument_parser.js +++ /dev/null @@ -1,1161 +0,0 @@ -/** - * class ArgumentParser - * - * Object for parsing command line strings into js objects. - * - * Inherited from [[ActionContainer]] - **/ -'use strict'; - -var util = require('util'); -var format = require('util').format; -var Path = require('path'); -var sprintf = require('sprintf-js').sprintf; - -// Constants -var c = require('./const'); - -var $$ = require('./utils'); - -var ActionContainer = require('./action_container'); - -// Errors -var argumentErrorHelper = require('./argument/error'); - -var HelpFormatter = require('./help/formatter'); - -var Namespace = require('./namespace'); - - -/** - * new ArgumentParser(options) - * - * Create a new ArgumentParser object. - * - * ##### Options: - * - `prog` The name of the program (default: Path.basename(process.argv[1])) - * - `usage` A usage message (default: auto-generated from arguments) - * - `description` A description of what the program does - * - `epilog` Text following the argument descriptions - * - `parents` Parsers whose arguments should be copied into this one - * - `formatterClass` HelpFormatter class for printing help messages - * - `prefixChars` Characters that prefix optional arguments - * - `fromfilePrefixChars` Characters that prefix files containing additional arguments - * - `argumentDefault` The default value for all arguments - * - `addHelp` Add a -h/-help option - * - `conflictHandler` Specifies how to handle conflicting argument names - * - `debug` Enable debug mode. Argument errors throw exception in - * debug mode and process.exit in normal. Used for development and - * testing (default: false) - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#argumentparser-objects - **/ -function ArgumentParser(options) { - if (!(this instanceof ArgumentParser)) { - return new ArgumentParser(options); - } - var self = this; - options = options || {}; - - options.description = (options.description || null); - options.argumentDefault = (options.argumentDefault || null); - options.prefixChars = (options.prefixChars || '-'); - options.conflictHandler = (options.conflictHandler || 'error'); - ActionContainer.call(this, options); - - options.addHelp = typeof options.addHelp === 'undefined' || !!options.addHelp; - options.parents = options.parents || []; - // default program name - options.prog = (options.prog || Path.basename(process.argv[1])); - this.prog = options.prog; - this.usage = options.usage; - this.epilog = options.epilog; - this.version = options.version; - - this.debug = (options.debug === true); - - this.formatterClass = (options.formatterClass || HelpFormatter); - this.fromfilePrefixChars = options.fromfilePrefixChars || null; - this._positionals = this.addArgumentGroup({ title: 'Positional arguments' }); - this._optionals = this.addArgumentGroup({ title: 'Optional arguments' }); - this._subparsers = null; - - // register types - function FUNCTION_IDENTITY(o) { - return o; - } - this.register('type', 'auto', FUNCTION_IDENTITY); - this.register('type', null, FUNCTION_IDENTITY); - this.register('type', 'int', function (x) { - var result = parseInt(x, 10); - if (isNaN(result)) { - throw new Error(x + ' is not a valid integer.'); - } - return result; - }); - this.register('type', 'float', function (x) { - var result = parseFloat(x); - if (isNaN(result)) { - throw new Error(x + ' is not a valid float.'); - } - return result; - }); - this.register('type', 'string', function (x) { - return '' + x; - }); - - // add help and version arguments if necessary - var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0]; - if (options.addHelp) { - this.addArgument( - [ defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help' ], - { - action: 'help', - defaultValue: c.SUPPRESS, - help: 'Show this help message and exit.' - } - ); - } - if (typeof this.version !== 'undefined') { - this.addArgument( - [ defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version' ], - { - action: 'version', - version: this.version, - defaultValue: c.SUPPRESS, - help: "Show program's version number and exit." - } - ); - } - - // add parent arguments and defaults - options.parents.forEach(function (parent) { - self._addContainerActions(parent); - if (typeof parent._defaults !== 'undefined') { - for (var defaultKey in parent._defaults) { - if (parent._defaults.hasOwnProperty(defaultKey)) { - self._defaults[defaultKey] = parent._defaults[defaultKey]; - } - } - } - }); -} - -util.inherits(ArgumentParser, ActionContainer); - -/** - * ArgumentParser#addSubparsers(options) -> [[ActionSubparsers]] - * - options (object): hash of options see [[ActionSubparsers.new]] - * - * See also [subcommands][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#sub-commands - **/ -ArgumentParser.prototype.addSubparsers = function (options) { - if (this._subparsers) { - this.error('Cannot have multiple subparser arguments.'); - } - - options = options || {}; - options.debug = (this.debug === true); - options.optionStrings = []; - options.parserClass = (options.parserClass || ArgumentParser); - - - if (!!options.title || !!options.description) { - - this._subparsers = this.addArgumentGroup({ - title: (options.title || 'subcommands'), - description: options.description - }); - delete options.title; - delete options.description; - - } else { - this._subparsers = this._positionals; - } - - // prog defaults to the usage message of this parser, skipping - // optional arguments and with no "usage:" prefix - if (!options.prog) { - var formatter = this._getFormatter(); - var positionals = this._getPositionalActions(); - var groups = this._mutuallyExclusiveGroups; - formatter.addUsage(this.usage, positionals, groups, ''); - options.prog = formatter.formatHelp().trim(); - } - - // create the parsers action and add it to the positionals list - var ParsersClass = this._popActionClass(options, 'parsers'); - var action = new ParsersClass(options); - this._subparsers._addAction(action); - - // return the created parsers action - return action; -}; - -ArgumentParser.prototype._addAction = function (action) { - if (action.isOptional()) { - this._optionals._addAction(action); - } else { - this._positionals._addAction(action); - } - return action; -}; - -ArgumentParser.prototype._getOptionalActions = function () { - return this._actions.filter(function (action) { - return action.isOptional(); - }); -}; - -ArgumentParser.prototype._getPositionalActions = function () { - return this._actions.filter(function (action) { - return action.isPositional(); - }); -}; - - -/** - * ArgumentParser#parseArgs(args, namespace) -> Namespace|Object - * - args (array): input elements - * - namespace (Namespace|Object): result object - * - * Parsed args and throws error if some arguments are not recognized - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#the-parse-args-method - **/ -ArgumentParser.prototype.parseArgs = function (args, namespace) { - var argv; - var result = this.parseKnownArgs(args, namespace); - - args = result[0]; - argv = result[1]; - if (argv && argv.length > 0) { - this.error( - format('Unrecognized arguments: %s.', argv.join(' ')) - ); - } - return args; -}; - -/** - * ArgumentParser#parseKnownArgs(args, namespace) -> array - * - args (array): input options - * - namespace (Namespace|Object): result object - * - * Parse known arguments and return tuple of result object - * and unknown args - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#partial-parsing - **/ -ArgumentParser.prototype.parseKnownArgs = function (args, namespace) { - var self = this; - - // args default to the system args - args = args || process.argv.slice(2); - - // default Namespace built from parser defaults - namespace = namespace || new Namespace(); - - self._actions.forEach(function (action) { - if (action.dest !== c.SUPPRESS) { - if (!$$.has(namespace, action.dest)) { - if (action.defaultValue !== c.SUPPRESS) { - var defaultValue = action.defaultValue; - if (typeof action.defaultValue === 'string') { - defaultValue = self._getValue(action, defaultValue); - } - namespace[action.dest] = defaultValue; - } - } - } - }); - - Object.keys(self._defaults).forEach(function (dest) { - namespace[dest] = self._defaults[dest]; - }); - - // parse the arguments and exit if there are any errors - try { - var res = this._parseKnownArgs(args, namespace); - - namespace = res[0]; - args = res[1]; - if ($$.has(namespace, c._UNRECOGNIZED_ARGS_ATTR)) { - args = $$.arrayUnion(args, namespace[c._UNRECOGNIZED_ARGS_ATTR]); - delete namespace[c._UNRECOGNIZED_ARGS_ATTR]; - } - return [ namespace, args ]; - } catch (e) { - this.error(e); - } -}; - -ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) { - var self = this; - - var extras = []; - - // replace arg strings that are file references - if (this.fromfilePrefixChars !== null) { - argStrings = this._readArgsFromFiles(argStrings); - } - // map all mutually exclusive arguments to the other arguments - // they can't occur with - // Python has 'conflicts = action_conflicts.setdefault(mutex_action, [])' - // though I can't conceive of a way in which an action could be a member - // of two different mutually exclusive groups. - - function actionHash(action) { - // some sort of hashable key for this action - // action itself cannot be a key in actionConflicts - // I think getName() (join of optionStrings) is unique enough - return action.getName(); - } - - var conflicts, key; - var actionConflicts = {}; - - this._mutuallyExclusiveGroups.forEach(function (mutexGroup) { - mutexGroup._groupActions.forEach(function (mutexAction, i, groupActions) { - key = actionHash(mutexAction); - if (!$$.has(actionConflicts, key)) { - actionConflicts[key] = []; - } - conflicts = actionConflicts[key]; - conflicts.push.apply(conflicts, groupActions.slice(0, i)); - conflicts.push.apply(conflicts, groupActions.slice(i + 1)); - }); - }); - - // find all option indices, and determine the arg_string_pattern - // which has an 'O' if there is an option at an index, - // an 'A' if there is an argument, or a '-' if there is a '--' - var optionStringIndices = {}; - - var argStringPatternParts = []; - - argStrings.forEach(function (argString, argStringIndex) { - if (argString === '--') { - argStringPatternParts.push('-'); - while (argStringIndex < argStrings.length) { - argStringPatternParts.push('A'); - argStringIndex++; - } - } else { - // otherwise, add the arg to the arg strings - // and note the index if it was an option - var pattern; - var optionTuple = self._parseOptional(argString); - if (!optionTuple) { - pattern = 'A'; - } else { - optionStringIndices[argStringIndex] = optionTuple; - pattern = 'O'; - } - argStringPatternParts.push(pattern); - } - }); - var argStringsPattern = argStringPatternParts.join(''); - - var seenActions = []; - var seenNonDefaultActions = []; - - - function takeAction(action, argumentStrings, optionString) { - seenActions.push(action); - var argumentValues = self._getValues(action, argumentStrings); - - // error if this argument is not allowed with other previously - // seen arguments, assuming that actions that use the default - // value don't really count as "present" - if (argumentValues !== action.defaultValue) { - seenNonDefaultActions.push(action); - if (actionConflicts[actionHash(action)]) { - actionConflicts[actionHash(action)].forEach(function (actionConflict) { - if (seenNonDefaultActions.indexOf(actionConflict) >= 0) { - throw argumentErrorHelper( - action, - format('Not allowed with argument "%s".', actionConflict.getName()) - ); - } - }); - } - } - - if (argumentValues !== c.SUPPRESS) { - action.call(self, namespace, argumentValues, optionString); - } - } - - function consumeOptional(startIndex) { - // get the optional identified at this index - var optionTuple = optionStringIndices[startIndex]; - var action = optionTuple[0]; - var optionString = optionTuple[1]; - var explicitArg = optionTuple[2]; - - // identify additional optionals in the same arg string - // (e.g. -xyz is the same as -x -y -z if no args are required) - var actionTuples = []; - - var args, argCount, start, stop; - - for (;;) { - if (!action) { - extras.push(argStrings[startIndex]); - return startIndex + 1; - } - if (explicitArg) { - argCount = self._matchArgument(action, 'A'); - - // if the action is a single-dash option and takes no - // arguments, try to parse more single-dash options out - // of the tail of the option string - var chars = self.prefixChars; - if (argCount === 0 && chars.indexOf(optionString[1]) < 0) { - actionTuples.push([ action, [], optionString ]); - optionString = optionString[0] + explicitArg[0]; - var newExplicitArg = explicitArg.slice(1) || null; - var optionalsMap = self._optionStringActions; - - if (Object.keys(optionalsMap).indexOf(optionString) >= 0) { - action = optionalsMap[optionString]; - explicitArg = newExplicitArg; - } else { - throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); - } - } else if (argCount === 1) { - // if the action expect exactly one argument, we've - // successfully matched the option; exit the loop - stop = startIndex + 1; - args = [ explicitArg ]; - actionTuples.push([ action, args, optionString ]); - break; - } else { - // error if a double-dash option did not use the - // explicit argument - throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg)); - } - } else { - // if there is no explicit argument, try to match the - // optional's string arguments with the following strings - // if successful, exit the loop - - start = startIndex + 1; - var selectedPatterns = argStringsPattern.substr(start); - - argCount = self._matchArgument(action, selectedPatterns); - stop = start + argCount; - - - args = argStrings.slice(start, stop); - - actionTuples.push([ action, args, optionString ]); - break; - } - - } - - // add the Optional to the list and return the index at which - // the Optional's string args stopped - if (actionTuples.length < 1) { - throw new Error('length should be > 0'); - } - for (var i = 0; i < actionTuples.length; i++) { - takeAction.apply(self, actionTuples[i]); - } - return stop; - } - - // the list of Positionals left to be parsed; this is modified - // by consume_positionals() - var positionals = self._getPositionalActions(); - - function consumePositionals(startIndex) { - // match as many Positionals as possible - var selectedPattern = argStringsPattern.substr(startIndex); - var argCounts = self._matchArgumentsPartial(positionals, selectedPattern); - - // slice off the appropriate arg strings for each Positional - // and add the Positional and its args to the list - for (var i = 0; i < positionals.length; i++) { - var action = positionals[i]; - var argCount = argCounts[i]; - if (typeof argCount === 'undefined') { - continue; - } - var args = argStrings.slice(startIndex, startIndex + argCount); - - startIndex += argCount; - takeAction(action, args); - } - - // slice off the Positionals that we just parsed and return the - // index at which the Positionals' string args stopped - positionals = positionals.slice(argCounts.length); - return startIndex; - } - - // consume Positionals and Optionals alternately, until we have - // passed the last option string - var startIndex = 0; - var position; - - var maxOptionStringIndex = -1; - - Object.keys(optionStringIndices).forEach(function (position) { - maxOptionStringIndex = Math.max(maxOptionStringIndex, parseInt(position, 10)); - }); - - var positionalsEndIndex, nextOptionStringIndex; - - while (startIndex <= maxOptionStringIndex) { - // consume any Positionals preceding the next option - nextOptionStringIndex = null; - for (position in optionStringIndices) { - if (!optionStringIndices.hasOwnProperty(position)) { continue; } - - position = parseInt(position, 10); - if (position >= startIndex) { - if (nextOptionStringIndex !== null) { - nextOptionStringIndex = Math.min(nextOptionStringIndex, position); - } else { - nextOptionStringIndex = position; - } - } - } - - if (startIndex !== nextOptionStringIndex) { - positionalsEndIndex = consumePositionals(startIndex); - // only try to parse the next optional if we didn't consume - // the option string during the positionals parsing - if (positionalsEndIndex > startIndex) { - startIndex = positionalsEndIndex; - continue; - } else { - startIndex = positionalsEndIndex; - } - } - - // if we consumed all the positionals we could and we're not - // at the index of an option string, there were extra arguments - if (!optionStringIndices[startIndex]) { - var strings = argStrings.slice(startIndex, nextOptionStringIndex); - extras = extras.concat(strings); - startIndex = nextOptionStringIndex; - } - // consume the next optional and any arguments for it - startIndex = consumeOptional(startIndex); - } - - // consume any positionals following the last Optional - var stopIndex = consumePositionals(startIndex); - - // if we didn't consume all the argument strings, there were extras - extras = extras.concat(argStrings.slice(stopIndex)); - - // if we didn't use all the Positional objects, there were too few - // arg strings supplied. - if (positionals.length > 0) { - self.error('too few arguments'); - } - - // make sure all required actions were present - self._actions.forEach(function (action) { - if (action.required) { - if (seenActions.indexOf(action) < 0) { - self.error(format('Argument "%s" is required', action.getName())); - } - } - }); - - // make sure all required groups have one option present - var actionUsed = false; - self._mutuallyExclusiveGroups.forEach(function (group) { - if (group.required) { - actionUsed = group._groupActions.some(function (action) { - return seenNonDefaultActions.indexOf(action) !== -1; - }); - - // if no actions were used, report the error - if (!actionUsed) { - var names = []; - group._groupActions.forEach(function (action) { - if (action.help !== c.SUPPRESS) { - names.push(action.getName()); - } - }); - names = names.join(' '); - var msg = 'one of the arguments ' + names + ' is required'; - self.error(msg); - } - } - }); - - // return the updated namespace and the extra arguments - return [ namespace, extras ]; -}; - -ArgumentParser.prototype._readArgsFromFiles = function (argStrings) { - // expand arguments referencing files - var self = this; - var fs = require('fs'); - var newArgStrings = []; - argStrings.forEach(function (argString) { - if (self.fromfilePrefixChars.indexOf(argString[0]) < 0) { - // for regular arguments, just add them back into the list - newArgStrings.push(argString); - } else { - // replace arguments referencing files with the file content - try { - var argstrs = []; - var filename = argString.slice(1); - var content = fs.readFileSync(filename, 'utf8'); - content = content.trim().split('\n'); - content.forEach(function (argLine) { - self.convertArgLineToArgs(argLine).forEach(function (arg) { - argstrs.push(arg); - }); - argstrs = self._readArgsFromFiles(argstrs); - }); - newArgStrings.push.apply(newArgStrings, argstrs); - } catch (error) { - return self.error(error.message); - } - } - }); - return newArgStrings; -}; - -ArgumentParser.prototype.convertArgLineToArgs = function (argLine) { - return [ argLine ]; -}; - -ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) { - - // match the pattern for this action to the arg strings - var regexpNargs = new RegExp('^' + this._getNargsPattern(action)); - var matches = regexpArgStrings.match(regexpNargs); - var message; - - // throw an exception if we weren't able to find a match - if (!matches) { - switch (action.nargs) { - /*eslint-disable no-undefined*/ - case undefined: - case null: - message = 'Expected one argument.'; - break; - case c.OPTIONAL: - message = 'Expected at most one argument.'; - break; - case c.ONE_OR_MORE: - message = 'Expected at least one argument.'; - break; - default: - message = 'Expected %s argument(s)'; - } - - throw argumentErrorHelper( - action, - format(message, action.nargs) - ); - } - // return the number of arguments matched - return matches[1].length; -}; - -ArgumentParser.prototype._matchArgumentsPartial = function (actions, regexpArgStrings) { - // progressively shorten the actions list by slicing off the - // final actions until we find a match - var self = this; - var result = []; - var actionSlice, pattern, matches; - var i, j; - - function getLength(string) { - return string.length; - } - - for (i = actions.length; i > 0; i--) { - pattern = ''; - actionSlice = actions.slice(0, i); - for (j = 0; j < actionSlice.length; j++) { - pattern += self._getNargsPattern(actionSlice[j]); - } - - pattern = new RegExp('^' + pattern); - matches = regexpArgStrings.match(pattern); - - if (matches && matches.length > 0) { - // need only groups - matches = matches.splice(1); - result = result.concat(matches.map(getLength)); - break; - } - } - - // return the list of arg string counts - return result; -}; - -ArgumentParser.prototype._parseOptional = function (argString) { - var action, optionString, argExplicit, optionTuples; - - // if it's an empty string, it was meant to be a positional - if (!argString) { - return null; - } - - // if it doesn't start with a prefix, it was meant to be positional - if (this.prefixChars.indexOf(argString[0]) < 0) { - return null; - } - - // if the option string is present in the parser, return the action - if (this._optionStringActions[argString]) { - return [ this._optionStringActions[argString], argString, null ]; - } - - // if it's just a single character, it was meant to be positional - if (argString.length === 1) { - return null; - } - - // if the option string before the "=" is present, return the action - if (argString.indexOf('=') >= 0) { - optionString = argString.split('=', 1)[0]; - argExplicit = argString.slice(optionString.length + 1); - - if (this._optionStringActions[optionString]) { - action = this._optionStringActions[optionString]; - return [ action, optionString, argExplicit ]; - } - } - - // search through all possible prefixes of the option string - // and all actions in the parser for possible interpretations - optionTuples = this._getOptionTuples(argString); - - // if multiple actions match, the option string was ambiguous - if (optionTuples.length > 1) { - var optionStrings = optionTuples.map(function (optionTuple) { - return optionTuple[1]; - }); - this.error(format( - 'Ambiguous option: "%s" could match %s.', - argString, optionStrings.join(', ') - )); - // if exactly one action matched, this segmentation is good, - // so return the parsed action - } else if (optionTuples.length === 1) { - return optionTuples[0]; - } - - // if it was not found as an option, but it looks like a negative - // number, it was meant to be positional - // unless there are negative-number-like options - if (argString.match(this._regexpNegativeNumber)) { - if (!this._hasNegativeNumberOptionals.some(Boolean)) { - return null; - } - } - // if it contains a space, it was meant to be a positional - if (argString.search(' ') >= 0) { - return null; - } - - // it was meant to be an optional but there is no such option - // in this parser (though it might be a valid option in a subparser) - return [ null, argString, null ]; -}; - -ArgumentParser.prototype._getOptionTuples = function (optionString) { - var result = []; - var chars = this.prefixChars; - var optionPrefix; - var argExplicit; - var action; - var actionOptionString; - - // option strings starting with two prefix characters are only split at - // the '=' - if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) >= 0) { - if (optionString.indexOf('=') >= 0) { - var optionStringSplit = optionString.split('=', 1); - - optionPrefix = optionStringSplit[0]; - argExplicit = optionStringSplit[1]; - } else { - optionPrefix = optionString; - argExplicit = null; - } - - for (actionOptionString in this._optionStringActions) { - if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { - action = this._optionStringActions[actionOptionString]; - result.push([ action, actionOptionString, argExplicit ]); - } - } - - // single character options can be concatenated with their arguments - // but multiple character options always have to have their argument - // separate - } else if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) < 0) { - optionPrefix = optionString; - argExplicit = null; - var optionPrefixShort = optionString.substr(0, 2); - var argExplicitShort = optionString.substr(2); - - for (actionOptionString in this._optionStringActions) { - if (!$$.has(this._optionStringActions, actionOptionString)) continue; - - action = this._optionStringActions[actionOptionString]; - if (actionOptionString === optionPrefixShort) { - result.push([ action, actionOptionString, argExplicitShort ]); - } else if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { - result.push([ action, actionOptionString, argExplicit ]); - } - } - - // shouldn't ever get here - } else { - throw new Error(format('Unexpected option string: %s.', optionString)); - } - // return the collected option tuples - return result; -}; - -ArgumentParser.prototype._getNargsPattern = function (action) { - // in all examples below, we have to allow for '--' args - // which are represented as '-' in the pattern - var regexpNargs; - - switch (action.nargs) { - // the default (null) is assumed to be a single argument - case undefined: - case null: - regexpNargs = '(-*A-*)'; - break; - // allow zero or more arguments - case c.OPTIONAL: - regexpNargs = '(-*A?-*)'; - break; - // allow zero or more arguments - case c.ZERO_OR_MORE: - regexpNargs = '(-*[A-]*)'; - break; - // allow one or more arguments - case c.ONE_OR_MORE: - regexpNargs = '(-*A[A-]*)'; - break; - // allow any number of options or arguments - case c.REMAINDER: - regexpNargs = '([-AO]*)'; - break; - // allow one argument followed by any number of options or arguments - case c.PARSER: - regexpNargs = '(-*A[-AO]*)'; - break; - // all others should be integers - default: - regexpNargs = '(-*' + $$.repeat('-*A', action.nargs) + '-*)'; - } - - // if this is an optional action, -- is not allowed - if (action.isOptional()) { - regexpNargs = regexpNargs.replace(/-\*/g, ''); - regexpNargs = regexpNargs.replace(/-/g, ''); - } - - // return the pattern - return regexpNargs; -}; - -// -// Value conversion methods -// - -ArgumentParser.prototype._getValues = function (action, argStrings) { - var self = this; - - // for everything but PARSER args, strip out '--' - if (action.nargs !== c.PARSER && action.nargs !== c.REMAINDER) { - argStrings = argStrings.filter(function (arrayElement) { - return arrayElement !== '--'; - }); - } - - var value, argString; - - // optional argument produces a default when not present - if (argStrings.length === 0 && action.nargs === c.OPTIONAL) { - - value = (action.isOptional()) ? action.constant : action.defaultValue; - - if (typeof (value) === 'string') { - value = this._getValue(action, value); - this._checkValue(action, value); - } - - // when nargs='*' on a positional, if there were no command-line - // args, use the default if it is anything other than None - } else if (argStrings.length === 0 && action.nargs === c.ZERO_OR_MORE && - action.optionStrings.length === 0) { - - value = (action.defaultValue || argStrings); - this._checkValue(action, value); - - // single argument or optional argument produces a single value - } else if (argStrings.length === 1 && - (!action.nargs || action.nargs === c.OPTIONAL)) { - - argString = argStrings[0]; - value = this._getValue(action, argString); - this._checkValue(action, value); - - // REMAINDER arguments convert all values, checking none - } else if (action.nargs === c.REMAINDER) { - value = argStrings.map(function (v) { - return self._getValue(action, v); - }); - - // PARSER arguments convert all values, but check only the first - } else if (action.nargs === c.PARSER) { - value = argStrings.map(function (v) { - return self._getValue(action, v); - }); - this._checkValue(action, value[0]); - - // all other types of nargs produce a list - } else { - value = argStrings.map(function (v) { - return self._getValue(action, v); - }); - value.forEach(function (v) { - self._checkValue(action, v); - }); - } - - // return the converted value - return value; -}; - -ArgumentParser.prototype._getValue = function (action, argString) { - var result; - - var typeFunction = this._registryGet('type', action.type, action.type); - if (typeof typeFunction !== 'function') { - var message = format('%s is not callable', typeFunction); - throw argumentErrorHelper(action, message); - } - - // convert the value to the appropriate type - try { - result = typeFunction(argString); - - // ArgumentTypeErrors indicate errors - // If action.type is not a registered string, it is a function - // Try to deduce its name for inclusion in the error message - // Failing that, include the error message it raised. - } catch (e) { - var name = null; - if (typeof action.type === 'string') { - name = action.type; - } else { - name = action.type.name || action.type.displayName || ''; - } - var msg = format('Invalid %s value: %s', name, argString); - if (name === '') { msg += '\n' + e.message; } - throw argumentErrorHelper(action, msg); - } - // return the converted value - return result; -}; - -ArgumentParser.prototype._checkValue = function (action, value) { - // converted value must be one of the choices (if specified) - var choices = action.choices; - if (choices) { - // choise for argument can by array or string - if ((typeof choices === 'string' || Array.isArray(choices)) && - choices.indexOf(value) !== -1) { - return; - } - // choise for subparsers can by only hash - if (typeof choices === 'object' && !Array.isArray(choices) && choices[value]) { - return; - } - - if (typeof choices === 'string') { - choices = choices.split('').join(', '); - } else if (Array.isArray(choices)) { - choices = choices.join(', '); - } else { - choices = Object.keys(choices).join(', '); - } - var message = format('Invalid choice: %s (choose from [%s])', value, choices); - throw argumentErrorHelper(action, message); - } -}; - -// -// Help formatting methods -// - -/** - * ArgumentParser#formatUsage -> string - * - * Return usage string - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.formatUsage = function () { - var formatter = this._getFormatter(); - formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); - return formatter.formatHelp(); -}; - -/** - * ArgumentParser#formatHelp -> string - * - * Return help - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.formatHelp = function () { - var formatter = this._getFormatter(); - - // usage - formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); - - // description - formatter.addText(this.description); - - // positionals, optionals and user-defined groups - this._actionGroups.forEach(function (actionGroup) { - formatter.startSection(actionGroup.title); - formatter.addText(actionGroup.description); - formatter.addArguments(actionGroup._groupActions); - formatter.endSection(); - }); - - // epilog - formatter.addText(this.epilog); - - // determine help from format above - return formatter.formatHelp(); -}; - -ArgumentParser.prototype._getFormatter = function () { - var FormatterClass = this.formatterClass; - var formatter = new FormatterClass({ prog: this.prog }); - return formatter; -}; - -// -// Print functions -// - -/** - * ArgumentParser#printUsage() -> Void - * - * Print usage - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.printUsage = function () { - this._printMessage(this.formatUsage()); -}; - -/** - * ArgumentParser#printHelp() -> Void - * - * Print help - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#printing-help - **/ -ArgumentParser.prototype.printHelp = function () { - this._printMessage(this.formatHelp()); -}; - -ArgumentParser.prototype._printMessage = function (message, stream) { - if (!stream) { - stream = process.stdout; - } - if (message) { - stream.write('' + message); - } -}; - -// -// Exit functions -// - -/** - * ArgumentParser#exit(status=0, message) -> Void - * - status (int): exit status - * - message (string): message - * - * Print message in stderr/stdout and exit program - **/ -ArgumentParser.prototype.exit = function (status, message) { - if (message) { - if (status === 0) { - this._printMessage(message); - } else { - this._printMessage(message, process.stderr); - } - } - - process.exit(status); -}; - -/** - * ArgumentParser#error(message) -> Void - * - err (Error|string): message - * - * Error method Prints a usage message incorporating the message to stderr and - * exits. If you override this in a subclass, - * it should not return -- it should - * either exit or throw an exception. - * - **/ -ArgumentParser.prototype.error = function (err) { - var message; - if (err instanceof Error) { - if (this.debug === true) { - throw err; - } - message = err.message; - } else { - message = err; - } - var msg = format('%s: error: %s', this.prog, message) + c.EOL; - - if (this.debug === true) { - throw new Error(msg); - } - - this.printUsage(process.stderr); - - return this.exit(2, msg); -}; - -module.exports = ArgumentParser; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/const.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/const.js deleted file mode 100644 index b1fd4ced4e888b..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/const.js +++ /dev/null @@ -1,21 +0,0 @@ -// -// Constants -// - -'use strict'; - -module.exports.EOL = '\n'; - -module.exports.SUPPRESS = '==SUPPRESS=='; - -module.exports.OPTIONAL = '?'; - -module.exports.ZERO_OR_MORE = '*'; - -module.exports.ONE_OR_MORE = '+'; - -module.exports.PARSER = 'A...'; - -module.exports.REMAINDER = '...'; - -module.exports._UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/help/added_formatters.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/help/added_formatters.js deleted file mode 100644 index f8e42998e9bf58..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/help/added_formatters.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -var util = require('util'); - -// Constants -var c = require('../const'); - -var $$ = require('../utils'); -var HelpFormatter = require('./formatter.js'); - -/** - * new RawDescriptionHelpFormatter(options) - * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) - * - * Help message formatter which adds default values to argument help. - * - * Only the name of this class is considered a public API. All the methods - * provided by the class are considered an implementation detail. - **/ - -function ArgumentDefaultsHelpFormatter(options) { - HelpFormatter.call(this, options); -} - -util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter); - -ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) { - var help = action.help; - if (action.help.indexOf('%(defaultValue)s') === -1) { - if (action.defaultValue !== c.SUPPRESS) { - var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ]; - if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) { - help += ' (default: %(defaultValue)s)'; - } - } - } - return help; -}; - -module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter; - -/** - * new RawDescriptionHelpFormatter(options) - * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) - * - * Help message formatter which retains any formatting in descriptions. - * - * Only the name of this class is considered a public API. All the methods - * provided by the class are considered an implementation detail. - **/ - -function RawDescriptionHelpFormatter(options) { - HelpFormatter.call(this, options); -} - -util.inherits(RawDescriptionHelpFormatter, HelpFormatter); - -RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) { - var lines = text.split('\n'); - lines = lines.map(function (line) { - return $$.trimEnd(indent + line); - }); - return lines.join('\n'); -}; -module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter; - -/** - * new RawTextHelpFormatter(options) - * new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...}) - * - * Help message formatter which retains formatting of all help text. - * - * Only the name of this class is considered a public API. All the methods - * provided by the class are considered an implementation detail. - **/ - -function RawTextHelpFormatter(options) { - RawDescriptionHelpFormatter.call(this, options); -} - -util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter); - -RawTextHelpFormatter.prototype._splitLines = function (text) { - return text.split('\n'); -}; - -module.exports.RawTextHelpFormatter = RawTextHelpFormatter; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/help/formatter.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/help/formatter.js deleted file mode 100644 index 29036c14b2e156..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/help/formatter.js +++ /dev/null @@ -1,795 +0,0 @@ -/** - * class HelpFormatter - * - * Formatter for generating usage messages and argument help strings. Only the - * name of this class is considered a public API. All the methods provided by - * the class are considered an implementation detail. - * - * Do not call in your code, use this class only for inherits your own forvatter - * - * ToDo add [additonal formatters][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#formatter-class - **/ -'use strict'; - -var sprintf = require('sprintf-js').sprintf; - -// Constants -var c = require('../const'); - -var $$ = require('../utils'); - - -/*:nodoc:* internal - * new Support(parent, heding) - * - parent (object): parent section - * - heading (string): header string - * - **/ -function Section(parent, heading) { - this._parent = parent; - this._heading = heading; - this._items = []; -} - -/*:nodoc:* internal - * Section#addItem(callback) -> Void - * - callback (array): tuple with function and args - * - * Add function for single element - **/ -Section.prototype.addItem = function (callback) { - this._items.push(callback); -}; - -/*:nodoc:* internal - * Section#formatHelp(formatter) -> string - * - formatter (HelpFormatter): current formatter - * - * Form help section string - * - **/ -Section.prototype.formatHelp = function (formatter) { - var itemHelp, heading; - - // format the indented section - if (this._parent) { - formatter._indent(); - } - - itemHelp = this._items.map(function (item) { - var obj, func, args; - - obj = formatter; - func = item[0]; - args = item[1]; - return func.apply(obj, args); - }); - itemHelp = formatter._joinParts(itemHelp); - - if (this._parent) { - formatter._dedent(); - } - - // return nothing if the section was empty - if (!itemHelp) { - return ''; - } - - // add the heading if the section was non-empty - heading = ''; - if (this._heading && this._heading !== c.SUPPRESS) { - var currentIndent = formatter.currentIndent; - heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL; - } - - // join the section-initialize newline, the heading and the help - return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]); -}; - -/** - * new HelpFormatter(options) - * - * #### Options: - * - `prog`: program name - * - `indentIncriment`: indent step, default value 2 - * - `maxHelpPosition`: max help position, default value = 24 - * - `width`: line width - * - **/ -var HelpFormatter = module.exports = function HelpFormatter(options) { - options = options || {}; - - this._prog = options.prog; - - this._maxHelpPosition = options.maxHelpPosition || 24; - this._width = (options.width || ((process.env.COLUMNS || 80) - 2)); - - this._currentIndent = 0; - this._indentIncriment = options.indentIncriment || 2; - this._level = 0; - this._actionMaxLength = 0; - - this._rootSection = new Section(null); - this._currentSection = this._rootSection; - - this._whitespaceMatcher = new RegExp('\\s+', 'g'); - this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g'); -}; - -HelpFormatter.prototype._indent = function () { - this._currentIndent += this._indentIncriment; - this._level += 1; -}; - -HelpFormatter.prototype._dedent = function () { - this._currentIndent -= this._indentIncriment; - this._level -= 1; - if (this._currentIndent < 0) { - throw new Error('Indent decreased below 0.'); - } -}; - -HelpFormatter.prototype._addItem = function (func, args) { - this._currentSection.addItem([ func, args ]); -}; - -// -// Message building methods -// - -/** - * HelpFormatter#startSection(heading) -> Void - * - heading (string): header string - * - * Start new help section - * - * See alse [code example][1] - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - * - **/ -HelpFormatter.prototype.startSection = function (heading) { - this._indent(); - var section = new Section(this._currentSection, heading); - var func = section.formatHelp.bind(section); - this._addItem(func, [ this ]); - this._currentSection = section; -}; - -/** - * HelpFormatter#endSection -> Void - * - * End help section - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - **/ -HelpFormatter.prototype.endSection = function () { - this._currentSection = this._currentSection._parent; - this._dedent(); -}; - -/** - * HelpFormatter#addText(text) -> Void - * - text (string): plain text - * - * Add plain text into current section - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - * - **/ -HelpFormatter.prototype.addText = function (text) { - if (text && text !== c.SUPPRESS) { - this._addItem(this._formatText, [ text ]); - } -}; - -/** - * HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void - * - usage (string): usage text - * - actions (array): actions list - * - groups (array): groups list - * - prefix (string): usage prefix - * - * Add usage data into current section - * - * ##### Example - * - * formatter.addUsage(this.usage, this._actions, []); - * return formatter.formatHelp(); - * - **/ -HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) { - if (usage !== c.SUPPRESS) { - this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]); - } -}; - -/** - * HelpFormatter#addArgument(action) -> Void - * - action (object): action - * - * Add argument into current section - * - * Single variant of [[HelpFormatter#addArguments]] - **/ -HelpFormatter.prototype.addArgument = function (action) { - if (action.help !== c.SUPPRESS) { - var self = this; - - // find all invocations - var invocations = [ this._formatActionInvocation(action) ]; - var invocationLength = invocations[0].length; - - var actionLength; - - if (action._getSubactions) { - this._indent(); - action._getSubactions().forEach(function (subaction) { - - var invocationNew = self._formatActionInvocation(subaction); - invocations.push(invocationNew); - invocationLength = Math.max(invocationLength, invocationNew.length); - - }); - this._dedent(); - } - - // update the maximum item length - actionLength = invocationLength + this._currentIndent; - this._actionMaxLength = Math.max(this._actionMaxLength, actionLength); - - // add the item to the list - this._addItem(this._formatAction, [ action ]); - } -}; - -/** - * HelpFormatter#addArguments(actions) -> Void - * - actions (array): actions list - * - * Mass add arguments into current section - * - * ##### Example - * - * formatter.startSection(actionGroup.title); - * formatter.addText(actionGroup.description); - * formatter.addArguments(actionGroup._groupActions); - * formatter.endSection(); - * - **/ -HelpFormatter.prototype.addArguments = function (actions) { - var self = this; - actions.forEach(function (action) { - self.addArgument(action); - }); -}; - -// -// Help-formatting methods -// - -/** - * HelpFormatter#formatHelp -> string - * - * Format help - * - * ##### Example - * - * formatter.addText(this.epilog); - * return formatter.formatHelp(); - * - **/ -HelpFormatter.prototype.formatHelp = function () { - var help = this._rootSection.formatHelp(this); - if (help) { - help = help.replace(this._longBreakMatcher, c.EOL + c.EOL); - help = $$.trimChars(help, c.EOL) + c.EOL; - } - return help; -}; - -HelpFormatter.prototype._joinParts = function (partStrings) { - return partStrings.filter(function (part) { - return (part && part !== c.SUPPRESS); - }).join(''); -}; - -HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) { - if (!prefix && typeof prefix !== 'string') { - prefix = 'usage: '; - } - - actions = actions || []; - groups = groups || []; - - - // if usage is specified, use that - if (usage) { - usage = sprintf(usage, { prog: this._prog }); - - // if no optionals or positionals are available, usage is just prog - } else if (!usage && actions.length === 0) { - usage = this._prog; - - // if optionals and positionals are available, calculate usage - } else if (!usage) { - var prog = this._prog; - var optionals = []; - var positionals = []; - var actionUsage; - var textWidth; - - // split optionals from positionals - actions.forEach(function (action) { - if (action.isOptional()) { - optionals.push(action); - } else { - positionals.push(action); - } - }); - - // build full usage string - actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups); - usage = [ prog, actionUsage ].join(' '); - - // wrap the usage parts if it's too long - textWidth = this._width - this._currentIndent; - if ((prefix.length + usage.length) > textWidth) { - - // break usage into wrappable parts - var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g'); - var optionalUsage = this._formatActionsUsage(optionals, groups); - var positionalUsage = this._formatActionsUsage(positionals, groups); - - - var optionalParts = optionalUsage.match(regexpPart); - var positionalParts = positionalUsage.match(regexpPart) || []; - - if (optionalParts.join(' ') !== optionalUsage) { - throw new Error('assert "optionalParts.join(\' \') === optionalUsage"'); - } - if (positionalParts.join(' ') !== positionalUsage) { - throw new Error('assert "positionalParts.join(\' \') === positionalUsage"'); - } - - // helper for wrapping lines - /*eslint-disable func-style*/ // node 0.10 compat - var _getLines = function (parts, indent, prefix) { - var lines = []; - var line = []; - - var lineLength = prefix ? prefix.length - 1 : indent.length - 1; - - parts.forEach(function (part) { - if (lineLength + 1 + part.length > textWidth) { - lines.push(indent + line.join(' ')); - line = []; - lineLength = indent.length - 1; - } - line.push(part); - lineLength += part.length + 1; - }); - - if (line) { - lines.push(indent + line.join(' ')); - } - if (prefix) { - lines[0] = lines[0].substr(indent.length); - } - return lines; - }; - - var lines, indent, parts; - // if prog is short, follow it with optionals or positionals - if (prefix.length + prog.length <= 0.75 * textWidth) { - indent = $$.repeat(' ', (prefix.length + prog.length + 1)); - if (optionalParts) { - lines = [].concat( - _getLines([ prog ].concat(optionalParts), indent, prefix), - _getLines(positionalParts, indent) - ); - } else if (positionalParts) { - lines = _getLines([ prog ].concat(positionalParts), indent, prefix); - } else { - lines = [ prog ]; - } - - // if prog is long, put it on its own line - } else { - indent = $$.repeat(' ', prefix.length); - parts = optionalParts.concat(positionalParts); - lines = _getLines(parts, indent); - if (lines.length > 1) { - lines = [].concat( - _getLines(optionalParts, indent), - _getLines(positionalParts, indent) - ); - } - lines = [ prog ].concat(lines); - } - // join lines into usage - usage = lines.join(c.EOL); - } - } - - // prefix with 'usage:' - return prefix + usage + c.EOL + c.EOL; -}; - -HelpFormatter.prototype._formatActionsUsage = function (actions, groups) { - // find group indices and identify actions in groups - var groupActions = []; - var inserts = []; - var self = this; - - groups.forEach(function (group) { - var end; - var i; - - var start = actions.indexOf(group._groupActions[0]); - if (start >= 0) { - end = start + group._groupActions.length; - - //if (actions.slice(start, end) === group._groupActions) { - if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) { - group._groupActions.forEach(function (action) { - groupActions.push(action); - }); - - if (!group.required) { - if (inserts[start]) { - inserts[start] += ' ['; - } else { - inserts[start] = '['; - } - inserts[end] = ']'; - } else { - if (inserts[start]) { - inserts[start] += ' ('; - } else { - inserts[start] = '('; - } - inserts[end] = ')'; - } - for (i = start + 1; i < end; i += 1) { - inserts[i] = '|'; - } - } - } - }); - - // collect all actions format strings - var parts = []; - - actions.forEach(function (action, actionIndex) { - var part; - var optionString; - var argsDefault; - var argsString; - - // suppressed arguments are marked with None - // remove | separators for suppressed arguments - if (action.help === c.SUPPRESS) { - parts.push(null); - if (inserts[actionIndex] === '|') { - inserts.splice(actionIndex, actionIndex); - } else if (inserts[actionIndex + 1] === '|') { - inserts.splice(actionIndex + 1, actionIndex + 1); - } - - // produce all arg strings - } else if (!action.isOptional()) { - part = self._formatArgs(action, action.dest); - - // if it's in a group, strip the outer [] - if (groupActions.indexOf(action) >= 0) { - if (part[0] === '[' && part[part.length - 1] === ']') { - part = part.slice(1, -1); - } - } - // add the action string to the list - parts.push(part); - - // produce the first way to invoke the option in brackets - } else { - optionString = action.optionStrings[0]; - - // if the Optional doesn't take a value, format is: -s or --long - if (action.nargs === 0) { - part = '' + optionString; - - // if the Optional takes a value, format is: -s ARGS or --long ARGS - } else { - argsDefault = action.dest.toUpperCase(); - argsString = self._formatArgs(action, argsDefault); - part = optionString + ' ' + argsString; - } - // make it look optional if it's not required or in a group - if (!action.required && groupActions.indexOf(action) < 0) { - part = '[' + part + ']'; - } - // add the action string to the list - parts.push(part); - } - }); - - // insert things at the necessary indices - for (var i = inserts.length - 1; i >= 0; --i) { - if (inserts[i] !== null) { - parts.splice(i, 0, inserts[i]); - } - } - - // join all the action items with spaces - var text = parts.filter(function (part) { - return !!part; - }).join(' '); - - // clean up separators for mutually exclusive groups - text = text.replace(/([\[(]) /g, '$1'); // remove spaces - text = text.replace(/ ([\])])/g, '$1'); - text = text.replace(/\[ *\]/g, ''); // remove empty groups - text = text.replace(/\( *\)/g, ''); - text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups - - text = text.trim(); - - // return the text - return text; -}; - -HelpFormatter.prototype._formatText = function (text) { - text = sprintf(text, { prog: this._prog }); - var textWidth = this._width - this._currentIndent; - var indentIncriment = $$.repeat(' ', this._currentIndent); - return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL; -}; - -HelpFormatter.prototype._formatAction = function (action) { - var self = this; - - var helpText; - var helpLines; - var parts; - var indentFirst; - - // determine the required width and the entry label - var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition); - var helpWidth = this._width - helpPosition; - var actionWidth = helpPosition - this._currentIndent - 2; - var actionHeader = this._formatActionInvocation(action); - - // no help; start on same line and add a final newline - if (!action.help) { - actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; - - // short action name; start on the same line and pad two spaces - } else if (actionHeader.length <= actionWidth) { - actionHeader = $$.repeat(' ', this._currentIndent) + - actionHeader + - ' ' + - $$.repeat(' ', actionWidth - actionHeader.length); - indentFirst = 0; - - // long action name; start on the next line - } else { - actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; - indentFirst = helpPosition; - } - - // collect the pieces of the action help - parts = [ actionHeader ]; - - // if there was help for the action, add lines of help text - if (action.help) { - helpText = this._expandHelp(action); - helpLines = this._splitLines(helpText, helpWidth); - parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL); - helpLines.slice(1).forEach(function (line) { - parts.push($$.repeat(' ', helpPosition) + line + c.EOL); - }); - - // or add a newline if the description doesn't end with one - } else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) { - parts.push(c.EOL); - } - // if there are any sub-actions, add their help as well - if (action._getSubactions) { - this._indent(); - action._getSubactions().forEach(function (subaction) { - parts.push(self._formatAction(subaction)); - }); - this._dedent(); - } - // return a single string - return this._joinParts(parts); -}; - -HelpFormatter.prototype._formatActionInvocation = function (action) { - if (!action.isOptional()) { - var format_func = this._metavarFormatter(action, action.dest); - var metavars = format_func(1); - return metavars[0]; - } - - var parts = []; - var argsDefault; - var argsString; - - // if the Optional doesn't take a value, format is: -s, --long - if (action.nargs === 0) { - parts = parts.concat(action.optionStrings); - - // if the Optional takes a value, format is: -s ARGS, --long ARGS - } else { - argsDefault = action.dest.toUpperCase(); - argsString = this._formatArgs(action, argsDefault); - action.optionStrings.forEach(function (optionString) { - parts.push(optionString + ' ' + argsString); - }); - } - return parts.join(', '); -}; - -HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) { - var result; - - if (action.metavar || action.metavar === '') { - result = action.metavar; - } else if (action.choices) { - var choices = action.choices; - - if (typeof choices === 'string') { - choices = choices.split('').join(', '); - } else if (Array.isArray(choices)) { - choices = choices.join(','); - } else { - choices = Object.keys(choices).join(','); - } - result = '{' + choices + '}'; - } else { - result = metavarDefault; - } - - return function (size) { - if (Array.isArray(result)) { - return result; - } - - var metavars = []; - for (var i = 0; i < size; i += 1) { - metavars.push(result); - } - return metavars; - }; -}; - -HelpFormatter.prototype._formatArgs = function (action, metavarDefault) { - var result; - var metavars; - - var buildMetavar = this._metavarFormatter(action, metavarDefault); - - switch (action.nargs) { - /*eslint-disable no-undefined*/ - case undefined: - case null: - metavars = buildMetavar(1); - result = '' + metavars[0]; - break; - case c.OPTIONAL: - metavars = buildMetavar(1); - result = '[' + metavars[0] + ']'; - break; - case c.ZERO_OR_MORE: - metavars = buildMetavar(2); - result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]'; - break; - case c.ONE_OR_MORE: - metavars = buildMetavar(2); - result = '' + metavars[0] + ' [' + metavars[1] + ' ...]'; - break; - case c.REMAINDER: - result = '...'; - break; - case c.PARSER: - metavars = buildMetavar(1); - result = metavars[0] + ' ...'; - break; - default: - metavars = buildMetavar(action.nargs); - result = metavars.join(' '); - } - return result; -}; - -HelpFormatter.prototype._expandHelp = function (action) { - var params = { prog: this._prog }; - - Object.keys(action).forEach(function (actionProperty) { - var actionValue = action[actionProperty]; - - if (actionValue !== c.SUPPRESS) { - params[actionProperty] = actionValue; - } - }); - - if (params.choices) { - if (typeof params.choices === 'string') { - params.choices = params.choices.split('').join(', '); - } else if (Array.isArray(params.choices)) { - params.choices = params.choices.join(', '); - } else { - params.choices = Object.keys(params.choices).join(', '); - } - } - - return sprintf(this._getHelpString(action), params); -}; - -HelpFormatter.prototype._splitLines = function (text, width) { - var lines = []; - var delimiters = [ ' ', '.', ',', '!', '?' ]; - var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$'); - - text = text.replace(/[\n\|\t]/g, ' '); - - text = text.trim(); - text = text.replace(this._whitespaceMatcher, ' '); - - // Wraps the single paragraph in text (a string) so every line - // is at most width characters long. - text.split(c.EOL).forEach(function (line) { - if (width >= line.length) { - lines.push(line); - return; - } - - var wrapStart = 0; - var wrapEnd = width; - var delimiterIndex = 0; - while (wrapEnd <= line.length) { - if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) { - delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index; - wrapEnd = wrapStart + delimiterIndex + 1; - } - lines.push(line.substring(wrapStart, wrapEnd)); - wrapStart = wrapEnd; - wrapEnd += width; - } - if (wrapStart < line.length) { - lines.push(line.substring(wrapStart, wrapEnd)); - } - }); - - return lines; -}; - -HelpFormatter.prototype._fillText = function (text, width, indent) { - var lines = this._splitLines(text, width); - lines = lines.map(function (line) { - return indent + line; - }); - return lines.join(c.EOL); -}; - -HelpFormatter.prototype._getHelpString = function (action) { - return action.help; -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/namespace.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/namespace.js deleted file mode 100644 index a860de9ecc48dd..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/namespace.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * class Namespace - * - * Simple object for storing attributes. Implements equality by attribute names - * and values, and provides a simple string representation. - * - * See also [original guide][1] - * - * [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object - **/ -'use strict'; - -var $$ = require('./utils'); - -/** - * new Namespace(options) - * - options(object): predefined propertis for result object - * - **/ -var Namespace = module.exports = function Namespace(options) { - $$.extend(this, options); -}; - -/** - * Namespace#isset(key) -> Boolean - * - key (string|number): property name - * - * Tells whenever `namespace` contains given `key` or not. - **/ -Namespace.prototype.isset = function (key) { - return $$.has(this, key); -}; - -/** - * Namespace#set(key, value) -> self - * -key (string|number|object): propery name - * -value (mixed): new property value - * - * Set the property named key with value. - * If key object then set all key properties to namespace object - **/ -Namespace.prototype.set = function (key, value) { - if (typeof (key) === 'object') { - $$.extend(this, key); - } else { - this[key] = value; - } - return this; -}; - -/** - * Namespace#get(key, defaultValue) -> mixed - * - key (string|number): property name - * - defaultValue (mixed): default value - * - * Return the property key or defaulValue if not set - **/ -Namespace.prototype.get = function (key, defaultValue) { - return !this[key] ? defaultValue : this[key]; -}; - -/** - * Namespace#unset(key, defaultValue) -> mixed - * - key (string|number): property name - * - defaultValue (mixed): default value - * - * Return data[key](and delete it) or defaultValue - **/ -Namespace.prototype.unset = function (key, defaultValue) { - var value = this[key]; - if (value !== null) { - delete this[key]; - return value; - } - return defaultValue; -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/utils.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/utils.js deleted file mode 100644 index 4a9cf3edb615ce..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/lib/utils.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -exports.repeat = function (str, num) { - var result = ''; - for (var i = 0; i < num; i++) { result += str; } - return result; -}; - -exports.arrayEqual = function (a, b) { - if (a.length !== b.length) { return false; } - for (var i = 0; i < a.length; i++) { - if (a[i] !== b[i]) { return false; } - } - return true; -}; - -exports.trimChars = function (str, chars) { - var start = 0; - var end = str.length - 1; - while (chars.indexOf(str.charAt(start)) >= 0) { start++; } - while (chars.indexOf(str.charAt(end)) >= 0) { end--; } - return str.slice(start, end + 1); -}; - -exports.capitalize = function (str) { - return str.charAt(0).toUpperCase() + str.slice(1); -}; - -exports.arrayUnion = function () { - var result = []; - for (var i = 0, values = {}; i < arguments.length; i++) { - var arr = arguments[i]; - for (var j = 0; j < arr.length; j++) { - if (!values[arr[j]]) { - values[arr[j]] = true; - result.push(arr[j]); - } - } - } - return result; -}; - -function has(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} - -exports.has = has; - -exports.extend = function (dest, src) { - for (var i in src) { - if (has(src, i)) { dest[i] = src[i]; } - } -}; - -exports.trimEnd = function (str) { - return str.replace(/\s+$/g, ''); -}; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/package.json b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/package.json deleted file mode 100644 index 62fba0a9fcfc87..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/argparse/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "argparse", - "description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library", - "version": "1.0.10", - "keywords": [ - "cli", - "parser", - "argparse", - "option", - "args" - ], - "contributors": [ - "Eugene Shkuropat", - "Paul Jacobson" - ], - "files": [ - "index.js", - "lib/" - ], - "license": "MIT", - "repository": "nodeca/argparse", - "scripts": { - "test": "make test" - }, - "dependencies": { - "sprintf-js": "~1.0.2" - }, - "devDependencies": { - "eslint": "^2.13.1", - "istanbul": "^0.4.5", - "mocha": "^3.1.0", - "ndoc": "^5.0.1" - } -} diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/LICENSE b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/LICENSE deleted file mode 100644 index 09d3a29e93d123..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -(The MIT License) - -Copyright (C) 2011-2015 by Vitaly Puzrin - -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: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -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. diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/README.md b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/README.md deleted file mode 100644 index 246e56355146df..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/README.md +++ /dev/null @@ -1,299 +0,0 @@ -JS-YAML - YAML 1.2 parser / writer for JavaScript -================================================= - -[![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) -[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) - -__[Online Demo](http://nodeca.github.com/js-yaml/)__ - - -This is an implementation of [YAML](http://yaml.org/), a human-friendly data -serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was -completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. - - -Installation ------------- - -### YAML module for node.js - -``` -npm install js-yaml -``` - - -### CLI executable - -If you want to inspect your YAML files from CLI, install js-yaml globally: - -``` -npm install -g js-yaml -``` - -#### Usage - -``` -usage: js-yaml [-h] [-v] [-c] [-t] file - -Positional arguments: - file File with YAML document(s) - -Optional arguments: - -h, --help Show this help message and exit. - -v, --version Show program's version number and exit. - -c, --compact Display errors in compact mode - -t, --trace Show stack trace on error -``` - - -### Bundled YAML library for browsers - -``` html - - - - -``` - -Browser support was done mostly for the online demo. If you find any errors - feel -free to send pull requests with fixes. Also note, that IE and other old browsers -needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. - -Notes: - -1. We have no resources to support browserified version. Don't expect it to be - well tested. Don't expect fast fixes if something goes wrong there. -2. `!!js/function` in browser bundle will not work by default. If you really need - it - load `esprima` parser first (via amd or directly). -3. `!!bin` in browser will return `Array`, because browsers do not support - node.js `Buffer` and adding Buffer shims is completely useless on practice. - - -API ---- - -Here we cover the most 'useful' methods. If you need advanced details (creating -your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and -[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more -info. - -``` javascript -const yaml = require('js-yaml'); -const fs = require('fs'); - -// Get document, or throw exception on error -try { - const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); - console.log(doc); -} catch (e) { - console.log(e); -} -``` - - -### safeLoad (string [ , options ]) - -**Recommended loading way.** Parses `string` as single YAML document. Returns either a -plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does -not support regexps, functions and undefined. This method is safe for untrusted data. - -options: - -- `filename` _(default: null)_ - string to be used as a file path in - error/warning messages. -- `onWarning` _(default: null)_ - function to call on warning messages. - Loader will call this function with an instance of `YAMLException` for each warning. -- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: - http://www.yaml.org/spec/1.2/spec.html#id2802346 - - `JSON_SCHEMA` - all JSON-supported types: - http://www.yaml.org/spec/1.2/spec.html#id2803231 - - `CORE_SCHEMA` - same as `JSON_SCHEMA`: - http://www.yaml.org/spec/1.2/spec.html#id2804923 - - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones - (`!!js/undefined`, `!!js/regexp` and `!!js/function`): - http://yaml.org/type/ - - `DEFAULT_FULL_SCHEMA` - all supported YAML types. -- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. - -NOTE: This function **does not** understand multi-document sources, it throws -exception on those. - -NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. -So, the JSON schema is not as strictly defined in the YAML specification. -It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. -The core schema also has no such restrictions. It allows binary notation for integers. - - -### load (string [ , options ]) - -**Use with care with untrusted sources**. The same as `safeLoad()` but uses -`DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: -`!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you -must additionally validate object structure to avoid injections: - -``` javascript -const untrusted_code = '"toString": ! "function (){very_evil_thing();}"'; - -// I'm just converting that string, what could possibly go wrong? -require('js-yaml').load(untrusted_code) + '' -``` - - -### safeLoadAll (string [, iterator] [, options ]) - -Same as `safeLoad()`, but understands multi-document sources. Applies -`iterator` to each document if specified, or returns array of documents. - -``` javascript -const yaml = require('js-yaml'); - -yaml.safeLoadAll(data, function (doc) { - console.log(doc); -}); -``` - - -### loadAll (string [, iterator] [ , options ]) - -Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. - - -### safeDump (object [ , options ]) - -Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will -throw an exception if you try to dump regexps or functions. However, you can -disable exceptions by setting the `skipInvalid` option to `true`. - -options: - -- `indent` _(default: 2)_ - indentation width to use (in spaces). -- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements -- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function - in the safe schema) and skip pairs and single values with such types. -- `flowLevel` (default: -1) - specifies level of nesting, when to switch from - block to flow style for collections. -1 means block style everwhere -- `styles` - "tag" => "style" map. Each tag may have own set of styles. -- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. -- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a - function, use the function to sort the keys. -- `lineWidth` _(default: `80`)_ - set max line width. -- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references -- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older - yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 -- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. - -The following table show availlable styles (e.g. "canonical", -"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml -output is shown on the right side after `=>` (default setting) or `->`: - -``` none -!!null - "canonical" -> "~" - "lowercase" => "null" - "uppercase" -> "NULL" - "camelcase" -> "Null" - -!!int - "binary" -> "0b1", "0b101010", "0b1110001111010" - "octal" -> "01", "052", "016172" - "decimal" => "1", "42", "7290" - "hexadecimal" -> "0x1", "0x2A", "0x1C7A" - -!!bool - "lowercase" => "true", "false" - "uppercase" -> "TRUE", "FALSE" - "camelcase" -> "True", "False" - -!!float - "lowercase" => ".nan", '.inf' - "uppercase" -> ".NAN", '.INF' - "camelcase" -> ".NaN", '.Inf' -``` - -Example: - -``` javascript -safeDump (object, { - 'styles': { - '!!null': 'canonical' // dump null as ~ - }, - 'sortKeys': true // sort object keys -}); -``` - -### dump (object [ , options ]) - -Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). - - -Supported YAML types --------------------- - -The list of standard YAML tags and corresponding JavaScipt types. See also -[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and -[YAML types repository](http://yaml.org/type/). - -``` -!!null '' # null -!!bool 'yes' # bool -!!int '3...' # number -!!float '3.14...' # number -!!binary '...base64...' # buffer -!!timestamp 'YYYY-...' # date -!!omap [ ... ] # array of key-value pairs -!!pairs [ ... ] # array or array pairs -!!set { ... } # array of objects with given keys and null values -!!str '...' # string -!!seq [ ... ] # array -!!map { ... } # object -``` - -**JavaScript-specific tags** - -``` -!!js/regexp /pattern/gim # RegExp -!!js/undefined '' # Undefined -!!js/function 'function () {...}' # Function -``` - -Caveats -------- - -Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects -or arrays as keys, and stringifies (by calling `toString()` method) them at the -moment of adding them. - -``` yaml ---- -? [ foo, bar ] -: - baz -? { foo: bar } -: - baz - - baz -``` - -``` javascript -{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } -``` - -Also, reading of properties on implicit block mapping keys is not supported yet. -So, the following YAML document cannot be loaded. - -``` yaml -&anchor foo: - foo: bar - *anchor: duplicate key - baz: bat - *anchor: duplicate key -``` - - -js-yaml for enterprise ----------------------- - -Available as part of the Tidelift Subscription - -The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/bin/js-yaml.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/bin/js-yaml.js deleted file mode 100755 index e79186be6f56f1..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/bin/js-yaml.js +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env node - - -'use strict'; - -/*eslint-disable no-console*/ - - -// stdlib -var fs = require('fs'); - - -// 3rd-party -var argparse = require('argparse'); - - -// internal -var yaml = require('..'); - - -//////////////////////////////////////////////////////////////////////////////// - - -var cli = new argparse.ArgumentParser({ - prog: 'js-yaml', - version: require('../package.json').version, - addHelp: true -}); - - -cli.addArgument([ '-c', '--compact' ], { - help: 'Display errors in compact mode', - action: 'storeTrue' -}); - - -// deprecated (not needed after we removed output colors) -// option suppressed, but not completely removed for compatibility -cli.addArgument([ '-j', '--to-json' ], { - help: argparse.Const.SUPPRESS, - dest: 'json', - action: 'storeTrue' -}); - - -cli.addArgument([ '-t', '--trace' ], { - help: 'Show stack trace on error', - action: 'storeTrue' -}); - -cli.addArgument([ 'file' ], { - help: 'File to read, utf-8 encoded without BOM', - nargs: '?', - defaultValue: '-' -}); - - -//////////////////////////////////////////////////////////////////////////////// - - -var options = cli.parseArgs(); - - -//////////////////////////////////////////////////////////////////////////////// - -function readFile(filename, encoding, callback) { - if (options.file === '-') { - // read from stdin - - var chunks = []; - - process.stdin.on('data', function (chunk) { - chunks.push(chunk); - }); - - process.stdin.on('end', function () { - return callback(null, Buffer.concat(chunks).toString(encoding)); - }); - } else { - fs.readFile(filename, encoding, callback); - } -} - -readFile(options.file, 'utf8', function (error, input) { - var output, isYaml; - - if (error) { - if (error.code === 'ENOENT') { - console.error('File not found: ' + options.file); - process.exit(2); - } - - console.error( - options.trace && error.stack || - error.message || - String(error)); - - process.exit(1); - } - - try { - output = JSON.parse(input); - isYaml = false; - } catch (err) { - if (err instanceof SyntaxError) { - try { - output = []; - yaml.loadAll(input, function (doc) { output.push(doc); }, {}); - isYaml = true; - - if (output.length === 0) output = null; - else if (output.length === 1) output = output[0]; - - } catch (e) { - if (options.trace && err.stack) console.error(e.stack); - else console.error(e.toString(options.compact)); - - process.exit(1); - } - } else { - console.error( - options.trace && err.stack || - err.message || - String(err)); - - process.exit(1); - } - } - - if (isYaml) console.log(JSON.stringify(output, null, ' ')); - else console.log(yaml.dump(output)); -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/dist/js-yaml.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/dist/js-yaml.js deleted file mode 100644 index 7878320743c2cb..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/dist/js-yaml.js +++ /dev/null @@ -1,3989 +0,0 @@ -/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; - -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; - - if (map === null) return {}; - - result = {}; - keys = Object.keys(map); - - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); - - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - type = schema.compiledTypeMap['fallback'][tag]; - - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } - - result[tag] = style; - } - - return result; -} - -function encodeHex(character) { - var string, handle, length; - - string = character.toString(16).toUpperCase(); - - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } - - return '\\' + handle + common.repeat('0', length - string.length) + string; -} - -function State(options) { - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; - - this.tag = null; - this.result = ''; - - this.duplicates = []; - this.usedDuplicates = null; -} - -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; - - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } - - if (line.length && line !== '\n') result += ind; - - result += line; - } - - return result; -} - -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); -} - -function testImplicitResolving(state, str) { - var index, length, type; - - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; - - if (type.resolve(str)) { - return true; - } - } - - return false; -} - -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} - -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) - || (0x10000 <= c && c <= 0x10FFFF); -} - -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// [24] b-line-feed ::= #xA /* LF */ -// [25] b-carriage-return ::= #xD /* CR */ -// [3] c-byte-order-mark ::= #xFEFF -function isNsChar(c) { - return isPrintable(c) && !isWhitespace(c) - // byte-order-mark - && c !== 0xFEFF - // b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; -} - -// Simplified test for values allowed after the first character in plain style. -function isPlainSafe(c, prev) { - // Uses a subset of nb-char - c-flow-indicator - ":" - "#" - // where nb-char ::= c-printable - b-char - c-byte-order-mark. - return isPrintable(c) && c !== 0xFEFF - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // - ":" - "#" - // /* An ns-char preceding */ "#" - && c !== CHAR_COLON - && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); -} - -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - return isPrintable(c) && c !== 0xFEFF - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} - -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); -} - -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; - -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { - var i; - var char, prev_char; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(string.charCodeAt(0)) - && !isWhitespace(string.charCodeAt(string.length - 1)); - - if (singleLineOnly) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); - } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - return plain && !testAmbiguousType(string) - ? STYLE_PLAIN : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; -} - -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey) { - state.dump = (function () { - if (string.length === 0) { - return "''"; - } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; - } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } - - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); - } - }()); -} - -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); - - return indentIndicator + chomp + '\n'; -} - -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} - -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; - - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } - - return result; -} - -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; - - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; - - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; - } - - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } - - return result.slice(1); // drop extra \n joiner -} - -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char, nextChar; - var escapeSeq; - - for (var i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). - if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { - nextChar = string.charCodeAt(i + 1); - if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { - // Combine the surrogate pair and store it escaped. - result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); - // Advance index one extra since we already used that char here. - i++; continue; - } - } - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); - } - - return result; -} - -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level, object[index], false, false)) { - if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; - } - } - - state.tag = _tag; - state.dump = '[' + _result + ']'; -} - -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level + 1, object[index], true, true)) { - if (!compact || index !== 0) { - _result += generateNextLine(state, level); - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } - - _result += state.dump; - } - } - - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. -} - -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - - pairBuffer = ''; - if (index !== 0) pairBuffer += ', '; - - if (state.condenseFlow) pairBuffer += '"'; - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = '{' + _result + '}'; -} - -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; - - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } - - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); - - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } - - pairBuffer += state.dump; - - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } - - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} - -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - - typeList = explicit ? state.explicitTypes : state.implicitTypes; - - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { - - state.tag = explicit ? type.tag : '?'; - - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; - - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } - - state.dump = _result; - } - - return true; - } - } - - return false; -} - -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); - } - - var type = _toString.call(state.dump); - - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } - - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; - - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } - - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } - - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; - if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, arrayLevel, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, arrayLevel, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey); - } - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } - - if (state.tag !== null && state.tag !== '?') { - state.dump = '!<' + state.tag + '> ' + state.dump; - } - } - - return true; -} - -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; - - inspectNode(object, objects, duplicatesIndexes); - - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); -} - -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; - - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); - - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } - } - } -} - -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - - if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; - - return ''; -} - -function safeDump(input, options) { - return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - -module.exports.dump = dump; -module.exports.safeDump = safeDump; - -},{"./common":2,"./exception":4,"./schema/default_full":9,"./schema/default_safe":10}],4:[function(require,module,exports){ -// YAML error class. http://stackoverflow.com/questions/8458984 -// -'use strict'; - -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } -} - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { - var result = this.name + ': '; - - result += this.reason || '(unknown reason)'; - - if (!compact && this.mark) { - result += ' ' + this.mark.toString(); - } - - return result; -}; - - -module.exports = YAMLException; - -},{}],5:[function(require,module,exports){ -'use strict'; - -/*eslint-disable max-len,no-use-before-define*/ - -var common = require('./common'); -var YAMLException = require('./exception'); -var Mark = require('./mark'); -var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); -var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); - - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - - -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; - - -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; - - -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - -function _class(obj) { return Object.prototype.toString.call(obj); } - -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} - -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} - -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} - -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; -} - -function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - /*eslint-disable no-bitwise*/ - lc = c | 0x20; - - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } - - return -1; -} - -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} - -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; -} - -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} - -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} - -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); -} - - -function State(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.onWarning = options['onWarning'] || null; - this.legacy = options['legacy'] || false; - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - -} - - -function generateError(state, message) { - return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); -} - -function throwError(state, message) { - throw generateError(state, message); -} - -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} - - -var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - state.tagMap[handle] = prefix; - } -}; - - -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; - } -} - -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } -} - -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { - var index, quantity; - - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); - - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } - - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } - - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } - - - keyNode = String(keyNode); - - if (_result === null) { - _result = {}; - } - - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - _result[keyNode] = valueNode; - delete overridableKeys[keyNode]; - } - - return _result; -} - -function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; -} - -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; -} - -function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; -} - -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} - - -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - - ch = state.input.charCodeAt(state.position); - - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } - - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; -} - -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} - -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); - } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); - } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} - -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = {}, - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); -} - -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); - } - - return true; -} - -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; -} - -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _pos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = {}, - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - _pos = state.position; - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else { - break; // Reading is done. Go to the epilogue. - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if (state.lineIndent > nodeIndent && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; -} - -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; -} - -function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; -} - -function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} - -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - - if (state.tag !== null && state.tag !== '!') { - if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - } - - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; -} - -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = {}; - state.anchorMap = {}; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } -} - - -function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); - } - } - - var state = new State(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; -} - - -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} - - -function load(input, options) { - var documents = loadDocuments(input, options); - - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); -} - - -function safeLoadAll(input, iterator, options) { - if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - - -function safeLoad(input, options) { - return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - - -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; - -},{"./common":2,"./exception":4,"./mark":6,"./schema/default_full":9,"./schema/default_safe":10}],6:[function(require,module,exports){ -'use strict'; - - -var common = require('./common'); - - -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; -} - - -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; - - if (!this.buffer) return null; - - indent = indent || 4; - maxLength = maxLength || 75; - - head = ''; - start = this.position; - - while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } - } - - tail = ''; - end = this.position; - - while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; - } - } - - snippet = this.buffer.slice(start, end); - - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; - - -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; - - if (this.name) { - where += 'in "' + this.name + '" '; - } - - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - - if (!compact) { - snippet = this.getSnippet(); - - if (snippet) { - where += ':\n' + snippet; - } - } - - return where; -}; - - -module.exports = Mark; - -},{"./common":2}],7:[function(require,module,exports){ -'use strict'; - -/*eslint-disable max-len*/ - -var common = require('./common'); -var YAMLException = require('./exception'); -var Type = require('./type'); - - -function compileList(schema, name, result) { - var exclude = []; - - schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); - }); - - schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { - exclude.push(previousIndex); - } - }); - - result.push(currentType); - }); - - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); -} - - -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {} - }, index, length; - - function collectType(type) { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; -} - - -function Schema(definition) { - this.include = definition.include || []; - this.implicit = definition.implicit || []; - this.explicit = definition.explicit || []; - - this.implicit.forEach(function (type) { - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } - }); - - this.compiledImplicit = compileList(this, 'implicit', []); - this.compiledExplicit = compileList(this, 'explicit', []); - this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); -} - - -Schema.DEFAULT = null; - - -Schema.create = function createSchema() { - var schemas, types; - - switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; - - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; - - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); - } - - schemas = common.toArray(schemas); - types = common.toArray(types); - - if (!schemas.every(function (schema) { return schema instanceof Schema; })) { - throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); - } - - if (!types.every(function (type) { return type instanceof Type; })) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - - return new Schema({ - include: schemas, - explicit: types - }); -}; - - -module.exports = Schema; - -},{"./common":2,"./exception":4,"./type":13}],8:[function(require,module,exports){ -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./json') - ] -}); - -},{"../schema":7,"./json":12}],9:[function(require,module,exports){ -// JS-YAML's default schema for `load` function. -// It is not described in the YAML specification. -// -// This schema is based on JS-YAML's default safe schema and includes -// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. -// -// Also this schema is used as default base schema at `Schema.create` function. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = Schema.DEFAULT = new Schema({ - include: [ - require('./default_safe') - ], - explicit: [ - require('../type/js/undefined'), - require('../type/js/regexp'), - require('../type/js/function') - ] -}); - -},{"../schema":7,"../type/js/function":18,"../type/js/regexp":19,"../type/js/undefined":20,"./default_safe":10}],10:[function(require,module,exports){ -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./core') - ], - implicit: [ - require('../type/timestamp'), - require('../type/merge') - ], - explicit: [ - require('../type/binary'), - require('../type/omap'), - require('../type/pairs'), - require('../type/set') - ] -}); - -},{"../schema":7,"../type/binary":14,"../type/merge":22,"../type/omap":24,"../type/pairs":25,"../type/set":27,"../type/timestamp":29,"./core":8}],11:[function(require,module,exports){ -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - explicit: [ - require('../type/str'), - require('../type/seq'), - require('../type/map') - ] -}); - -},{"../schema":7,"../type/map":21,"../type/seq":26,"../type/str":28}],12:[function(require,module,exports){ -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./failsafe') - ], - implicit: [ - require('../type/null'), - require('../type/bool'), - require('../type/int'), - require('../type/float') - ] -}); - -},{"../schema":7,"../type/bool":15,"../type/float":16,"../type/int":17,"../type/null":23,"./failsafe":11}],13:[function(require,module,exports){ -'use strict'; - -var YAMLException = require('./exception'); - -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'defaultStyle', - 'styleAliases' -]; - -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; - -function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; -} - -function Type(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} - -module.exports = Type; - -},{"./exception":4}],14:[function(require,module,exports){ -'use strict'; - -/*eslint-disable no-bitwise*/ - -var NodeBuffer; - -try { - // A trick for browserified version, to not include `Buffer` shim - var _require = require; - NodeBuffer = _require('buffer').Buffer; -} catch (__) {} - -var Type = require('../type'); - - -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - -function resolveYamlBinary(data) { - if (data === null) return false; - - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; - } - - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} - -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } - - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } - - // Wrap into Buffer for NodeJS and leave Array for browser - if (NodeBuffer) { - // Support node 6.+ Buffer API when available - return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); - } - - return result; -} - -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; - } - - // Dump tail - - tail = max % 3; - - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } - - return result; -} - -function isBinary(object) { - return NodeBuffer && NodeBuffer.isBuffer(object); -} - -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); - -},{"../type":13}],15:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} - -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} - -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} - -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); - -},{"../type":13}],16:[function(require,module,exports){ -'use strict'; - -var common = require('../common'); -var Type = require('../type'); - -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // 20:59 - '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); - -function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } - - return true; -} - -function constructYamlFloat(data) { - var value, sign, base, digits; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); - - value = 0.0; - base = 1; - - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); - - return sign * value; - - } - return sign * parseFloat(value, 10); -} - - -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - -function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} - -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); - -},{"../common":2,"../type":13}],17:[function(require,module,exports){ -'use strict'; - -var common = require('../common'); -var Type = require('../type'); - -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} - -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} - -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} - -function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - - if (!max) return false; - - ch = data[index]; - - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - // base 8 - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - // base 10 (except 0) or base 60 - - // value should not start with `_`; - if (ch === '_') return false; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch === ':') break; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; - } - - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; - - // if !base60 - done; - if (ch !== ':') return true; - - // base60 almost not used, no needs to optimize - return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); -} - -function constructYamlInteger(data) { - var value = data, sign = 1, ch, base, digits = []; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } - - ch = value[0]; - - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } - - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value, 16); - return sign * parseInt(value, 8); - } - - if (value.indexOf(':') !== -1) { - value.split(':').forEach(function (v) { - digits.unshift(parseInt(v, 10)); - }); - - value = 0; - base = 1; - - digits.forEach(function (d) { - value += (d * base); - base *= 60; - }); - - return sign * value; - - } - - return sign * parseInt(value, 10); -} - -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } -}); - -},{"../common":2,"../type":13}],18:[function(require,module,exports){ -'use strict'; - -var esprima; - -// Browserified version does not have esprima -// -// 1. For node.js just require module as deps -// 2. For browser try to require mudule via external AMD system. -// If not found - try to fallback to window.esprima. If not -// found too - then fail to parse. -// -try { - // workaround to exclude package from browserify list. - var _require = require; - esprima = _require('esprima'); -} catch (_) { - /* eslint-disable no-redeclare */ - /* global window */ - if (typeof window !== 'undefined') esprima = window.esprima; -} - -var Type = require('../../type'); - -function resolveJavascriptFunction(data) { - if (data === null) return false; - - try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); - - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - return false; - } - - return true; - } catch (err) { - return false; - } -} - -function constructJavascriptFunction(data) { - /*jslint evil:true*/ - - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; - - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - throw new Error('Failed to resolve function'); - } - - ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); - }); - - body = ast.body[0].expression.body.range; - - // Esprima's ranges include the first '{' and the last '}' characters on - // function expressions. So cut them out. - if (ast.body[0].expression.body.type === 'BlockStatement') { - /*eslint-disable no-new-func*/ - return new Function(params, source.slice(body[0] + 1, body[1] - 1)); - } - // ES6 arrow functions can omit the BlockStatement. In that case, just return - // the body. - /*eslint-disable no-new-func*/ - return new Function(params, 'return ' + source.slice(body[0], body[1])); -} - -function representJavascriptFunction(object /*, style*/) { - return object.toString(); -} - -function isFunction(object) { - return Object.prototype.toString.call(object) === '[object Function]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/function', { - kind: 'scalar', - resolve: resolveJavascriptFunction, - construct: constructJavascriptFunction, - predicate: isFunction, - represent: representJavascriptFunction -}); - -},{"../../type":13}],19:[function(require,module,exports){ -'use strict'; - -var Type = require('../../type'); - -function resolveJavascriptRegExp(data) { - if (data === null) return false; - if (data.length === 0) return false; - - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // if regexp starts with '/' it can have modifiers and must be properly closed - // `/foo/gim` - modifiers tail can be maximum 3 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - - if (modifiers.length > 3) return false; - // if expression starts with /, is should be properly terminated - if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; - } - - return true; -} - -function constructJavascriptRegExp(data) { - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // `/foo/gim` - tail can be maximum 4 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - regexp = regexp.slice(1, regexp.length - modifiers.length - 1); - } - - return new RegExp(regexp, modifiers); -} - -function representJavascriptRegExp(object /*, style*/) { - var result = '/' + object.source + '/'; - - if (object.global) result += 'g'; - if (object.multiline) result += 'm'; - if (object.ignoreCase) result += 'i'; - - return result; -} - -function isRegExp(object) { - return Object.prototype.toString.call(object) === '[object RegExp]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/regexp', { - kind: 'scalar', - resolve: resolveJavascriptRegExp, - construct: constructJavascriptRegExp, - predicate: isRegExp, - represent: representJavascriptRegExp -}); - -},{"../../type":13}],20:[function(require,module,exports){ -'use strict'; - -var Type = require('../../type'); - -function resolveJavascriptUndefined() { - return true; -} - -function constructJavascriptUndefined() { - /*eslint-disable no-undefined*/ - return undefined; -} - -function representJavascriptUndefined() { - return ''; -} - -function isUndefined(object) { - return typeof object === 'undefined'; -} - -module.exports = new Type('tag:yaml.org,2002:js/undefined', { - kind: 'scalar', - resolve: resolveJavascriptUndefined, - construct: constructJavascriptUndefined, - predicate: isUndefined, - represent: representJavascriptUndefined -}); - -},{"../../type":13}],21:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); - -},{"../type":13}],22:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} - -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); - -},{"../type":13}],23:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} - -function constructYamlNull() { - return null; -} - -function isNull(object) { - return object === null; -} - -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; } - }, - defaultStyle: 'lowercase' -}); - -},{"../type":13}],24:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; - -function resolveYamlOmap(data) { - if (data === null) return true; - - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; -} - -function constructYamlOmap(data) { - return data !== null ? data : []; -} - -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - -},{"../type":13}],25:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var _toString = Object.prototype.toString; - -function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return true; -} - -function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return result; -} - -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); - -},{"../type":13}],26:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); - -},{"../type":13}],27:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; - - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } - } - - return true; -} - -function constructYamlSet(data) { - return data !== null ? data : {}; -} - -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); - -},{"../type":13}],28:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); - -},{"../type":13}],29:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} - -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; -} - -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} - -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); - -},{"../type":13}],"/":[function(require,module,exports){ -'use strict'; - - -var yaml = require('./lib/js-yaml.js'); - - -module.exports = yaml; - -},{"./lib/js-yaml.js":1}]},{},[])("/") -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/dist/js-yaml.min.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/dist/js-yaml.min.js deleted file mode 100644 index 1b6ecc16b2a691..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/dist/js-yaml.min.js +++ /dev/null @@ -1 +0,0 @@ -/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsyaml=e()}(function(){return function i(r,o,a){function s(t,e){if(!o[t]){if(!r[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(c)return c(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=o[t]={exports:{}},r[t][0].call(n.exports,function(e){return s(r[t][1][e]||e)},n,n.exports,i,r,o,a)}return o[t].exports}for(var c="function"==typeof require&&require,e=0;e=i.flowLevel;switch(V(r,n,i.indent,t,function(e){return function(e,t){for(var n=0,i=e.implicitTypes.length;n"+z(r,i.indent)+J(U(function(t,n){var e,i=/(\n+)([^\n]*)/g,r=function(){var e=-1!==(e=t.indexOf("\n"))?e:t.length;return i.lastIndex=e,Q(t.slice(0,e),n)}(),o="\n"===t[0]||" "===t[0];for(;e=i.exec(t);){var a=e[1],s=e[2];e=" "===s[0],r+=a+(o||e||""===s?"":"\n")+Q(s,n),o=e}return r}(r,t),e));case G:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+o+'" style');i=r.represent[o](t,o)}e.dump=i}return 1}}function ee(e,t,n,i,r,o){e.tag=null,e.dump=n,X(e,n,!1)||X(e,n,!0);var a=l.call(e.dump);i=i&&(e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return 1}function te(e,t){var n,i,r=[],o=[];for(!function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;o>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else S(u)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}}function K(e,t){var n,i,r=e.tag,o=e.anchor,a=[],s=!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&45===i&&O(e.input.charCodeAt(e.position+1));)if(s=!0,e.position++,Y(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,P(e,t,x,!1,!0),a.push(e.result),Y(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt)&&(P(e,t,A,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentc&&(c=e.lineIndent),S(p))u++;else{if(e.lineIndent=t){a=!0,f=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),I(f)||(o=e.position+1),f=e.input.charCodeAt(++e.position)}if(L(e,r,o,!1),e.result)return 1;e.kind=l,e.result=p}}(e,i,g===n)&&(d=!0,null===e.tag&&(e.tag="?")):(d=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===p&&(d=s&&K(e,r))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&N(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||d}function $(e,t){t=t||{},0!==(e=String(e)).length&&(10!==e.charCodeAt(e.length-1)&&13!==e.charCodeAt(e.length-1)&&(e+="\n"),65279===e.charCodeAt(0)&&(e=e.slice(1)));var n=new F(e,t),e=e.indexOf("\0");for(-1!==e&&(n.position=e,N(n,"null byte is not allowed in input")),n.input+="\0";32===n.input.charCodeAt(n.position);)n.lineIndent+=1,n.position+=1;for(;n.positiont/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t="";return this.name&&(t+='in "'+this.name+'" '),t+="at line "+(this.line+1)+", column "+(this.column+1),e||(e=this.getSnippet())&&(t+=":\n"+e),t},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var r=e("./common"),o=e("./exception"),a=e("./type");function s(e,t,i){var r=[];return e.include.forEach(function(e){i=s(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function c(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=s(this,"implicit",[]),this.compiledExplicit=s(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),o.push(r>>8&255),o.push(255&r)),r=r<<6|i.indexOf(t.charAt(a));return 0==(e=n%4*6)?(o.push(r>>16&255),o.push(r>>8&255),o.push(255&r)):18==e?(o.push(r>>10&255),o.push(r>>2&255)):12==e&&o.push(r>>4&255),s?s.from?s.from(o):new s(o):o},predicate:function(e){return s&&s.isBuffer(e)},represent:function(e){for(var t,n="",i=0,r=e.length,o=c,a=0;a>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]),i=(i<<8)+e[a];return 0==(t=r%3)?(n+=o[i>>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]):2==t?(n+=o[i>>10&63],n+=o[i>>4&63],n+=o[i<<2&63],n+=o[64]):1==t&&(n+=o[i>>2&63],n+=o[i<<4&63],n+=o[64],n+=o[64]),n}})},{"../type":13}],15:[function(e,t,n){"use strict";e=e("../type");t.exports=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type"),r=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var o=/^[-+]?[0-9]+e/;t.exports=new e("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!r.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n=e.replace(/_/g,"").toLowerCase(),e="-"===n[0]?-1:1,i=[];return 0<="+-".indexOf(n[0])&&(n=n.slice(1)),".inf"===n?1==e?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===n?NaN:0<=n.indexOf(":")?(n.split(":").forEach(function(e){i.unshift(parseFloat(e,10))}),n=0,t=1,i.forEach(function(e){n+=e*t,t*=60}),e*n):e*parseFloat(n,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return e=e.toString(10),o.test(e)?e.replace("e",".e"):e},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type");t.exports=new e("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; - -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; - - if (map === null) return {}; - - result = {}; - keys = Object.keys(map); - - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); - - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - type = schema.compiledTypeMap['fallback'][tag]; - - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } - - result[tag] = style; - } - - return result; -} - -function encodeHex(character) { - var string, handle, length; - - string = character.toString(16).toUpperCase(); - - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } - - return '\\' + handle + common.repeat('0', length - string.length) + string; -} - -function State(options) { - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; - - this.tag = null; - this.result = ''; - - this.duplicates = []; - this.usedDuplicates = null; -} - -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; - - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } - - if (line.length && line !== '\n') result += ind; - - result += line; - } - - return result; -} - -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); -} - -function testImplicitResolving(state, str) { - var index, length, type; - - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; - - if (type.resolve(str)) { - return true; - } - } - - return false; -} - -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} - -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) - || (0x10000 <= c && c <= 0x10FFFF); -} - -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// [24] b-line-feed ::= #xA /* LF */ -// [25] b-carriage-return ::= #xD /* CR */ -// [3] c-byte-order-mark ::= #xFEFF -function isNsChar(c) { - return isPrintable(c) && !isWhitespace(c) - // byte-order-mark - && c !== 0xFEFF - // b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; -} - -// Simplified test for values allowed after the first character in plain style. -function isPlainSafe(c, prev) { - // Uses a subset of nb-char - c-flow-indicator - ":" - "#" - // where nb-char ::= c-printable - b-char - c-byte-order-mark. - return isPrintable(c) && c !== 0xFEFF - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // - ":" - "#" - // /* An ns-char preceding */ "#" - && c !== CHAR_COLON - && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); -} - -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - return isPrintable(c) && c !== 0xFEFF - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} - -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); -} - -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; - -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { - var i; - var char, prev_char; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(string.charCodeAt(0)) - && !isWhitespace(string.charCodeAt(string.length - 1)); - - if (singleLineOnly) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); - } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - return plain && !testAmbiguousType(string) - ? STYLE_PLAIN : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; -} - -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey) { - state.dump = (function () { - if (string.length === 0) { - return "''"; - } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; - } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } - - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); - } - }()); -} - -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); - - return indentIndicator + chomp + '\n'; -} - -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} - -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; - - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } - - return result; -} - -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; - - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; - - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; - } - - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } - - return result.slice(1); // drop extra \n joiner -} - -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char, nextChar; - var escapeSeq; - - for (var i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). - if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { - nextChar = string.charCodeAt(i + 1); - if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { - // Combine the surrogate pair and store it escaped. - result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); - // Advance index one extra since we already used that char here. - i++; continue; - } - } - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); - } - - return result; -} - -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level, object[index], false, false)) { - if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; - } - } - - state.tag = _tag; - state.dump = '[' + _result + ']'; -} - -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level + 1, object[index], true, true)) { - if (!compact || index !== 0) { - _result += generateNextLine(state, level); - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } - - _result += state.dump; - } - } - - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. -} - -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - - pairBuffer = ''; - if (index !== 0) pairBuffer += ', '; - - if (state.condenseFlow) pairBuffer += '"'; - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = '{' + _result + '}'; -} - -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; - - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } - - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); - - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } - - pairBuffer += state.dump; - - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } - - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} - -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - - typeList = explicit ? state.explicitTypes : state.implicitTypes; - - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { - - state.tag = explicit ? type.tag : '?'; - - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; - - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } - - state.dump = _result; - } - - return true; - } - } - - return false; -} - -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); - } - - var type = _toString.call(state.dump); - - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } - - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; - - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } - - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } - - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; - if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, arrayLevel, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, arrayLevel, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey); - } - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } - - if (state.tag !== null && state.tag !== '?') { - state.dump = '!<' + state.tag + '> ' + state.dump; - } - } - - return true; -} - -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; - - inspectNode(object, objects, duplicatesIndexes); - - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); -} - -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; - - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); - - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } - } - } -} - -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - - if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; - - return ''; -} - -function safeDump(input, options) { - return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - -module.exports.dump = dump; -module.exports.safeDump = safeDump; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/exception.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/exception.js deleted file mode 100644 index b744a1ee4ef4d0..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/exception.js +++ /dev/null @@ -1,43 +0,0 @@ -// YAML error class. http://stackoverflow.com/questions/8458984 -// -'use strict'; - -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } -} - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { - var result = this.name + ': '; - - result += this.reason || '(unknown reason)'; - - if (!compact && this.mark) { - result += ' ' + this.mark.toString(); - } - - return result; -}; - - -module.exports = YAMLException; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/loader.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/loader.js deleted file mode 100644 index d7484a59191036..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/loader.js +++ /dev/null @@ -1,1644 +0,0 @@ -'use strict'; - -/*eslint-disable max-len,no-use-before-define*/ - -var common = require('./common'); -var YAMLException = require('./exception'); -var Mark = require('./mark'); -var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); -var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); - - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - - -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; - - -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; - - -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - -function _class(obj) { return Object.prototype.toString.call(obj); } - -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} - -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} - -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} - -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; -} - -function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - /*eslint-disable no-bitwise*/ - lc = c | 0x20; - - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } - - return -1; -} - -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} - -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; -} - -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} - -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} - -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); -} - - -function State(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.onWarning = options['onWarning'] || null; - this.legacy = options['legacy'] || false; - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - -} - - -function generateError(state, message) { - return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); -} - -function throwError(state, message) { - throw generateError(state, message); -} - -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} - - -var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - state.tagMap[handle] = prefix; - } -}; - - -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; - } -} - -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } -} - -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { - var index, quantity; - - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); - - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } - - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } - - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } - - - keyNode = String(keyNode); - - if (_result === null) { - _result = {}; - } - - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - _result[keyNode] = valueNode; - delete overridableKeys[keyNode]; - } - - return _result; -} - -function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; -} - -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; -} - -function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; -} - -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} - - -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - - ch = state.input.charCodeAt(state.position); - - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } - - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; -} - -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} - -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); - } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); - } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} - -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = {}, - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); -} - -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); - } - - return true; -} - -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; -} - -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _pos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = {}, - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - _pos = state.position; - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else { - break; // Reading is done. Go to the epilogue. - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if (state.lineIndent > nodeIndent && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; -} - -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; -} - -function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; -} - -function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} - -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - - if (state.tag !== null && state.tag !== '!') { - if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - } - - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; -} - -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = {}; - state.anchorMap = {}; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } -} - - -function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); - } - } - - var state = new State(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; -} - - -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} - - -function load(input, options) { - var documents = loadDocuments(input, options); - - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); -} - - -function safeLoadAll(input, iterator, options) { - if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - - -function safeLoad(input, options) { - return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - - -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/mark.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/mark.js deleted file mode 100644 index 47b265c20cea4c..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/mark.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - - -var common = require('./common'); - - -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; -} - - -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; - - if (!this.buffer) return null; - - indent = indent || 4; - maxLength = maxLength || 75; - - head = ''; - start = this.position; - - while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } - } - - tail = ''; - end = this.position; - - while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; - } - } - - snippet = this.buffer.slice(start, end); - - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; - - -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; - - if (this.name) { - where += 'in "' + this.name + '" '; - } - - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - - if (!compact) { - snippet = this.getSnippet(); - - if (snippet) { - where += ':\n' + snippet; - } - } - - return where; -}; - - -module.exports = Mark; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema.js deleted file mode 100644 index ca7cf47e705319..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema.js +++ /dev/null @@ -1,108 +0,0 @@ -'use strict'; - -/*eslint-disable max-len*/ - -var common = require('./common'); -var YAMLException = require('./exception'); -var Type = require('./type'); - - -function compileList(schema, name, result) { - var exclude = []; - - schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); - }); - - schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { - exclude.push(previousIndex); - } - }); - - result.push(currentType); - }); - - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); -} - - -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {} - }, index, length; - - function collectType(type) { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; -} - - -function Schema(definition) { - this.include = definition.include || []; - this.implicit = definition.implicit || []; - this.explicit = definition.explicit || []; - - this.implicit.forEach(function (type) { - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } - }); - - this.compiledImplicit = compileList(this, 'implicit', []); - this.compiledExplicit = compileList(this, 'explicit', []); - this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); -} - - -Schema.DEFAULT = null; - - -Schema.create = function createSchema() { - var schemas, types; - - switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; - - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; - - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); - } - - schemas = common.toArray(schemas); - types = common.toArray(types); - - if (!schemas.every(function (schema) { return schema instanceof Schema; })) { - throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); - } - - if (!types.every(function (type) { return type instanceof Type; })) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - - return new Schema({ - include: schemas, - explicit: types - }); -}; - - -module.exports = Schema; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/core.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/core.js deleted file mode 100644 index 206daab56c0586..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/core.js +++ /dev/null @@ -1,18 +0,0 @@ -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./json') - ] -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/default_full.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/default_full.js deleted file mode 100644 index a55ef42accdaf9..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/default_full.js +++ /dev/null @@ -1,25 +0,0 @@ -// JS-YAML's default schema for `load` function. -// It is not described in the YAML specification. -// -// This schema is based on JS-YAML's default safe schema and includes -// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. -// -// Also this schema is used as default base schema at `Schema.create` function. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = Schema.DEFAULT = new Schema({ - include: [ - require('./default_safe') - ], - explicit: [ - require('../type/js/undefined'), - require('../type/js/regexp'), - require('../type/js/function') - ] -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js deleted file mode 100644 index 11d89bbfbba45e..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js +++ /dev/null @@ -1,28 +0,0 @@ -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./core') - ], - implicit: [ - require('../type/timestamp'), - require('../type/merge') - ], - explicit: [ - require('../type/binary'), - require('../type/omap'), - require('../type/pairs'), - require('../type/set') - ] -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js deleted file mode 100644 index b7a33eb7a1ccea..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js +++ /dev/null @@ -1,17 +0,0 @@ -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - explicit: [ - require('../type/str'), - require('../type/seq'), - require('../type/map') - ] -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/json.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/json.js deleted file mode 100644 index 5be3dbf805bc5d..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/schema/json.js +++ /dev/null @@ -1,25 +0,0 @@ -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./failsafe') - ], - implicit: [ - require('../type/null'), - require('../type/bool'), - require('../type/int'), - require('../type/float') - ] -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type.js deleted file mode 100644 index 90b702ac06f11b..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var YAMLException = require('./exception'); - -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'defaultStyle', - 'styleAliases' -]; - -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; - -function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; -} - -function Type(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} - -module.exports = Type; diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/binary.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/binary.js deleted file mode 100644 index 10b1875595be31..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/binary.js +++ /dev/null @@ -1,138 +0,0 @@ -'use strict'; - -/*eslint-disable no-bitwise*/ - -var NodeBuffer; - -try { - // A trick for browserified version, to not include `Buffer` shim - var _require = require; - NodeBuffer = _require('buffer').Buffer; -} catch (__) {} - -var Type = require('../type'); - - -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - -function resolveYamlBinary(data) { - if (data === null) return false; - - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; - } - - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} - -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } - - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } - - // Wrap into Buffer for NodeJS and leave Array for browser - if (NodeBuffer) { - // Support node 6.+ Buffer API when available - return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); - } - - return result; -} - -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; - } - - // Dump tail - - tail = max % 3; - - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } - - return result; -} - -function isBinary(object) { - return NodeBuffer && NodeBuffer.isBuffer(object); -} - -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/bool.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/bool.js deleted file mode 100644 index cb7745930a6e7f..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/bool.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} - -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} - -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} - -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/float.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/float.js deleted file mode 100644 index 127671b21392fc..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/float.js +++ /dev/null @@ -1,116 +0,0 @@ -'use strict'; - -var common = require('../common'); -var Type = require('../type'); - -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // 20:59 - '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); - -function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } - - return true; -} - -function constructYamlFloat(data) { - var value, sign, base, digits; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); - - value = 0.0; - base = 1; - - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); - - return sign * value; - - } - return sign * parseFloat(value, 10); -} - - -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - -function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} - -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/int.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/int.js deleted file mode 100644 index ba61c5f958e2ff..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/int.js +++ /dev/null @@ -1,173 +0,0 @@ -'use strict'; - -var common = require('../common'); -var Type = require('../type'); - -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} - -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} - -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} - -function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - - if (!max) return false; - - ch = data[index]; - - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - // base 8 - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - // base 10 (except 0) or base 60 - - // value should not start with `_`; - if (ch === '_') return false; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch === ':') break; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; - } - - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; - - // if !base60 - done; - if (ch !== ':') return true; - - // base60 almost not used, no needs to optimize - return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); -} - -function constructYamlInteger(data) { - var value = data, sign = 1, ch, base, digits = []; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } - - ch = value[0]; - - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } - - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value, 16); - return sign * parseInt(value, 8); - } - - if (value.indexOf(':') !== -1) { - value.split(':').forEach(function (v) { - digits.unshift(parseInt(v, 10)); - }); - - value = 0; - base = 1; - - digits.forEach(function (d) { - value += (d * base); - base *= 60; - }); - - return sign * value; - - } - - return sign * parseInt(value, 10); -} - -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/function.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/function.js deleted file mode 100644 index 8fab8c43089ff2..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/function.js +++ /dev/null @@ -1,93 +0,0 @@ -'use strict'; - -var esprima; - -// Browserified version does not have esprima -// -// 1. For node.js just require module as deps -// 2. For browser try to require mudule via external AMD system. -// If not found - try to fallback to window.esprima. If not -// found too - then fail to parse. -// -try { - // workaround to exclude package from browserify list. - var _require = require; - esprima = _require('esprima'); -} catch (_) { - /* eslint-disable no-redeclare */ - /* global window */ - if (typeof window !== 'undefined') esprima = window.esprima; -} - -var Type = require('../../type'); - -function resolveJavascriptFunction(data) { - if (data === null) return false; - - try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); - - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - return false; - } - - return true; - } catch (err) { - return false; - } -} - -function constructJavascriptFunction(data) { - /*jslint evil:true*/ - - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; - - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - throw new Error('Failed to resolve function'); - } - - ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); - }); - - body = ast.body[0].expression.body.range; - - // Esprima's ranges include the first '{' and the last '}' characters on - // function expressions. So cut them out. - if (ast.body[0].expression.body.type === 'BlockStatement') { - /*eslint-disable no-new-func*/ - return new Function(params, source.slice(body[0] + 1, body[1] - 1)); - } - // ES6 arrow functions can omit the BlockStatement. In that case, just return - // the body. - /*eslint-disable no-new-func*/ - return new Function(params, 'return ' + source.slice(body[0], body[1])); -} - -function representJavascriptFunction(object /*, style*/) { - return object.toString(); -} - -function isFunction(object) { - return Object.prototype.toString.call(object) === '[object Function]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/function', { - kind: 'scalar', - resolve: resolveJavascriptFunction, - construct: constructJavascriptFunction, - predicate: isFunction, - represent: representJavascriptFunction -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js deleted file mode 100644 index 43fa47017619ec..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -var Type = require('../../type'); - -function resolveJavascriptRegExp(data) { - if (data === null) return false; - if (data.length === 0) return false; - - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // if regexp starts with '/' it can have modifiers and must be properly closed - // `/foo/gim` - modifiers tail can be maximum 3 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - - if (modifiers.length > 3) return false; - // if expression starts with /, is should be properly terminated - if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; - } - - return true; -} - -function constructJavascriptRegExp(data) { - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // `/foo/gim` - tail can be maximum 4 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - regexp = regexp.slice(1, regexp.length - modifiers.length - 1); - } - - return new RegExp(regexp, modifiers); -} - -function representJavascriptRegExp(object /*, style*/) { - var result = '/' + object.source + '/'; - - if (object.global) result += 'g'; - if (object.multiline) result += 'm'; - if (object.ignoreCase) result += 'i'; - - return result; -} - -function isRegExp(object) { - return Object.prototype.toString.call(object) === '[object RegExp]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/regexp', { - kind: 'scalar', - resolve: resolveJavascriptRegExp, - construct: constructJavascriptRegExp, - predicate: isRegExp, - represent: representJavascriptRegExp -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js deleted file mode 100644 index 95b5569fdfa510..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var Type = require('../../type'); - -function resolveJavascriptUndefined() { - return true; -} - -function constructJavascriptUndefined() { - /*eslint-disable no-undefined*/ - return undefined; -} - -function representJavascriptUndefined() { - return ''; -} - -function isUndefined(object) { - return typeof object === 'undefined'; -} - -module.exports = new Type('tag:yaml.org,2002:js/undefined', { - kind: 'scalar', - resolve: resolveJavascriptUndefined, - construct: constructJavascriptUndefined, - predicate: isUndefined, - represent: representJavascriptUndefined -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/map.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/map.js deleted file mode 100644 index f327beebd53bdb..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/map.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/merge.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/merge.js deleted file mode 100644 index ae08a86444cf1c..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/merge.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} - -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/null.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/null.js deleted file mode 100644 index 6874daa6471eca..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/null.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} - -function constructYamlNull() { - return null; -} - -function isNull(object) { - return object === null; -} - -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; } - }, - defaultStyle: 'lowercase' -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/omap.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/omap.js deleted file mode 100644 index b2b5323bd1cd9e..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/omap.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; - -function resolveYamlOmap(data) { - if (data === null) return true; - - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; -} - -function constructYamlOmap(data) { - return data !== null ? data : []; -} - -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/pairs.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/pairs.js deleted file mode 100644 index 74b52403fc125d..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/pairs.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -var _toString = Object.prototype.toString; - -function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return true; -} - -function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return result; -} - -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/seq.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/seq.js deleted file mode 100644 index be8f77f2844bdd..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/seq.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/set.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/set.js deleted file mode 100644 index f885a329c2ca0a..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/set.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; - - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } - } - - return true; -} - -function constructYamlSet(data) { - return data !== null ? data : {}; -} - -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/str.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/str.js deleted file mode 100644 index 27acc106caaf75..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/str.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/timestamp.js b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/timestamp.js deleted file mode 100644 index 8fa9c5865697ed..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/lib/js-yaml/type/timestamp.js +++ /dev/null @@ -1,88 +0,0 @@ -'use strict'; - -var Type = require('../type'); - -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} - -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; -} - -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} - -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/package.json b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/package.json deleted file mode 100644 index 0d2366762c5448..00000000000000 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/node_modules/js-yaml/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "js-yaml", - "version": "3.14.1", - "description": "YAML 1.2 parser and serializer", - "keywords": [ - "yaml", - "parser", - "serializer", - "pyyaml" - ], - "homepage": "https://github.com/nodeca/js-yaml", - "author": "Vladimir Zapparov ", - "contributors": [ - "Aleksey V Zapparov (http://www.ixti.net/)", - "Vitaly Puzrin (https://github.com/puzrin)", - "Martin Grenfell (http://got-ravings.blogspot.com)" - ], - "license": "MIT", - "repository": "nodeca/js-yaml", - "files": [ - "index.js", - "lib/", - "bin/", - "dist/" - ], - "bin": { - "js-yaml": "bin/js-yaml.js" - }, - "unpkg": "dist/js-yaml.min.js", - "jsdelivr": "dist/js-yaml.min.js", - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "devDependencies": { - "ansi": "^0.3.1", - "benchmark": "^2.1.4", - "browserify": "^16.2.2", - "codemirror": "^5.13.4", - "eslint": "^7.0.0", - "fast-check": "^1.24.2", - "istanbul": "^0.4.5", - "mocha": "^7.1.2", - "uglify-js": "^3.0.1" - }, - "scripts": { - "test": "make test" - } -} diff --git a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json index ae56ceeac196a3..e7a7e8f01af8cb 100644 --- a/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json +++ b/tools/node_modules/eslint/node_modules/@eslint/eslintrc/package.json @@ -1,6 +1,6 @@ { "name": "@eslint/eslintrc", - "version": "1.0.3", + "version": "1.0.4", "description": "The legacy ESLintRC config file format for ESLint", "type": "module", "main": "./dist/eslintrc.cjs", @@ -56,7 +56,7 @@ "eslint-config-eslint": "^7.0.0", "eslint-plugin-jsdoc": "^35.4.1", "eslint-plugin-node": "^11.1.0", - "eslint-release": "^3.1.2", + "eslint-release": "^3.2.0", "fs-teardown": "^0.1.3", "mocha": "^9.0.3", "rollup": "^2.54.0", @@ -71,7 +71,7 @@ "globals": "^13.9.0", "ignore": "^4.0.6", "import-fresh": "^3.2.1", - "js-yaml": "^3.13.1", + "js-yaml": "^4.1.0", "minimatch": "^3.0.4", "strip-json-comments": "^3.1.1" }, diff --git a/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/package.json b/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/package.json index ba829090e55bd4..9fc90bf3f9dd61 100644 --- a/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/package.json +++ b/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/package.json @@ -1,6 +1,6 @@ { "name": "@humanwhocodes/object-schema", - "version": "1.2.0", + "version": "1.2.1", "description": "An object schema merger/validator", "main": "src/index.js", "directories": { @@ -30,4 +30,4 @@ "eslint": "^5.13.0", "mocha": "^5.2.0" } -} \ No newline at end of file +} diff --git a/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/src/object-schema.js b/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/src/object-schema.js index 25864f5a280cbb..b663236539a668 100644 --- a/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/src/object-schema.js +++ b/tools/node_modules/eslint/node_modules/@humanwhocodes/object-schema/src/object-schema.js @@ -104,12 +104,8 @@ class ObjectSchema { const schema = new ObjectSchema(definitions[key].schema); definitions[key] = { ...definitions[key], - merge(first, second) { - if (first && second) { - return schema.merge(first, second); - } - - return MergeStrategy.assign(first, second); + merge(first = {}, second = {}) { + return schema.merge(first, second); }, validate(value) { ValidationStrategy.object(value); diff --git a/tools/node_modules/eslint/node_modules/esprima/LICENSE.BSD b/tools/node_modules/eslint/node_modules/esprima/LICENSE.BSD deleted file mode 100644 index 7a55160f562ddb..00000000000000 --- a/tools/node_modules/eslint/node_modules/esprima/LICENSE.BSD +++ /dev/null @@ -1,21 +0,0 @@ -Copyright JS Foundation and other contributors, https://js.foundation/ - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/node_modules/eslint/node_modules/esprima/README.md b/tools/node_modules/eslint/node_modules/esprima/README.md deleted file mode 100644 index 8fb25e6c1fa6a4..00000000000000 --- a/tools/node_modules/eslint/node_modules/esprima/README.md +++ /dev/null @@ -1,46 +0,0 @@ -[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) -[![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) -[![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) -[![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) - -**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, -standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) -parser written in ECMAScript (also popularly known as -[JavaScript](https://en.wikipedia.org/wiki/JavaScript)). -Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), -with the help of [many contributors](https://github.com/jquery/esprima/contributors). - -### Features - -- Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) -- Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) -- Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) -- Optional tracking of syntax node location (index-based and line-column) -- [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) - -### API - -Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. - -A simple example on Node.js REPL: - -```javascript -> var esprima = require('esprima'); -> var program = 'const answer = 42'; - -> esprima.tokenize(program); -[ { type: 'Keyword', value: 'const' }, - { type: 'Identifier', value: 'answer' }, - { type: 'Punctuator', value: '=' }, - { type: 'Numeric', value: '42' } ] - -> esprima.parseScript(program); -{ type: 'Program', - body: - [ { type: 'VariableDeclaration', - declarations: [Object], - kind: 'const' } ], - sourceType: 'script' } -``` - -For more information, please read the [complete documentation](http://esprima.org/doc). \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/esprima/bin/esparse.js b/tools/node_modules/eslint/node_modules/esprima/bin/esparse.js deleted file mode 100755 index 45d05fbb732673..00000000000000 --- a/tools/node_modules/eslint/node_modules/esprima/bin/esparse.js +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env node -/* - Copyright JS Foundation and other contributors, https://js.foundation/ - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/*jslint sloppy:true node:true rhino:true */ - -var fs, esprima, fname, forceFile, content, options, syntax; - -if (typeof require === 'function') { - fs = require('fs'); - try { - esprima = require('esprima'); - } catch (e) { - esprima = require('../'); - } -} else if (typeof load === 'function') { - try { - load('esprima.js'); - } catch (e) { - load('../esprima.js'); - } -} - -// Shims to Node.js objects when running under Rhino. -if (typeof console === 'undefined' && typeof process === 'undefined') { - console = { log: print }; - fs = { readFileSync: readFile }; - process = { argv: arguments, exit: quit }; - process.argv.unshift('esparse.js'); - process.argv.unshift('rhino'); -} - -function showUsage() { - console.log('Usage:'); - console.log(' esparse [options] [file.js]'); - console.log(); - console.log('Available options:'); - console.log(); - console.log(' --comment Gather all line and block comments in an array'); - console.log(' --loc Include line-column location info for each syntax node'); - console.log(' --range Include index-based range for each syntax node'); - console.log(' --raw Display the raw value of literals'); - console.log(' --tokens List all tokens in an array'); - console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); - console.log(' -v, --version Shows program version'); - console.log(); - process.exit(1); -} - -options = {}; - -process.argv.splice(2).forEach(function (entry) { - - if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { - if (typeof fname === 'string') { - console.log('Error: more than one input file.'); - process.exit(1); - } else { - fname = entry; - } - } else if (entry === '-h' || entry === '--help') { - showUsage(); - } else if (entry === '-v' || entry === '--version') { - console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); - console.log(); - process.exit(0); - } else if (entry === '--comment') { - options.comment = true; - } else if (entry === '--loc') { - options.loc = true; - } else if (entry === '--range') { - options.range = true; - } else if (entry === '--raw') { - options.raw = true; - } else if (entry === '--tokens') { - options.tokens = true; - } else if (entry === '--tolerant') { - options.tolerant = true; - } else if (entry === '--') { - forceFile = true; - } else { - console.log('Error: unknown option ' + entry + '.'); - process.exit(1); - } -}); - -// Special handling for regular expression literal since we need to -// convert it to a string literal, otherwise it will be decoded -// as object "{}" and the regular expression would be lost. -function adjustRegexLiteral(key, value) { - if (key === 'value' && value instanceof RegExp) { - value = value.toString(); - } - return value; -} - -function run(content) { - syntax = esprima.parse(content, options); - console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); -} - -try { - if (fname && (fname !== '-' || forceFile)) { - run(fs.readFileSync(fname, 'utf-8')); - } else { - var content = ''; - process.stdin.resume(); - process.stdin.on('data', function(chunk) { - content += chunk; - }); - process.stdin.on('end', function() { - run(content); - }); - } -} catch (e) { - console.log('Error: ' + e.message); - process.exit(1); -} diff --git a/tools/node_modules/eslint/node_modules/esprima/bin/esvalidate.js b/tools/node_modules/eslint/node_modules/esprima/bin/esvalidate.js deleted file mode 100755 index d49a7e40a8c3d4..00000000000000 --- a/tools/node_modules/eslint/node_modules/esprima/bin/esvalidate.js +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env node -/* - Copyright JS Foundation and other contributors, https://js.foundation/ - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/*jslint sloppy:true plusplus:true node:true rhino:true */ -/*global phantom:true */ - -var fs, system, esprima, options, fnames, forceFile, count; - -if (typeof esprima === 'undefined') { - // PhantomJS can only require() relative files - if (typeof phantom === 'object') { - fs = require('fs'); - system = require('system'); - esprima = require('./esprima'); - } else if (typeof require === 'function') { - fs = require('fs'); - try { - esprima = require('esprima'); - } catch (e) { - esprima = require('../'); - } - } else if (typeof load === 'function') { - try { - load('esprima.js'); - } catch (e) { - load('../esprima.js'); - } - } -} - -// Shims to Node.js objects when running under PhantomJS 1.7+. -if (typeof phantom === 'object') { - fs.readFileSync = fs.read; - process = { - argv: [].slice.call(system.args), - exit: phantom.exit, - on: function (evt, callback) { - callback(); - } - }; - process.argv.unshift('phantomjs'); -} - -// Shims to Node.js objects when running under Rhino. -if (typeof console === 'undefined' && typeof process === 'undefined') { - console = { log: print }; - fs = { readFileSync: readFile }; - process = { - argv: arguments, - exit: quit, - on: function (evt, callback) { - callback(); - } - }; - process.argv.unshift('esvalidate.js'); - process.argv.unshift('rhino'); -} - -function showUsage() { - console.log('Usage:'); - console.log(' esvalidate [options] [file.js...]'); - console.log(); - console.log('Available options:'); - console.log(); - console.log(' --format=type Set the report format, plain (default) or junit'); - console.log(' -v, --version Print program version'); - console.log(); - process.exit(1); -} - -options = { - format: 'plain' -}; - -fnames = []; - -process.argv.splice(2).forEach(function (entry) { - - if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { - fnames.push(entry); - } else if (entry === '-h' || entry === '--help') { - showUsage(); - } else if (entry === '-v' || entry === '--version') { - console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); - console.log(); - process.exit(0); - } else if (entry.slice(0, 9) === '--format=') { - options.format = entry.slice(9); - if (options.format !== 'plain' && options.format !== 'junit') { - console.log('Error: unknown report format ' + options.format + '.'); - process.exit(1); - } - } else if (entry === '--') { - forceFile = true; - } else { - console.log('Error: unknown option ' + entry + '.'); - process.exit(1); - } -}); - -if (fnames.length === 0) { - fnames.push(''); -} - -if (options.format === 'junit') { - console.log(''); - console.log(''); -} - -count = 0; - -function run(fname, content) { - var timestamp, syntax, name; - try { - if (typeof content !== 'string') { - throw content; - } - - if (content[0] === '#' && content[1] === '!') { - content = '//' + content.substr(2, content.length); - } - - timestamp = Date.now(); - syntax = esprima.parse(content, { tolerant: true }); - - if (options.format === 'junit') { - - name = fname; - if (name.lastIndexOf('/') >= 0) { - name = name.slice(name.lastIndexOf('/') + 1); - } - - console.log(''); - - syntax.errors.forEach(function (error) { - var msg = error.message; - msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); - console.log(' '); - console.log(' ' + - error.message + '(' + name + ':' + error.lineNumber + ')' + - ''); - console.log(' '); - }); - - console.log(''); - - } else if (options.format === 'plain') { - - syntax.errors.forEach(function (error) { - var msg = error.message; - msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); - msg = fname + ':' + error.lineNumber + ': ' + msg; - console.log(msg); - ++count; - }); - - } - } catch (e) { - ++count; - if (options.format === 'junit') { - console.log(''); - console.log(' '); - console.log(' ' + - e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + - ')'); - console.log(' '); - console.log(''); - } else { - console.log(fname + ':' + e.lineNumber + ': ' + e.message.replace(/^Line\ [0-9]*\:\ /, '')); - } - } -} - -fnames.forEach(function (fname) { - var content = ''; - try { - if (fname && (fname !== '-' || forceFile)) { - content = fs.readFileSync(fname, 'utf-8'); - } else { - fname = ''; - process.stdin.resume(); - process.stdin.on('data', function(chunk) { - content += chunk; - }); - process.stdin.on('end', function() { - run(fname, content); - }); - return; - } - } catch (e) { - content = e; - } - run(fname, content); -}); - -process.on('exit', function () { - if (options.format === 'junit') { - console.log(''); - } - - if (count > 0) { - process.exit(1); - } - - if (count === 0 && typeof phantom === 'object') { - process.exit(0); - } -}); diff --git a/tools/node_modules/eslint/node_modules/esprima/dist/esprima.js b/tools/node_modules/eslint/node_modules/esprima/dist/esprima.js deleted file mode 100644 index 2af3eee125b0cf..00000000000000 --- a/tools/node_modules/eslint/node_modules/esprima/dist/esprima.js +++ /dev/null @@ -1,6709 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { -/* istanbul ignore next */ - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); -/* istanbul ignore next */ - else if(typeof exports === 'object') - exports["esprima"] = factory(); - else - root["esprima"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/* istanbul ignore if */ -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - /* - Copyright JS Foundation and other contributors, https://js.foundation/ - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - Object.defineProperty(exports, "__esModule", { value: true }); - var comment_handler_1 = __webpack_require__(1); - var jsx_parser_1 = __webpack_require__(3); - var parser_1 = __webpack_require__(8); - var tokenizer_1 = __webpack_require__(15); - function parse(code, options, delegate) { - var commentHandler = null; - var proxyDelegate = function (node, metadata) { - if (delegate) { - delegate(node, metadata); - } - if (commentHandler) { - commentHandler.visit(node, metadata); - } - }; - var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; - var collectComment = false; - if (options) { - collectComment = (typeof options.comment === 'boolean' && options.comment); - var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); - if (collectComment || attachComment) { - commentHandler = new comment_handler_1.CommentHandler(); - commentHandler.attach = attachComment; - options.comment = true; - parserDelegate = proxyDelegate; - } - } - var isModule = false; - if (options && typeof options.sourceType === 'string') { - isModule = (options.sourceType === 'module'); - } - var parser; - if (options && typeof options.jsx === 'boolean' && options.jsx) { - parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); - } - else { - parser = new parser_1.Parser(code, options, parserDelegate); - } - var program = isModule ? parser.parseModule() : parser.parseScript(); - var ast = program; - if (collectComment && commentHandler) { - ast.comments = commentHandler.comments; - } - if (parser.config.tokens) { - ast.tokens = parser.tokens; - } - if (parser.config.tolerant) { - ast.errors = parser.errorHandler.errors; - } - return ast; - } - exports.parse = parse; - function parseModule(code, options, delegate) { - var parsingOptions = options || {}; - parsingOptions.sourceType = 'module'; - return parse(code, parsingOptions, delegate); - } - exports.parseModule = parseModule; - function parseScript(code, options, delegate) { - var parsingOptions = options || {}; - parsingOptions.sourceType = 'script'; - return parse(code, parsingOptions, delegate); - } - exports.parseScript = parseScript; - function tokenize(code, options, delegate) { - var tokenizer = new tokenizer_1.Tokenizer(code, options); - var tokens; - tokens = []; - try { - while (true) { - var token = tokenizer.getNextToken(); - if (!token) { - break; - } - if (delegate) { - token = delegate(token); - } - tokens.push(token); - } - } - catch (e) { - tokenizer.errorHandler.tolerate(e); - } - if (tokenizer.errorHandler.tolerant) { - tokens.errors = tokenizer.errors(); - } - return tokens; - } - exports.tokenize = tokenize; - var syntax_1 = __webpack_require__(2); - exports.Syntax = syntax_1.Syntax; - // Sync with *.json manifests. - exports.version = '4.0.1'; - - -/***/ }, -/* 1 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var syntax_1 = __webpack_require__(2); - var CommentHandler = (function () { - function CommentHandler() { - this.attach = false; - this.comments = []; - this.stack = []; - this.leading = []; - this.trailing = []; - } - CommentHandler.prototype.insertInnerComments = function (node, metadata) { - // innnerComments for properties empty block - // `function a() {/** comments **\/}` - if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { - var innerComments = []; - for (var i = this.leading.length - 1; i >= 0; --i) { - var entry = this.leading[i]; - if (metadata.end.offset >= entry.start) { - innerComments.unshift(entry.comment); - this.leading.splice(i, 1); - this.trailing.splice(i, 1); - } - } - if (innerComments.length) { - node.innerComments = innerComments; - } - } - }; - CommentHandler.prototype.findTrailingComments = function (metadata) { - var trailingComments = []; - if (this.trailing.length > 0) { - for (var i = this.trailing.length - 1; i >= 0; --i) { - var entry_1 = this.trailing[i]; - if (entry_1.start >= metadata.end.offset) { - trailingComments.unshift(entry_1.comment); - } - } - this.trailing.length = 0; - return trailingComments; - } - var entry = this.stack[this.stack.length - 1]; - if (entry && entry.node.trailingComments) { - var firstComment = entry.node.trailingComments[0]; - if (firstComment && firstComment.range[0] >= metadata.end.offset) { - trailingComments = entry.node.trailingComments; - delete entry.node.trailingComments; - } - } - return trailingComments; - }; - CommentHandler.prototype.findLeadingComments = function (metadata) { - var leadingComments = []; - var target; - while (this.stack.length > 0) { - var entry = this.stack[this.stack.length - 1]; - if (entry && entry.start >= metadata.start.offset) { - target = entry.node; - this.stack.pop(); - } - else { - break; - } - } - if (target) { - var count = target.leadingComments ? target.leadingComments.length : 0; - for (var i = count - 1; i >= 0; --i) { - var comment = target.leadingComments[i]; - if (comment.range[1] <= metadata.start.offset) { - leadingComments.unshift(comment); - target.leadingComments.splice(i, 1); - } - } - if (target.leadingComments && target.leadingComments.length === 0) { - delete target.leadingComments; - } - return leadingComments; - } - for (var i = this.leading.length - 1; i >= 0; --i) { - var entry = this.leading[i]; - if (entry.start <= metadata.start.offset) { - leadingComments.unshift(entry.comment); - this.leading.splice(i, 1); - } - } - return leadingComments; - }; - CommentHandler.prototype.visitNode = function (node, metadata) { - if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { - return; - } - this.insertInnerComments(node, metadata); - var trailingComments = this.findTrailingComments(metadata); - var leadingComments = this.findLeadingComments(metadata); - if (leadingComments.length > 0) { - node.leadingComments = leadingComments; - } - if (trailingComments.length > 0) { - node.trailingComments = trailingComments; - } - this.stack.push({ - node: node, - start: metadata.start.offset - }); - }; - CommentHandler.prototype.visitComment = function (node, metadata) { - var type = (node.type[0] === 'L') ? 'Line' : 'Block'; - var comment = { - type: type, - value: node.value - }; - if (node.range) { - comment.range = node.range; - } - if (node.loc) { - comment.loc = node.loc; - } - this.comments.push(comment); - if (this.attach) { - var entry = { - comment: { - type: type, - value: node.value, - range: [metadata.start.offset, metadata.end.offset] - }, - start: metadata.start.offset - }; - if (node.loc) { - entry.comment.loc = node.loc; - } - node.type = type; - this.leading.push(entry); - this.trailing.push(entry); - } - }; - CommentHandler.prototype.visit = function (node, metadata) { - if (node.type === 'LineComment') { - this.visitComment(node, metadata); - } - else if (node.type === 'BlockComment') { - this.visitComment(node, metadata); - } - else if (this.attach) { - this.visitNode(node, metadata); - } - }; - return CommentHandler; - }()); - exports.CommentHandler = CommentHandler; - - -/***/ }, -/* 2 */ -/***/ function(module, exports) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Syntax = { - AssignmentExpression: 'AssignmentExpression', - AssignmentPattern: 'AssignmentPattern', - ArrayExpression: 'ArrayExpression', - ArrayPattern: 'ArrayPattern', - ArrowFunctionExpression: 'ArrowFunctionExpression', - AwaitExpression: 'AwaitExpression', - BlockStatement: 'BlockStatement', - BinaryExpression: 'BinaryExpression', - BreakStatement: 'BreakStatement', - CallExpression: 'CallExpression', - CatchClause: 'CatchClause', - ClassBody: 'ClassBody', - ClassDeclaration: 'ClassDeclaration', - ClassExpression: 'ClassExpression', - ConditionalExpression: 'ConditionalExpression', - ContinueStatement: 'ContinueStatement', - DoWhileStatement: 'DoWhileStatement', - DebuggerStatement: 'DebuggerStatement', - EmptyStatement: 'EmptyStatement', - ExportAllDeclaration: 'ExportAllDeclaration', - ExportDefaultDeclaration: 'ExportDefaultDeclaration', - ExportNamedDeclaration: 'ExportNamedDeclaration', - ExportSpecifier: 'ExportSpecifier', - ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', - ForOfStatement: 'ForOfStatement', - ForInStatement: 'ForInStatement', - FunctionDeclaration: 'FunctionDeclaration', - FunctionExpression: 'FunctionExpression', - Identifier: 'Identifier', - IfStatement: 'IfStatement', - ImportDeclaration: 'ImportDeclaration', - ImportDefaultSpecifier: 'ImportDefaultSpecifier', - ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', - ImportSpecifier: 'ImportSpecifier', - Literal: 'Literal', - LabeledStatement: 'LabeledStatement', - LogicalExpression: 'LogicalExpression', - MemberExpression: 'MemberExpression', - MetaProperty: 'MetaProperty', - MethodDefinition: 'MethodDefinition', - NewExpression: 'NewExpression', - ObjectExpression: 'ObjectExpression', - ObjectPattern: 'ObjectPattern', - Program: 'Program', - Property: 'Property', - RestElement: 'RestElement', - ReturnStatement: 'ReturnStatement', - SequenceExpression: 'SequenceExpression', - SpreadElement: 'SpreadElement', - Super: 'Super', - SwitchCase: 'SwitchCase', - SwitchStatement: 'SwitchStatement', - TaggedTemplateExpression: 'TaggedTemplateExpression', - TemplateElement: 'TemplateElement', - TemplateLiteral: 'TemplateLiteral', - ThisExpression: 'ThisExpression', - ThrowStatement: 'ThrowStatement', - TryStatement: 'TryStatement', - UnaryExpression: 'UnaryExpression', - UpdateExpression: 'UpdateExpression', - VariableDeclaration: 'VariableDeclaration', - VariableDeclarator: 'VariableDeclarator', - WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement', - YieldExpression: 'YieldExpression' - }; - - -/***/ }, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; -/* istanbul ignore next */ - var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - Object.defineProperty(exports, "__esModule", { value: true }); - var character_1 = __webpack_require__(4); - var JSXNode = __webpack_require__(5); - var jsx_syntax_1 = __webpack_require__(6); - var Node = __webpack_require__(7); - var parser_1 = __webpack_require__(8); - var token_1 = __webpack_require__(13); - var xhtml_entities_1 = __webpack_require__(14); - token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; - token_1.TokenName[101 /* Text */] = 'JSXText'; - // Fully qualified element name, e.g. returns "svg:path" - function getQualifiedElementName(elementName) { - var qualifiedName; - switch (elementName.type) { - case jsx_syntax_1.JSXSyntax.JSXIdentifier: - var id = elementName; - qualifiedName = id.name; - break; - case jsx_syntax_1.JSXSyntax.JSXNamespacedName: - var ns = elementName; - qualifiedName = getQualifiedElementName(ns.namespace) + ':' + - getQualifiedElementName(ns.name); - break; - case jsx_syntax_1.JSXSyntax.JSXMemberExpression: - var expr = elementName; - qualifiedName = getQualifiedElementName(expr.object) + '.' + - getQualifiedElementName(expr.property); - break; - /* istanbul ignore next */ - default: - break; - } - return qualifiedName; - } - var JSXParser = (function (_super) { - __extends(JSXParser, _super); - function JSXParser(code, options, delegate) { - return _super.call(this, code, options, delegate) || this; - } - JSXParser.prototype.parsePrimaryExpression = function () { - return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); - }; - JSXParser.prototype.startJSX = function () { - // Unwind the scanner before the lookahead token. - this.scanner.index = this.startMarker.index; - this.scanner.lineNumber = this.startMarker.line; - this.scanner.lineStart = this.startMarker.index - this.startMarker.column; - }; - JSXParser.prototype.finishJSX = function () { - // Prime the next lookahead. - this.nextToken(); - }; - JSXParser.prototype.reenterJSX = function () { - this.startJSX(); - this.expectJSX('}'); - // Pop the closing '}' added from the lookahead. - if (this.config.tokens) { - this.tokens.pop(); - } - }; - JSXParser.prototype.createJSXNode = function () { - this.collectComments(); - return { - index: this.scanner.index, - line: this.scanner.lineNumber, - column: this.scanner.index - this.scanner.lineStart - }; - }; - JSXParser.prototype.createJSXChildNode = function () { - return { - index: this.scanner.index, - line: this.scanner.lineNumber, - column: this.scanner.index - this.scanner.lineStart - }; - }; - JSXParser.prototype.scanXHTMLEntity = function (quote) { - var result = '&'; - var valid = true; - var terminated = false; - var numeric = false; - var hex = false; - while (!this.scanner.eof() && valid && !terminated) { - var ch = this.scanner.source[this.scanner.index]; - if (ch === quote) { - break; - } - terminated = (ch === ';'); - result += ch; - ++this.scanner.index; - if (!terminated) { - switch (result.length) { - case 2: - // e.g. '{' - numeric = (ch === '#'); - break; - case 3: - if (numeric) { - // e.g. 'A' - hex = (ch === 'x'); - valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); - numeric = numeric && !hex; - } - break; - default: - valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); - valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); - break; - } - } - } - if (valid && terminated && result.length > 2) { - // e.g. 'A' becomes just '#x41' - var str = result.substr(1, result.length - 2); - if (numeric && str.length > 1) { - result = String.fromCharCode(parseInt(str.substr(1), 10)); - } - else if (hex && str.length > 2) { - result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); - } - else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { - result = xhtml_entities_1.XHTMLEntities[str]; - } - } - return result; - }; - // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. - JSXParser.prototype.lexJSX = function () { - var cp = this.scanner.source.charCodeAt(this.scanner.index); - // < > / : = { } - if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { - var value = this.scanner.source[this.scanner.index++]; - return { - type: 7 /* Punctuator */, - value: value, - lineNumber: this.scanner.lineNumber, - lineStart: this.scanner.lineStart, - start: this.scanner.index - 1, - end: this.scanner.index - }; - } - // " ' - if (cp === 34 || cp === 39) { - var start = this.scanner.index; - var quote = this.scanner.source[this.scanner.index++]; - var str = ''; - while (!this.scanner.eof()) { - var ch = this.scanner.source[this.scanner.index++]; - if (ch === quote) { - break; - } - else if (ch === '&') { - str += this.scanXHTMLEntity(quote); - } - else { - str += ch; - } - } - return { - type: 8 /* StringLiteral */, - value: str, - lineNumber: this.scanner.lineNumber, - lineStart: this.scanner.lineStart, - start: start, - end: this.scanner.index - }; - } - // ... or . - if (cp === 46) { - var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); - var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); - var value = (n1 === 46 && n2 === 46) ? '...' : '.'; - var start = this.scanner.index; - this.scanner.index += value.length; - return { - type: 7 /* Punctuator */, - value: value, - lineNumber: this.scanner.lineNumber, - lineStart: this.scanner.lineStart, - start: start, - end: this.scanner.index - }; - } - // ` - if (cp === 96) { - // Only placeholder, since it will be rescanned as a real assignment expression. - return { - type: 10 /* Template */, - value: '', - lineNumber: this.scanner.lineNumber, - lineStart: this.scanner.lineStart, - start: this.scanner.index, - end: this.scanner.index - }; - } - // Identifer can not contain backslash (char code 92). - if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { - var start = this.scanner.index; - ++this.scanner.index; - while (!this.scanner.eof()) { - var ch = this.scanner.source.charCodeAt(this.scanner.index); - if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { - ++this.scanner.index; - } - else if (ch === 45) { - // Hyphen (char code 45) can be part of an identifier. - ++this.scanner.index; - } - else { - break; - } - } - var id = this.scanner.source.slice(start, this.scanner.index); - return { - type: 100 /* Identifier */, - value: id, - lineNumber: this.scanner.lineNumber, - lineStart: this.scanner.lineStart, - start: start, - end: this.scanner.index - }; - } - return this.scanner.lex(); - }; - JSXParser.prototype.nextJSXToken = function () { - this.collectComments(); - this.startMarker.index = this.scanner.index; - this.startMarker.line = this.scanner.lineNumber; - this.startMarker.column = this.scanner.index - this.scanner.lineStart; - var token = this.lexJSX(); - this.lastMarker.index = this.scanner.index; - this.lastMarker.line = this.scanner.lineNumber; - this.lastMarker.column = this.scanner.index - this.scanner.lineStart; - if (this.config.tokens) { - this.tokens.push(this.convertToken(token)); - } - return token; - }; - JSXParser.prototype.nextJSXText = function () { - this.startMarker.index = this.scanner.index; - this.startMarker.line = this.scanner.lineNumber; - this.startMarker.column = this.scanner.index - this.scanner.lineStart; - var start = this.scanner.index; - var text = ''; - while (!this.scanner.eof()) { - var ch = this.scanner.source[this.scanner.index]; - if (ch === '{' || ch === '<') { - break; - } - ++this.scanner.index; - text += ch; - if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { - ++this.scanner.lineNumber; - if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { - ++this.scanner.index; - } - this.scanner.lineStart = this.scanner.index; - } - } - this.lastMarker.index = this.scanner.index; - this.lastMarker.line = this.scanner.lineNumber; - this.lastMarker.column = this.scanner.index - this.scanner.lineStart; - var token = { - type: 101 /* Text */, - value: text, - lineNumber: this.scanner.lineNumber, - lineStart: this.scanner.lineStart, - start: start, - end: this.scanner.index - }; - if ((text.length > 0) && this.config.tokens) { - this.tokens.push(this.convertToken(token)); - } - return token; - }; - JSXParser.prototype.peekJSXToken = function () { - var state = this.scanner.saveState(); - this.scanner.scanComments(); - var next = this.lexJSX(); - this.scanner.restoreState(state); - return next; - }; - // Expect the next JSX token to match the specified punctuator. - // If not, an exception will be thrown. - JSXParser.prototype.expectJSX = function (value) { - var token = this.nextJSXToken(); - if (token.type !== 7 /* Punctuator */ || token.value !== value) { - this.throwUnexpectedToken(token); - } - }; - // Return true if the next JSX token matches the specified punctuator. - JSXParser.prototype.matchJSX = function (value) { - var next = this.peekJSXToken(); - return next.type === 7 /* Punctuator */ && next.value === value; - }; - JSXParser.prototype.parseJSXIdentifier = function () { - var node = this.createJSXNode(); - var token = this.nextJSXToken(); - if (token.type !== 100 /* Identifier */) { - this.throwUnexpectedToken(token); - } - return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); - }; - JSXParser.prototype.parseJSXElementName = function () { - var node = this.createJSXNode(); - var elementName = this.parseJSXIdentifier(); - if (this.matchJSX(':')) { - var namespace = elementName; - this.expectJSX(':'); - var name_1 = this.parseJSXIdentifier(); - elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); - } - else if (this.matchJSX('.')) { - while (this.matchJSX('.')) { - var object = elementName; - this.expectJSX('.'); - var property = this.parseJSXIdentifier(); - elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); - } - } - return elementName; - }; - JSXParser.prototype.parseJSXAttributeName = function () { - var node = this.createJSXNode(); - var attributeName; - var identifier = this.parseJSXIdentifier(); - if (this.matchJSX(':')) { - var namespace = identifier; - this.expectJSX(':'); - var name_2 = this.parseJSXIdentifier(); - attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); - } - else { - attributeName = identifier; - } - return attributeName; - }; - JSXParser.prototype.parseJSXStringLiteralAttribute = function () { - var node = this.createJSXNode(); - var token = this.nextJSXToken(); - if (token.type !== 8 /* StringLiteral */) { - this.throwUnexpectedToken(token); - } - var raw = this.getTokenRaw(token); - return this.finalize(node, new Node.Literal(token.value, raw)); - }; - JSXParser.prototype.parseJSXExpressionAttribute = function () { - var node = this.createJSXNode(); - this.expectJSX('{'); - this.finishJSX(); - if (this.match('}')) { - this.tolerateError('JSX attributes must only be assigned a non-empty expression'); - } - var expression = this.parseAssignmentExpression(); - this.reenterJSX(); - return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); - }; - JSXParser.prototype.parseJSXAttributeValue = function () { - return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : - this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); - }; - JSXParser.prototype.parseJSXNameValueAttribute = function () { - var node = this.createJSXNode(); - var name = this.parseJSXAttributeName(); - var value = null; - if (this.matchJSX('=')) { - this.expectJSX('='); - value = this.parseJSXAttributeValue(); - } - return this.finalize(node, new JSXNode.JSXAttribute(name, value)); - }; - JSXParser.prototype.parseJSXSpreadAttribute = function () { - var node = this.createJSXNode(); - this.expectJSX('{'); - this.expectJSX('...'); - this.finishJSX(); - var argument = this.parseAssignmentExpression(); - this.reenterJSX(); - return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); - }; - JSXParser.prototype.parseJSXAttributes = function () { - var attributes = []; - while (!this.matchJSX('/') && !this.matchJSX('>')) { - var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : - this.parseJSXNameValueAttribute(); - attributes.push(attribute); - } - return attributes; - }; - JSXParser.prototype.parseJSXOpeningElement = function () { - var node = this.createJSXNode(); - this.expectJSX('<'); - var name = this.parseJSXElementName(); - var attributes = this.parseJSXAttributes(); - var selfClosing = this.matchJSX('/'); - if (selfClosing) { - this.expectJSX('/'); - } - this.expectJSX('>'); - return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); - }; - JSXParser.prototype.parseJSXBoundaryElement = function () { - var node = this.createJSXNode(); - this.expectJSX('<'); - if (this.matchJSX('/')) { - this.expectJSX('/'); - var name_3 = this.parseJSXElementName(); - this.expectJSX('>'); - return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); - } - var name = this.parseJSXElementName(); - var attributes = this.parseJSXAttributes(); - var selfClosing = this.matchJSX('/'); - if (selfClosing) { - this.expectJSX('/'); - } - this.expectJSX('>'); - return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); - }; - JSXParser.prototype.parseJSXEmptyExpression = function () { - var node = this.createJSXChildNode(); - this.collectComments(); - this.lastMarker.index = this.scanner.index; - this.lastMarker.line = this.scanner.lineNumber; - this.lastMarker.column = this.scanner.index - this.scanner.lineStart; - return this.finalize(node, new JSXNode.JSXEmptyExpression()); - }; - JSXParser.prototype.parseJSXExpressionContainer = function () { - var node = this.createJSXNode(); - this.expectJSX('{'); - var expression; - if (this.matchJSX('}')) { - expression = this.parseJSXEmptyExpression(); - this.expectJSX('}'); - } - else { - this.finishJSX(); - expression = this.parseAssignmentExpression(); - this.reenterJSX(); - } - return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); - }; - JSXParser.prototype.parseJSXChildren = function () { - var children = []; - while (!this.scanner.eof()) { - var node = this.createJSXChildNode(); - var token = this.nextJSXText(); - if (token.start < token.end) { - var raw = this.getTokenRaw(token); - var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); - children.push(child); - } - if (this.scanner.source[this.scanner.index] === '{') { - var container = this.parseJSXExpressionContainer(); - children.push(container); - } - else { - break; - } - } - return children; - }; - JSXParser.prototype.parseComplexJSXElement = function (el) { - var stack = []; - while (!this.scanner.eof()) { - el.children = el.children.concat(this.parseJSXChildren()); - var node = this.createJSXChildNode(); - var element = this.parseJSXBoundaryElement(); - if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { - var opening = element; - if (opening.selfClosing) { - var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); - el.children.push(child); - } - else { - stack.push(el); - el = { node: node, opening: opening, closing: null, children: [] }; - } - } - if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { - el.closing = element; - var open_1 = getQualifiedElementName(el.opening.name); - var close_1 = getQualifiedElementName(el.closing.name); - if (open_1 !== close_1) { - this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); - } - if (stack.length > 0) { - var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); - el = stack[stack.length - 1]; - el.children.push(child); - stack.pop(); - } - else { - break; - } - } - } - return el; - }; - JSXParser.prototype.parseJSXElement = function () { - var node = this.createJSXNode(); - var opening = this.parseJSXOpeningElement(); - var children = []; - var closing = null; - if (!opening.selfClosing) { - var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); - children = el.children; - closing = el.closing; - } - return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); - }; - JSXParser.prototype.parseJSXRoot = function () { - // Pop the opening '<' added from the lookahead. - if (this.config.tokens) { - this.tokens.pop(); - } - this.startJSX(); - var element = this.parseJSXElement(); - this.finishJSX(); - return element; - }; - JSXParser.prototype.isStartOfExpression = function () { - return _super.prototype.isStartOfExpression.call(this) || this.match('<'); - }; - return JSXParser; - }(parser_1.Parser)); - exports.JSXParser = JSXParser; - - -/***/ }, -/* 4 */ -/***/ function(module, exports) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - // See also tools/generate-unicode-regex.js. - var Regex = { - // Unicode v8.0.0 NonAsciiIdentifierStart: - NonAsciiIdentifierStart: /[\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\u08A0-\u08B4\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\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\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\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-\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\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\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\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\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\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[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\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]|\uD82C[\uDC00\uDC01]|\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]|\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]|\uD87E[\uDC00-\uDE1D]/, - // Unicode v8.0.0 NonAsciiIdentifierPart: - NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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\u08A0-\u08B4\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\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\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\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\u1369-\u1371\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-\u19DA\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\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\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[\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\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\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\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\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]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ - }; - exports.Character = { - /* tslint:disable:no-bitwise */ - fromCodePoint: function (cp) { - return (cp < 0x10000) ? String.fromCharCode(cp) : - String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + - String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); - }, - // https://tc39.github.io/ecma262/#sec-white-space - isWhiteSpace: function (cp) { - return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || - (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); - }, - // https://tc39.github.io/ecma262/#sec-line-terminators - isLineTerminator: function (cp) { - return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); - }, - // https://tc39.github.io/ecma262/#sec-names-and-keywords - isIdentifierStart: function (cp) { - return (cp === 0x24) || (cp === 0x5F) || - (cp >= 0x41 && cp <= 0x5A) || - (cp >= 0x61 && cp <= 0x7A) || - (cp === 0x5C) || - ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); - }, - isIdentifierPart: function (cp) { - return (cp === 0x24) || (cp === 0x5F) || - (cp >= 0x41 && cp <= 0x5A) || - (cp >= 0x61 && cp <= 0x7A) || - (cp >= 0x30 && cp <= 0x39) || - (cp === 0x5C) || - ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); - }, - // https://tc39.github.io/ecma262/#sec-literals-numeric-literals - isDecimalDigit: function (cp) { - return (cp >= 0x30 && cp <= 0x39); // 0..9 - }, - isHexDigit: function (cp) { - return (cp >= 0x30 && cp <= 0x39) || - (cp >= 0x41 && cp <= 0x46) || - (cp >= 0x61 && cp <= 0x66); // a..f - }, - isOctalDigit: function (cp) { - return (cp >= 0x30 && cp <= 0x37); // 0..7 - } - }; - - -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var jsx_syntax_1 = __webpack_require__(6); - /* tslint:disable:max-classes-per-file */ - var JSXClosingElement = (function () { - function JSXClosingElement(name) { - this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; - this.name = name; - } - return JSXClosingElement; - }()); - exports.JSXClosingElement = JSXClosingElement; - var JSXElement = (function () { - function JSXElement(openingElement, children, closingElement) { - this.type = jsx_syntax_1.JSXSyntax.JSXElement; - this.openingElement = openingElement; - this.children = children; - this.closingElement = closingElement; - } - return JSXElement; - }()); - exports.JSXElement = JSXElement; - var JSXEmptyExpression = (function () { - function JSXEmptyExpression() { - this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; - } - return JSXEmptyExpression; - }()); - exports.JSXEmptyExpression = JSXEmptyExpression; - var JSXExpressionContainer = (function () { - function JSXExpressionContainer(expression) { - this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; - this.expression = expression; - } - return JSXExpressionContainer; - }()); - exports.JSXExpressionContainer = JSXExpressionContainer; - var JSXIdentifier = (function () { - function JSXIdentifier(name) { - this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; - this.name = name; - } - return JSXIdentifier; - }()); - exports.JSXIdentifier = JSXIdentifier; - var JSXMemberExpression = (function () { - function JSXMemberExpression(object, property) { - this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; - this.object = object; - this.property = property; - } - return JSXMemberExpression; - }()); - exports.JSXMemberExpression = JSXMemberExpression; - var JSXAttribute = (function () { - function JSXAttribute(name, value) { - this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; - this.name = name; - this.value = value; - } - return JSXAttribute; - }()); - exports.JSXAttribute = JSXAttribute; - var JSXNamespacedName = (function () { - function JSXNamespacedName(namespace, name) { - this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; - this.namespace = namespace; - this.name = name; - } - return JSXNamespacedName; - }()); - exports.JSXNamespacedName = JSXNamespacedName; - var JSXOpeningElement = (function () { - function JSXOpeningElement(name, selfClosing, attributes) { - this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; - this.name = name; - this.selfClosing = selfClosing; - this.attributes = attributes; - } - return JSXOpeningElement; - }()); - exports.JSXOpeningElement = JSXOpeningElement; - var JSXSpreadAttribute = (function () { - function JSXSpreadAttribute(argument) { - this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; - this.argument = argument; - } - return JSXSpreadAttribute; - }()); - exports.JSXSpreadAttribute = JSXSpreadAttribute; - var JSXText = (function () { - function JSXText(value, raw) { - this.type = jsx_syntax_1.JSXSyntax.JSXText; - this.value = value; - this.raw = raw; - } - return JSXText; - }()); - exports.JSXText = JSXText; - - -/***/ }, -/* 6 */ -/***/ function(module, exports) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.JSXSyntax = { - JSXAttribute: 'JSXAttribute', - JSXClosingElement: 'JSXClosingElement', - JSXElement: 'JSXElement', - JSXEmptyExpression: 'JSXEmptyExpression', - JSXExpressionContainer: 'JSXExpressionContainer', - JSXIdentifier: 'JSXIdentifier', - JSXMemberExpression: 'JSXMemberExpression', - JSXNamespacedName: 'JSXNamespacedName', - JSXOpeningElement: 'JSXOpeningElement', - JSXSpreadAttribute: 'JSXSpreadAttribute', - JSXText: 'JSXText' - }; - - -/***/ }, -/* 7 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var syntax_1 = __webpack_require__(2); - /* tslint:disable:max-classes-per-file */ - var ArrayExpression = (function () { - function ArrayExpression(elements) { - this.type = syntax_1.Syntax.ArrayExpression; - this.elements = elements; - } - return ArrayExpression; - }()); - exports.ArrayExpression = ArrayExpression; - var ArrayPattern = (function () { - function ArrayPattern(elements) { - this.type = syntax_1.Syntax.ArrayPattern; - this.elements = elements; - } - return ArrayPattern; - }()); - exports.ArrayPattern = ArrayPattern; - var ArrowFunctionExpression = (function () { - function ArrowFunctionExpression(params, body, expression) { - this.type = syntax_1.Syntax.ArrowFunctionExpression; - this.id = null; - this.params = params; - this.body = body; - this.generator = false; - this.expression = expression; - this.async = false; - } - return ArrowFunctionExpression; - }()); - exports.ArrowFunctionExpression = ArrowFunctionExpression; - var AssignmentExpression = (function () { - function AssignmentExpression(operator, left, right) { - this.type = syntax_1.Syntax.AssignmentExpression; - this.operator = operator; - this.left = left; - this.right = right; - } - return AssignmentExpression; - }()); - exports.AssignmentExpression = AssignmentExpression; - var AssignmentPattern = (function () { - function AssignmentPattern(left, right) { - this.type = syntax_1.Syntax.AssignmentPattern; - this.left = left; - this.right = right; - } - return AssignmentPattern; - }()); - exports.AssignmentPattern = AssignmentPattern; - var AsyncArrowFunctionExpression = (function () { - function AsyncArrowFunctionExpression(params, body, expression) { - this.type = syntax_1.Syntax.ArrowFunctionExpression; - this.id = null; - this.params = params; - this.body = body; - this.generator = false; - this.expression = expression; - this.async = true; - } - return AsyncArrowFunctionExpression; - }()); - exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; - var AsyncFunctionDeclaration = (function () { - function AsyncFunctionDeclaration(id, params, body) { - this.type = syntax_1.Syntax.FunctionDeclaration; - this.id = id; - this.params = params; - this.body = body; - this.generator = false; - this.expression = false; - this.async = true; - } - return AsyncFunctionDeclaration; - }()); - exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; - var AsyncFunctionExpression = (function () { - function AsyncFunctionExpression(id, params, body) { - this.type = syntax_1.Syntax.FunctionExpression; - this.id = id; - this.params = params; - this.body = body; - this.generator = false; - this.expression = false; - this.async = true; - } - return AsyncFunctionExpression; - }()); - exports.AsyncFunctionExpression = AsyncFunctionExpression; - var AwaitExpression = (function () { - function AwaitExpression(argument) { - this.type = syntax_1.Syntax.AwaitExpression; - this.argument = argument; - } - return AwaitExpression; - }()); - exports.AwaitExpression = AwaitExpression; - var BinaryExpression = (function () { - function BinaryExpression(operator, left, right) { - var logical = (operator === '||' || operator === '&&'); - this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; - this.operator = operator; - this.left = left; - this.right = right; - } - return BinaryExpression; - }()); - exports.BinaryExpression = BinaryExpression; - var BlockStatement = (function () { - function BlockStatement(body) { - this.type = syntax_1.Syntax.BlockStatement; - this.body = body; - } - return BlockStatement; - }()); - exports.BlockStatement = BlockStatement; - var BreakStatement = (function () { - function BreakStatement(label) { - this.type = syntax_1.Syntax.BreakStatement; - this.label = label; - } - return BreakStatement; - }()); - exports.BreakStatement = BreakStatement; - var CallExpression = (function () { - function CallExpression(callee, args) { - this.type = syntax_1.Syntax.CallExpression; - this.callee = callee; - this.arguments = args; - } - return CallExpression; - }()); - exports.CallExpression = CallExpression; - var CatchClause = (function () { - function CatchClause(param, body) { - this.type = syntax_1.Syntax.CatchClause; - this.param = param; - this.body = body; - } - return CatchClause; - }()); - exports.CatchClause = CatchClause; - var ClassBody = (function () { - function ClassBody(body) { - this.type = syntax_1.Syntax.ClassBody; - this.body = body; - } - return ClassBody; - }()); - exports.ClassBody = ClassBody; - var ClassDeclaration = (function () { - function ClassDeclaration(id, superClass, body) { - this.type = syntax_1.Syntax.ClassDeclaration; - this.id = id; - this.superClass = superClass; - this.body = body; - } - return ClassDeclaration; - }()); - exports.ClassDeclaration = ClassDeclaration; - var ClassExpression = (function () { - function ClassExpression(id, superClass, body) { - this.type = syntax_1.Syntax.ClassExpression; - this.id = id; - this.superClass = superClass; - this.body = body; - } - return ClassExpression; - }()); - exports.ClassExpression = ClassExpression; - var ComputedMemberExpression = (function () { - function ComputedMemberExpression(object, property) { - this.type = syntax_1.Syntax.MemberExpression; - this.computed = true; - this.object = object; - this.property = property; - } - return ComputedMemberExpression; - }()); - exports.ComputedMemberExpression = ComputedMemberExpression; - var ConditionalExpression = (function () { - function ConditionalExpression(test, consequent, alternate) { - this.type = syntax_1.Syntax.ConditionalExpression; - this.test = test; - this.consequent = consequent; - this.alternate = alternate; - } - return ConditionalExpression; - }()); - exports.ConditionalExpression = ConditionalExpression; - var ContinueStatement = (function () { - function ContinueStatement(label) { - this.type = syntax_1.Syntax.ContinueStatement; - this.label = label; - } - return ContinueStatement; - }()); - exports.ContinueStatement = ContinueStatement; - var DebuggerStatement = (function () { - function DebuggerStatement() { - this.type = syntax_1.Syntax.DebuggerStatement; - } - return DebuggerStatement; - }()); - exports.DebuggerStatement = DebuggerStatement; - var Directive = (function () { - function Directive(expression, directive) { - this.type = syntax_1.Syntax.ExpressionStatement; - this.expression = expression; - this.directive = directive; - } - return Directive; - }()); - exports.Directive = Directive; - var DoWhileStatement = (function () { - function DoWhileStatement(body, test) { - this.type = syntax_1.Syntax.DoWhileStatement; - this.body = body; - this.test = test; - } - return DoWhileStatement; - }()); - exports.DoWhileStatement = DoWhileStatement; - var EmptyStatement = (function () { - function EmptyStatement() { - this.type = syntax_1.Syntax.EmptyStatement; - } - return EmptyStatement; - }()); - exports.EmptyStatement = EmptyStatement; - var ExportAllDeclaration = (function () { - function ExportAllDeclaration(source) { - this.type = syntax_1.Syntax.ExportAllDeclaration; - this.source = source; - } - return ExportAllDeclaration; - }()); - exports.ExportAllDeclaration = ExportAllDeclaration; - var ExportDefaultDeclaration = (function () { - function ExportDefaultDeclaration(declaration) { - this.type = syntax_1.Syntax.ExportDefaultDeclaration; - this.declaration = declaration; - } - return ExportDefaultDeclaration; - }()); - exports.ExportDefaultDeclaration = ExportDefaultDeclaration; - var ExportNamedDeclaration = (function () { - function ExportNamedDeclaration(declaration, specifiers, source) { - this.type = syntax_1.Syntax.ExportNamedDeclaration; - this.declaration = declaration; - this.specifiers = specifiers; - this.source = source; - } - return ExportNamedDeclaration; - }()); - exports.ExportNamedDeclaration = ExportNamedDeclaration; - var ExportSpecifier = (function () { - function ExportSpecifier(local, exported) { - this.type = syntax_1.Syntax.ExportSpecifier; - this.exported = exported; - this.local = local; - } - return ExportSpecifier; - }()); - exports.ExportSpecifier = ExportSpecifier; - var ExpressionStatement = (function () { - function ExpressionStatement(expression) { - this.type = syntax_1.Syntax.ExpressionStatement; - this.expression = expression; - } - return ExpressionStatement; - }()); - exports.ExpressionStatement = ExpressionStatement; - var ForInStatement = (function () { - function ForInStatement(left, right, body) { - this.type = syntax_1.Syntax.ForInStatement; - this.left = left; - this.right = right; - this.body = body; - this.each = false; - } - return ForInStatement; - }()); - exports.ForInStatement = ForInStatement; - var ForOfStatement = (function () { - function ForOfStatement(left, right, body) { - this.type = syntax_1.Syntax.ForOfStatement; - this.left = left; - this.right = right; - this.body = body; - } - return ForOfStatement; - }()); - exports.ForOfStatement = ForOfStatement; - var ForStatement = (function () { - function ForStatement(init, test, update, body) { - this.type = syntax_1.Syntax.ForStatement; - this.init = init; - this.test = test; - this.update = update; - this.body = body; - } - return ForStatement; - }()); - exports.ForStatement = ForStatement; - var FunctionDeclaration = (function () { - function FunctionDeclaration(id, params, body, generator) { - this.type = syntax_1.Syntax.FunctionDeclaration; - this.id = id; - this.params = params; - this.body = body; - this.generator = generator; - this.expression = false; - this.async = false; - } - return FunctionDeclaration; - }()); - exports.FunctionDeclaration = FunctionDeclaration; - var FunctionExpression = (function () { - function FunctionExpression(id, params, body, generator) { - this.type = syntax_1.Syntax.FunctionExpression; - this.id = id; - this.params = params; - this.body = body; - this.generator = generator; - this.expression = false; - this.async = false; - } - return FunctionExpression; - }()); - exports.FunctionExpression = FunctionExpression; - var Identifier = (function () { - function Identifier(name) { - this.type = syntax_1.Syntax.Identifier; - this.name = name; - } - return Identifier; - }()); - exports.Identifier = Identifier; - var IfStatement = (function () { - function IfStatement(test, consequent, alternate) { - this.type = syntax_1.Syntax.IfStatement; - this.test = test; - this.consequent = consequent; - this.alternate = alternate; - } - return IfStatement; - }()); - exports.IfStatement = IfStatement; - var ImportDeclaration = (function () { - function ImportDeclaration(specifiers, source) { - this.type = syntax_1.Syntax.ImportDeclaration; - this.specifiers = specifiers; - this.source = source; - } - return ImportDeclaration; - }()); - exports.ImportDeclaration = ImportDeclaration; - var ImportDefaultSpecifier = (function () { - function ImportDefaultSpecifier(local) { - this.type = syntax_1.Syntax.ImportDefaultSpecifier; - this.local = local; - } - return ImportDefaultSpecifier; - }()); - exports.ImportDefaultSpecifier = ImportDefaultSpecifier; - var ImportNamespaceSpecifier = (function () { - function ImportNamespaceSpecifier(local) { - this.type = syntax_1.Syntax.ImportNamespaceSpecifier; - this.local = local; - } - return ImportNamespaceSpecifier; - }()); - exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; - var ImportSpecifier = (function () { - function ImportSpecifier(local, imported) { - this.type = syntax_1.Syntax.ImportSpecifier; - this.local = local; - this.imported = imported; - } - return ImportSpecifier; - }()); - exports.ImportSpecifier = ImportSpecifier; - var LabeledStatement = (function () { - function LabeledStatement(label, body) { - this.type = syntax_1.Syntax.LabeledStatement; - this.label = label; - this.body = body; - } - return LabeledStatement; - }()); - exports.LabeledStatement = LabeledStatement; - var Literal = (function () { - function Literal(value, raw) { - this.type = syntax_1.Syntax.Literal; - this.value = value; - this.raw = raw; - } - return Literal; - }()); - exports.Literal = Literal; - var MetaProperty = (function () { - function MetaProperty(meta, property) { - this.type = syntax_1.Syntax.MetaProperty; - this.meta = meta; - this.property = property; - } - return MetaProperty; - }()); - exports.MetaProperty = MetaProperty; - var MethodDefinition = (function () { - function MethodDefinition(key, computed, value, kind, isStatic) { - this.type = syntax_1.Syntax.MethodDefinition; - this.key = key; - this.computed = computed; - this.value = value; - this.kind = kind; - this.static = isStatic; - } - return MethodDefinition; - }()); - exports.MethodDefinition = MethodDefinition; - var Module = (function () { - function Module(body) { - this.type = syntax_1.Syntax.Program; - this.body = body; - this.sourceType = 'module'; - } - return Module; - }()); - exports.Module = Module; - var NewExpression = (function () { - function NewExpression(callee, args) { - this.type = syntax_1.Syntax.NewExpression; - this.callee = callee; - this.arguments = args; - } - return NewExpression; - }()); - exports.NewExpression = NewExpression; - var ObjectExpression = (function () { - function ObjectExpression(properties) { - this.type = syntax_1.Syntax.ObjectExpression; - this.properties = properties; - } - return ObjectExpression; - }()); - exports.ObjectExpression = ObjectExpression; - var ObjectPattern = (function () { - function ObjectPattern(properties) { - this.type = syntax_1.Syntax.ObjectPattern; - this.properties = properties; - } - return ObjectPattern; - }()); - exports.ObjectPattern = ObjectPattern; - var Property = (function () { - function Property(kind, key, computed, value, method, shorthand) { - this.type = syntax_1.Syntax.Property; - this.key = key; - this.computed = computed; - this.value = value; - this.kind = kind; - this.method = method; - this.shorthand = shorthand; - } - return Property; - }()); - exports.Property = Property; - var RegexLiteral = (function () { - function RegexLiteral(value, raw, pattern, flags) { - this.type = syntax_1.Syntax.Literal; - this.value = value; - this.raw = raw; - this.regex = { pattern: pattern, flags: flags }; - } - return RegexLiteral; - }()); - exports.RegexLiteral = RegexLiteral; - var RestElement = (function () { - function RestElement(argument) { - this.type = syntax_1.Syntax.RestElement; - this.argument = argument; - } - return RestElement; - }()); - exports.RestElement = RestElement; - var ReturnStatement = (function () { - function ReturnStatement(argument) { - this.type = syntax_1.Syntax.ReturnStatement; - this.argument = argument; - } - return ReturnStatement; - }()); - exports.ReturnStatement = ReturnStatement; - var Script = (function () { - function Script(body) { - this.type = syntax_1.Syntax.Program; - this.body = body; - this.sourceType = 'script'; - } - return Script; - }()); - exports.Script = Script; - var SequenceExpression = (function () { - function SequenceExpression(expressions) { - this.type = syntax_1.Syntax.SequenceExpression; - this.expressions = expressions; - } - return SequenceExpression; - }()); - exports.SequenceExpression = SequenceExpression; - var SpreadElement = (function () { - function SpreadElement(argument) { - this.type = syntax_1.Syntax.SpreadElement; - this.argument = argument; - } - return SpreadElement; - }()); - exports.SpreadElement = SpreadElement; - var StaticMemberExpression = (function () { - function StaticMemberExpression(object, property) { - this.type = syntax_1.Syntax.MemberExpression; - this.computed = false; - this.object = object; - this.property = property; - } - return StaticMemberExpression; - }()); - exports.StaticMemberExpression = StaticMemberExpression; - var Super = (function () { - function Super() { - this.type = syntax_1.Syntax.Super; - } - return Super; - }()); - exports.Super = Super; - var SwitchCase = (function () { - function SwitchCase(test, consequent) { - this.type = syntax_1.Syntax.SwitchCase; - this.test = test; - this.consequent = consequent; - } - return SwitchCase; - }()); - exports.SwitchCase = SwitchCase; - var SwitchStatement = (function () { - function SwitchStatement(discriminant, cases) { - this.type = syntax_1.Syntax.SwitchStatement; - this.discriminant = discriminant; - this.cases = cases; - } - return SwitchStatement; - }()); - exports.SwitchStatement = SwitchStatement; - var TaggedTemplateExpression = (function () { - function TaggedTemplateExpression(tag, quasi) { - this.type = syntax_1.Syntax.TaggedTemplateExpression; - this.tag = tag; - this.quasi = quasi; - } - return TaggedTemplateExpression; - }()); - exports.TaggedTemplateExpression = TaggedTemplateExpression; - var TemplateElement = (function () { - function TemplateElement(value, tail) { - this.type = syntax_1.Syntax.TemplateElement; - this.value = value; - this.tail = tail; - } - return TemplateElement; - }()); - exports.TemplateElement = TemplateElement; - var TemplateLiteral = (function () { - function TemplateLiteral(quasis, expressions) { - this.type = syntax_1.Syntax.TemplateLiteral; - this.quasis = quasis; - this.expressions = expressions; - } - return TemplateLiteral; - }()); - exports.TemplateLiteral = TemplateLiteral; - var ThisExpression = (function () { - function ThisExpression() { - this.type = syntax_1.Syntax.ThisExpression; - } - return ThisExpression; - }()); - exports.ThisExpression = ThisExpression; - var ThrowStatement = (function () { - function ThrowStatement(argument) { - this.type = syntax_1.Syntax.ThrowStatement; - this.argument = argument; - } - return ThrowStatement; - }()); - exports.ThrowStatement = ThrowStatement; - var TryStatement = (function () { - function TryStatement(block, handler, finalizer) { - this.type = syntax_1.Syntax.TryStatement; - this.block = block; - this.handler = handler; - this.finalizer = finalizer; - } - return TryStatement; - }()); - exports.TryStatement = TryStatement; - var UnaryExpression = (function () { - function UnaryExpression(operator, argument) { - this.type = syntax_1.Syntax.UnaryExpression; - this.operator = operator; - this.argument = argument; - this.prefix = true; - } - return UnaryExpression; - }()); - exports.UnaryExpression = UnaryExpression; - var UpdateExpression = (function () { - function UpdateExpression(operator, argument, prefix) { - this.type = syntax_1.Syntax.UpdateExpression; - this.operator = operator; - this.argument = argument; - this.prefix = prefix; - } - return UpdateExpression; - }()); - exports.UpdateExpression = UpdateExpression; - var VariableDeclaration = (function () { - function VariableDeclaration(declarations, kind) { - this.type = syntax_1.Syntax.VariableDeclaration; - this.declarations = declarations; - this.kind = kind; - } - return VariableDeclaration; - }()); - exports.VariableDeclaration = VariableDeclaration; - var VariableDeclarator = (function () { - function VariableDeclarator(id, init) { - this.type = syntax_1.Syntax.VariableDeclarator; - this.id = id; - this.init = init; - } - return VariableDeclarator; - }()); - exports.VariableDeclarator = VariableDeclarator; - var WhileStatement = (function () { - function WhileStatement(test, body) { - this.type = syntax_1.Syntax.WhileStatement; - this.test = test; - this.body = body; - } - return WhileStatement; - }()); - exports.WhileStatement = WhileStatement; - var WithStatement = (function () { - function WithStatement(object, body) { - this.type = syntax_1.Syntax.WithStatement; - this.object = object; - this.body = body; - } - return WithStatement; - }()); - exports.WithStatement = WithStatement; - var YieldExpression = (function () { - function YieldExpression(argument, delegate) { - this.type = syntax_1.Syntax.YieldExpression; - this.argument = argument; - this.delegate = delegate; - } - return YieldExpression; - }()); - exports.YieldExpression = YieldExpression; - - -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var assert_1 = __webpack_require__(9); - var error_handler_1 = __webpack_require__(10); - var messages_1 = __webpack_require__(11); - var Node = __webpack_require__(7); - var scanner_1 = __webpack_require__(12); - var syntax_1 = __webpack_require__(2); - var token_1 = __webpack_require__(13); - var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; - var Parser = (function () { - function Parser(code, options, delegate) { - if (options === void 0) { options = {}; } - this.config = { - range: (typeof options.range === 'boolean') && options.range, - loc: (typeof options.loc === 'boolean') && options.loc, - source: null, - tokens: (typeof options.tokens === 'boolean') && options.tokens, - comment: (typeof options.comment === 'boolean') && options.comment, - tolerant: (typeof options.tolerant === 'boolean') && options.tolerant - }; - if (this.config.loc && options.source && options.source !== null) { - this.config.source = String(options.source); - } - this.delegate = delegate; - this.errorHandler = new error_handler_1.ErrorHandler(); - this.errorHandler.tolerant = this.config.tolerant; - this.scanner = new scanner_1.Scanner(code, this.errorHandler); - this.scanner.trackComment = this.config.comment; - this.operatorPrecedence = { - ')': 0, - ';': 0, - ',': 0, - '=': 0, - ']': 0, - '||': 1, - '&&': 2, - '|': 3, - '^': 4, - '&': 5, - '==': 6, - '!=': 6, - '===': 6, - '!==': 6, - '<': 7, - '>': 7, - '<=': 7, - '>=': 7, - '<<': 8, - '>>': 8, - '>>>': 8, - '+': 9, - '-': 9, - '*': 11, - '/': 11, - '%': 11 - }; - this.lookahead = { - type: 2 /* EOF */, - value: '', - lineNumber: this.scanner.lineNumber, - lineStart: 0, - start: 0, - end: 0 - }; - this.hasLineTerminator = false; - this.context = { - isModule: false, - await: false, - allowIn: true, - allowStrictDirective: true, - allowYield: true, - firstCoverInitializedNameError: null, - isAssignmentTarget: false, - isBindingElement: false, - inFunctionBody: false, - inIteration: false, - inSwitch: false, - labelSet: {}, - strict: false - }; - this.tokens = []; - this.startMarker = { - index: 0, - line: this.scanner.lineNumber, - column: 0 - }; - this.lastMarker = { - index: 0, - line: this.scanner.lineNumber, - column: 0 - }; - this.nextToken(); - this.lastMarker = { - index: this.scanner.index, - line: this.scanner.lineNumber, - column: this.scanner.index - this.scanner.lineStart - }; - } - Parser.prototype.throwError = function (messageFormat) { - var values = []; - for (var _i = 1; _i < arguments.length; _i++) { - values[_i - 1] = arguments[_i]; - } - var args = Array.prototype.slice.call(arguments, 1); - var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { - assert_1.assert(idx < args.length, 'Message reference must be in range'); - return args[idx]; - }); - var index = this.lastMarker.index; - var line = this.lastMarker.line; - var column = this.lastMarker.column + 1; - throw this.errorHandler.createError(index, line, column, msg); - }; - Parser.prototype.tolerateError = function (messageFormat) { - var values = []; - for (var _i = 1; _i < arguments.length; _i++) { - values[_i - 1] = arguments[_i]; - } - var args = Array.prototype.slice.call(arguments, 1); - var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { - assert_1.assert(idx < args.length, 'Message reference must be in range'); - return args[idx]; - }); - var index = this.lastMarker.index; - var line = this.scanner.lineNumber; - var column = this.lastMarker.column + 1; - this.errorHandler.tolerateError(index, line, column, msg); - }; - // Throw an exception because of the token. - Parser.prototype.unexpectedTokenError = function (token, message) { - var msg = message || messages_1.Messages.UnexpectedToken; - var value; - if (token) { - if (!message) { - msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : - (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : - (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : - (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : - (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : - messages_1.Messages.UnexpectedToken; - if (token.type === 4 /* Keyword */) { - if (this.scanner.isFutureReservedWord(token.value)) { - msg = messages_1.Messages.UnexpectedReserved; - } - else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { - msg = messages_1.Messages.StrictReservedWord; - } - } - } - value = token.value; - } - else { - value = 'ILLEGAL'; - } - msg = msg.replace('%0', value); - if (token && typeof token.lineNumber === 'number') { - var index = token.start; - var line = token.lineNumber; - var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; - var column = token.start - lastMarkerLineStart + 1; - return this.errorHandler.createError(index, line, column, msg); - } - else { - var index = this.lastMarker.index; - var line = this.lastMarker.line; - var column = this.lastMarker.column + 1; - return this.errorHandler.createError(index, line, column, msg); - } - }; - Parser.prototype.throwUnexpectedToken = function (token, message) { - throw this.unexpectedTokenError(token, message); - }; - Parser.prototype.tolerateUnexpectedToken = function (token, message) { - this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); - }; - Parser.prototype.collectComments = function () { - if (!this.config.comment) { - this.scanner.scanComments(); - } - else { - var comments = this.scanner.scanComments(); - if (comments.length > 0 && this.delegate) { - for (var i = 0; i < comments.length; ++i) { - var e = comments[i]; - var node = void 0; - node = { - type: e.multiLine ? 'BlockComment' : 'LineComment', - value: this.scanner.source.slice(e.slice[0], e.slice[1]) - }; - if (this.config.range) { - node.range = e.range; - } - if (this.config.loc) { - node.loc = e.loc; - } - var metadata = { - start: { - line: e.loc.start.line, - column: e.loc.start.column, - offset: e.range[0] - }, - end: { - line: e.loc.end.line, - column: e.loc.end.column, - offset: e.range[1] - } - }; - this.delegate(node, metadata); - } - } - } - }; - // From internal representation to an external structure - Parser.prototype.getTokenRaw = function (token) { - return this.scanner.source.slice(token.start, token.end); - }; - Parser.prototype.convertToken = function (token) { - var t = { - type: token_1.TokenName[token.type], - value: this.getTokenRaw(token) - }; - if (this.config.range) { - t.range = [token.start, token.end]; - } - if (this.config.loc) { - t.loc = { - start: { - line: this.startMarker.line, - column: this.startMarker.column - }, - end: { - line: this.scanner.lineNumber, - column: this.scanner.index - this.scanner.lineStart - } - }; - } - if (token.type === 9 /* RegularExpression */) { - var pattern = token.pattern; - var flags = token.flags; - t.regex = { pattern: pattern, flags: flags }; - } - return t; - }; - Parser.prototype.nextToken = function () { - var token = this.lookahead; - this.lastMarker.index = this.scanner.index; - this.lastMarker.line = this.scanner.lineNumber; - this.lastMarker.column = this.scanner.index - this.scanner.lineStart; - this.collectComments(); - if (this.scanner.index !== this.startMarker.index) { - this.startMarker.index = this.scanner.index; - this.startMarker.line = this.scanner.lineNumber; - this.startMarker.column = this.scanner.index - this.scanner.lineStart; - } - var next = this.scanner.lex(); - this.hasLineTerminator = (token.lineNumber !== next.lineNumber); - if (next && this.context.strict && next.type === 3 /* Identifier */) { - if (this.scanner.isStrictModeReservedWord(next.value)) { - next.type = 4 /* Keyword */; - } - } - this.lookahead = next; - if (this.config.tokens && next.type !== 2 /* EOF */) { - this.tokens.push(this.convertToken(next)); - } - return token; - }; - Parser.prototype.nextRegexToken = function () { - this.collectComments(); - var token = this.scanner.scanRegExp(); - if (this.config.tokens) { - // Pop the previous token, '/' or '/=' - // This is added from the lookahead token. - this.tokens.pop(); - this.tokens.push(this.convertToken(token)); - } - // Prime the next lookahead. - this.lookahead = token; - this.nextToken(); - return token; - }; - Parser.prototype.createNode = function () { - return { - index: this.startMarker.index, - line: this.startMarker.line, - column: this.startMarker.column - }; - }; - Parser.prototype.startNode = function (token, lastLineStart) { - if (lastLineStart === void 0) { lastLineStart = 0; } - var column = token.start - token.lineStart; - var line = token.lineNumber; - if (column < 0) { - column += lastLineStart; - line--; - } - return { - index: token.start, - line: line, - column: column - }; - }; - Parser.prototype.finalize = function (marker, node) { - if (this.config.range) { - node.range = [marker.index, this.lastMarker.index]; - } - if (this.config.loc) { - node.loc = { - start: { - line: marker.line, - column: marker.column, - }, - end: { - line: this.lastMarker.line, - column: this.lastMarker.column - } - }; - if (this.config.source) { - node.loc.source = this.config.source; - } - } - if (this.delegate) { - var metadata = { - start: { - line: marker.line, - column: marker.column, - offset: marker.index - }, - end: { - line: this.lastMarker.line, - column: this.lastMarker.column, - offset: this.lastMarker.index - } - }; - this.delegate(node, metadata); - } - return node; - }; - // Expect the next token to match the specified punctuator. - // If not, an exception will be thrown. - Parser.prototype.expect = function (value) { - var token = this.nextToken(); - if (token.type !== 7 /* Punctuator */ || token.value !== value) { - this.throwUnexpectedToken(token); - } - }; - // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). - Parser.prototype.expectCommaSeparator = function () { - if (this.config.tolerant) { - var token = this.lookahead; - if (token.type === 7 /* Punctuator */ && token.value === ',') { - this.nextToken(); - } - else if (token.type === 7 /* Punctuator */ && token.value === ';') { - this.nextToken(); - this.tolerateUnexpectedToken(token); - } - else { - this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); - } - } - else { - this.expect(','); - } - }; - // Expect the next token to match the specified keyword. - // If not, an exception will be thrown. - Parser.prototype.expectKeyword = function (keyword) { - var token = this.nextToken(); - if (token.type !== 4 /* Keyword */ || token.value !== keyword) { - this.throwUnexpectedToken(token); - } - }; - // Return true if the next token matches the specified punctuator. - Parser.prototype.match = function (value) { - return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; - }; - // Return true if the next token matches the specified keyword - Parser.prototype.matchKeyword = function (keyword) { - return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; - }; - // Return true if the next token matches the specified contextual keyword - // (where an identifier is sometimes a keyword depending on the context) - Parser.prototype.matchContextualKeyword = function (keyword) { - return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; - }; - // Return true if the next token is an assignment operator - Parser.prototype.matchAssign = function () { - if (this.lookahead.type !== 7 /* Punctuator */) { - return false; - } - var op = this.lookahead.value; - return op === '=' || - op === '*=' || - op === '**=' || - op === '/=' || - op === '%=' || - op === '+=' || - op === '-=' || - op === '<<=' || - op === '>>=' || - op === '>>>=' || - op === '&=' || - op === '^=' || - op === '|='; - }; - // Cover grammar support. - // - // When an assignment expression position starts with an left parenthesis, the determination of the type - // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) - // or the first comma. This situation also defers the determination of all the expressions nested in the pair. - // - // There are three productions that can be parsed in a parentheses pair that needs to be determined - // after the outermost pair is closed. They are: - // - // 1. AssignmentExpression - // 2. BindingElements - // 3. AssignmentTargets - // - // In order to avoid exponential backtracking, we use two flags to denote if the production can be - // binding element or assignment target. - // - // The three productions have the relationship: - // - // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression - // - // with a single exception that CoverInitializedName when used directly in an Expression, generates - // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the - // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. - // - // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not - // effect the current flags. This means the production the parser parses is only used as an expression. Therefore - // the CoverInitializedName check is conducted. - // - // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates - // the flags outside of the parser. This means the production the parser parses is used as a part of a potential - // pattern. The CoverInitializedName check is deferred. - Parser.prototype.isolateCoverGrammar = function (parseFunction) { - var previousIsBindingElement = this.context.isBindingElement; - var previousIsAssignmentTarget = this.context.isAssignmentTarget; - var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; - this.context.isBindingElement = true; - this.context.isAssignmentTarget = true; - this.context.firstCoverInitializedNameError = null; - var result = parseFunction.call(this); - if (this.context.firstCoverInitializedNameError !== null) { - this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); - } - this.context.isBindingElement = previousIsBindingElement; - this.context.isAssignmentTarget = previousIsAssignmentTarget; - this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; - return result; - }; - Parser.prototype.inheritCoverGrammar = function (parseFunction) { - var previousIsBindingElement = this.context.isBindingElement; - var previousIsAssignmentTarget = this.context.isAssignmentTarget; - var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; - this.context.isBindingElement = true; - this.context.isAssignmentTarget = true; - this.context.firstCoverInitializedNameError = null; - var result = parseFunction.call(this); - this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; - this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; - this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; - return result; - }; - Parser.prototype.consumeSemicolon = function () { - if (this.match(';')) { - this.nextToken(); - } - else if (!this.hasLineTerminator) { - if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { - this.throwUnexpectedToken(this.lookahead); - } - this.lastMarker.index = this.startMarker.index; - this.lastMarker.line = this.startMarker.line; - this.lastMarker.column = this.startMarker.column; - } - }; - // https://tc39.github.io/ecma262/#sec-primary-expression - Parser.prototype.parsePrimaryExpression = function () { - var node = this.createNode(); - var expr; - var token, raw; - switch (this.lookahead.type) { - case 3 /* Identifier */: - if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { - this.tolerateUnexpectedToken(this.lookahead); - } - expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); - break; - case 6 /* NumericLiteral */: - case 8 /* StringLiteral */: - if (this.context.strict && this.lookahead.octal) { - this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); - } - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - token = this.nextToken(); - raw = this.getTokenRaw(token); - expr = this.finalize(node, new Node.Literal(token.value, raw)); - break; - case 1 /* BooleanLiteral */: - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - token = this.nextToken(); - raw = this.getTokenRaw(token); - expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); - break; - case 5 /* NullLiteral */: - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - token = this.nextToken(); - raw = this.getTokenRaw(token); - expr = this.finalize(node, new Node.Literal(null, raw)); - break; - case 10 /* Template */: - expr = this.parseTemplateLiteral(); - break; - case 7 /* Punctuator */: - switch (this.lookahead.value) { - case '(': - this.context.isBindingElement = false; - expr = this.inheritCoverGrammar(this.parseGroupExpression); - break; - case '[': - expr = this.inheritCoverGrammar(this.parseArrayInitializer); - break; - case '{': - expr = this.inheritCoverGrammar(this.parseObjectInitializer); - break; - case '/': - case '/=': - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - this.scanner.index = this.startMarker.index; - token = this.nextRegexToken(); - raw = this.getTokenRaw(token); - expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); - break; - default: - expr = this.throwUnexpectedToken(this.nextToken()); - } - break; - case 4 /* Keyword */: - if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { - expr = this.parseIdentifierName(); - } - else if (!this.context.strict && this.matchKeyword('let')) { - expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); - } - else { - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - if (this.matchKeyword('function')) { - expr = this.parseFunctionExpression(); - } - else if (this.matchKeyword('this')) { - this.nextToken(); - expr = this.finalize(node, new Node.ThisExpression()); - } - else if (this.matchKeyword('class')) { - expr = this.parseClassExpression(); - } - else { - expr = this.throwUnexpectedToken(this.nextToken()); - } - } - break; - default: - expr = this.throwUnexpectedToken(this.nextToken()); - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-array-initializer - Parser.prototype.parseSpreadElement = function () { - var node = this.createNode(); - this.expect('...'); - var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); - return this.finalize(node, new Node.SpreadElement(arg)); - }; - Parser.prototype.parseArrayInitializer = function () { - var node = this.createNode(); - var elements = []; - this.expect('['); - while (!this.match(']')) { - if (this.match(',')) { - this.nextToken(); - elements.push(null); - } - else if (this.match('...')) { - var element = this.parseSpreadElement(); - if (!this.match(']')) { - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - this.expect(','); - } - elements.push(element); - } - else { - elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); - if (!this.match(']')) { - this.expect(','); - } - } - } - this.expect(']'); - return this.finalize(node, new Node.ArrayExpression(elements)); - }; - // https://tc39.github.io/ecma262/#sec-object-initializer - Parser.prototype.parsePropertyMethod = function (params) { - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - var previousStrict = this.context.strict; - var previousAllowStrictDirective = this.context.allowStrictDirective; - this.context.allowStrictDirective = params.simple; - var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); - if (this.context.strict && params.firstRestricted) { - this.tolerateUnexpectedToken(params.firstRestricted, params.message); - } - if (this.context.strict && params.stricted) { - this.tolerateUnexpectedToken(params.stricted, params.message); - } - this.context.strict = previousStrict; - this.context.allowStrictDirective = previousAllowStrictDirective; - return body; - }; - Parser.prototype.parsePropertyMethodFunction = function () { - var isGenerator = false; - var node = this.createNode(); - var previousAllowYield = this.context.allowYield; - this.context.allowYield = true; - var params = this.parseFormalParameters(); - var method = this.parsePropertyMethod(params); - this.context.allowYield = previousAllowYield; - return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); - }; - Parser.prototype.parsePropertyMethodAsyncFunction = function () { - var node = this.createNode(); - var previousAllowYield = this.context.allowYield; - var previousAwait = this.context.await; - this.context.allowYield = false; - this.context.await = true; - var params = this.parseFormalParameters(); - var method = this.parsePropertyMethod(params); - this.context.allowYield = previousAllowYield; - this.context.await = previousAwait; - return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); - }; - Parser.prototype.parseObjectPropertyKey = function () { - var node = this.createNode(); - var token = this.nextToken(); - var key; - switch (token.type) { - case 8 /* StringLiteral */: - case 6 /* NumericLiteral */: - if (this.context.strict && token.octal) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); - } - var raw = this.getTokenRaw(token); - key = this.finalize(node, new Node.Literal(token.value, raw)); - break; - case 3 /* Identifier */: - case 1 /* BooleanLiteral */: - case 5 /* NullLiteral */: - case 4 /* Keyword */: - key = this.finalize(node, new Node.Identifier(token.value)); - break; - case 7 /* Punctuator */: - if (token.value === '[') { - key = this.isolateCoverGrammar(this.parseAssignmentExpression); - this.expect(']'); - } - else { - key = this.throwUnexpectedToken(token); - } - break; - default: - key = this.throwUnexpectedToken(token); - } - return key; - }; - Parser.prototype.isPropertyKey = function (key, value) { - return (key.type === syntax_1.Syntax.Identifier && key.name === value) || - (key.type === syntax_1.Syntax.Literal && key.value === value); - }; - Parser.prototype.parseObjectProperty = function (hasProto) { - var node = this.createNode(); - var token = this.lookahead; - var kind; - var key = null; - var value = null; - var computed = false; - var method = false; - var shorthand = false; - var isAsync = false; - if (token.type === 3 /* Identifier */) { - var id = token.value; - this.nextToken(); - computed = this.match('['); - isAsync = !this.hasLineTerminator && (id === 'async') && - !this.match(':') && !this.match('(') && !this.match('*') && !this.match(','); - key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); - } - else if (this.match('*')) { - this.nextToken(); - } - else { - computed = this.match('['); - key = this.parseObjectPropertyKey(); - } - var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); - if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { - kind = 'get'; - computed = this.match('['); - key = this.parseObjectPropertyKey(); - this.context.allowYield = false; - value = this.parseGetterMethod(); - } - else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { - kind = 'set'; - computed = this.match('['); - key = this.parseObjectPropertyKey(); - value = this.parseSetterMethod(); - } - else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { - kind = 'init'; - computed = this.match('['); - key = this.parseObjectPropertyKey(); - value = this.parseGeneratorMethod(); - method = true; - } - else { - if (!key) { - this.throwUnexpectedToken(this.lookahead); - } - kind = 'init'; - if (this.match(':') && !isAsync) { - if (!computed && this.isPropertyKey(key, '__proto__')) { - if (hasProto.value) { - this.tolerateError(messages_1.Messages.DuplicateProtoProperty); - } - hasProto.value = true; - } - this.nextToken(); - value = this.inheritCoverGrammar(this.parseAssignmentExpression); - } - else if (this.match('(')) { - value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); - method = true; - } - else if (token.type === 3 /* Identifier */) { - var id = this.finalize(node, new Node.Identifier(token.value)); - if (this.match('=')) { - this.context.firstCoverInitializedNameError = this.lookahead; - this.nextToken(); - shorthand = true; - var init = this.isolateCoverGrammar(this.parseAssignmentExpression); - value = this.finalize(node, new Node.AssignmentPattern(id, init)); - } - else { - shorthand = true; - value = id; - } - } - else { - this.throwUnexpectedToken(this.nextToken()); - } - } - return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); - }; - Parser.prototype.parseObjectInitializer = function () { - var node = this.createNode(); - this.expect('{'); - var properties = []; - var hasProto = { value: false }; - while (!this.match('}')) { - properties.push(this.parseObjectProperty(hasProto)); - if (!this.match('}')) { - this.expectCommaSeparator(); - } - } - this.expect('}'); - return this.finalize(node, new Node.ObjectExpression(properties)); - }; - // https://tc39.github.io/ecma262/#sec-template-literals - Parser.prototype.parseTemplateHead = function () { - assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); - var node = this.createNode(); - var token = this.nextToken(); - var raw = token.value; - var cooked = token.cooked; - return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); - }; - Parser.prototype.parseTemplateElement = function () { - if (this.lookahead.type !== 10 /* Template */) { - this.throwUnexpectedToken(); - } - var node = this.createNode(); - var token = this.nextToken(); - var raw = token.value; - var cooked = token.cooked; - return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); - }; - Parser.prototype.parseTemplateLiteral = function () { - var node = this.createNode(); - var expressions = []; - var quasis = []; - var quasi = this.parseTemplateHead(); - quasis.push(quasi); - while (!quasi.tail) { - expressions.push(this.parseExpression()); - quasi = this.parseTemplateElement(); - quasis.push(quasi); - } - return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); - }; - // https://tc39.github.io/ecma262/#sec-grouping-operator - Parser.prototype.reinterpretExpressionAsPattern = function (expr) { - switch (expr.type) { - case syntax_1.Syntax.Identifier: - case syntax_1.Syntax.MemberExpression: - case syntax_1.Syntax.RestElement: - case syntax_1.Syntax.AssignmentPattern: - break; - case syntax_1.Syntax.SpreadElement: - expr.type = syntax_1.Syntax.RestElement; - this.reinterpretExpressionAsPattern(expr.argument); - break; - case syntax_1.Syntax.ArrayExpression: - expr.type = syntax_1.Syntax.ArrayPattern; - for (var i = 0; i < expr.elements.length; i++) { - if (expr.elements[i] !== null) { - this.reinterpretExpressionAsPattern(expr.elements[i]); - } - } - break; - case syntax_1.Syntax.ObjectExpression: - expr.type = syntax_1.Syntax.ObjectPattern; - for (var i = 0; i < expr.properties.length; i++) { - this.reinterpretExpressionAsPattern(expr.properties[i].value); - } - break; - case syntax_1.Syntax.AssignmentExpression: - expr.type = syntax_1.Syntax.AssignmentPattern; - delete expr.operator; - this.reinterpretExpressionAsPattern(expr.left); - break; - default: - // Allow other node type for tolerant parsing. - break; - } - }; - Parser.prototype.parseGroupExpression = function () { - var expr; - this.expect('('); - if (this.match(')')) { - this.nextToken(); - if (!this.match('=>')) { - this.expect('=>'); - } - expr = { - type: ArrowParameterPlaceHolder, - params: [], - async: false - }; - } - else { - var startToken = this.lookahead; - var params = []; - if (this.match('...')) { - expr = this.parseRestElement(params); - this.expect(')'); - if (!this.match('=>')) { - this.expect('=>'); - } - expr = { - type: ArrowParameterPlaceHolder, - params: [expr], - async: false - }; - } - else { - var arrow = false; - this.context.isBindingElement = true; - expr = this.inheritCoverGrammar(this.parseAssignmentExpression); - if (this.match(',')) { - var expressions = []; - this.context.isAssignmentTarget = false; - expressions.push(expr); - while (this.lookahead.type !== 2 /* EOF */) { - if (!this.match(',')) { - break; - } - this.nextToken(); - if (this.match(')')) { - this.nextToken(); - for (var i = 0; i < expressions.length; i++) { - this.reinterpretExpressionAsPattern(expressions[i]); - } - arrow = true; - expr = { - type: ArrowParameterPlaceHolder, - params: expressions, - async: false - }; - } - else if (this.match('...')) { - if (!this.context.isBindingElement) { - this.throwUnexpectedToken(this.lookahead); - } - expressions.push(this.parseRestElement(params)); - this.expect(')'); - if (!this.match('=>')) { - this.expect('=>'); - } - this.context.isBindingElement = false; - for (var i = 0; i < expressions.length; i++) { - this.reinterpretExpressionAsPattern(expressions[i]); - } - arrow = true; - expr = { - type: ArrowParameterPlaceHolder, - params: expressions, - async: false - }; - } - else { - expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); - } - if (arrow) { - break; - } - } - if (!arrow) { - expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); - } - } - if (!arrow) { - this.expect(')'); - if (this.match('=>')) { - if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { - arrow = true; - expr = { - type: ArrowParameterPlaceHolder, - params: [expr], - async: false - }; - } - if (!arrow) { - if (!this.context.isBindingElement) { - this.throwUnexpectedToken(this.lookahead); - } - if (expr.type === syntax_1.Syntax.SequenceExpression) { - for (var i = 0; i < expr.expressions.length; i++) { - this.reinterpretExpressionAsPattern(expr.expressions[i]); - } - } - else { - this.reinterpretExpressionAsPattern(expr); - } - var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); - expr = { - type: ArrowParameterPlaceHolder, - params: parameters, - async: false - }; - } - } - this.context.isBindingElement = false; - } - } - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions - Parser.prototype.parseArguments = function () { - this.expect('('); - var args = []; - if (!this.match(')')) { - while (true) { - var expr = this.match('...') ? this.parseSpreadElement() : - this.isolateCoverGrammar(this.parseAssignmentExpression); - args.push(expr); - if (this.match(')')) { - break; - } - this.expectCommaSeparator(); - if (this.match(')')) { - break; - } - } - } - this.expect(')'); - return args; - }; - Parser.prototype.isIdentifierName = function (token) { - return token.type === 3 /* Identifier */ || - token.type === 4 /* Keyword */ || - token.type === 1 /* BooleanLiteral */ || - token.type === 5 /* NullLiteral */; - }; - Parser.prototype.parseIdentifierName = function () { - var node = this.createNode(); - var token = this.nextToken(); - if (!this.isIdentifierName(token)) { - this.throwUnexpectedToken(token); - } - return this.finalize(node, new Node.Identifier(token.value)); - }; - Parser.prototype.parseNewExpression = function () { - var node = this.createNode(); - var id = this.parseIdentifierName(); - assert_1.assert(id.name === 'new', 'New expression must start with `new`'); - var expr; - if (this.match('.')) { - this.nextToken(); - if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { - var property = this.parseIdentifierName(); - expr = new Node.MetaProperty(id, property); - } - else { - this.throwUnexpectedToken(this.lookahead); - } - } - else { - var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); - var args = this.match('(') ? this.parseArguments() : []; - expr = new Node.NewExpression(callee, args); - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - } - return this.finalize(node, expr); - }; - Parser.prototype.parseAsyncArgument = function () { - var arg = this.parseAssignmentExpression(); - this.context.firstCoverInitializedNameError = null; - return arg; - }; - Parser.prototype.parseAsyncArguments = function () { - this.expect('('); - var args = []; - if (!this.match(')')) { - while (true) { - var expr = this.match('...') ? this.parseSpreadElement() : - this.isolateCoverGrammar(this.parseAsyncArgument); - args.push(expr); - if (this.match(')')) { - break; - } - this.expectCommaSeparator(); - if (this.match(')')) { - break; - } - } - } - this.expect(')'); - return args; - }; - Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { - var startToken = this.lookahead; - var maybeAsync = this.matchContextualKeyword('async'); - var previousAllowIn = this.context.allowIn; - this.context.allowIn = true; - var expr; - if (this.matchKeyword('super') && this.context.inFunctionBody) { - expr = this.createNode(); - this.nextToken(); - expr = this.finalize(expr, new Node.Super()); - if (!this.match('(') && !this.match('.') && !this.match('[')) { - this.throwUnexpectedToken(this.lookahead); - } - } - else { - expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); - } - while (true) { - if (this.match('.')) { - this.context.isBindingElement = false; - this.context.isAssignmentTarget = true; - this.expect('.'); - var property = this.parseIdentifierName(); - expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); - } - else if (this.match('(')) { - var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); - this.context.isBindingElement = false; - this.context.isAssignmentTarget = false; - var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); - expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); - if (asyncArrow && this.match('=>')) { - for (var i = 0; i < args.length; ++i) { - this.reinterpretExpressionAsPattern(args[i]); - } - expr = { - type: ArrowParameterPlaceHolder, - params: args, - async: true - }; - } - } - else if (this.match('[')) { - this.context.isBindingElement = false; - this.context.isAssignmentTarget = true; - this.expect('['); - var property = this.isolateCoverGrammar(this.parseExpression); - this.expect(']'); - expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); - } - else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { - var quasi = this.parseTemplateLiteral(); - expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); - } - else { - break; - } - } - this.context.allowIn = previousAllowIn; - return expr; - }; - Parser.prototype.parseSuper = function () { - var node = this.createNode(); - this.expectKeyword('super'); - if (!this.match('[') && !this.match('.')) { - this.throwUnexpectedToken(this.lookahead); - } - return this.finalize(node, new Node.Super()); - }; - Parser.prototype.parseLeftHandSideExpression = function () { - assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); - var node = this.startNode(this.lookahead); - var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : - this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); - while (true) { - if (this.match('[')) { - this.context.isBindingElement = false; - this.context.isAssignmentTarget = true; - this.expect('['); - var property = this.isolateCoverGrammar(this.parseExpression); - this.expect(']'); - expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); - } - else if (this.match('.')) { - this.context.isBindingElement = false; - this.context.isAssignmentTarget = true; - this.expect('.'); - var property = this.parseIdentifierName(); - expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); - } - else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { - var quasi = this.parseTemplateLiteral(); - expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); - } - else { - break; - } - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-update-expressions - Parser.prototype.parseUpdateExpression = function () { - var expr; - var startToken = this.lookahead; - if (this.match('++') || this.match('--')) { - var node = this.startNode(startToken); - var token = this.nextToken(); - expr = this.inheritCoverGrammar(this.parseUnaryExpression); - if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { - this.tolerateError(messages_1.Messages.StrictLHSPrefix); - } - if (!this.context.isAssignmentTarget) { - this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); - } - var prefix = true; - expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - } - else { - expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); - if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { - if (this.match('++') || this.match('--')) { - if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { - this.tolerateError(messages_1.Messages.StrictLHSPostfix); - } - if (!this.context.isAssignmentTarget) { - this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); - } - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - var operator = this.nextToken().value; - var prefix = false; - expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); - } - } - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-unary-operators - Parser.prototype.parseAwaitExpression = function () { - var node = this.createNode(); - this.nextToken(); - var argument = this.parseUnaryExpression(); - return this.finalize(node, new Node.AwaitExpression(argument)); - }; - Parser.prototype.parseUnaryExpression = function () { - var expr; - if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || - this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { - var node = this.startNode(this.lookahead); - var token = this.nextToken(); - expr = this.inheritCoverGrammar(this.parseUnaryExpression); - expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); - if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { - this.tolerateError(messages_1.Messages.StrictDelete); - } - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - } - else if (this.context.await && this.matchContextualKeyword('await')) { - expr = this.parseAwaitExpression(); - } - else { - expr = this.parseUpdateExpression(); - } - return expr; - }; - Parser.prototype.parseExponentiationExpression = function () { - var startToken = this.lookahead; - var expr = this.inheritCoverGrammar(this.parseUnaryExpression); - if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { - this.nextToken(); - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - var left = expr; - var right = this.isolateCoverGrammar(this.parseExponentiationExpression); - expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-exp-operator - // https://tc39.github.io/ecma262/#sec-multiplicative-operators - // https://tc39.github.io/ecma262/#sec-additive-operators - // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators - // https://tc39.github.io/ecma262/#sec-relational-operators - // https://tc39.github.io/ecma262/#sec-equality-operators - // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators - // https://tc39.github.io/ecma262/#sec-binary-logical-operators - Parser.prototype.binaryPrecedence = function (token) { - var op = token.value; - var precedence; - if (token.type === 7 /* Punctuator */) { - precedence = this.operatorPrecedence[op] || 0; - } - else if (token.type === 4 /* Keyword */) { - precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; - } - else { - precedence = 0; - } - return precedence; - }; - Parser.prototype.parseBinaryExpression = function () { - var startToken = this.lookahead; - var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); - var token = this.lookahead; - var prec = this.binaryPrecedence(token); - if (prec > 0) { - this.nextToken(); - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - var markers = [startToken, this.lookahead]; - var left = expr; - var right = this.isolateCoverGrammar(this.parseExponentiationExpression); - var stack = [left, token.value, right]; - var precedences = [prec]; - while (true) { - prec = this.binaryPrecedence(this.lookahead); - if (prec <= 0) { - break; - } - // Reduce: make a binary expression from the three topmost entries. - while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { - right = stack.pop(); - var operator = stack.pop(); - precedences.pop(); - left = stack.pop(); - markers.pop(); - var node = this.startNode(markers[markers.length - 1]); - stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); - } - // Shift. - stack.push(this.nextToken().value); - precedences.push(prec); - markers.push(this.lookahead); - stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); - } - // Final reduce to clean-up the stack. - var i = stack.length - 1; - expr = stack[i]; - var lastMarker = markers.pop(); - while (i > 1) { - var marker = markers.pop(); - var lastLineStart = lastMarker && lastMarker.lineStart; - var node = this.startNode(marker, lastLineStart); - var operator = stack[i - 1]; - expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); - i -= 2; - lastMarker = marker; - } - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-conditional-operator - Parser.prototype.parseConditionalExpression = function () { - var startToken = this.lookahead; - var expr = this.inheritCoverGrammar(this.parseBinaryExpression); - if (this.match('?')) { - this.nextToken(); - var previousAllowIn = this.context.allowIn; - this.context.allowIn = true; - var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); - this.context.allowIn = previousAllowIn; - this.expect(':'); - var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); - expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-assignment-operators - Parser.prototype.checkPatternParam = function (options, param) { - switch (param.type) { - case syntax_1.Syntax.Identifier: - this.validateParam(options, param, param.name); - break; - case syntax_1.Syntax.RestElement: - this.checkPatternParam(options, param.argument); - break; - case syntax_1.Syntax.AssignmentPattern: - this.checkPatternParam(options, param.left); - break; - case syntax_1.Syntax.ArrayPattern: - for (var i = 0; i < param.elements.length; i++) { - if (param.elements[i] !== null) { - this.checkPatternParam(options, param.elements[i]); - } - } - break; - case syntax_1.Syntax.ObjectPattern: - for (var i = 0; i < param.properties.length; i++) { - this.checkPatternParam(options, param.properties[i].value); - } - break; - default: - break; - } - options.simple = options.simple && (param instanceof Node.Identifier); - }; - Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { - var params = [expr]; - var options; - var asyncArrow = false; - switch (expr.type) { - case syntax_1.Syntax.Identifier: - break; - case ArrowParameterPlaceHolder: - params = expr.params; - asyncArrow = expr.async; - break; - default: - return null; - } - options = { - simple: true, - paramSet: {} - }; - for (var i = 0; i < params.length; ++i) { - var param = params[i]; - if (param.type === syntax_1.Syntax.AssignmentPattern) { - if (param.right.type === syntax_1.Syntax.YieldExpression) { - if (param.right.argument) { - this.throwUnexpectedToken(this.lookahead); - } - param.right.type = syntax_1.Syntax.Identifier; - param.right.name = 'yield'; - delete param.right.argument; - delete param.right.delegate; - } - } - else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { - this.throwUnexpectedToken(this.lookahead); - } - this.checkPatternParam(options, param); - params[i] = param; - } - if (this.context.strict || !this.context.allowYield) { - for (var i = 0; i < params.length; ++i) { - var param = params[i]; - if (param.type === syntax_1.Syntax.YieldExpression) { - this.throwUnexpectedToken(this.lookahead); - } - } - } - if (options.message === messages_1.Messages.StrictParamDupe) { - var token = this.context.strict ? options.stricted : options.firstRestricted; - this.throwUnexpectedToken(token, options.message); - } - return { - simple: options.simple, - params: params, - stricted: options.stricted, - firstRestricted: options.firstRestricted, - message: options.message - }; - }; - Parser.prototype.parseAssignmentExpression = function () { - var expr; - if (!this.context.allowYield && this.matchKeyword('yield')) { - expr = this.parseYieldExpression(); - } - else { - var startToken = this.lookahead; - var token = startToken; - expr = this.parseConditionalExpression(); - if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { - if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { - var arg = this.parsePrimaryExpression(); - this.reinterpretExpressionAsPattern(arg); - expr = { - type: ArrowParameterPlaceHolder, - params: [arg], - async: true - }; - } - } - if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { - // https://tc39.github.io/ecma262/#sec-arrow-function-definitions - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - var isAsync = expr.async; - var list = this.reinterpretAsCoverFormalsList(expr); - if (list) { - if (this.hasLineTerminator) { - this.tolerateUnexpectedToken(this.lookahead); - } - this.context.firstCoverInitializedNameError = null; - var previousStrict = this.context.strict; - var previousAllowStrictDirective = this.context.allowStrictDirective; - this.context.allowStrictDirective = list.simple; - var previousAllowYield = this.context.allowYield; - var previousAwait = this.context.await; - this.context.allowYield = true; - this.context.await = isAsync; - var node = this.startNode(startToken); - this.expect('=>'); - var body = void 0; - if (this.match('{')) { - var previousAllowIn = this.context.allowIn; - this.context.allowIn = true; - body = this.parseFunctionSourceElements(); - this.context.allowIn = previousAllowIn; - } - else { - body = this.isolateCoverGrammar(this.parseAssignmentExpression); - } - var expression = body.type !== syntax_1.Syntax.BlockStatement; - if (this.context.strict && list.firstRestricted) { - this.throwUnexpectedToken(list.firstRestricted, list.message); - } - if (this.context.strict && list.stricted) { - this.tolerateUnexpectedToken(list.stricted, list.message); - } - expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : - this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); - this.context.strict = previousStrict; - this.context.allowStrictDirective = previousAllowStrictDirective; - this.context.allowYield = previousAllowYield; - this.context.await = previousAwait; - } - } - else { - if (this.matchAssign()) { - if (!this.context.isAssignmentTarget) { - this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); - } - if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { - var id = expr; - if (this.scanner.isRestrictedWord(id.name)) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); - } - if (this.scanner.isStrictModeReservedWord(id.name)) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); - } - } - if (!this.match('=')) { - this.context.isAssignmentTarget = false; - this.context.isBindingElement = false; - } - else { - this.reinterpretExpressionAsPattern(expr); - } - token = this.nextToken(); - var operator = token.value; - var right = this.isolateCoverGrammar(this.parseAssignmentExpression); - expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); - this.context.firstCoverInitializedNameError = null; - } - } - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-comma-operator - Parser.prototype.parseExpression = function () { - var startToken = this.lookahead; - var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); - if (this.match(',')) { - var expressions = []; - expressions.push(expr); - while (this.lookahead.type !== 2 /* EOF */) { - if (!this.match(',')) { - break; - } - this.nextToken(); - expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); - } - expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); - } - return expr; - }; - // https://tc39.github.io/ecma262/#sec-block - Parser.prototype.parseStatementListItem = function () { - var statement; - this.context.isAssignmentTarget = true; - this.context.isBindingElement = true; - if (this.lookahead.type === 4 /* Keyword */) { - switch (this.lookahead.value) { - case 'export': - if (!this.context.isModule) { - this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); - } - statement = this.parseExportDeclaration(); - break; - case 'import': - if (!this.context.isModule) { - this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); - } - statement = this.parseImportDeclaration(); - break; - case 'const': - statement = this.parseLexicalDeclaration({ inFor: false }); - break; - case 'function': - statement = this.parseFunctionDeclaration(); - break; - case 'class': - statement = this.parseClassDeclaration(); - break; - case 'let': - statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); - break; - default: - statement = this.parseStatement(); - break; - } - } - else { - statement = this.parseStatement(); - } - return statement; - }; - Parser.prototype.parseBlock = function () { - var node = this.createNode(); - this.expect('{'); - var block = []; - while (true) { - if (this.match('}')) { - break; - } - block.push(this.parseStatementListItem()); - } - this.expect('}'); - return this.finalize(node, new Node.BlockStatement(block)); - }; - // https://tc39.github.io/ecma262/#sec-let-and-const-declarations - Parser.prototype.parseLexicalBinding = function (kind, options) { - var node = this.createNode(); - var params = []; - var id = this.parsePattern(params, kind); - if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { - if (this.scanner.isRestrictedWord(id.name)) { - this.tolerateError(messages_1.Messages.StrictVarName); - } - } - var init = null; - if (kind === 'const') { - if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { - if (this.match('=')) { - this.nextToken(); - init = this.isolateCoverGrammar(this.parseAssignmentExpression); - } - else { - this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); - } - } - } - else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { - this.expect('='); - init = this.isolateCoverGrammar(this.parseAssignmentExpression); - } - return this.finalize(node, new Node.VariableDeclarator(id, init)); - }; - Parser.prototype.parseBindingList = function (kind, options) { - var list = [this.parseLexicalBinding(kind, options)]; - while (this.match(',')) { - this.nextToken(); - list.push(this.parseLexicalBinding(kind, options)); - } - return list; - }; - Parser.prototype.isLexicalDeclaration = function () { - var state = this.scanner.saveState(); - this.scanner.scanComments(); - var next = this.scanner.lex(); - this.scanner.restoreState(state); - return (next.type === 3 /* Identifier */) || - (next.type === 7 /* Punctuator */ && next.value === '[') || - (next.type === 7 /* Punctuator */ && next.value === '{') || - (next.type === 4 /* Keyword */ && next.value === 'let') || - (next.type === 4 /* Keyword */ && next.value === 'yield'); - }; - Parser.prototype.parseLexicalDeclaration = function (options) { - var node = this.createNode(); - var kind = this.nextToken().value; - assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); - var declarations = this.parseBindingList(kind, options); - this.consumeSemicolon(); - return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); - }; - // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns - Parser.prototype.parseBindingRestElement = function (params, kind) { - var node = this.createNode(); - this.expect('...'); - var arg = this.parsePattern(params, kind); - return this.finalize(node, new Node.RestElement(arg)); - }; - Parser.prototype.parseArrayPattern = function (params, kind) { - var node = this.createNode(); - this.expect('['); - var elements = []; - while (!this.match(']')) { - if (this.match(',')) { - this.nextToken(); - elements.push(null); - } - else { - if (this.match('...')) { - elements.push(this.parseBindingRestElement(params, kind)); - break; - } - else { - elements.push(this.parsePatternWithDefault(params, kind)); - } - if (!this.match(']')) { - this.expect(','); - } - } - } - this.expect(']'); - return this.finalize(node, new Node.ArrayPattern(elements)); - }; - Parser.prototype.parsePropertyPattern = function (params, kind) { - var node = this.createNode(); - var computed = false; - var shorthand = false; - var method = false; - var key; - var value; - if (this.lookahead.type === 3 /* Identifier */) { - var keyToken = this.lookahead; - key = this.parseVariableIdentifier(); - var init = this.finalize(node, new Node.Identifier(keyToken.value)); - if (this.match('=')) { - params.push(keyToken); - shorthand = true; - this.nextToken(); - var expr = this.parseAssignmentExpression(); - value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); - } - else if (!this.match(':')) { - params.push(keyToken); - shorthand = true; - value = init; - } - else { - this.expect(':'); - value = this.parsePatternWithDefault(params, kind); - } - } - else { - computed = this.match('['); - key = this.parseObjectPropertyKey(); - this.expect(':'); - value = this.parsePatternWithDefault(params, kind); - } - return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); - }; - Parser.prototype.parseObjectPattern = function (params, kind) { - var node = this.createNode(); - var properties = []; - this.expect('{'); - while (!this.match('}')) { - properties.push(this.parsePropertyPattern(params, kind)); - if (!this.match('}')) { - this.expect(','); - } - } - this.expect('}'); - return this.finalize(node, new Node.ObjectPattern(properties)); - }; - Parser.prototype.parsePattern = function (params, kind) { - var pattern; - if (this.match('[')) { - pattern = this.parseArrayPattern(params, kind); - } - else if (this.match('{')) { - pattern = this.parseObjectPattern(params, kind); - } - else { - if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { - this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); - } - params.push(this.lookahead); - pattern = this.parseVariableIdentifier(kind); - } - return pattern; - }; - Parser.prototype.parsePatternWithDefault = function (params, kind) { - var startToken = this.lookahead; - var pattern = this.parsePattern(params, kind); - if (this.match('=')) { - this.nextToken(); - var previousAllowYield = this.context.allowYield; - this.context.allowYield = true; - var right = this.isolateCoverGrammar(this.parseAssignmentExpression); - this.context.allowYield = previousAllowYield; - pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); - } - return pattern; - }; - // https://tc39.github.io/ecma262/#sec-variable-statement - Parser.prototype.parseVariableIdentifier = function (kind) { - var node = this.createNode(); - var token = this.nextToken(); - if (token.type === 4 /* Keyword */ && token.value === 'yield') { - if (this.context.strict) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); - } - else if (!this.context.allowYield) { - this.throwUnexpectedToken(token); - } - } - else if (token.type !== 3 /* Identifier */) { - if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); - } - else { - if (this.context.strict || token.value !== 'let' || kind !== 'var') { - this.throwUnexpectedToken(token); - } - } - } - else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { - this.tolerateUnexpectedToken(token); - } - return this.finalize(node, new Node.Identifier(token.value)); - }; - Parser.prototype.parseVariableDeclaration = function (options) { - var node = this.createNode(); - var params = []; - var id = this.parsePattern(params, 'var'); - if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { - if (this.scanner.isRestrictedWord(id.name)) { - this.tolerateError(messages_1.Messages.StrictVarName); - } - } - var init = null; - if (this.match('=')) { - this.nextToken(); - init = this.isolateCoverGrammar(this.parseAssignmentExpression); - } - else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { - this.expect('='); - } - return this.finalize(node, new Node.VariableDeclarator(id, init)); - }; - Parser.prototype.parseVariableDeclarationList = function (options) { - var opt = { inFor: options.inFor }; - var list = []; - list.push(this.parseVariableDeclaration(opt)); - while (this.match(',')) { - this.nextToken(); - list.push(this.parseVariableDeclaration(opt)); - } - return list; - }; - Parser.prototype.parseVariableStatement = function () { - var node = this.createNode(); - this.expectKeyword('var'); - var declarations = this.parseVariableDeclarationList({ inFor: false }); - this.consumeSemicolon(); - return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); - }; - // https://tc39.github.io/ecma262/#sec-empty-statement - Parser.prototype.parseEmptyStatement = function () { - var node = this.createNode(); - this.expect(';'); - return this.finalize(node, new Node.EmptyStatement()); - }; - // https://tc39.github.io/ecma262/#sec-expression-statement - Parser.prototype.parseExpressionStatement = function () { - var node = this.createNode(); - var expr = this.parseExpression(); - this.consumeSemicolon(); - return this.finalize(node, new Node.ExpressionStatement(expr)); - }; - // https://tc39.github.io/ecma262/#sec-if-statement - Parser.prototype.parseIfClause = function () { - if (this.context.strict && this.matchKeyword('function')) { - this.tolerateError(messages_1.Messages.StrictFunction); - } - return this.parseStatement(); - }; - Parser.prototype.parseIfStatement = function () { - var node = this.createNode(); - var consequent; - var alternate = null; - this.expectKeyword('if'); - this.expect('('); - var test = this.parseExpression(); - if (!this.match(')') && this.config.tolerant) { - this.tolerateUnexpectedToken(this.nextToken()); - consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); - } - else { - this.expect(')'); - consequent = this.parseIfClause(); - if (this.matchKeyword('else')) { - this.nextToken(); - alternate = this.parseIfClause(); - } - } - return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); - }; - // https://tc39.github.io/ecma262/#sec-do-while-statement - Parser.prototype.parseDoWhileStatement = function () { - var node = this.createNode(); - this.expectKeyword('do'); - var previousInIteration = this.context.inIteration; - this.context.inIteration = true; - var body = this.parseStatement(); - this.context.inIteration = previousInIteration; - this.expectKeyword('while'); - this.expect('('); - var test = this.parseExpression(); - if (!this.match(')') && this.config.tolerant) { - this.tolerateUnexpectedToken(this.nextToken()); - } - else { - this.expect(')'); - if (this.match(';')) { - this.nextToken(); - } - } - return this.finalize(node, new Node.DoWhileStatement(body, test)); - }; - // https://tc39.github.io/ecma262/#sec-while-statement - Parser.prototype.parseWhileStatement = function () { - var node = this.createNode(); - var body; - this.expectKeyword('while'); - this.expect('('); - var test = this.parseExpression(); - if (!this.match(')') && this.config.tolerant) { - this.tolerateUnexpectedToken(this.nextToken()); - body = this.finalize(this.createNode(), new Node.EmptyStatement()); - } - else { - this.expect(')'); - var previousInIteration = this.context.inIteration; - this.context.inIteration = true; - body = this.parseStatement(); - this.context.inIteration = previousInIteration; - } - return this.finalize(node, new Node.WhileStatement(test, body)); - }; - // https://tc39.github.io/ecma262/#sec-for-statement - // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements - Parser.prototype.parseForStatement = function () { - var init = null; - var test = null; - var update = null; - var forIn = true; - var left, right; - var node = this.createNode(); - this.expectKeyword('for'); - this.expect('('); - if (this.match(';')) { - this.nextToken(); - } - else { - if (this.matchKeyword('var')) { - init = this.createNode(); - this.nextToken(); - var previousAllowIn = this.context.allowIn; - this.context.allowIn = false; - var declarations = this.parseVariableDeclarationList({ inFor: true }); - this.context.allowIn = previousAllowIn; - if (declarations.length === 1 && this.matchKeyword('in')) { - var decl = declarations[0]; - if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { - this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); - } - init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); - this.nextToken(); - left = init; - right = this.parseExpression(); - init = null; - } - else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { - init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); - this.nextToken(); - left = init; - right = this.parseAssignmentExpression(); - init = null; - forIn = false; - } - else { - init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); - this.expect(';'); - } - } - else if (this.matchKeyword('const') || this.matchKeyword('let')) { - init = this.createNode(); - var kind = this.nextToken().value; - if (!this.context.strict && this.lookahead.value === 'in') { - init = this.finalize(init, new Node.Identifier(kind)); - this.nextToken(); - left = init; - right = this.parseExpression(); - init = null; - } - else { - var previousAllowIn = this.context.allowIn; - this.context.allowIn = false; - var declarations = this.parseBindingList(kind, { inFor: true }); - this.context.allowIn = previousAllowIn; - if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { - init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); - this.nextToken(); - left = init; - right = this.parseExpression(); - init = null; - } - else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { - init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); - this.nextToken(); - left = init; - right = this.parseAssignmentExpression(); - init = null; - forIn = false; - } - else { - this.consumeSemicolon(); - init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); - } - } - } - else { - var initStartToken = this.lookahead; - var previousAllowIn = this.context.allowIn; - this.context.allowIn = false; - init = this.inheritCoverGrammar(this.parseAssignmentExpression); - this.context.allowIn = previousAllowIn; - if (this.matchKeyword('in')) { - if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { - this.tolerateError(messages_1.Messages.InvalidLHSInForIn); - } - this.nextToken(); - this.reinterpretExpressionAsPattern(init); - left = init; - right = this.parseExpression(); - init = null; - } - else if (this.matchContextualKeyword('of')) { - if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { - this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); - } - this.nextToken(); - this.reinterpretExpressionAsPattern(init); - left = init; - right = this.parseAssignmentExpression(); - init = null; - forIn = false; - } - else { - if (this.match(',')) { - var initSeq = [init]; - while (this.match(',')) { - this.nextToken(); - initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); - } - init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); - } - this.expect(';'); - } - } - } - if (typeof left === 'undefined') { - if (!this.match(';')) { - test = this.parseExpression(); - } - this.expect(';'); - if (!this.match(')')) { - update = this.parseExpression(); - } - } - var body; - if (!this.match(')') && this.config.tolerant) { - this.tolerateUnexpectedToken(this.nextToken()); - body = this.finalize(this.createNode(), new Node.EmptyStatement()); - } - else { - this.expect(')'); - var previousInIteration = this.context.inIteration; - this.context.inIteration = true; - body = this.isolateCoverGrammar(this.parseStatement); - this.context.inIteration = previousInIteration; - } - return (typeof left === 'undefined') ? - this.finalize(node, new Node.ForStatement(init, test, update, body)) : - forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : - this.finalize(node, new Node.ForOfStatement(left, right, body)); - }; - // https://tc39.github.io/ecma262/#sec-continue-statement - Parser.prototype.parseContinueStatement = function () { - var node = this.createNode(); - this.expectKeyword('continue'); - var label = null; - if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { - var id = this.parseVariableIdentifier(); - label = id; - var key = '$' + id.name; - if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { - this.throwError(messages_1.Messages.UnknownLabel, id.name); - } - } - this.consumeSemicolon(); - if (label === null && !this.context.inIteration) { - this.throwError(messages_1.Messages.IllegalContinue); - } - return this.finalize(node, new Node.ContinueStatement(label)); - }; - // https://tc39.github.io/ecma262/#sec-break-statement - Parser.prototype.parseBreakStatement = function () { - var node = this.createNode(); - this.expectKeyword('break'); - var label = null; - if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { - var id = this.parseVariableIdentifier(); - var key = '$' + id.name; - if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { - this.throwError(messages_1.Messages.UnknownLabel, id.name); - } - label = id; - } - this.consumeSemicolon(); - if (label === null && !this.context.inIteration && !this.context.inSwitch) { - this.throwError(messages_1.Messages.IllegalBreak); - } - return this.finalize(node, new Node.BreakStatement(label)); - }; - // https://tc39.github.io/ecma262/#sec-return-statement - Parser.prototype.parseReturnStatement = function () { - if (!this.context.inFunctionBody) { - this.tolerateError(messages_1.Messages.IllegalReturn); - } - var node = this.createNode(); - this.expectKeyword('return'); - var hasArgument = (!this.match(';') && !this.match('}') && - !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) || - this.lookahead.type === 8 /* StringLiteral */ || - this.lookahead.type === 10 /* Template */; - var argument = hasArgument ? this.parseExpression() : null; - this.consumeSemicolon(); - return this.finalize(node, new Node.ReturnStatement(argument)); - }; - // https://tc39.github.io/ecma262/#sec-with-statement - Parser.prototype.parseWithStatement = function () { - if (this.context.strict) { - this.tolerateError(messages_1.Messages.StrictModeWith); - } - var node = this.createNode(); - var body; - this.expectKeyword('with'); - this.expect('('); - var object = this.parseExpression(); - if (!this.match(')') && this.config.tolerant) { - this.tolerateUnexpectedToken(this.nextToken()); - body = this.finalize(this.createNode(), new Node.EmptyStatement()); - } - else { - this.expect(')'); - body = this.parseStatement(); - } - return this.finalize(node, new Node.WithStatement(object, body)); - }; - // https://tc39.github.io/ecma262/#sec-switch-statement - Parser.prototype.parseSwitchCase = function () { - var node = this.createNode(); - var test; - if (this.matchKeyword('default')) { - this.nextToken(); - test = null; - } - else { - this.expectKeyword('case'); - test = this.parseExpression(); - } - this.expect(':'); - var consequent = []; - while (true) { - if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { - break; - } - consequent.push(this.parseStatementListItem()); - } - return this.finalize(node, new Node.SwitchCase(test, consequent)); - }; - Parser.prototype.parseSwitchStatement = function () { - var node = this.createNode(); - this.expectKeyword('switch'); - this.expect('('); - var discriminant = this.parseExpression(); - this.expect(')'); - var previousInSwitch = this.context.inSwitch; - this.context.inSwitch = true; - var cases = []; - var defaultFound = false; - this.expect('{'); - while (true) { - if (this.match('}')) { - break; - } - var clause = this.parseSwitchCase(); - if (clause.test === null) { - if (defaultFound) { - this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); - } - defaultFound = true; - } - cases.push(clause); - } - this.expect('}'); - this.context.inSwitch = previousInSwitch; - return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); - }; - // https://tc39.github.io/ecma262/#sec-labelled-statements - Parser.prototype.parseLabelledStatement = function () { - var node = this.createNode(); - var expr = this.parseExpression(); - var statement; - if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { - this.nextToken(); - var id = expr; - var key = '$' + id.name; - if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { - this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); - } - this.context.labelSet[key] = true; - var body = void 0; - if (this.matchKeyword('class')) { - this.tolerateUnexpectedToken(this.lookahead); - body = this.parseClassDeclaration(); - } - else if (this.matchKeyword('function')) { - var token = this.lookahead; - var declaration = this.parseFunctionDeclaration(); - if (this.context.strict) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); - } - else if (declaration.generator) { - this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); - } - body = declaration; - } - else { - body = this.parseStatement(); - } - delete this.context.labelSet[key]; - statement = new Node.LabeledStatement(id, body); - } - else { - this.consumeSemicolon(); - statement = new Node.ExpressionStatement(expr); - } - return this.finalize(node, statement); - }; - // https://tc39.github.io/ecma262/#sec-throw-statement - Parser.prototype.parseThrowStatement = function () { - var node = this.createNode(); - this.expectKeyword('throw'); - if (this.hasLineTerminator) { - this.throwError(messages_1.Messages.NewlineAfterThrow); - } - var argument = this.parseExpression(); - this.consumeSemicolon(); - return this.finalize(node, new Node.ThrowStatement(argument)); - }; - // https://tc39.github.io/ecma262/#sec-try-statement - Parser.prototype.parseCatchClause = function () { - var node = this.createNode(); - this.expectKeyword('catch'); - this.expect('('); - if (this.match(')')) { - this.throwUnexpectedToken(this.lookahead); - } - var params = []; - var param = this.parsePattern(params); - var paramMap = {}; - for (var i = 0; i < params.length; i++) { - var key = '$' + params[i].value; - if (Object.prototype.hasOwnProperty.call(paramMap, key)) { - this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); - } - paramMap[key] = true; - } - if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { - if (this.scanner.isRestrictedWord(param.name)) { - this.tolerateError(messages_1.Messages.StrictCatchVariable); - } - } - this.expect(')'); - var body = this.parseBlock(); - return this.finalize(node, new Node.CatchClause(param, body)); - }; - Parser.prototype.parseFinallyClause = function () { - this.expectKeyword('finally'); - return this.parseBlock(); - }; - Parser.prototype.parseTryStatement = function () { - var node = this.createNode(); - this.expectKeyword('try'); - var block = this.parseBlock(); - var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; - var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; - if (!handler && !finalizer) { - this.throwError(messages_1.Messages.NoCatchOrFinally); - } - return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); - }; - // https://tc39.github.io/ecma262/#sec-debugger-statement - Parser.prototype.parseDebuggerStatement = function () { - var node = this.createNode(); - this.expectKeyword('debugger'); - this.consumeSemicolon(); - return this.finalize(node, new Node.DebuggerStatement()); - }; - // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations - Parser.prototype.parseStatement = function () { - var statement; - switch (this.lookahead.type) { - case 1 /* BooleanLiteral */: - case 5 /* NullLiteral */: - case 6 /* NumericLiteral */: - case 8 /* StringLiteral */: - case 10 /* Template */: - case 9 /* RegularExpression */: - statement = this.parseExpressionStatement(); - break; - case 7 /* Punctuator */: - var value = this.lookahead.value; - if (value === '{') { - statement = this.parseBlock(); - } - else if (value === '(') { - statement = this.parseExpressionStatement(); - } - else if (value === ';') { - statement = this.parseEmptyStatement(); - } - else { - statement = this.parseExpressionStatement(); - } - break; - case 3 /* Identifier */: - statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); - break; - case 4 /* Keyword */: - switch (this.lookahead.value) { - case 'break': - statement = this.parseBreakStatement(); - break; - case 'continue': - statement = this.parseContinueStatement(); - break; - case 'debugger': - statement = this.parseDebuggerStatement(); - break; - case 'do': - statement = this.parseDoWhileStatement(); - break; - case 'for': - statement = this.parseForStatement(); - break; - case 'function': - statement = this.parseFunctionDeclaration(); - break; - case 'if': - statement = this.parseIfStatement(); - break; - case 'return': - statement = this.parseReturnStatement(); - break; - case 'switch': - statement = this.parseSwitchStatement(); - break; - case 'throw': - statement = this.parseThrowStatement(); - break; - case 'try': - statement = this.parseTryStatement(); - break; - case 'var': - statement = this.parseVariableStatement(); - break; - case 'while': - statement = this.parseWhileStatement(); - break; - case 'with': - statement = this.parseWithStatement(); - break; - default: - statement = this.parseExpressionStatement(); - break; - } - break; - default: - statement = this.throwUnexpectedToken(this.lookahead); - } - return statement; - }; - // https://tc39.github.io/ecma262/#sec-function-definitions - Parser.prototype.parseFunctionSourceElements = function () { - var node = this.createNode(); - this.expect('{'); - var body = this.parseDirectivePrologues(); - var previousLabelSet = this.context.labelSet; - var previousInIteration = this.context.inIteration; - var previousInSwitch = this.context.inSwitch; - var previousInFunctionBody = this.context.inFunctionBody; - this.context.labelSet = {}; - this.context.inIteration = false; - this.context.inSwitch = false; - this.context.inFunctionBody = true; - while (this.lookahead.type !== 2 /* EOF */) { - if (this.match('}')) { - break; - } - body.push(this.parseStatementListItem()); - } - this.expect('}'); - this.context.labelSet = previousLabelSet; - this.context.inIteration = previousInIteration; - this.context.inSwitch = previousInSwitch; - this.context.inFunctionBody = previousInFunctionBody; - return this.finalize(node, new Node.BlockStatement(body)); - }; - Parser.prototype.validateParam = function (options, param, name) { - var key = '$' + name; - if (this.context.strict) { - if (this.scanner.isRestrictedWord(name)) { - options.stricted = param; - options.message = messages_1.Messages.StrictParamName; - } - if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { - options.stricted = param; - options.message = messages_1.Messages.StrictParamDupe; - } - } - else if (!options.firstRestricted) { - if (this.scanner.isRestrictedWord(name)) { - options.firstRestricted = param; - options.message = messages_1.Messages.StrictParamName; - } - else if (this.scanner.isStrictModeReservedWord(name)) { - options.firstRestricted = param; - options.message = messages_1.Messages.StrictReservedWord; - } - else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { - options.stricted = param; - options.message = messages_1.Messages.StrictParamDupe; - } - } - /* istanbul ignore next */ - if (typeof Object.defineProperty === 'function') { - Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); - } - else { - options.paramSet[key] = true; - } - }; - Parser.prototype.parseRestElement = function (params) { - var node = this.createNode(); - this.expect('...'); - var arg = this.parsePattern(params); - if (this.match('=')) { - this.throwError(messages_1.Messages.DefaultRestParameter); - } - if (!this.match(')')) { - this.throwError(messages_1.Messages.ParameterAfterRestParameter); - } - return this.finalize(node, new Node.RestElement(arg)); - }; - Parser.prototype.parseFormalParameter = function (options) { - var params = []; - var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); - for (var i = 0; i < params.length; i++) { - this.validateParam(options, params[i], params[i].value); - } - options.simple = options.simple && (param instanceof Node.Identifier); - options.params.push(param); - }; - Parser.prototype.parseFormalParameters = function (firstRestricted) { - var options; - options = { - simple: true, - params: [], - firstRestricted: firstRestricted - }; - this.expect('('); - if (!this.match(')')) { - options.paramSet = {}; - while (this.lookahead.type !== 2 /* EOF */) { - this.parseFormalParameter(options); - if (this.match(')')) { - break; - } - this.expect(','); - if (this.match(')')) { - break; - } - } - } - this.expect(')'); - return { - simple: options.simple, - params: options.params, - stricted: options.stricted, - firstRestricted: options.firstRestricted, - message: options.message - }; - }; - Parser.prototype.matchAsyncFunction = function () { - var match = this.matchContextualKeyword('async'); - if (match) { - var state = this.scanner.saveState(); - this.scanner.scanComments(); - var next = this.scanner.lex(); - this.scanner.restoreState(state); - match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); - } - return match; - }; - Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { - var node = this.createNode(); - var isAsync = this.matchContextualKeyword('async'); - if (isAsync) { - this.nextToken(); - } - this.expectKeyword('function'); - var isGenerator = isAsync ? false : this.match('*'); - if (isGenerator) { - this.nextToken(); - } - var message; - var id = null; - var firstRestricted = null; - if (!identifierIsOptional || !this.match('(')) { - var token = this.lookahead; - id = this.parseVariableIdentifier(); - if (this.context.strict) { - if (this.scanner.isRestrictedWord(token.value)) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); - } - } - else { - if (this.scanner.isRestrictedWord(token.value)) { - firstRestricted = token; - message = messages_1.Messages.StrictFunctionName; - } - else if (this.scanner.isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = messages_1.Messages.StrictReservedWord; - } - } - } - var previousAllowAwait = this.context.await; - var previousAllowYield = this.context.allowYield; - this.context.await = isAsync; - this.context.allowYield = !isGenerator; - var formalParameters = this.parseFormalParameters(firstRestricted); - var params = formalParameters.params; - var stricted = formalParameters.stricted; - firstRestricted = formalParameters.firstRestricted; - if (formalParameters.message) { - message = formalParameters.message; - } - var previousStrict = this.context.strict; - var previousAllowStrictDirective = this.context.allowStrictDirective; - this.context.allowStrictDirective = formalParameters.simple; - var body = this.parseFunctionSourceElements(); - if (this.context.strict && firstRestricted) { - this.throwUnexpectedToken(firstRestricted, message); - } - if (this.context.strict && stricted) { - this.tolerateUnexpectedToken(stricted, message); - } - this.context.strict = previousStrict; - this.context.allowStrictDirective = previousAllowStrictDirective; - this.context.await = previousAllowAwait; - this.context.allowYield = previousAllowYield; - return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : - this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); - }; - Parser.prototype.parseFunctionExpression = function () { - var node = this.createNode(); - var isAsync = this.matchContextualKeyword('async'); - if (isAsync) { - this.nextToken(); - } - this.expectKeyword('function'); - var isGenerator = isAsync ? false : this.match('*'); - if (isGenerator) { - this.nextToken(); - } - var message; - var id = null; - var firstRestricted; - var previousAllowAwait = this.context.await; - var previousAllowYield = this.context.allowYield; - this.context.await = isAsync; - this.context.allowYield = !isGenerator; - if (!this.match('(')) { - var token = this.lookahead; - id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); - if (this.context.strict) { - if (this.scanner.isRestrictedWord(token.value)) { - this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); - } - } - else { - if (this.scanner.isRestrictedWord(token.value)) { - firstRestricted = token; - message = messages_1.Messages.StrictFunctionName; - } - else if (this.scanner.isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = messages_1.Messages.StrictReservedWord; - } - } - } - var formalParameters = this.parseFormalParameters(firstRestricted); - var params = formalParameters.params; - var stricted = formalParameters.stricted; - firstRestricted = formalParameters.firstRestricted; - if (formalParameters.message) { - message = formalParameters.message; - } - var previousStrict = this.context.strict; - var previousAllowStrictDirective = this.context.allowStrictDirective; - this.context.allowStrictDirective = formalParameters.simple; - var body = this.parseFunctionSourceElements(); - if (this.context.strict && firstRestricted) { - this.throwUnexpectedToken(firstRestricted, message); - } - if (this.context.strict && stricted) { - this.tolerateUnexpectedToken(stricted, message); - } - this.context.strict = previousStrict; - this.context.allowStrictDirective = previousAllowStrictDirective; - this.context.await = previousAllowAwait; - this.context.allowYield = previousAllowYield; - return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : - this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); - }; - // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive - Parser.prototype.parseDirective = function () { - var token = this.lookahead; - var node = this.createNode(); - var expr = this.parseExpression(); - var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; - this.consumeSemicolon(); - return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); - }; - Parser.prototype.parseDirectivePrologues = function () { - var firstRestricted = null; - var body = []; - while (true) { - var token = this.lookahead; - if (token.type !== 8 /* StringLiteral */) { - break; - } - var statement = this.parseDirective(); - body.push(statement); - var directive = statement.directive; - if (typeof directive !== 'string') { - break; - } - if (directive === 'use strict') { - this.context.strict = true; - if (firstRestricted) { - this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); - } - if (!this.context.allowStrictDirective) { - this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); - } - } - else { - if (!firstRestricted && token.octal) { - firstRestricted = token; - } - } - } - return body; - }; - // https://tc39.github.io/ecma262/#sec-method-definitions - Parser.prototype.qualifiedPropertyName = function (token) { - switch (token.type) { - case 3 /* Identifier */: - case 8 /* StringLiteral */: - case 1 /* BooleanLiteral */: - case 5 /* NullLiteral */: - case 6 /* NumericLiteral */: - case 4 /* Keyword */: - return true; - case 7 /* Punctuator */: - return token.value === '['; - default: - break; - } - return false; - }; - Parser.prototype.parseGetterMethod = function () { - var node = this.createNode(); - var isGenerator = false; - var previousAllowYield = this.context.allowYield; - this.context.allowYield = !isGenerator; - var formalParameters = this.parseFormalParameters(); - if (formalParameters.params.length > 0) { - this.tolerateError(messages_1.Messages.BadGetterArity); - } - var method = this.parsePropertyMethod(formalParameters); - this.context.allowYield = previousAllowYield; - return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); - }; - Parser.prototype.parseSetterMethod = function () { - var node = this.createNode(); - var isGenerator = false; - var previousAllowYield = this.context.allowYield; - this.context.allowYield = !isGenerator; - var formalParameters = this.parseFormalParameters(); - if (formalParameters.params.length !== 1) { - this.tolerateError(messages_1.Messages.BadSetterArity); - } - else if (formalParameters.params[0] instanceof Node.RestElement) { - this.tolerateError(messages_1.Messages.BadSetterRestParameter); - } - var method = this.parsePropertyMethod(formalParameters); - this.context.allowYield = previousAllowYield; - return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); - }; - Parser.prototype.parseGeneratorMethod = function () { - var node = this.createNode(); - var isGenerator = true; - var previousAllowYield = this.context.allowYield; - this.context.allowYield = true; - var params = this.parseFormalParameters(); - this.context.allowYield = false; - var method = this.parsePropertyMethod(params); - this.context.allowYield = previousAllowYield; - return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); - }; - // https://tc39.github.io/ecma262/#sec-generator-function-definitions - Parser.prototype.isStartOfExpression = function () { - var start = true; - var value = this.lookahead.value; - switch (this.lookahead.type) { - case 7 /* Punctuator */: - start = (value === '[') || (value === '(') || (value === '{') || - (value === '+') || (value === '-') || - (value === '!') || (value === '~') || - (value === '++') || (value === '--') || - (value === '/') || (value === '/='); // regular expression literal - break; - case 4 /* Keyword */: - start = (value === 'class') || (value === 'delete') || - (value === 'function') || (value === 'let') || (value === 'new') || - (value === 'super') || (value === 'this') || (value === 'typeof') || - (value === 'void') || (value === 'yield'); - break; - default: - break; - } - return start; - }; - Parser.prototype.parseYieldExpression = function () { - var node = this.createNode(); - this.expectKeyword('yield'); - var argument = null; - var delegate = false; - if (!this.hasLineTerminator) { - var previousAllowYield = this.context.allowYield; - this.context.allowYield = false; - delegate = this.match('*'); - if (delegate) { - this.nextToken(); - argument = this.parseAssignmentExpression(); - } - else if (this.isStartOfExpression()) { - argument = this.parseAssignmentExpression(); - } - this.context.allowYield = previousAllowYield; - } - return this.finalize(node, new Node.YieldExpression(argument, delegate)); - }; - // https://tc39.github.io/ecma262/#sec-class-definitions - Parser.prototype.parseClassElement = function (hasConstructor) { - var token = this.lookahead; - var node = this.createNode(); - var kind = ''; - var key = null; - var value = null; - var computed = false; - var method = false; - var isStatic = false; - var isAsync = false; - if (this.match('*')) { - this.nextToken(); - } - else { - computed = this.match('['); - key = this.parseObjectPropertyKey(); - var id = key; - if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { - token = this.lookahead; - isStatic = true; - computed = this.match('['); - if (this.match('*')) { - this.nextToken(); - } - else { - key = this.parseObjectPropertyKey(); - } - } - if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { - var punctuator = this.lookahead.value; - if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { - isAsync = true; - token = this.lookahead; - key = this.parseObjectPropertyKey(); - if (token.type === 3 /* Identifier */ && token.value === 'constructor') { - this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); - } - } - } - } - var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); - if (token.type === 3 /* Identifier */) { - if (token.value === 'get' && lookaheadPropertyKey) { - kind = 'get'; - computed = this.match('['); - key = this.parseObjectPropertyKey(); - this.context.allowYield = false; - value = this.parseGetterMethod(); - } - else if (token.value === 'set' && lookaheadPropertyKey) { - kind = 'set'; - computed = this.match('['); - key = this.parseObjectPropertyKey(); - value = this.parseSetterMethod(); - } - } - else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { - kind = 'init'; - computed = this.match('['); - key = this.parseObjectPropertyKey(); - value = this.parseGeneratorMethod(); - method = true; - } - if (!kind && key && this.match('(')) { - kind = 'init'; - value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); - method = true; - } - if (!kind) { - this.throwUnexpectedToken(this.lookahead); - } - if (kind === 'init') { - kind = 'method'; - } - if (!computed) { - if (isStatic && this.isPropertyKey(key, 'prototype')) { - this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); - } - if (!isStatic && this.isPropertyKey(key, 'constructor')) { - if (kind !== 'method' || !method || (value && value.generator)) { - this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); - } - if (hasConstructor.value) { - this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); - } - else { - hasConstructor.value = true; - } - kind = 'constructor'; - } - } - return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); - }; - Parser.prototype.parseClassElementList = function () { - var body = []; - var hasConstructor = { value: false }; - this.expect('{'); - while (!this.match('}')) { - if (this.match(';')) { - this.nextToken(); - } - else { - body.push(this.parseClassElement(hasConstructor)); - } - } - this.expect('}'); - return body; - }; - Parser.prototype.parseClassBody = function () { - var node = this.createNode(); - var elementList = this.parseClassElementList(); - return this.finalize(node, new Node.ClassBody(elementList)); - }; - Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { - var node = this.createNode(); - var previousStrict = this.context.strict; - this.context.strict = true; - this.expectKeyword('class'); - var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); - var superClass = null; - if (this.matchKeyword('extends')) { - this.nextToken(); - superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); - } - var classBody = this.parseClassBody(); - this.context.strict = previousStrict; - return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); - }; - Parser.prototype.parseClassExpression = function () { - var node = this.createNode(); - var previousStrict = this.context.strict; - this.context.strict = true; - this.expectKeyword('class'); - var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; - var superClass = null; - if (this.matchKeyword('extends')) { - this.nextToken(); - superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); - } - var classBody = this.parseClassBody(); - this.context.strict = previousStrict; - return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); - }; - // https://tc39.github.io/ecma262/#sec-scripts - // https://tc39.github.io/ecma262/#sec-modules - Parser.prototype.parseModule = function () { - this.context.strict = true; - this.context.isModule = true; - this.scanner.isModule = true; - var node = this.createNode(); - var body = this.parseDirectivePrologues(); - while (this.lookahead.type !== 2 /* EOF */) { - body.push(this.parseStatementListItem()); - } - return this.finalize(node, new Node.Module(body)); - }; - Parser.prototype.parseScript = function () { - var node = this.createNode(); - var body = this.parseDirectivePrologues(); - while (this.lookahead.type !== 2 /* EOF */) { - body.push(this.parseStatementListItem()); - } - return this.finalize(node, new Node.Script(body)); - }; - // https://tc39.github.io/ecma262/#sec-imports - Parser.prototype.parseModuleSpecifier = function () { - var node = this.createNode(); - if (this.lookahead.type !== 8 /* StringLiteral */) { - this.throwError(messages_1.Messages.InvalidModuleSpecifier); - } - var token = this.nextToken(); - var raw = this.getTokenRaw(token); - return this.finalize(node, new Node.Literal(token.value, raw)); - }; - // import {} ...; - Parser.prototype.parseImportSpecifier = function () { - var node = this.createNode(); - var imported; - var local; - if (this.lookahead.type === 3 /* Identifier */) { - imported = this.parseVariableIdentifier(); - local = imported; - if (this.matchContextualKeyword('as')) { - this.nextToken(); - local = this.parseVariableIdentifier(); - } - } - else { - imported = this.parseIdentifierName(); - local = imported; - if (this.matchContextualKeyword('as')) { - this.nextToken(); - local = this.parseVariableIdentifier(); - } - else { - this.throwUnexpectedToken(this.nextToken()); - } - } - return this.finalize(node, new Node.ImportSpecifier(local, imported)); - }; - // {foo, bar as bas} - Parser.prototype.parseNamedImports = function () { - this.expect('{'); - var specifiers = []; - while (!this.match('}')) { - specifiers.push(this.parseImportSpecifier()); - if (!this.match('}')) { - this.expect(','); - } - } - this.expect('}'); - return specifiers; - }; - // import ...; - Parser.prototype.parseImportDefaultSpecifier = function () { - var node = this.createNode(); - var local = this.parseIdentifierName(); - return this.finalize(node, new Node.ImportDefaultSpecifier(local)); - }; - // import <* as foo> ...; - Parser.prototype.parseImportNamespaceSpecifier = function () { - var node = this.createNode(); - this.expect('*'); - if (!this.matchContextualKeyword('as')) { - this.throwError(messages_1.Messages.NoAsAfterImportNamespace); - } - this.nextToken(); - var local = this.parseIdentifierName(); - return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); - }; - Parser.prototype.parseImportDeclaration = function () { - if (this.context.inFunctionBody) { - this.throwError(messages_1.Messages.IllegalImportDeclaration); - } - var node = this.createNode(); - this.expectKeyword('import'); - var src; - var specifiers = []; - if (this.lookahead.type === 8 /* StringLiteral */) { - // import 'foo'; - src = this.parseModuleSpecifier(); - } - else { - if (this.match('{')) { - // import {bar} - specifiers = specifiers.concat(this.parseNamedImports()); - } - else if (this.match('*')) { - // import * as foo - specifiers.push(this.parseImportNamespaceSpecifier()); - } - else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { - // import foo - specifiers.push(this.parseImportDefaultSpecifier()); - if (this.match(',')) { - this.nextToken(); - if (this.match('*')) { - // import foo, * as foo - specifiers.push(this.parseImportNamespaceSpecifier()); - } - else if (this.match('{')) { - // import foo, {bar} - specifiers = specifiers.concat(this.parseNamedImports()); - } - else { - this.throwUnexpectedToken(this.lookahead); - } - } - } - else { - this.throwUnexpectedToken(this.nextToken()); - } - if (!this.matchContextualKeyword('from')) { - var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; - this.throwError(message, this.lookahead.value); - } - this.nextToken(); - src = this.parseModuleSpecifier(); - } - this.consumeSemicolon(); - return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); - }; - // https://tc39.github.io/ecma262/#sec-exports - Parser.prototype.parseExportSpecifier = function () { - var node = this.createNode(); - var local = this.parseIdentifierName(); - var exported = local; - if (this.matchContextualKeyword('as')) { - this.nextToken(); - exported = this.parseIdentifierName(); - } - return this.finalize(node, new Node.ExportSpecifier(local, exported)); - }; - Parser.prototype.parseExportDeclaration = function () { - if (this.context.inFunctionBody) { - this.throwError(messages_1.Messages.IllegalExportDeclaration); - } - var node = this.createNode(); - this.expectKeyword('export'); - var exportDeclaration; - if (this.matchKeyword('default')) { - // export default ... - this.nextToken(); - if (this.matchKeyword('function')) { - // export default function foo () {} - // export default function () {} - var declaration = this.parseFunctionDeclaration(true); - exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); - } - else if (this.matchKeyword('class')) { - // export default class foo {} - var declaration = this.parseClassDeclaration(true); - exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); - } - else if (this.matchContextualKeyword('async')) { - // export default async function f () {} - // export default async function () {} - // export default async x => x - var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); - exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); - } - else { - if (this.matchContextualKeyword('from')) { - this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); - } - // export default {}; - // export default []; - // export default (1 + 2); - var declaration = this.match('{') ? this.parseObjectInitializer() : - this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); - this.consumeSemicolon(); - exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); - } - } - else if (this.match('*')) { - // export * from 'foo'; - this.nextToken(); - if (!this.matchContextualKeyword('from')) { - var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; - this.throwError(message, this.lookahead.value); - } - this.nextToken(); - var src = this.parseModuleSpecifier(); - this.consumeSemicolon(); - exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); - } - else if (this.lookahead.type === 4 /* Keyword */) { - // export var f = 1; - var declaration = void 0; - switch (this.lookahead.value) { - case 'let': - case 'const': - declaration = this.parseLexicalDeclaration({ inFor: false }); - break; - case 'var': - case 'class': - case 'function': - declaration = this.parseStatementListItem(); - break; - default: - this.throwUnexpectedToken(this.lookahead); - } - exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); - } - else if (this.matchAsyncFunction()) { - var declaration = this.parseFunctionDeclaration(); - exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); - } - else { - var specifiers = []; - var source = null; - var isExportFromIdentifier = false; - this.expect('{'); - while (!this.match('}')) { - isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); - specifiers.push(this.parseExportSpecifier()); - if (!this.match('}')) { - this.expect(','); - } - } - this.expect('}'); - if (this.matchContextualKeyword('from')) { - // export {default} from 'foo'; - // export {foo} from 'foo'; - this.nextToken(); - source = this.parseModuleSpecifier(); - this.consumeSemicolon(); - } - else if (isExportFromIdentifier) { - // export {default}; // missing fromClause - var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; - this.throwError(message, this.lookahead.value); - } - else { - // export {foo}; - this.consumeSemicolon(); - } - exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); - } - return exportDeclaration; - }; - return Parser; - }()); - exports.Parser = Parser; - - -/***/ }, -/* 9 */ -/***/ function(module, exports) { - - "use strict"; - // Ensure the condition is true, otherwise throw an error. - // This is only to have a better contract semantic, i.e. another safety net - // to catch a logic error. The condition shall be fulfilled in normal case. - // Do NOT use this to enforce a certain condition on any user input. - Object.defineProperty(exports, "__esModule", { value: true }); - function assert(condition, message) { - /* istanbul ignore if */ - if (!condition) { - throw new Error('ASSERT: ' + message); - } - } - exports.assert = assert; - - -/***/ }, -/* 10 */ -/***/ function(module, exports) { - - "use strict"; - /* tslint:disable:max-classes-per-file */ - Object.defineProperty(exports, "__esModule", { value: true }); - var ErrorHandler = (function () { - function ErrorHandler() { - this.errors = []; - this.tolerant = false; - } - ErrorHandler.prototype.recordError = function (error) { - this.errors.push(error); - }; - ErrorHandler.prototype.tolerate = function (error) { - if (this.tolerant) { - this.recordError(error); - } - else { - throw error; - } - }; - ErrorHandler.prototype.constructError = function (msg, column) { - var error = new Error(msg); - try { - throw error; - } - catch (base) { - /* istanbul ignore else */ - if (Object.create && Object.defineProperty) { - error = Object.create(base); - Object.defineProperty(error, 'column', { value: column }); - } - } - /* istanbul ignore next */ - return error; - }; - ErrorHandler.prototype.createError = function (index, line, col, description) { - var msg = 'Line ' + line + ': ' + description; - var error = this.constructError(msg, col); - error.index = index; - error.lineNumber = line; - error.description = description; - return error; - }; - ErrorHandler.prototype.throwError = function (index, line, col, description) { - throw this.createError(index, line, col, description); - }; - ErrorHandler.prototype.tolerateError = function (index, line, col, description) { - var error = this.createError(index, line, col, description); - if (this.tolerant) { - this.recordError(error); - } - else { - throw error; - } - }; - return ErrorHandler; - }()); - exports.ErrorHandler = ErrorHandler; - - -/***/ }, -/* 11 */ -/***/ function(module, exports) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - // Error messages should be identical to V8. - exports.Messages = { - BadGetterArity: 'Getter must not have any formal parameters', - BadSetterArity: 'Setter must have exactly one formal parameter', - BadSetterRestParameter: 'Setter function argument must not be a rest parameter', - ConstructorIsAsync: 'Class constructor may not be an async method', - ConstructorSpecialMethod: 'Class constructor may not be an accessor', - DeclarationMissingInitializer: 'Missing initializer in %0 declaration', - DefaultRestParameter: 'Unexpected token =', - DuplicateBinding: 'Duplicate binding %0', - DuplicateConstructor: 'A class may only have one constructor', - DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', - ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', - GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', - IllegalBreak: 'Illegal break statement', - IllegalContinue: 'Illegal continue statement', - IllegalExportDeclaration: 'Unexpected token', - IllegalImportDeclaration: 'Unexpected token', - IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', - IllegalReturn: 'Illegal return statement', - InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', - InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', - InvalidLHSInAssignment: 'Invalid left-hand side in assignment', - InvalidLHSInForIn: 'Invalid left-hand side in for-in', - InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', - InvalidModuleSpecifier: 'Unexpected token', - InvalidRegExp: 'Invalid regular expression', - LetInLexicalBinding: 'let is disallowed as a lexically bound name', - MissingFromClause: 'Unexpected token', - MultipleDefaultsInSwitch: 'More than one default clause in switch statement', - NewlineAfterThrow: 'Illegal newline after throw', - NoAsAfterImportNamespace: 'Unexpected token', - NoCatchOrFinally: 'Missing catch or finally after try', - ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', - Redeclaration: '%0 \'%1\' has already been declared', - StaticPrototype: 'Classes may not have static property named prototype', - StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', - StrictDelete: 'Delete of an unqualified identifier in strict mode.', - StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', - StrictFunctionName: 'Function name may not be eval or arguments in strict mode', - StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', - StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', - StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', - StrictModeWith: 'Strict mode code may not include a with statement', - StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', - StrictParamDupe: 'Strict mode function may not have duplicate parameter names', - StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', - StrictReservedWord: 'Use of future reserved word in strict mode', - StrictVarName: 'Variable name may not be eval or arguments in strict mode', - TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', - UnexpectedEOS: 'Unexpected end of input', - UnexpectedIdentifier: 'Unexpected identifier', - UnexpectedNumber: 'Unexpected number', - UnexpectedReserved: 'Unexpected reserved word', - UnexpectedString: 'Unexpected string', - UnexpectedTemplate: 'Unexpected quasi %0', - UnexpectedToken: 'Unexpected token %0', - UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', - UnknownLabel: 'Undefined label \'%0\'', - UnterminatedRegExp: 'Invalid regular expression: missing /' - }; - - -/***/ }, -/* 12 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var assert_1 = __webpack_require__(9); - var character_1 = __webpack_require__(4); - var messages_1 = __webpack_require__(11); - function hexValue(ch) { - return '0123456789abcdef'.indexOf(ch.toLowerCase()); - } - function octalValue(ch) { - return '01234567'.indexOf(ch); - } - var Scanner = (function () { - function Scanner(code, handler) { - this.source = code; - this.errorHandler = handler; - this.trackComment = false; - this.isModule = false; - this.length = code.length; - this.index = 0; - this.lineNumber = (code.length > 0) ? 1 : 0; - this.lineStart = 0; - this.curlyStack = []; - } - Scanner.prototype.saveState = function () { - return { - index: this.index, - lineNumber: this.lineNumber, - lineStart: this.lineStart - }; - }; - Scanner.prototype.restoreState = function (state) { - this.index = state.index; - this.lineNumber = state.lineNumber; - this.lineStart = state.lineStart; - }; - Scanner.prototype.eof = function () { - return this.index >= this.length; - }; - Scanner.prototype.throwUnexpectedToken = function (message) { - if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } - return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); - }; - Scanner.prototype.tolerateUnexpectedToken = function (message) { - if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } - this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); - }; - // https://tc39.github.io/ecma262/#sec-comments - Scanner.prototype.skipSingleLineComment = function (offset) { - var comments = []; - var start, loc; - if (this.trackComment) { - comments = []; - start = this.index - offset; - loc = { - start: { - line: this.lineNumber, - column: this.index - this.lineStart - offset - }, - end: {} - }; - } - while (!this.eof()) { - var ch = this.source.charCodeAt(this.index); - ++this.index; - if (character_1.Character.isLineTerminator(ch)) { - if (this.trackComment) { - loc.end = { - line: this.lineNumber, - column: this.index - this.lineStart - 1 - }; - var entry = { - multiLine: false, - slice: [start + offset, this.index - 1], - range: [start, this.index - 1], - loc: loc - }; - comments.push(entry); - } - if (ch === 13 && this.source.charCodeAt(this.index) === 10) { - ++this.index; - } - ++this.lineNumber; - this.lineStart = this.index; - return comments; - } - } - if (this.trackComment) { - loc.end = { - line: this.lineNumber, - column: this.index - this.lineStart - }; - var entry = { - multiLine: false, - slice: [start + offset, this.index], - range: [start, this.index], - loc: loc - }; - comments.push(entry); - } - return comments; - }; - Scanner.prototype.skipMultiLineComment = function () { - var comments = []; - var start, loc; - if (this.trackComment) { - comments = []; - start = this.index - 2; - loc = { - start: { - line: this.lineNumber, - column: this.index - this.lineStart - 2 - }, - end: {} - }; - } - while (!this.eof()) { - var ch = this.source.charCodeAt(this.index); - if (character_1.Character.isLineTerminator(ch)) { - if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { - ++this.index; - } - ++this.lineNumber; - ++this.index; - this.lineStart = this.index; - } - else if (ch === 0x2A) { - // Block comment ends with '*/'. - if (this.source.charCodeAt(this.index + 1) === 0x2F) { - this.index += 2; - if (this.trackComment) { - loc.end = { - line: this.lineNumber, - column: this.index - this.lineStart - }; - var entry = { - multiLine: true, - slice: [start + 2, this.index - 2], - range: [start, this.index], - loc: loc - }; - comments.push(entry); - } - return comments; - } - ++this.index; - } - else { - ++this.index; - } - } - // Ran off the end of the file - the whole thing is a comment - if (this.trackComment) { - loc.end = { - line: this.lineNumber, - column: this.index - this.lineStart - }; - var entry = { - multiLine: true, - slice: [start + 2, this.index], - range: [start, this.index], - loc: loc - }; - comments.push(entry); - } - this.tolerateUnexpectedToken(); - return comments; - }; - Scanner.prototype.scanComments = function () { - var comments; - if (this.trackComment) { - comments = []; - } - var start = (this.index === 0); - while (!this.eof()) { - var ch = this.source.charCodeAt(this.index); - if (character_1.Character.isWhiteSpace(ch)) { - ++this.index; - } - else if (character_1.Character.isLineTerminator(ch)) { - ++this.index; - if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { - ++this.index; - } - ++this.lineNumber; - this.lineStart = this.index; - start = true; - } - else if (ch === 0x2F) { - ch = this.source.charCodeAt(this.index + 1); - if (ch === 0x2F) { - this.index += 2; - var comment = this.skipSingleLineComment(2); - if (this.trackComment) { - comments = comments.concat(comment); - } - start = true; - } - else if (ch === 0x2A) { - this.index += 2; - var comment = this.skipMultiLineComment(); - if (this.trackComment) { - comments = comments.concat(comment); - } - } - else { - break; - } - } - else if (start && ch === 0x2D) { - // U+003E is '>' - if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { - // '-->' is a single-line comment - this.index += 3; - var comment = this.skipSingleLineComment(3); - if (this.trackComment) { - comments = comments.concat(comment); - } - } - else { - break; - } - } - else if (ch === 0x3C && !this.isModule) { - if (this.source.slice(this.index + 1, this.index + 4) === '!--') { - this.index += 4; // ` - -* **Test**: -* **Platform**: -* **Console Output:** -``` -REPLACE ME -``` -* **Build Links**: diff --git a/.github/ISSUE_TEMPLATE/4-report-a-flaky-test.yml b/.github/ISSUE_TEMPLATE/4-report-a-flaky-test.yml new file mode 100644 index 00000000000000..2ad659dec38917 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/4-report-a-flaky-test.yml @@ -0,0 +1,47 @@ +name: Report a flaky test +description: Report a flaky test in our CI +title: "Investigate flaky test - " +labels: ["flaky-test"] +body: + - type: markdown + attributes: + value: | + Thank you for reporting a flaky test. + + Flaky tests are tests that fail occasionally in the Node.js CI, but not + consistently enough to block PRs from landing, or that are failing in CI + jobs or test modes that are not run for every PR. + + Please fill in as much of the form below as you're able. + - type: input + attributes: + label: Test + description: The test that is flaky. + placeholder: e.g. `test-fs-stat-bigint` + validations: + required: true + - type: input + attributes: + label: Platform + description: The platform the test is flaky on. + placeholder: e.g. `macos` or `linux` + - type: textarea + attributes: + label: Console output + description: > + A pasted console output from a failed CI job showing the whole failure + of the test. + render: console + - type: textarea + attributes: + label: Build links + description: Links to builds affected by the flaky test. + value: '- ' + - type: textarea + attributes: + label: Additional information + description: > + If any investigation has been done, please include any information + found, such as how consistently the test fails, whether the failure + could be reproduced locally, when the test started failing, or anything + else you think is relevant. From 01ffe0316cf1cd270d13efd5bd61752d87d4dd0f Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Wed, 17 Nov 2021 13:10:19 +0100 Subject: [PATCH 117/118] test: deflake child-process-pipe-dataflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes: https://github.com/nodejs/node/issues/25988 PR-URL: https://github.com/nodejs/node/pull/40838 Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen Reviewed-By: Michael Dawson Reviewed-By: Rich Trott --- test/parallel/test-child-process-pipe-dataflow.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/parallel/test-child-process-pipe-dataflow.js b/test/parallel/test-child-process-pipe-dataflow.js index 2e2edc65e9e0d5..e989ff135c8047 100644 --- a/test/parallel/test-child-process-pipe-dataflow.js +++ b/test/parallel/test-child-process-pipe-dataflow.js @@ -3,7 +3,6 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); const fs = require('fs'); -const os = require('os'); const spawn = require('child_process').spawn; const tmpdir = require('../common/tmpdir'); @@ -22,12 +21,13 @@ const MB = KB * KB; const file = path.resolve(tmpdir.path, 'data.txt'); const buf = Buffer.alloc(MB).fill('x'); - // Most OS commands that deal with data, attach special - // meanings to new line - for example, line buffering. - // So cut the buffer into lines at some points, forcing - // data flow to be split in the stream. + // Most OS commands that deal with data, attach special meanings to new line - + // for example, line buffering. So cut the buffer into lines at some points, + // forcing data flow to be split in the stream. Do not use os.EOL for \n as + // that is 2 characters on Windows and is sometimes converted to 1 character + // which causes the test to fail. for (let i = 1; i < KB; i++) - buf.write(os.EOL, i * KB); + buf.write('\n', i * KB); fs.writeFileSync(file, buf.toString()); cat = spawn('cat', [file]); From 12029ce9e7f2f157c1a8ca60a7eab1c9c68aaa12 Mon Sep 17 00:00:00 2001 From: Beth Griggs Date: Fri, 26 Nov 2021 00:10:19 +0000 Subject: [PATCH 118/118] 2021-12-01, Version 16.13.1 'Gallium' (LTS) Notable changes: - **deps**: upgrade npm to 8.1.2 (npm team) [#40643](https://github.com/nodejs/node/pull/40643) - **deps**: update c-ares to 1.18.1 (Richard Lau) [#40660](https://github.com/nodejs/node/pull/40660) - **doc**: add VoltrexMaster to collaborators (voltrexmaster) [#40566](https://github.com/nodejs/node/pull/40566) - **lib**: fix regular expression to detect \`/\` and \`\\\` (Francesco Trotta) [#40325](https://github.com/nodejs/node/pull/40325) PR-URL: https://github.com/nodejs/node/pull/40974 --- CHANGELOG.md | 3 +- doc/changelogs/CHANGELOG_V16.md | 133 ++++++++++++++++++++++++++++++++ src/node_version.h | 2 +- 3 files changed, 136 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c74234918300fc..766d86e4a82504 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,7 +33,8 @@ release. -16.13.0
+16.13.1
+16.13.0
16.12.0
16.11.1
16.11.0
diff --git a/doc/changelogs/CHANGELOG_V16.md b/doc/changelogs/CHANGELOG_V16.md index 9c8e089841b18e..546457cd6ce1fa 100644 --- a/doc/changelogs/CHANGELOG_V16.md +++ b/doc/changelogs/CHANGELOG_V16.md @@ -9,6 +9,7 @@ +16.13.1
16.13.0
@@ -53,6 +54,138 @@ * [io.js](CHANGELOG\_IOJS.md) * [Archive](CHANGELOG\_ARCHIVE.md) + + +## 2021-12-01, Version 16.13.1 'Gallium' (LTS), @BethGriggs + +### Notable Changes + +* \[[`c14eb2325d`](https://github.com/nodejs/node/commit/c14eb2325d)] - **deps**: upgrade npm to 8.1.2 (npm team) [#40643](https://github.com/nodejs/node/pull/40643) +* \[[`a901b6c53c`](https://github.com/nodejs/node/commit/a901b6c53c)] - **deps**: update c-ares to 1.18.1 (Richard Lau) [#40660](https://github.com/nodejs/node/pull/40660) + * This release contains a c-ares update to fix a regression introduced in Node.js v16.6.2 resolving CNAME records containing underscores ([#39780](https://github.com/nodejs/node/issues/39780)). +* \[[`755c08573f`](https://github.com/nodejs/node/commit/755c08573f)] - **doc**: add VoltrexMaster to collaborators (voltrexmaster) [#40566](https://github.com/nodejs/node/pull/40566) +* \[[`881dd7ba2a`](https://github.com/nodejs/node/commit/881dd7ba2a)] - **lib**: fix regular expression to detect \`/\` and \`\\\` (Francesco Trotta) [#40325](https://github.com/nodejs/node/pull/40325) + +### Commits + +* \[[`996bc6e840`](https://github.com/nodejs/node/commit/996bc6e840)] - **benchmark**: increase crypto DSA keygen params (Brian White) [#40416](https://github.com/nodejs/node/pull/40416) +* \[[`27009092c8`](https://github.com/nodejs/node/commit/27009092c8)] - **build**: skip long-running Actions for README-only modifications (Rich Trott) [#40571](https://github.com/nodejs/node/pull/40571) +* \[[`4581997ed0`](https://github.com/nodejs/node/commit/4581997ed0)] - **build**: disable v8 pointer compression on 32bit archs (Cheng Zhao) [#40418](https://github.com/nodejs/node/pull/40418) +* \[[`17433060d4`](https://github.com/nodejs/node/commit/17433060d4)] - **build**: fix actions pull request's branch (Mestery) [#40494](https://github.com/nodejs/node/pull/40494) +* \[[`bfdd32fa62`](https://github.com/nodejs/node/commit/bfdd32fa62)] - **build**: avoid run find inactive authors on forked repo (Jiawen Geng) [#40465](https://github.com/nodejs/node/pull/40465) +* \[[`134e8afc59`](https://github.com/nodejs/node/commit/134e8afc59)] - **build**: update codeowners-validator to 0.6 (FrankQiu) [#40307](https://github.com/nodejs/node/pull/40307) +* \[[`de125a556c`](https://github.com/nodejs/node/commit/de125a556c)] - **crypto**: avoid double free (Michael Dawson) [#40380](https://github.com/nodejs/node/pull/40380) +* \[[`c14eb2325d`](https://github.com/nodejs/node/commit/c14eb2325d)] - **deps**: upgrade npm to 8.1.2 (npm team) [#40643](https://github.com/nodejs/node/pull/40643) +* \[[`a901b6c53c`](https://github.com/nodejs/node/commit/a901b6c53c)] - **deps**: update c-ares to 1.18.1 (Richard Lau) [#40660](https://github.com/nodejs/node/pull/40660) +* \[[`76e2c3769e`](https://github.com/nodejs/node/commit/76e2c3769e)] - **deps**: upgrade npm to 8.1.1 (npm team) [#40554](https://github.com/nodejs/node/pull/40554) +* \[[`91c3cf5d0a`](https://github.com/nodejs/node/commit/91c3cf5d0a)] - **deps**: V8: cherry-pick 422dc378a1da (Ray Wang) [#40450](https://github.com/nodejs/node/pull/40450) +* \[[`769336ab8c`](https://github.com/nodejs/node/commit/769336ab8c)] - **deps**: add riscv64 config into openssl gypi (Lu Yahan) [#40473](https://github.com/nodejs/node/pull/40473) +* \[[`76d1b5d868`](https://github.com/nodejs/node/commit/76d1b5d868)] - **deps**: patch V8 to 9.4.146.24 (Michaël Zasso) [#40616](https://github.com/nodejs/node/pull/40616) +* \[[`23d11a1dd9`](https://github.com/nodejs/node/commit/23d11a1dd9)] - **dgram**: fix send with out of bounds offset + length (Nitzan Uziely) [#40568](https://github.com/nodejs/node/pull/40568) +* \[[`45bdc77dc0`](https://github.com/nodejs/node/commit/45bdc77dc0)] - **doc**: update cjs-module-lexer repo link (Guy Bedford) [#40707](https://github.com/nodejs/node/pull/40707) +* \[[`de5c5c8509`](https://github.com/nodejs/node/commit/de5c5c8509)] - **doc**: remove `--experimental-modules` documentation (FrankQiu) [#38974](https://github.com/nodejs/node/pull/38974) +* \[[`befac5ddd9`](https://github.com/nodejs/node/commit/befac5ddd9)] - **doc**: update tracking issues of startup performance (Joyee Cheung) [#40629](https://github.com/nodejs/node/pull/40629) +* \[[`3cb74d72f8`](https://github.com/nodejs/node/commit/3cb74d72f8)] - **doc**: fix markdown syntax and HTML tag misses (ryan) [#40608](https://github.com/nodejs/node/pull/40608) +* \[[`eea061f8f1`](https://github.com/nodejs/node/commit/eea061f8f1)] - **doc**: use 'GitHub Actions workflow' instead (Mestery) [#40586](https://github.com/nodejs/node/pull/40586) +* \[[`7a6e833677`](https://github.com/nodejs/node/commit/7a6e833677)] - **doc**: add node: url scheme (Daniel Nalborczyk) [#40573](https://github.com/nodejs/node/pull/40573) +* \[[`d72fb7df4a`](https://github.com/nodejs/node/commit/d72fb7df4a)] - **doc**: call cwd function (Daniel Nalborczyk) [#40573](https://github.com/nodejs/node/pull/40573) +* \[[`d732ff4614`](https://github.com/nodejs/node/commit/d732ff4614)] - **doc**: remove unused imports (Daniel Nalborczyk) [#40573](https://github.com/nodejs/node/pull/40573) +* \[[`e2114e21f4`](https://github.com/nodejs/node/commit/e2114e21f4)] - **doc**: add info on project's usage of coverity (Michael Dawson) [#40506](https://github.com/nodejs/node/pull/40506) +* \[[`d38077babe`](https://github.com/nodejs/node/commit/d38077babe)] - **doc**: fix typo in changelogs (Luigi Pinca) [#40585](https://github.com/nodejs/node/pull/40585) +* \[[`7c7f8791c6`](https://github.com/nodejs/node/commit/7c7f8791c6)] - **doc**: update onboarding task (Rich Trott) [#40570](https://github.com/nodejs/node/pull/40570) +* \[[`0a7c4ff248`](https://github.com/nodejs/node/commit/0a7c4ff248)] - **doc**: simplify ccache instructions (Rich Trott) [#40550](https://github.com/nodejs/node/pull/40550) +* \[[`5593dd1b25`](https://github.com/nodejs/node/commit/5593dd1b25)] - **doc**: fix macOS environment variables for ccache (Rich Trott) [#40550](https://github.com/nodejs/node/pull/40550) +* \[[`2d4a042675`](https://github.com/nodejs/node/commit/2d4a042675)] - **doc**: improve async\_context introduction (Michaël Zasso) [#40560](https://github.com/nodejs/node/pull/40560) +* \[[`9fcfef09ac`](https://github.com/nodejs/node/commit/9fcfef09ac)] - **doc**: use GFM footnotes in webcrypto.md (Rich Trott) [#40477](https://github.com/nodejs/node/pull/40477) +* \[[`579f01c0a3`](https://github.com/nodejs/node/commit/579f01c0a3)] - **doc**: describe buffer limit of v8.serialize (Ray Wang) [#40243](https://github.com/nodejs/node/pull/40243) +* \[[`3b6cf090a0`](https://github.com/nodejs/node/commit/3b6cf090a0)] - **doc**: use GFM footnotes in maintaining-V8.md (#40476) (Rich Trott) [#40476](https://github.com/nodejs/node/pull/40476) +* \[[`dea701004e`](https://github.com/nodejs/node/commit/dea701004e)] - **doc**: fix `fs.symlink` code example (Juan José Arboleda) [#40414](https://github.com/nodejs/node/pull/40414) +* \[[`595117ff0b`](https://github.com/nodejs/node/commit/595117ff0b)] - **doc**: explain backport labels (Stephen Belanger) [#40520](https://github.com/nodejs/node/pull/40520) +* \[[`042f01e3ed`](https://github.com/nodejs/node/commit/042f01e3ed)] - **doc**: fix entry for Slack channel in onboarding.md (Rich Trott) [#40563](https://github.com/nodejs/node/pull/40563) +* \[[`755c08573f`](https://github.com/nodejs/node/commit/755c08573f)] - **doc**: add VoltrexMaster to collaborators (voltrexmaster) [#40566](https://github.com/nodejs/node/pull/40566) +* \[[`c029d0b61f`](https://github.com/nodejs/node/commit/c029d0b61f)] - **doc**: document considerations for inclusion in core (Rich Trott) [#40338](https://github.com/nodejs/node/pull/40338) +* \[[`836fc274e4`](https://github.com/nodejs/node/commit/836fc274e4)] - _**Revert**_ "**doc**: fix typo in stream docs" (Luigi Pinca) [#40819](https://github.com/nodejs/node/pull/40819) +* \[[`b3a12767a4`](https://github.com/nodejs/node/commit/b3a12767a4)] - **doc**: update link in onboarding doc (Rich Trott) [#40539](https://github.com/nodejs/node/pull/40539) +* \[[`aa47c9f38f`](https://github.com/nodejs/node/commit/aa47c9f38f)] - **doc**: clarify behavior of napi\_extended\_error\_info (Michael Dawson) [#40458](https://github.com/nodejs/node/pull/40458) +* \[[`bf88328bdc`](https://github.com/nodejs/node/commit/bf88328bdc)] - **doc**: add updating expected assets to release guide (Richard Lau) [#40470](https://github.com/nodejs/node/pull/40470) +* \[[`621266afc7`](https://github.com/nodejs/node/commit/621266afc7)] - **doc**: format doc/api/\*.md with markdown formatter (Rich Trott) [#40403](https://github.com/nodejs/node/pull/40403) +* \[[`7b746381ce`](https://github.com/nodejs/node/commit/7b746381ce)] - **doc**: specify that maxFreeSockets is per host (Luigi Pinca) [#40483](https://github.com/nodejs/node/pull/40483) +* \[[`934dcc85c3`](https://github.com/nodejs/node/commit/934dcc85c3)] - **doc**: update Collaborator guide to reflect GitHub web UI update (Antoine du Hamel) [#40456](https://github.com/nodejs/node/pull/40456) +* \[[`4724e07476`](https://github.com/nodejs/node/commit/4724e07476)] - **doc**: indicate n-api out params that may be NULL (Isaac Brodsky) [#40371](https://github.com/nodejs/node/pull/40371) +* \[[`3b1499c971`](https://github.com/nodejs/node/commit/3b1499c971)] - **doc**: update CHANGELOG.md for Node.js 16.13.0 (Richard Lau) [#40617](https://github.com/nodejs/node/pull/40617) +* \[[`881dd7ba2a`](https://github.com/nodejs/node/commit/881dd7ba2a)] - **lib**: fix regular expression to detect \`/\` and \`\\\` (Francesco Trotta) [#40325](https://github.com/nodejs/node/pull/40325) +* \[[`0a8c33123e`](https://github.com/nodejs/node/commit/0a8c33123e)] - **lib,url**: correct URL's argument to pass idlharness (Khaidi Chu) [#39848](https://github.com/nodejs/node/pull/39848) +* \[[`480f0e1d20`](https://github.com/nodejs/node/commit/480f0e1d20)] - **meta**: use form schema for flaky test template (Michaël Zasso) [#40737](https://github.com/nodejs/node/pull/40737) +* \[[`55ff97342d`](https://github.com/nodejs/node/commit/55ff97342d)] - **meta**: update AUTHORS (Node.js GitHub Bot) [#40668](https://github.com/nodejs/node/pull/40668) +* \[[`ef46cb428d`](https://github.com/nodejs/node/commit/ef46cb428d)] - **meta**: consolidate AUTHORS entries for brettkiefer (Rich Trott) [#40599](https://github.com/nodejs/node/pull/40599) +* \[[`7230b6d33d`](https://github.com/nodejs/node/commit/7230b6d33d)] - **meta**: consolidate AUTHORS entries for alexzherdev (Rich Trott) [#40620](https://github.com/nodejs/node/pull/40620) +* \[[`9e12ed4f68`](https://github.com/nodejs/node/commit/9e12ed4f68)] - **meta**: consolidate AUTHORS entries for Azard (Rich Trott) [#40619](https://github.com/nodejs/node/pull/40619) +* \[[`97aa8e42b8`](https://github.com/nodejs/node/commit/97aa8e42b8)] - **meta**: move Fishrock123 to emeritus (Jeremiah Senkpiel) [#40596](https://github.com/nodejs/node/pull/40596) +* \[[`7b1c89f357`](https://github.com/nodejs/node/commit/7b1c89f357)] - **meta**: consolidate AUTHORS entries for clakech (Rich Trott) [#40589](https://github.com/nodejs/node/pull/40589) +* \[[`0003cb6b3b`](https://github.com/nodejs/node/commit/0003cb6b3b)] - **meta**: consolidate AUTHORS entries for darai0512 (Rich Trott) [#40569](https://github.com/nodejs/node/pull/40569) +* \[[`7590bacec1`](https://github.com/nodejs/node/commit/7590bacec1)] - **meta**: update AUTHORS (Node.js GitHub Bot) [#40580](https://github.com/nodejs/node/pull/40580) +* \[[`a5475df083`](https://github.com/nodejs/node/commit/a5475df083)] - **meta**: consolidate AUTHORS entries for dfabulich (Rich Trott) [#40527](https://github.com/nodejs/node/pull/40527) +* \[[`c021a7f169`](https://github.com/nodejs/node/commit/c021a7f169)] - **meta**: move one or more collaborators to emeritus (Node.js GitHub Bot) [#40464](https://github.com/nodejs/node/pull/40464) +* \[[`d64cf1706c`](https://github.com/nodejs/node/commit/d64cf1706c)] - **meta**: add Richard Lau to TSC list in README.md (Rich Trott) [#40523](https://github.com/nodejs/node/pull/40523) +* \[[`d09b8239bf`](https://github.com/nodejs/node/commit/d09b8239bf)] - **meta**: consolidate AUTHORS entries for dguo (Rich Trott) [#40517](https://github.com/nodejs/node/pull/40517) +* \[[`66192060e7`](https://github.com/nodejs/node/commit/66192060e7)] - **meta**: consolidate AUTHORS entries for cxreg (Rich Trott) [#40490](https://github.com/nodejs/node/pull/40490) +* \[[`b4f51276cb`](https://github.com/nodejs/node/commit/b4f51276cb)] - **meta**: update AUTHORS (Node.js GitHub Bot) [#40485](https://github.com/nodejs/node/pull/40485) +* \[[`2a2b549a28`](https://github.com/nodejs/node/commit/2a2b549a28)] - **meta**: consolidate AUTHORS entries for emanuelbuholzer (Rich Trott) [#40469](https://github.com/nodejs/node/pull/40469) +* \[[`618bbbf2f4`](https://github.com/nodejs/node/commit/618bbbf2f4)] - **meta**: consolidate AUTHORS entries for ebickle (Rich Trott) [#40447](https://github.com/nodejs/node/pull/40447) +* \[[`06706e8dd2`](https://github.com/nodejs/node/commit/06706e8dd2)] - **meta**: add `typings` to label-pr-config (Mestery) [#40401](https://github.com/nodejs/node/pull/40401) +* \[[`e2c9e1ccdd`](https://github.com/nodejs/node/commit/e2c9e1ccdd)] - **meta**: consolidate AUTHORS entries for evantorrie (Rich Trott) [#40430](https://github.com/nodejs/node/pull/40430) +* \[[`dab574e937`](https://github.com/nodejs/node/commit/dab574e937)] - **policy**: fix message for invalid manifest specifier (Rich Trott) [#40574](https://github.com/nodejs/node/pull/40574) +* \[[`58de6cebb6`](https://github.com/nodejs/node/commit/58de6cebb6)] - **process**: refactor execution (Voltrex) [#40664](https://github.com/nodejs/node/pull/40664) +* \[[`bc0eb0a3ea`](https://github.com/nodejs/node/commit/bc0eb0a3ea)] - **src**: make LoadEnvironment with string work with builtin modules path (Michaël Zasso) [#40607](https://github.com/nodejs/node/pull/40607) +* \[[`2c8a6ec28e`](https://github.com/nodejs/node/commit/2c8a6ec28e)] - **src**: remove usage of `AllocatedBuffer` from `node_http2` (Darshan Sen) [#40584](https://github.com/nodejs/node/pull/40584) +* \[[`59c26a2b2c`](https://github.com/nodejs/node/commit/59c26a2b2c)] - **src**: fix #endif description in crypto\_keygen.h (Tobias Nießen) [#40639](https://github.com/nodejs/node/pull/40639) +* \[[`789fef1309`](https://github.com/nodejs/node/commit/789fef1309)] - **src**: throw error instead of assertion (Ray Wang) [#40243](https://github.com/nodejs/node/pull/40243) +* \[[`7a8a6deee7`](https://github.com/nodejs/node/commit/7a8a6deee7)] - **src**: register external references in os bindings (Joyee Cheung) [#40239](https://github.com/nodejs/node/pull/40239) +* \[[`7bb3d43432`](https://github.com/nodejs/node/commit/7bb3d43432)] - **src**: register external references in crypto bindings (Joyee Cheung) [#40239](https://github.com/nodejs/node/pull/40239) +* \[[`143c881ccb`](https://github.com/nodejs/node/commit/143c881ccb)] - **src**: add missing inialization in agent.h (Michael Dawson) [#40379](https://github.com/nodejs/node/pull/40379) +* \[[`c15afda79f`](https://github.com/nodejs/node/commit/c15afda79f)] - **src**: get embedder options on-demand (Joyee Cheung) [#40357](https://github.com/nodejs/node/pull/40357) +* \[[`ff3b7d228e`](https://github.com/nodejs/node/commit/ff3b7d228e)] - **src**: ensure V8 initialized before marking milestone (Shelley Vohr) [#40405](https://github.com/nodejs/node/pull/40405) +* \[[`774bc46327`](https://github.com/nodejs/node/commit/774bc46327)] - **src,crypto**: remove `AllocatedBuffer` from `crypto_cipher.cc` (Darshan Sen) [#40400](https://github.com/nodejs/node/pull/40400) +* \[[`4030eff3d6`](https://github.com/nodejs/node/commit/4030eff3d6)] - **src,fs**: remove `ToLocalChecked()` call from `fs::AfterMkdirp()` (Darshan Sen) [#40386](https://github.com/nodejs/node/pull/40386) +* \[[`3ac99a2417`](https://github.com/nodejs/node/commit/3ac99a2417)] - **src,stream**: remove `*Check*()` calls from non-`Initialize()` functions (Darshan Sen) [#40425](https://github.com/nodejs/node/pull/40425) +* \[[`36d3b123a0`](https://github.com/nodejs/node/commit/36d3b123a0)] - **stream**: support array of streams in promises pipeline (Mestery) [#40193](https://github.com/nodejs/node/pull/40193) +* \[[`01ffe0316c`](https://github.com/nodejs/node/commit/01ffe0316c)] - **test**: deflake child-process-pipe-dataflow (Luigi Pinca) [#40838](https://github.com/nodejs/node/pull/40838) +* \[[`63b44fc429`](https://github.com/nodejs/node/commit/63b44fc429)] - **test**: skip macos sandbox test with builtin modules path (Michaël Zasso) [#40607](https://github.com/nodejs/node/pull/40607) +* \[[`3d50997ccb`](https://github.com/nodejs/node/commit/3d50997ccb)] - **test**: add semicolon after chunk size (Luigi Pinca) [#40487](https://github.com/nodejs/node/pull/40487) +* \[[`f114e35115`](https://github.com/nodejs/node/commit/f114e35115)] - **test**: deflake http2-cancel-while-client-reading (Luigi Pinca) [#40659](https://github.com/nodejs/node/pull/40659) +* \[[`f778fa230b`](https://github.com/nodejs/node/commit/f778fa230b)] - **test**: test `crypto.setEngine()` using an actual engine (Darshan Sen) [#40481](https://github.com/nodejs/node/pull/40481) +* \[[`b9533c592a`](https://github.com/nodejs/node/commit/b9533c592a)] - **test**: use conventional argument order in assertion (Tobias Nießen) [#40591](https://github.com/nodejs/node/pull/40591) +* \[[`e72c95c580`](https://github.com/nodejs/node/commit/e72c95c580)] - **test**: fix test description (Luigi Pinca) [#40486](https://github.com/nodejs/node/pull/40486) +* \[[`af4e682758`](https://github.com/nodejs/node/commit/af4e682758)] - **test**: pass URL's toascii.window\.js WPT (Khaidi Chu) [#39910](https://github.com/nodejs/node/pull/39910) +* \[[`6de88bc5ed`](https://github.com/nodejs/node/commit/6de88bc5ed)] - **test**: adjust CLI flags test to ignore blank lines in doc (Rich Trott) [#40403](https://github.com/nodejs/node/pull/40403) +* \[[`8226690097`](https://github.com/nodejs/node/commit/8226690097)] - **test**: mark test-policy-integrity flaky on Windows (Rich Trott) [#40684](https://github.com/nodejs/node/pull/40684) +* \[[`50c6666b37`](https://github.com/nodejs/node/commit/50c6666b37)] - **test**: fix test-datetime-change-notify after daylight change (Piotr Rybak) [#40684](https://github.com/nodejs/node/pull/40684) +* \[[`9227f2af79`](https://github.com/nodejs/node/commit/9227f2af79)] - **test**: split test-crypto-dh.js (Joyee Cheung) [#40451](https://github.com/nodejs/node/pull/40451) +* \[[`c593cff0af`](https://github.com/nodejs/node/commit/c593cff0af)] - **test,doc**: correct documentation for runBenchmark() (Rich Trott) [#40683](https://github.com/nodejs/node/pull/40683) +* \[[`aef809f5c8`](https://github.com/nodejs/node/commit/aef809f5c8)] - **test,tools**: increase pummel/benchmark test timeout from 4x to 6x (Rich Trott) [#40684](https://github.com/nodejs/node/pull/40684) +* \[[`908f6447cd`](https://github.com/nodejs/node/commit/908f6447cd)] - **test,tools**: increase timeout for benchmark tests (Rich Trott) [#40684](https://github.com/nodejs/node/pull/40684) +* \[[`64c6575f44`](https://github.com/nodejs/node/commit/64c6575f44)] - **tools**: simplify and fix commit queue (Michaël Zasso) [#40742](https://github.com/nodejs/node/pull/40742) +* \[[`cba8eaf264`](https://github.com/nodejs/node/commit/cba8eaf264)] - **tools**: ensure the PR was not pushed before merging (Antoine du Hamel) [#40747](https://github.com/nodejs/node/pull/40747) +* \[[`1c8590e1fe`](https://github.com/nodejs/node/commit/1c8590e1fe)] - **tools**: update ESLint to 8.2.0 (Luigi Pinca) [#40734](https://github.com/nodejs/node/pull/40734) +* \[[`18800dee0a`](https://github.com/nodejs/node/commit/18800dee0a)] - **tools**: use GitHub Squash and Merge feature when using CQ (Antoine du Hamel) [#40666](https://github.com/nodejs/node/pull/40666) +* \[[`48a785edb7`](https://github.com/nodejs/node/commit/48a785edb7)] - **tools**: fix bug in `prefer-primordials` ESLint rule (Antoine du Hamel) [#40628](https://github.com/nodejs/node/pull/40628) +* \[[`adde2a7a8c`](https://github.com/nodejs/node/commit/adde2a7a8c)] - **tools**: add script to update c-ares (Richard Lau) [#40660](https://github.com/nodejs/node/pull/40660) +* \[[`c12ce898e8`](https://github.com/nodejs/node/commit/c12ce898e8)] - **tools**: abort CQ session when landing several commits (Antoine du Hamel) [#40577](https://github.com/nodejs/node/pull/40577) +* \[[`dd08e532a2`](https://github.com/nodejs/node/commit/dd08e532a2)] - **tools**: fix commit-lint workflow (Antoine du Hamel) [#40673](https://github.com/nodejs/node/pull/40673) +* \[[`b4a80dba79`](https://github.com/nodejs/node/commit/b4a80dba79)] - **tools**: avoid fetch extra commits when validating commit messages (Antoine du Hamel) [#39128](https://github.com/nodejs/node/pull/39128) +* \[[`2a53995442`](https://github.com/nodejs/node/commit/2a53995442)] - **tools**: update ESLint to 8.1.0 (Luigi Pinca) [#40582](https://github.com/nodejs/node/pull/40582) +* \[[`8648e50183`](https://github.com/nodejs/node/commit/8648e50183)] - **tools**: fix formatting of warning message in update-authors.js (Rich Trott) [#40600](https://github.com/nodejs/node/pull/40600) +* \[[`59de0f703f`](https://github.com/nodejs/node/commit/59de0f703f)] - **tools**: udpate doc tools to accommodate GFM footnotes (Rich Trott) [#40477](https://github.com/nodejs/node/pull/40477) +* \[[`abf3b84d77`](https://github.com/nodejs/node/commit/abf3b84d77)] - **tools**: add support for import assertions in linter (Antoine du Hamel) [#39924](https://github.com/nodejs/node/pull/39924) +* \[[`04c2cbecb9`](https://github.com/nodejs/node/commit/04c2cbecb9)] - **tools**: update tools/lint-md dependencies to support GFM footnotes (Rich Trott) [#40445](https://github.com/nodejs/node/pull/40445) +* \[[`a9990876f7`](https://github.com/nodejs/node/commit/a9990876f7)] - **tools**: update lint-md dependencies (Rich Trott) [#40404](https://github.com/nodejs/node/pull/40404) +* \[[`f45814bad1`](https://github.com/nodejs/node/commit/f45814bad1)] - **tools,meta**: remove exclusions from AUTHORS (Rich Trott) [#40648](https://github.com/nodejs/node/pull/40648) +* \[[`7d550ad966`](https://github.com/nodejs/node/commit/7d550ad966)] - **tty**: support more CI services in `getColorDepth` (Richie Bendall) [#40385](https://github.com/nodejs/node/pull/40385) +* \[[`cdea5b671b`](https://github.com/nodejs/node/commit/cdea5b671b)] - **typings**: add more bindings typings (Mestery) [#40415](https://github.com/nodejs/node/pull/40415) +* \[[`67c7d11f1a`](https://github.com/nodejs/node/commit/67c7d11f1a)] - **typings**: add JSDoc typings for inspector (Voltrex) [#38390](https://github.com/nodejs/node/pull/38390) +* \[[`fbe0323ebf`](https://github.com/nodejs/node/commit/fbe0323ebf)] - **typings**: improve internal bindings typings (Mestery) [#40411](https://github.com/nodejs/node/pull/40411) +* \[[`63ab0031c3`](https://github.com/nodejs/node/commit/63ab0031c3)] - **typings**: separate `internalBinding` typings (Mestery) [#40409](https://github.com/nodejs/node/pull/40409) + ## 2021-10-26, Version 16.13.0 'Gallium' (LTS), @richardlau diff --git a/src/node_version.h b/src/node_version.h index f73467e8ff1a5e..e46385fd509a48 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -29,7 +29,7 @@ #define NODE_VERSION_IS_LTS 1 #define NODE_VERSION_LTS_CODENAME "Gallium" -#define NODE_VERSION_IS_RELEASE 0 +#define NODE_VERSION_IS_RELEASE 1 #ifndef NODE_STRINGIFY #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)