diff --git a/.eslintignore b/.eslintignore index 6791fbf312a08b..1ccb8f831baa0b 100644 --- a/.eslintignore +++ b/.eslintignore @@ -6,3 +6,4 @@ test/disabled test/tmp*/ tools/eslint node_modules +benchmark/tmp/ diff --git a/.eslintrc b/.eslintrc.yaml similarity index 94% rename from .eslintrc rename to .eslintrc.yaml index 0aed06ca55f5c3..cf1f36c86bcbdc 100644 --- a/.eslintrc +++ b/.eslintrc.yaml @@ -84,7 +84,11 @@ rules: eol-last: 2 func-call-spacing: 2 func-name-matching: 2 - indent: [2, 2, {SwitchCase: 1, MemberExpression: 1}] + indent: [2, 2, {ArrayExpression: first, + CallExpression: {arguments: first}, + MemberExpression: 1, + ObjectExpression: first, + SwitchCase: 1}] key-spacing: [2, {mode: minimum}] keyword-spacing: 2 linebreak-style: [2, unix] @@ -120,12 +124,11 @@ rules: template-curly-spacing: 2 # Custom rules in tools/eslint-rules - align-function-arguments: 2 align-multiline-assignment: 2 assert-fail-single-argument: 2 assert-throws-arguments: [2, { requireTwo: false }] new-with-error: [2, Error, RangeError, TypeError, SyntaxError, ReferenceError] - no-useless-regex-char-class-escape: [2, { override: ['[', ']'] }] + timer-arguments: 2 # Global scoped method and vars globals: diff --git a/AUTHORS b/AUTHORS index f52fb4d2d72c28..6d4c9842d4774c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -935,7 +935,7 @@ Felix Becker Igor Klopov Tsarevich Dmitry Ojas Shirekar -Noah Rose +Noah Rose Ledesma Rafael Cepeda Chinedu Francis Nwafili Braydon Fuller diff --git a/BUILDING.md b/BUILDING.md index b98bb75d79b656..03a18ef3baf9eb 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -109,7 +109,8 @@ Prerequisites: * One of: * [Visual C++ Build Tools](http://landinghub.visualstudio.com/visual-cpp-build-tools) * [Visual Studio 2015 Update 3](https://www.visualstudio.com/), all editions - including the Community edition. + including the Community edition (remember to select + "Common Tools for Visual C++ 2015" feature during installation). * Basic Unix tools required for some tests, [Git for Windows](http://git-scm.com/download/win) includes Git Bash and tools which can be included in the global `PATH`. diff --git a/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index 32533304fecc67..7ac8f49ee09ff0 100644 --- a/COLLABORATOR_GUIDE.md +++ b/COLLABORATOR_GUIDE.md @@ -120,6 +120,7 @@ information regarding the change process: for an issue, and/or the hash and commit message if the commit fixes a bug in a previous commit. Multiple `Fixes:` lines may be added if appropriate. +- A `Refs:` line referencing a URL for any relevant background. - A `Reviewed-By: Name ` line for yourself and any other Collaborators who have reviewed the change. - Useful for @mentions / contact list if something goes wrong in the PR. @@ -318,9 +319,8 @@ CTC for further discussion. #### How are LTS Branches Managed? -There are currently three LTS branches: `v4.x`, `v0.10`, and `v0.12`. Each -of these is paired with a "staging" branch: `v4.x-staging`, `v0.10-staging`, -and `v0.12-staging`. +There are currently two LTS branches: `v6.x` and `v4.x`. Each of these is paired +with a "staging" branch: `v6.x-staging` and `v4.x-staging`. As commits land in `master`, they are cherry-picked back to each staging branch as appropriate. If the commit applies only to the LTS branch, the @@ -341,18 +341,14 @@ please feel free to include that information in the PR thread. Several LTS related issue and PR labels have been provided: +* `lts-watch-v6.x` - tells the LTS WG that the issue/PR needs to be considered + for landing in the `v6.x-staging` branch. * `lts-watch-v4.x` - tells the LTS WG that the issue/PR needs to be considered for landing in the `v4.x-staging` branch. -* `lts-watch-v0.10` - tells the LTS WG that the issue/PR needs to be considered - for landing in the `v0.10-staging` branch. -* `lts-watch-v0.12` - tells the LTS WG that the issue/PR needs to be considered - for landing in the `v0.12-staging` branch. +* `land-on-v6.x` - tells the release team that the commit should be landed + in a future v6.x release * `land-on-v4.x` - tells the release team that the commit should be landed in a future v4.x release -* `land-on-v0.10` - tells the release team that the commit should be landed - in a future v0.10 release -* `land-on-v0.12` - tells the release team that the commit should be landed - in a future v0.12 release Any collaborator can attach these labels to any PR/issue. As commits are landed into the staging branches, the `lts-watch-` label will be removed. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6d419aa4954fde..c60eeb1c6e3040 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -136,10 +136,13 @@ Check the output of `git log --oneline files_that_you_changed` to find out what subsystem (or subsystems) your changes touch. If your patch fixes an open issue, you can add a reference to it at the end -of the log. Use the `Fixes:` prefix and the full issue URL. For example: +of the log. Use the `Fixes:` prefix and the full issue URL. For other references +use `Refs:`. For example: ```txt Fixes: https://github.com/nodejs/node/issues/1337 +Refs: http://eslint.org/docs/rules/space-in-parens.html +Refs: https://github.com/nodejs/node/pull/3615 ``` ### Step 4: Rebase diff --git a/README.md b/README.md index 3bc0bea7020e8b..1cc6eb11dc053b 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,8 @@ more information about the governance of the Node.js project, see **Julien Gilli** <jgilli@nodejs.org> * [mscdex](https://github.com/mscdex) - **Brian White** <mscdex@mscdex.net> +* [MylesBorins](https://github.com/MylesBorins) - +**Myles Borins** <myles.borins@gmail.com> * [ofrobots](https://github.com/ofrobots) - **Ali Ijaz Sheikh** <ofrobots@google.com> * [rvagg](https://github.com/rvagg) - @@ -186,8 +188,6 @@ more information about the governance of the Node.js project, see **Shigeki Ohtsu** <ohtsu@iij.ad.jp> * [targos](https://github.com/targos) - **Michaël Zasso** <targos@protonmail.com> -* [TheAlphaNerd](https://github.com/TheAlphaNerd) - -**Myles Borins** <myles.borins@gmail.com> * [thefourtheye](https://github.com/thefourtheye) - **Sakthipriyan Vairamani** <thechargingvolcano@gmail.com> * [trevnorris](https://github.com/trevnorris) - @@ -219,6 +219,8 @@ more information about the governance of the Node.js project, see **Claudio Rodriguez** <cjrodr@yahoo.com> * [danbev](https://github.com/danbev) - **Daniel Bevenius** <daniel.bevenius@gmail.com> +* [edsadr](https://github.com/edsadr) - +**Adrian Estrada** <edsadr@gmail.com> * [eljefedelrodeodeljefe](https://github.com/eljefedelrodeodeljefe) - **Robert Jefe Lindstaedt** <robert.lindstaedt@gmail.com> * [estliberitas](https://github.com/estliberitas) - @@ -327,6 +329,8 @@ more information about the governance of the Node.js project, see **Glen Keane** <glenkeane.94@gmail.com> * [thlorenz](https://github.com/thlorenz) - **Thorsten Lorenz** <thlorenz@gmx.de> +* [TimothyGu](https://github.com/TimothyGu) - +**Timothy Gu** <timothygu99@gmail.com> * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com> * [vkurchatkin](https://github.com/vkurchatkin) - diff --git a/WORKING_GROUPS.md b/WORKING_GROUPS.md index 0367165a81a5d2..6ba06c9cafa697 100644 --- a/WORKING_GROUPS.md +++ b/WORKING_GROUPS.md @@ -42,7 +42,6 @@ Top Level Working Group](https://github.com/nodejs/TSC/blob/master/WORKING_GROUP * [Benchmarking](#benchmarking) * [Post-mortem](#post-mortem) * [Intl](#intl) -* [HTTP](#http) * [Documentation](#documentation) * [Testing](#testing) @@ -189,21 +188,6 @@ Responsibilities include: * Publishing regular update summaries and other promotional content. -### [HTTP](https://github.com/nodejs/http) - -The HTTP Working Group is chartered for the support and improvement of the -HTTP implementation in Node.js. - -Responsibilities include: -* Addressing HTTP issues on the Node.js issue tracker. -* Authoring and editing HTTP documentation within the Node.js project. -* Reviewing changes to HTTP functionality within the Node.js project. -* Working with the ecosystem of HTTP related module developers to evolve the - HTTP implementation and APIs in core. -* Advising the CTC on all HTTP related issues and discussions. -* Messaging about the future of HTTP to give the community advance notice of - changes. - ### [Docker](https://github.com/nodejs/docker-iojs) The Docker Working Group's purpose is to build, maintain, and improve official diff --git a/benchmark/README.md b/benchmark/README.md index aa198f2b414444..8796e1e7b6ad38 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -161,7 +161,7 @@ For analysing the benchmark results use the `compare.R` tool. ```console $ cat compare-pr-5134.csv | Rscript benchmark/compare.R - improvement significant p.value + improvement confidence p.value string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=ascii 12.46 % *** 1.165345e-04 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=base64-ascii 24.70 % *** 1.820615e-15 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=base64-utf8 23.60 % *** 2.105625e-12 @@ -171,7 +171,7 @@ string_decoder/string-decoder.js n=250000 chunk=1024 inlen=128 encoding=ascii ``` In the output, _improvement_ is the relative improvement of the new version, -hopefully this is positive. _significant_ tells if there is enough +hopefully this is positive. _confidence_ tells if there is enough statistical evidence to validate the _improvement_. If there is enough evidence then there will be at least one star (`*`), more stars is just better. **However if there are no stars, then you shouldn't make any conclusions based on the @@ -189,7 +189,7 @@ may require more runs to obtain (can be set with `--runs`). _For the statistically minded, the R script performs an [independent/unpaired 2-group t-test][t-test], with the null hypothesis that the performance is the -same for both versions. The significant field will show a star if the p-value +same for both versions. The confidence field will show a star if the p-value is less than `0.05`._ The `compare.R` tool can also produce a box plot by using the `--plot filename` @@ -202,7 +202,7 @@ keep the first line since that contains the header information. ```console $ cat compare-pr-5134.csv | sed '1p;/encoding=ascii/!d' | Rscript benchmark/compare.R --plot compare-plot.png - improvement significant p.value + improvement confidence p.value string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=ascii 12.46 % *** 1.165345e-04 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=128 encoding=ascii 6.70 % * 2.928003e-02 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=32 encoding=ascii 7.47 % *** 5.780583e-04 diff --git a/benchmark/buffers/buffer-tojson.js b/benchmark/buffers/buffer-tojson.js new file mode 100644 index 00000000000000..1be59952c3fe60 --- /dev/null +++ b/benchmark/buffers/buffer-tojson.js @@ -0,0 +1,18 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [1e4], + len: [0, 10, 256, 4 * 1024] +}); + +function main(conf) { + var n = +conf.n; + var buf = Buffer.allocUnsafe(+conf.len); + + bench.start(); + for (var i = 0; i < n; ++i) + buf.toJSON(); + bench.end(n); +} diff --git a/benchmark/child_process/child-process-read-ipc.js b/benchmark/child_process/child-process-read-ipc.js index 28f2b6f9272772..30dead18032f98 100644 --- a/benchmark/child_process/child-process-read-ipc.js +++ b/benchmark/child_process/child-process-read-ipc.js @@ -1,14 +1,20 @@ 'use strict'; if (process.argv[2] === 'child') { const len = +process.argv[3]; - const msg = `"${'.'.repeat(len)}"`; - while (true) { - process.send(msg); - } + const msg = '.'.repeat(len); + const send = () => { + while (process.send(msg)); + // Wait: backlog of unsent messages exceeds threshold + setImmediate(send); + }; + send(); } else { const common = require('../common.js'); const bench = common.createBenchmark(main, { - len: [64, 256, 1024, 4096, 32768], + len: [ + 64, 256, 1024, 4096, 16384, 65536, + 65536 << 4, 65536 << 8 + ], dur: [5] }); const spawn = require('child_process').spawn; @@ -18,7 +24,7 @@ if (process.argv[2] === 'child') { const dur = +conf.dur; const len = +conf.len; - const options = { 'stdio': ['ignore', 'ignore', 'ignore', 'ipc'] }; + const options = { 'stdio': ['ignore', 1, 2, 'ipc'] }; const child = spawn(process.argv[0], [process.argv[1], 'child', len], options); @@ -29,8 +35,7 @@ if (process.argv[2] === 'child') { setTimeout(function() { child.kill(); - const gbits = (bytes * 8) / (1024 * 1024 * 1024); - bench.end(gbits); + bench.end(bytes); }, dur * 1000); } } diff --git a/benchmark/common.js b/benchmark/common.js index 9e7253504f9e7e..4ce9501dd9cff7 100644 --- a/benchmark/common.js +++ b/benchmark/common.js @@ -195,8 +195,9 @@ function formatResult(data) { conf += ' ' + key + '=' + JSON.stringify(data.conf[key]); } - const rate = Math.floor(data.rate) - .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + var rate = data.rate.toString().split('.'); + rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + rate = (rate[1] ? rate.join('.') : rate[0]); return `${data.name}${conf}: ${rate}`; } diff --git a/benchmark/compare.R b/benchmark/compare.R index b4316ca7f81600..3f37cad74ad847 100644 --- a/benchmark/compare.R +++ b/benchmark/compare.R @@ -46,7 +46,7 @@ statistics = ddply(dat, "name", function(subdat) { improvement = sprintf("%.2f %%", ((new.mu - old.mu) / old.mu * 100)); p.value = NA; - significant = 'NA'; + confidence = 'NA'; # Check if there is enough data to calulate the calculate the p-value if (length(old.rate) > 1 && length(new.rate) > 1) { # Perform a statistics test to see of there actually is a difference in @@ -56,19 +56,19 @@ statistics = ddply(dat, "name", function(subdat) { # Add user friendly stars to the table. There should be at least one star # before you can say that there is an improvement. - significant = ''; + confidence = ''; if (p.value < 0.001) { - significant = '***'; + confidence = '***'; } else if (p.value < 0.01) { - significant = '**'; + confidence = '**'; } else if (p.value < 0.05) { - significant = '*'; + confidence = '*'; } } r = list( improvement = improvement, - significant = significant, + confidence = confidence, p.value = p.value ); return(data.frame(r)); diff --git a/benchmark/http/create-clientrequest.js b/benchmark/http/create-clientrequest.js new file mode 100644 index 00000000000000..76134663d00a79 --- /dev/null +++ b/benchmark/http/create-clientrequest.js @@ -0,0 +1,23 @@ +'use strict'; + +var common = require('../common.js'); +var ClientRequest = require('http').ClientRequest; + +var bench = common.createBenchmark(main, { + pathlen: [1, 8, 16, 32, 64, 128], + n: [1e6] +}); + +function main(conf) { + var pathlen = +conf.pathlen; + var n = +conf.n; + + var path = '/'.repeat(pathlen); + var opts = { path: path, createConnection: function() {} }; + + bench.start(); + for (var i = 0; i < n; i++) { + new ClientRequest(opts); + } + bench.end(n); +} diff --git a/benchmark/net/punycode.js b/benchmark/misc/punycode.js similarity index 100% rename from benchmark/net/punycode.js rename to benchmark/misc/punycode.js diff --git a/benchmark/net/net-c2s.js b/benchmark/net/net-c2s.js index 9b4df2f5a79fe7..7e59bc528b681c 100644 --- a/benchmark/net/net-c2s.js +++ b/benchmark/net/net-c2s.js @@ -65,8 +65,17 @@ Writer.prototype.emit = function() {}; Writer.prototype.prependListener = function() {}; +function flow() { + var dest = this.dest; + var res = dest.write(chunk, encoding); + if (!res) + dest.once('drain', this.flow); + else + process.nextTick(this.flow); +} + function Reader() { - this.flow = this.flow.bind(this); + this.flow = flow.bind(this); this.readable = true; } @@ -76,15 +85,6 @@ Reader.prototype.pipe = function(dest) { return dest; }; -Reader.prototype.flow = function() { - var dest = this.dest; - var res = dest.write(chunk, encoding); - if (!res) - dest.once('drain', this.flow); - else - process.nextTick(this.flow); -}; - function server() { var reader = new Reader(); diff --git a/benchmark/net/net-pipe.js b/benchmark/net/net-pipe.js index 03db348878ede0..7d4849c4ef7bbb 100644 --- a/benchmark/net/net-pipe.js +++ b/benchmark/net/net-pipe.js @@ -65,8 +65,17 @@ Writer.prototype.emit = function() {}; Writer.prototype.prependListener = function() {}; +function flow() { + var dest = this.dest; + var res = dest.write(chunk, encoding); + if (!res) + dest.once('drain', this.flow); + else + process.nextTick(this.flow); +} + function Reader() { - this.flow = this.flow.bind(this); + this.flow = flow.bind(this); this.readable = true; } @@ -76,15 +85,6 @@ Reader.prototype.pipe = function(dest) { return dest; }; -Reader.prototype.flow = function() { - var dest = this.dest; - var res = dest.write(chunk, encoding); - if (!res) - dest.once('drain', this.flow); - else - process.nextTick(this.flow); -}; - function server() { var reader = new Reader(); diff --git a/benchmark/net/net-s2c.js b/benchmark/net/net-s2c.js index 469b66a25a3ee4..a4a5b4ab4987a0 100644 --- a/benchmark/net/net-s2c.js +++ b/benchmark/net/net-s2c.js @@ -65,8 +65,17 @@ Writer.prototype.emit = function() {}; Writer.prototype.prependListener = function() {}; +function flow() { + var dest = this.dest; + var res = dest.write(chunk, encoding); + if (!res) + dest.once('drain', this.flow); + else + process.nextTick(this.flow); +} + function Reader() { - this.flow = this.flow.bind(this); + this.flow = flow.bind(this); this.readable = true; } @@ -76,15 +85,6 @@ Reader.prototype.pipe = function(dest) { return dest; }; -Reader.prototype.flow = function() { - var dest = this.dest; - var res = dest.write(chunk, encoding); - if (!res) - dest.once('drain', this.flow); - else - process.nextTick(this.flow); -}; - function server() { var reader = new Reader(); diff --git a/benchmark/run.js b/benchmark/run.js index 52ce74024e1ae4..c04824866710a8 100644 --- a/benchmark/run.js +++ b/benchmark/run.js @@ -6,7 +6,7 @@ const CLI = require('./_cli.js'); const cli = CLI(`usage: ./node run.js [options] [--] ... Run each benchmark in the directory a single time, more than one - directory can be specified. + directory can be specified. --filter pattern string to filter benchmark scripts --set variable=value set benchmark variable (can be repeated) @@ -56,8 +56,9 @@ if (format === 'csv') { conf = conf.replace(/"/g, '""'); console.log(`"${data.name}", "${conf}", ${data.rate}, ${data.time}`); } else { - const rate = Math.floor(data.rate) - .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + var rate = data.rate.toString().split('.'); + rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + rate = (rate[1] ? rate.join('.') : rate[0]); console.log(`${data.name} ${conf}: ${rate}`); } }); diff --git a/benchmark/streams/writable-manywrites.js b/benchmark/streams/writable-manywrites.js new file mode 100644 index 00000000000000..fadafe86e4cf70 --- /dev/null +++ b/benchmark/streams/writable-manywrites.js @@ -0,0 +1,23 @@ +'use strict'; + +const common = require('../common'); +const Writable = require('stream').Writable; + +const bench = common.createBenchmark(main, { + n: [2e6] +}); + +function main(conf) { + const n = +conf.n; + const b = Buffer.allocUnsafe(1024); + const s = new Writable(); + s._write = function(chunk, encoding, cb) { + cb(); + }; + + bench.start(); + for (var k = 0; k < n; ++k) { + s.write(b); + } + bench.end(n); +} diff --git a/benchmark/url/legacy-vs-whatwg-url-get-prop.js b/benchmark/url/legacy-vs-whatwg-url-get-prop.js new file mode 100644 index 00000000000000..f703b75b16f6f7 --- /dev/null +++ b/benchmark/url/legacy-vs-whatwg-url-get-prop.js @@ -0,0 +1,109 @@ +'use strict'; +const common = require('../common.js'); +const url = require('url'); +const URL = url.URL; +const assert = require('assert'); + +const inputs = { + long: 'http://nodejs.org:89/docs/latest/api/url.html#test?' + + 'payload1=true&payload2=false&test=1&benchmark=3&' + + 'foo=38.38.011.293&bar=1234834910480&test=19299&3992&' + + 'key=f5c65e1e98fe07e648249ad41e1cfdb0', + short: 'https://nodejs.org/en/blog/', + idn: 'http://你好你好', + auth: 'https://user:pass@example.com/path?search=1', + special: 'file:///foo/bar/test/node.js', + percent: 'https://%E4%BD%A0/foo', + dot: 'https://example.org/./a/../b/./c' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + method: ['legacy', 'whatwg'], + n: [1e5] +}); + +// At the time of writing, when using a passed property name to index +// the object, Crankshaft would generate a LoadKeyedGeneric even when it +// remains a constant in the function, so here we must use the literal +// instead to get a LoadNamedField. +function useLegacy(n, input) { + var obj = url.parse(input); + var noDead = { + protocol: obj.protocol, + auth: obj.auth, + host: obj.host, + hostname: obj.hostname, + port: obj.port, + pathname: obj.pathname, + search: obj.search, + hash: obj.hash + }; + // It's necessary to assign the values to an object + // to avoid loop invariant code motion. + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead.protocol = obj.protocol; + noDead.auth = obj.auth; + noDead.host = obj.host; + noDead.hostname = obj.hostname; + noDead.port = obj.port; + noDead.pathname = obj.pathname; + noDead.search = obj.search; + noDead.hash = obj.hash; + } + bench.end(n); + return noDead; +} + +function useWHATWG(n, input) { + var obj = new URL(input); + var noDead = { + protocol: obj.protocol, + auth: obj.username + ':' + obj.password, + host: obj.host, + hostname: obj.hostname, + port: obj.port, + pathname: obj.pathname, + search: obj.search, + hash: obj.hash + }; + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead.protocol = obj.protocol; + noDead.auth = obj.username + ':' + obj.password; + noDead.host = obj.host; + noDead.hostname = obj.hostname; + noDead.port = obj.port; + noDead.pathname = obj.pathname; + noDead.search = obj.search; + noDead.hash = obj.hash; + } + bench.end(n); + return noDead; +} + +function main(conf) { + const type = conf.type; + const n = conf.n | 0; + const method = conf.method; + + const input = inputs[type]; + if (!input) { + throw new Error('Unknown input type'); + } + + var noDead; // Avoid dead code elimination. + switch (method) { + case 'legacy': + noDead = useLegacy(n, input); + break; + case 'whatwg': + noDead = useWHATWG(n, input); + break; + default: + throw new Error('Unknown method'); + } + + assert.ok(noDead); +} diff --git a/benchmark/url/legacy-vs-whatwg-url-parse.js b/benchmark/url/legacy-vs-whatwg-url-parse.js new file mode 100644 index 00000000000000..ca7a48466c7dc3 --- /dev/null +++ b/benchmark/url/legacy-vs-whatwg-url-parse.js @@ -0,0 +1,69 @@ +'use strict'; +const common = require('../common.js'); +const url = require('url'); +const URL = url.URL; +const assert = require('assert'); + +const inputs = { + long: 'http://nodejs.org:89/docs/latest/api/url.html#test?' + + 'payload1=true&payload2=false&test=1&benchmark=3&' + + 'foo=38.38.011.293&bar=1234834910480&test=19299&3992&' + + 'key=f5c65e1e98fe07e648249ad41e1cfdb0', + short: 'https://nodejs.org/en/blog/', + idn: 'http://你好你好', + auth: 'https://user:pass@example.com/path?search=1', + special: 'file:///foo/bar/test/node.js', + percent: 'https://%E4%BD%A0/foo', + dot: 'https://example.org/./a/../b/./c' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + method: ['legacy', 'whatwg'], + n: [1e5] +}); + +function useLegacy(n, input) { + var noDead = url.parse(input); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = url.parse(input); + } + bench.end(n); + return noDead; +} + +function useWHATWG(n, input) { + var noDead = url.parse(input); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = new URL(input); + } + bench.end(n); + return noDead; +} + +function main(conf) { + const type = conf.type; + const n = conf.n | 0; + const method = conf.method; + + const input = inputs[type]; + if (!input) { + throw new Error('Unknown input type'); + } + + var noDead; // Avoid dead code elimination. + switch (method) { + case 'legacy': + noDead = useLegacy(n, input); + break; + case 'whatwg': + noDead = useWHATWG(n, input); + break; + default: + throw new Error('Unknown method'); + } + + assert.ok(noDead); +} diff --git a/benchmark/url/legacy-vs-whatwg-url-serialize.js b/benchmark/url/legacy-vs-whatwg-url-serialize.js new file mode 100644 index 00000000000000..c0b7f5a6ce1565 --- /dev/null +++ b/benchmark/url/legacy-vs-whatwg-url-serialize.js @@ -0,0 +1,71 @@ +'use strict'; +const common = require('../common.js'); +const url = require('url'); +const URL = url.URL; +const assert = require('assert'); + +const inputs = { + long: 'http://nodejs.org:89/docs/latest/api/url.html#test?' + + 'payload1=true&payload2=false&test=1&benchmark=3&' + + 'foo=38.38.011.293&bar=1234834910480&test=19299&3992&' + + 'key=f5c65e1e98fe07e648249ad41e1cfdb0', + short: 'https://nodejs.org/en/blog/', + idn: 'http://你好你好', + auth: 'https://user:pass@example.com/path?search=1', + special: 'file:///foo/bar/test/node.js', + percent: 'https://%E4%BD%A0/foo', + dot: 'https://example.org/./a/../b/./c' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + method: ['legacy', 'whatwg'], + n: [1e5] +}); + +function useLegacy(n, input, prop) { + var obj = url.parse(input); + var noDead = url.format(obj); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = url.format(obj); + } + bench.end(n); + return noDead; +} + +function useWHATWG(n, input, prop) { + var obj = new URL(input); + var noDead = obj.toString(); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = obj.toString(); + } + bench.end(n); + return noDead; +} + +function main(conf) { + const type = conf.type; + const n = conf.n | 0; + const method = conf.method; + + const input = inputs[type]; + if (!input) { + throw new Error('Unknown input type'); + } + + var noDead; // Avoid dead code elimination. + switch (method) { + case 'legacy': + noDead = useLegacy(n, input); + break; + case 'whatwg': + noDead = useWHATWG(n, input); + break; + default: + throw new Error('Unknown method'); + } + + assert.ok(noDead); +} diff --git a/benchmark/url/new-url-parse.js b/benchmark/url/new-url-parse.js deleted file mode 100644 index ef60e81847682b..00000000000000 --- a/benchmark/url/new-url-parse.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; -const common = require('../common.js'); -const url = require('url'); -const v8 = require('v8'); - -const bench = common.createBenchmark(main, { - type: 'one two three four five'.split(' '), - method: ['old', 'new'], - n: [25e4] -}); - -function useOld(n, input) { - // Force-optimize url.parse() so that the benchmark doesn't get - // disrupted by the optimizer kicking in halfway through. - url.parse(input); - v8.setFlagsFromString('--allow_natives_syntax'); - eval('%OptimizeFunctionOnNextCall(url.parse)'); - - bench.start(); - for (var i = 0; i < n; i += 1) - url.parse(input); - bench.end(n); -} - -function useNew(n, input) { - bench.start(); - for (var i = 0; i < n; i += 1) - new url.URL(input); - bench.end(n); -} - -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - const method = conf.method; - - var inputs = { - one: 'http://nodejs.org/docs/latest/api/url.html#url_url_format_urlobj', - two: 'http://blog.nodejs.org/', - three: 'https://encrypted.google.com/search?q=url&q=site:npmjs.org&hl=en', - four: 'javascript:alert("node is awesome");', - //five: 'some.ran/dom/url.thing?oh=yes#whoo', - five: 'https://user:pass@example.com/', - }; - var input = inputs[type] || ''; - - switch (method) { - case 'old': - useOld(n, input); - break; - case 'new': - useNew(n, input); - break; - default: - throw new Error('Unknown method'); - } -} diff --git a/benchmark/url/url-searchparams-iteration.js b/benchmark/url/url-searchparams-iteration.js new file mode 100644 index 00000000000000..caa4e45c41247e --- /dev/null +++ b/benchmark/url/url-searchparams-iteration.js @@ -0,0 +1,60 @@ +'use strict'; +const common = require('../common.js'); +const assert = require('assert'); +const URLSearchParams = new (require('url').URL)('a:').searchParams.constructor; + +const bench = common.createBenchmark(main, { + method: ['forEach', 'iterator'], + n: [1e6] +}); + +const str = 'one=single&two=first&three=first&two=2nd&three=2nd&three=3rd'; + +function forEach(n) { + const params = new URLSearchParams(str); + const noDead = []; + const cb = (val, key) => { + noDead[0] = key; + noDead[1] = val; + }; + + bench.start(); + for (var i = 0; i < n; i += 1) + params.forEach(cb); + bench.end(n); + + assert.strictEqual(noDead[0], 'three'); + assert.strictEqual(noDead[1], '3rd'); +} + +function iterator(n) { + const params = new URLSearchParams(str); + const noDead = []; + + bench.start(); + for (var i = 0; i < n; i += 1) + for (var pair of params) { + noDead[0] = pair[0]; + noDead[1] = pair[1]; + } + bench.end(n); + + assert.strictEqual(noDead[0], 'three'); + assert.strictEqual(noDead[1], '3rd'); +} + +function main(conf) { + const method = conf.method; + const n = conf.n | 0; + + switch (method) { + case 'forEach': + forEach(n); + break; + case 'iterator': + iterator(n); + break; + default: + throw new Error('Unknown method'); + } +} diff --git a/benchmark/url/url-searchparams-parse.js b/benchmark/url/url-searchparams-parse.js new file mode 100644 index 00000000000000..61796a7d327bd4 --- /dev/null +++ b/benchmark/url/url-searchparams-parse.js @@ -0,0 +1,31 @@ +'use strict'; +const common = require('../common.js'); +const URLSearchParams = new (require('url').URL)('a:').searchParams.constructor; + +const inputs = { + noencode: 'foo=bar&baz=quux&xyzzy=thud', + // multicharsep: 'foo=bar&&&&&&&&&&baz=quux&&&&&&&&&&xyzzy=thud', + multicharsep: '&&&&&&&&&&&&&&&&&&&&&&&&&&&&', + encodemany: '%66%6F%6F=bar&%62%61%7A=quux&xyzzy=%74h%75d', + encodelast: 'foo=bar&baz=quux&xyzzy=thu%64', + multivalue: 'foo=bar&foo=baz&foo=quux&quuy=quuz', + multivaluemany: 'foo=bar&foo=baz&foo=quux&quuy=quuz&foo=abc&foo=def&' + + 'foo=ghi&foo=jkl&foo=mno&foo=pqr&foo=stu&foo=vwxyz', + manypairs: 'a&b&c&d&e&f&g&h&i&j&k&l&m&n&o&p&q&r&s&t&u&v&w&x&y&z' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + n: [1e5] +}); + +function main(conf) { + const input = inputs[conf.type]; + const n = conf.n | 0; + + var i; + bench.start(); + for (i = 0; i < n; i++) + new URLSearchParams(input); + bench.end(n); +} diff --git a/benchmark/url/url-searchparams-read.js b/benchmark/url/url-searchparams-read.js new file mode 100644 index 00000000000000..4cee49c74d2baa --- /dev/null +++ b/benchmark/url/url-searchparams-read.js @@ -0,0 +1,58 @@ +'use strict'; +const common = require('../common.js'); +const URLSearchParams = new (require('url').URL)('a:').searchParams.constructor; + +const bench = common.createBenchmark(main, { + method: ['get', 'getAll', 'has'], + param: ['one', 'two', 'three', 'nonexistent'], + n: [1e6] +}); + +const str = 'one=single&two=first&three=first&two=2nd&three=2nd&three=3rd'; + +function get(n, param) { + const params = new URLSearchParams(str); + + bench.start(); + for (var i = 0; i < n; i += 1) + params.get(param); + bench.end(n); +} + +function getAll(n, param) { + const params = new URLSearchParams(str); + + bench.start(); + for (var i = 0; i < n; i += 1) + params.getAll(param); + bench.end(n); +} + +function has(n, param) { + const params = new URLSearchParams(str); + + bench.start(); + for (var i = 0; i < n; i += 1) + params.has(param); + bench.end(n); +} + +function main(conf) { + const method = conf.method; + const param = conf.param; + const n = conf.n | 0; + + switch (method) { + case 'get': + get(n, param); + break; + case 'getAll': + getAll(n, param); + break; + case 'has': + has(n, param); + break; + default: + throw new Error('Unknown method'); + } +} diff --git a/benchmark/url/url-searchparams-stringifier.js b/benchmark/url/url-searchparams-stringifier.js new file mode 100644 index 00000000000000..2979064b322592 --- /dev/null +++ b/benchmark/url/url-searchparams-stringifier.js @@ -0,0 +1,35 @@ +'use strict'; +const common = require('../common.js'); +const Buffer = require('buffer').Buffer; +const URLSearchParams = new (require('url').URL)('a:').searchParams.constructor; + +const inputs = { + noencode: 'foo=bar&baz=quux&xyzzy=thud', + // multicharsep: 'foo=bar&&&&&&&&&&baz=quux&&&&&&&&&&xyzzy=thud', + multicharsep: '&&&&&&&&&&&&&&&&&&&&&&&&&&&&', + encodemany: '%66%6F%6F=bar&%62%61%7A=quux&xyzzy=%74h%75d', + encodelast: 'foo=bar&baz=quux&xyzzy=thu%64', + multivalue: 'foo=bar&foo=baz&foo=quux&quuy=quuz', + multivaluemany: 'foo=bar&foo=baz&foo=quux&quuy=quuz&foo=abc&foo=def&' + + 'foo=ghi&foo=jkl&foo=mno&foo=pqr&foo=stu&foo=vwxyz', + manypairs: 'a&b&c&d&e&f&g&h&i&j&k&l&m&n&o&p&q&r&s&t&u&v&w&x&y&z' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + n: [1e5] +}); + +function main(conf) { + const input = inputs[conf.type]; + const n = conf.n | 0; + + const params = new URLSearchParams(input); + + bench.start(); + // Using Buffer.from to prevent JS version from cheating with ropes instead + // of strings + for (var i = 0; i < n; i += 1) + Buffer.from(params.toString()); + bench.end(n); +} diff --git a/benchmark/url/whatwg-url-properties.js b/benchmark/url/whatwg-url-properties.js index a3c4d886bd3c90..375939c601d363 100644 --- a/benchmark/url/whatwg-url-properties.js +++ b/benchmark/url/whatwg-url-properties.js @@ -11,8 +11,8 @@ var bench = common.createBenchmark(main, { 'http://user:pass@foo.bar.com:21/aaa/zzz?l=24#test' ], prop: ['toString', 'href', 'origin', 'protocol', - 'username', 'password', 'host', 'hostname', 'port', - 'pathname', 'search', 'searchParams', 'hash'], + 'username', 'password', 'host', 'hostname', 'port', + 'pathname', 'search', 'searchParams', 'hash'], n: [1e4] }); diff --git a/benchmark/util/normalize-encoding.js b/benchmark/util/normalize-encoding.js new file mode 100644 index 00000000000000..8c4d03478104b0 --- /dev/null +++ b/benchmark/util/normalize-encoding.js @@ -0,0 +1,65 @@ +'use strict'; + +const common = require('../common.js'); +const assert = require('assert'); + +const groupedInputs = { + group_common: ['undefined', 'utf8', 'utf-8', 'base64', 'binary', 'latin1'], + group_upper: ['UTF-8', 'UTF8', 'UCS2', 'UTF-16LE', 'UTF16LE', 'BASE64'], + group_uncommon: [ 'foo', '1', 'false', 'undefined', '[]'], + group_misc: ['', 'utf16le', 'usc2', 'hex', 'HEX', 'BINARY'] +}; + +const inputs = [ + '', 'utf8', 'utf-8', 'UTF-8', + 'UTF8', 'Utf8', 'uTf-8', 'utF-8', 'ucs2', + 'UCS2', 'utf16le', 'utf-16le', 'UTF-16LE', 'UTF16LE', + 'binary', 'BINARY', 'latin1', 'base64', 'BASE64', + 'hex', 'HEX', 'foo', '1', 'false', 'undefined', '[]']; + +const bench = common.createBenchmark(main, { + input: inputs.concat(Object.keys(groupedInputs)), + n: [1e5] +}, { + flags: '--expose-internals' +}); + +function getInput(input) { + switch (input) { + case 'group_common': + return groupedInputs.group_common; + case 'group_upper': + return groupedInputs.group_upper; + case 'group_uncommon': + return groupedInputs.group_uncommon; + case 'group_misc': + return groupedInputs.group_misc; + case '1': + return [1]; + case 'false': + return [false]; + case 'undefined': + return [undefined]; + case '[]': + return [[]]; + default: + return [input]; + } +} + +function main(conf) { + const normalizeEncoding = require('internal/util').normalizeEncoding; + + const n = conf.n | 0; + const inputs = getInput(conf.input); + var noDead = ''; + + bench.start(); + for (var i = 0; i < n; i += 1) { + for (var j = 0; j < inputs.length; ++j) { + noDead = normalizeEncoding(inputs[j]); + } + } + bench.end(n); + assert.ok(noDead === undefined || noDead.length > 0); +} diff --git a/benchmark/vm/run-in-context.js b/benchmark/vm/run-in-context.js new file mode 100644 index 00000000000000..62ebe29146e705 --- /dev/null +++ b/benchmark/vm/run-in-context.js @@ -0,0 +1,32 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [1], + breakOnSigint: [0, 1], + withSigintListener: [0, 1] +}); + +const vm = require('vm'); + +function main(conf) { + const n = +conf.n; + const options = conf.breakOnSigint ? {breakOnSigint: true} : {}; + const withSigintListener = !!conf.withSigintListener; + + process.removeAllListeners('SIGINT'); + if (withSigintListener) + process.on('SIGINT', () => {}); + + var i = 0; + + const contextifiedSandbox = vm.createContext(); + + common.v8ForceOptimization(vm.runInContext, + '0', contextifiedSandbox, options); + bench.start(); + for (; i < n; i++) + vm.runInContext('0', contextifiedSandbox, options); + bench.end(n); +} diff --git a/benchmark/vm/run-in-this-context.js b/benchmark/vm/run-in-this-context.js new file mode 100644 index 00000000000000..f66fd31a1a949e --- /dev/null +++ b/benchmark/vm/run-in-this-context.js @@ -0,0 +1,29 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [1], + breakOnSigint: [0, 1], + withSigintListener: [0, 1] +}); + +const vm = require('vm'); + +function main(conf) { + const n = +conf.n; + const options = conf.breakOnSigint ? {breakOnSigint: true} : {}; + const withSigintListener = !!conf.withSigintListener; + + process.removeAllListeners('SIGINT'); + if (withSigintListener) + process.on('SIGINT', () => {}); + + var i = 0; + + common.v8ForceOptimization(vm.runInThisContext, '0', options); + bench.start(); + for (; i < n; i++) + vm.runInThisContext('0', options); + bench.end(n); +} diff --git a/configure b/configure index d926cec7d5d7ea..e12a5382a1960f 100755 --- a/configure +++ b/configure @@ -144,6 +144,11 @@ parser.add_option('--openssl-fips', dest='openssl_fips', help='Build OpenSSL using FIPS canister .o file in supplied folder') +parser.add_option('--openssl-use-def-ca-store', + action='store_true', + dest='use_openssl_ca_store', + help='Use OpenSSL supplied CA store instead of compiled-in Mozilla CA copy.') + shared_optgroup.add_option('--shared-http-parser', action='store_true', dest='shared_http_parser', @@ -940,6 +945,8 @@ def configure_openssl(o): o['variables']['node_use_openssl'] = b(not options.without_ssl) o['variables']['node_shared_openssl'] = b(options.shared_openssl) o['variables']['openssl_no_asm'] = 1 if options.openssl_no_asm else 0 + if options.use_openssl_ca_store: + o['defines'] += ['NODE_OPENSSL_CERT_STORE'] if options.openssl_fips: o['variables']['openssl_fips'] = options.openssl_fips fips_dir = os.path.join(root_dir, 'deps', 'openssl', 'fips') diff --git a/deps/uv/AUTHORS b/deps/uv/AUTHORS index 50916c67cdc30a..49c8e17f23b35c 100644 --- a/deps/uv/AUTHORS +++ b/deps/uv/AUTHORS @@ -278,3 +278,4 @@ Brad King Philippe Laferriere Will Speak Hitesh Kanwathirtha +Eric Sciple diff --git a/deps/uv/ChangeLog b/deps/uv/ChangeLog index b6f89af51f40bf..d865f22667ec39 100644 --- a/deps/uv/ChangeLog +++ b/deps/uv/ChangeLog @@ -1,3 +1,31 @@ +2017.01.10, Version 1.10.2 (Stable), cb9f579a454b8db592030ffa274ae58df78dbe20 + +Changes since version 1.10.1: + +* Now working on version 1.10.2 (cjihrig) + +* darwin: fix fsync and fdatasync (Joran Dirk Greef) + +* Revert "Revert "win,tty: add support for ANSI codes in win10 v1511"" + (Santiago Gimeno) + +* win,tty: fix MultiByteToWideChar output buffer (Santiago Gimeno) + +* win: remove dead code related to BACKUP_SEMANTICS (Sam Roberts) + +* win: fix comment in quote_cmd_arg (Eric Sciple) + +* darwin: use clock_gettime in macOS 10.12 (Saúl Ibarra Corretgé) + +* win, tty: fix crash on restarting with pending data (Nicholas Vavilov) + +* fs: fix uv__to_stat on BSD platforms (Santiago Gimeno) + +* win: map ERROR_ELEVATION_REQUIRED to UV_EACCES (Richard Lau) + +* win: fix free() on bad input in uv_getaddrinfo() (Ben Noordhuis) + + 2016.11.17, Version 1.10.1 (Stable), 2e49e332bdede6db7cf17fa784a902e8386d5d86 Changes since version 1.10.0: diff --git a/deps/uv/appveyor.yml b/deps/uv/appveyor.yml index 6b785611536c39..63294137833fb7 100644 --- a/deps/uv/appveyor.yml +++ b/deps/uv/appveyor.yml @@ -1,4 +1,4 @@ -version: v1.10.1.build{build} +version: v1.10.2.build{build} install: - cinst -y nsis diff --git a/deps/uv/configure.ac b/deps/uv/configure.ac index d3787c0d6dd9f7..abaf971772ffe7 100644 --- a/deps/uv/configure.ac +++ b/deps/uv/configure.ac @@ -13,7 +13,7 @@ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. AC_PREREQ(2.57) -AC_INIT([libuv], [1.10.1], [https://github.com/libuv/libuv/issues]) +AC_INIT([libuv], [1.10.2], [https://github.com/libuv/libuv/issues]) AC_CONFIG_MACRO_DIR([m4]) m4_include([m4/libuv-extra-automake-flags.m4]) m4_include([m4/as_case.m4]) diff --git a/deps/uv/include/uv-version.h b/deps/uv/include/uv-version.h index 63454a5d0aee39..99f7eb8c1fae1d 100644 --- a/deps/uv/include/uv-version.h +++ b/deps/uv/include/uv-version.h @@ -32,7 +32,7 @@ #define UV_VERSION_MAJOR 1 #define UV_VERSION_MINOR 10 -#define UV_VERSION_PATCH 1 +#define UV_VERSION_PATCH 2 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/deps/uv/src/unix/darwin.c b/deps/uv/src/unix/darwin.c index cf95da21693b9a..b1ffbc37b47b78 100644 --- a/deps/uv/src/unix/darwin.c +++ b/deps/uv/src/unix/darwin.c @@ -34,8 +34,12 @@ #include /* _NSGetExecutablePath */ #include #include +#include #include /* sysconf */ +#undef NANOSEC +#define NANOSEC ((uint64_t) 1e9) + int uv__platform_loop_init(uv_loop_t* loop) { loop->cf_state = NULL; @@ -53,6 +57,11 @@ void uv__platform_loop_delete(uv_loop_t* loop) { uint64_t uv__hrtime(uv_clocktype_t type) { +#ifdef MAC_OS_X_VERSION_10_12 + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec); +#else static mach_timebase_info_data_t info; if ((ACCESS_ONCE(uint32_t, info.numer) == 0 || @@ -61,6 +70,7 @@ uint64_t uv__hrtime(uv_clocktype_t type) { abort(); return mach_absolute_time() * info.numer / info.denom; +#endif } diff --git a/deps/uv/src/unix/fs.c b/deps/uv/src/unix/fs.c index 3d478b790e6c5a..e047b671651466 100644 --- a/deps/uv/src/unix/fs.c +++ b/deps/uv/src/unix/fs.c @@ -129,8 +129,23 @@ static ssize_t uv__fs_fdatasync(uv_fs_t* req) { #if defined(__linux__) || defined(__sun) || defined(__NetBSD__) return fdatasync(req->file); -#elif defined(__APPLE__) && defined(SYS_fdatasync) - return syscall(SYS_fdatasync, req->file); +#elif defined(__APPLE__) + /* Apple's fdatasync and fsync explicitly do NOT flush the drive write cache + * to the drive platters. This is in contrast to Linux's fdatasync and fsync + * which do, according to recent man pages. F_FULLFSYNC is Apple's equivalent + * for flushing buffered data to permanent storage. + */ + return fcntl(req->file, F_FULLFSYNC); +#else + return fsync(req->file); +#endif +} + + +static ssize_t uv__fs_fsync(uv_fs_t* req) { +#if defined(__APPLE__) + /* See the comment in uv__fs_fdatasync. */ + return fcntl(req->file, F_FULLFSYNC); #else return fsync(req->file); #endif @@ -798,6 +813,10 @@ static void uv__to_stat(struct stat* src, uv_stat_t* dst) { dst->st_flags = 0; dst->st_gen = 0; #elif !defined(_AIX) && ( \ + defined(__DragonFly__) || \ + defined(__FreeBSD__) || \ + defined(__OpenBSD__) || \ + defined(__NetBSD__) || \ defined(_GNU_SOURCE) || \ defined(_BSD_SOURCE) || \ defined(_SVID_SOURCE) || \ @@ -809,9 +828,7 @@ static void uv__to_stat(struct stat* src, uv_stat_t* dst) { dst->st_mtim.tv_nsec = src->st_mtim.tv_nsec; dst->st_ctim.tv_sec = src->st_ctim.tv_sec; dst->st_ctim.tv_nsec = src->st_ctim.tv_nsec; -# if defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__OpenBSD__) || \ +# if defined(__FreeBSD__) || \ defined(__NetBSD__) dst->st_birthtim.tv_sec = src->st_birthtim.tv_sec; dst->st_birthtim.tv_nsec = src->st_birthtim.tv_nsec; @@ -945,7 +962,7 @@ static void uv__fs_work(struct uv__work* w) { X(FCHOWN, fchown(req->file, req->uid, req->gid)); X(FDATASYNC, uv__fs_fdatasync(req)); X(FSTAT, uv__fs_fstat(req->file, &req->statbuf)); - X(FSYNC, fsync(req->file)); + X(FSYNC, uv__fs_fsync(req)); X(FTRUNCATE, ftruncate(req->file, req->off)); X(FUTIME, uv__fs_futime(req)); X(LSTAT, uv__fs_lstat(req->path, &req->statbuf)); diff --git a/deps/uv/src/win/error.c b/deps/uv/src/win/error.c index c512f35af979a3..642d1112e11928 100644 --- a/deps/uv/src/win/error.c +++ b/deps/uv/src/win/error.c @@ -71,6 +71,7 @@ int uv_translate_sys_error(int sys_errno) { switch (sys_errno) { case ERROR_NOACCESS: return UV_EACCES; case WSAEACCES: return UV_EACCES; + case ERROR_ELEVATION_REQUIRED: return UV_EACCES; case ERROR_ADDRESS_ALREADY_ASSOCIATED: return UV_EADDRINUSE; case WSAEADDRINUSE: return UV_EADDRINUSE; case WSAEADDRNOTAVAIL: return UV_EADDRNOTAVAIL; diff --git a/deps/uv/src/win/fs.c b/deps/uv/src/win/fs.c index dc0ac89a35293e..6902d4f1a69485 100644 --- a/deps/uv/src/win/fs.c +++ b/deps/uv/src/win/fs.c @@ -403,7 +403,6 @@ void fs__open(uv_fs_t* req) { switch (flags & (_O_RDONLY | _O_WRONLY | _O_RDWR)) { case _O_RDONLY: access = FILE_GENERIC_READ; - attributes |= FILE_FLAG_BACKUP_SEMANTICS; break; case _O_WRONLY: access = FILE_GENERIC_WRITE; @@ -418,7 +417,6 @@ void fs__open(uv_fs_t* req) { if (flags & _O_APPEND) { access &= ~FILE_WRITE_DATA; access |= FILE_APPEND_DATA; - attributes &= ~FILE_FLAG_BACKUP_SEMANTICS; } /* diff --git a/deps/uv/src/win/getaddrinfo.c b/deps/uv/src/win/getaddrinfo.c index 744f8e02629ccd..c13bfec350f27e 100644 --- a/deps/uv/src/win/getaddrinfo.c +++ b/deps/uv/src/win/getaddrinfo.c @@ -262,8 +262,7 @@ int uv_getaddrinfo(uv_loop_t* loop, int err; if (req == NULL || (node == NULL && service == NULL)) { - err = WSAEINVAL; - goto error; + return UV_EINVAL; } uv_req_init(loop, (uv_req_t*)req); diff --git a/deps/uv/src/win/process.c b/deps/uv/src/win/process.c index 855c3740816db2..bdf88d2cdd944c 100644 --- a/deps/uv/src/win/process.c +++ b/deps/uv/src/win/process.c @@ -492,7 +492,7 @@ WCHAR* quote_cmd_arg(const WCHAR *source, WCHAR *target) { * input : hello\\"world * output: "hello\\\\\"world" * input : hello world\ - * output: "hello world\" + * output: "hello world\\" */ *(target++) = L'"'; diff --git a/deps/uv/src/win/tty.c b/deps/uv/src/win/tty.c index 76dc2fab8aa3c7..1b7adf64ffcbdb 100644 --- a/deps/uv/src/win/tty.c +++ b/deps/uv/src/win/tty.c @@ -56,7 +56,11 @@ #define ANSI_BACKSLASH_SEEN 0x80 #define MAX_INPUT_BUFFER_LENGTH 8192 +#define MAX_CONSOLE_CHAR 8192 +#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING +#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 +#endif static void uv_tty_capture_initial_style(CONSOLE_SCREEN_BUFFER_INFO* info); static void uv_tty_update_virtual_window(CONSOLE_SCREEN_BUFFER_INFO* info); @@ -125,6 +129,14 @@ static char uv_tty_default_fg_bright = 0; static char uv_tty_default_bg_bright = 0; static char uv_tty_default_inverse = 0; +typedef enum { + UV_SUPPORTED, + UV_UNCHECKED, + UV_UNSUPPORTED +} uv_vtermstate_t; +/* Determine whether or not ANSI support is enabled. */ +static uv_vtermstate_t uv__vterm_state = UV_UNCHECKED; +static void uv__determine_vterm_state(HANDLE handle); void uv_console_init() { if (uv_sem_init(&uv_tty_output_lock, 1)) @@ -168,6 +180,9 @@ int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, uv_file fd, int readable) { /* shared between all uv_tty_t handles. */ uv_sem_wait(&uv_tty_output_lock); + if (uv__vterm_state == UV_UNCHECKED) + uv__determine_vterm_state(handle); + /* Store the global tty output handle. This handle is used by TTY read */ /* streams to update the virtual window when a CONSOLE_BUFFER_SIZE_EVENT */ /* is received. */ @@ -989,6 +1004,9 @@ int uv_tty_read_start(uv_tty_t* handle, uv_alloc_cb alloc_cb, if (handle->tty.rd.last_key_len > 0) { SET_REQ_SUCCESS(&handle->read_req); uv_insert_pending_req(handle->loop, (uv_req_t*) &handle->read_req); + /* Make sure no attempt is made to insert it again until it's handled. */ + handle->flags |= UV_HANDLE_READ_PENDING; + handle->reqs_pending++; return 0; } @@ -1602,17 +1620,29 @@ static int uv_tty_write_bufs(uv_tty_t* handle, DWORD* error) { /* We can only write 8k characters at a time. Windows can't handle */ /* much more characters in a single console write anyway. */ - WCHAR utf16_buf[8192]; + WCHAR utf16_buf[MAX_CONSOLE_CHAR]; + WCHAR* utf16_buffer; DWORD utf16_buf_used = 0; - unsigned int i; - -#define FLUSH_TEXT() \ - do { \ - if (utf16_buf_used > 0) { \ - uv_tty_emit_text(handle, utf16_buf, utf16_buf_used, error); \ - utf16_buf_used = 0; \ - } \ - } while (0) + unsigned int i, len, max_len, pos; + int allocate = 0; + +#define FLUSH_TEXT() \ + do { \ + pos = 0; \ + do { \ + len = utf16_buf_used - pos; \ + if (len > MAX_CONSOLE_CHAR) \ + len = MAX_CONSOLE_CHAR; \ + uv_tty_emit_text(handle, &utf16_buffer[pos], len, error); \ + pos += len; \ + } while (pos < utf16_buf_used); \ + if (allocate) { \ + uv__free(utf16_buffer); \ + allocate = 0; \ + utf16_buffer = utf16_buf; \ + } \ + utf16_buf_used = 0; \ + } while (0) #define ENSURE_BUFFER_SPACE(wchars_needed) \ if (wchars_needed > ARRAY_SIZE(utf16_buf) - utf16_buf_used) { \ @@ -1630,12 +1660,48 @@ static int uv_tty_write_bufs(uv_tty_t* handle, /* state. */ *error = ERROR_SUCCESS; + utf16_buffer = utf16_buf; + uv_sem_wait(&uv_tty_output_lock); for (i = 0; i < nbufs; i++) { uv_buf_t buf = bufs[i]; unsigned int j; + if (uv__vterm_state == UV_SUPPORTED && buf.len > 0) { + utf16_buf_used = MultiByteToWideChar(CP_UTF8, + 0, + buf.base, + buf.len, + NULL, + 0); + + if (utf16_buf_used == 0) { + *error = GetLastError(); + break; + } + + max_len = (utf16_buf_used + 1) * sizeof(WCHAR); + allocate = max_len > MAX_CONSOLE_CHAR; + if (allocate) + utf16_buffer = uv__malloc(max_len); + if (!MultiByteToWideChar(CP_UTF8, + 0, + buf.base, + buf.len, + utf16_buffer, + utf16_buf_used)) { + if (allocate) + uv__free(utf16_buffer); + *error = GetLastError(); + break; + } + + FLUSH_TEXT(); + + continue; + } + for (j = 0; j < buf.len; j++) { unsigned char c = buf.base[j]; @@ -2193,3 +2259,24 @@ int uv_tty_reset_mode(void) { /* Not necessary to do anything. */ return 0; } + +/* Determine whether or not this version of windows supports + * proper ANSI color codes. Should be supported as of windows + * 10 version 1511, build number 10.0.10586. + */ +static void uv__determine_vterm_state(HANDLE handle) { + DWORD dwMode = 0; + + if (!GetConsoleMode(handle, &dwMode)) { + uv__vterm_state = UV_UNSUPPORTED; + return; + } + + dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; + if (!SetConsoleMode(handle, dwMode)) { + uv__vterm_state = UV_UNSUPPORTED; + return; + } + + uv__vterm_state = UV_SUPPORTED; +} diff --git a/deps/uv/test/test-error.c b/deps/uv/test/test-error.c index 4c4efa30cddd4b..ff53eb1d777903 100644 --- a/deps/uv/test/test-error.c +++ b/deps/uv/test/test-error.c @@ -53,6 +53,7 @@ TEST_IMPL(error_message) { TEST_IMPL(sys_error) { #if defined(_WIN32) ASSERT(uv_translate_sys_error(ERROR_NOACCESS) == UV_EACCES); + ASSERT(uv_translate_sys_error(ERROR_ELEVATION_REQUIRED) == UV_EACCES); ASSERT(uv_translate_sys_error(WSAEADDRINUSE) == UV_EADDRINUSE); ASSERT(uv_translate_sys_error(ERROR_BAD_PIPE) == UV_EPIPE); #else diff --git a/deps/uv/test/test-fs.c b/deps/uv/test/test-fs.c index 06718f285ed7ae..70a23999624741 100644 --- a/deps/uv/test/test-fs.c +++ b/deps/uv/test/test-fs.c @@ -1141,11 +1141,15 @@ TEST_IMPL(fs_fstat) { ASSERT(s->st_mtim.tv_nsec == t.st_mtimensec); ASSERT(s->st_ctim.tv_sec == t.st_ctime); ASSERT(s->st_ctim.tv_nsec == t.st_ctimensec); -#elif defined(__sun) || \ - defined(_GNU_SOURCE) || \ - defined(_BSD_SOURCE) || \ - defined(_SVID_SOURCE) || \ - defined(_XOPEN_SOURCE) || \ +#elif defined(__sun) || \ + defined(__DragonFly__) || \ + defined(__FreeBSD__) || \ + defined(__OpenBSD__) || \ + defined(__NetBSD__) || \ + defined(_GNU_SOURCE) || \ + defined(_BSD_SOURCE) || \ + defined(_SVID_SOURCE) || \ + defined(_XOPEN_SOURCE) || \ defined(_DEFAULT_SOURCE) ASSERT(s->st_atim.tv_sec == t.st_atim.tv_sec); ASSERT(s->st_atim.tv_nsec == t.st_atim.tv_nsec); @@ -1153,10 +1157,8 @@ TEST_IMPL(fs_fstat) { ASSERT(s->st_mtim.tv_nsec == t.st_mtim.tv_nsec); ASSERT(s->st_ctim.tv_sec == t.st_ctim.tv_sec); ASSERT(s->st_ctim.tv_nsec == t.st_ctim.tv_nsec); -# if defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__OpenBSD__) || \ - defined(__NetBSD__) +# if defined(__FreeBSD__) || \ + defined(__NetBSD__) ASSERT(s->st_birthtim.tv_sec == t.st_birthtim.tv_sec); ASSERT(s->st_birthtim.tv_nsec == t.st_birthtim.tv_nsec); ASSERT(s->st_flags == t.st_flags); diff --git a/deps/uv/test/test-getaddrinfo.c b/deps/uv/test/test-getaddrinfo.c index 6b644a8d442a3a..03dc126956162c 100644 --- a/deps/uv/test/test-getaddrinfo.c +++ b/deps/uv/test/test-getaddrinfo.c @@ -83,6 +83,13 @@ static void getaddrinfo_cuncurrent_cb(uv_getaddrinfo_t* handle, TEST_IMPL(getaddrinfo_fail) { uv_getaddrinfo_t req; + ASSERT(UV_EINVAL == uv_getaddrinfo(uv_default_loop(), + &req, + (uv_getaddrinfo_cb) abort, + NULL, + NULL, + NULL)); + /* Use a FQDN by ending in a period */ ASSERT(0 == uv_getaddrinfo(uv_default_loop(), &req, diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index 08886a6f4a5b31..be3f9069cc7779 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -47,6 +47,8 @@ TEST_DECLARE (semaphore_3) TEST_DECLARE (tty) #ifdef _WIN32 TEST_DECLARE (tty_raw) +TEST_DECLARE (tty_empty_write) +TEST_DECLARE (tty_large_write) #endif TEST_DECLARE (tty_file) TEST_DECLARE (tty_pty) @@ -404,6 +406,8 @@ TASK_LIST_START TEST_ENTRY (tty) #ifdef _WIN32 TEST_ENTRY (tty_raw) + TEST_ENTRY (tty_empty_write) + TEST_ENTRY (tty_large_write) #endif TEST_ENTRY (tty_file) TEST_ENTRY (tty_pty) diff --git a/deps/uv/test/test-tty.c b/deps/uv/test/test-tty.c index d03f07a4418e49..d1f7deb2319e44 100644 --- a/deps/uv/test/test-tty.c +++ b/deps/uv/test/test-tty.c @@ -212,6 +212,93 @@ TEST_IMPL(tty_raw) { MAKE_VALGRIND_HAPPY(); return 0; } + +TEST_IMPL(tty_empty_write) { + int r; + int ttyout_fd; + uv_tty_t tty_out; + char dummy[1]; + uv_buf_t bufs[1]; + uv_loop_t* loop; + + /* Make sure we have an FD that refers to a tty */ + HANDLE handle; + + loop = uv_default_loop(); + + handle = CreateFileA("conout$", + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + ASSERT(handle != INVALID_HANDLE_VALUE); + ttyout_fd = _open_osfhandle((intptr_t) handle, 0); + + ASSERT(ttyout_fd >= 0); + + ASSERT(UV_TTY == uv_guess_handle(ttyout_fd)); + + r = uv_tty_init(uv_default_loop(), &tty_out, ttyout_fd, 0); /* Writable. */ + ASSERT(r == 0); + + bufs[0].len = 0; + bufs[0].base = &dummy; + + r = uv_try_write((uv_stream_t*) &tty_out, bufs, 1); + ASSERT(r == 0); + + uv_close((uv_handle_t*) &tty_out, NULL); + + uv_run(loop, UV_RUN_DEFAULT); + + MAKE_VALGRIND_HAPPY(); + return 0; +} + +TEST_IMPL(tty_large_write) { + int r; + int ttyout_fd; + uv_tty_t tty_out; + char dummy[10000]; + uv_buf_t bufs[1]; + uv_loop_t* loop; + + /* Make sure we have an FD that refers to a tty */ + HANDLE handle; + + loop = uv_default_loop(); + + handle = CreateFileA("conout$", + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + ASSERT(handle != INVALID_HANDLE_VALUE); + ttyout_fd = _open_osfhandle((intptr_t) handle, 0); + + ASSERT(ttyout_fd >= 0); + + ASSERT(UV_TTY == uv_guess_handle(ttyout_fd)); + + r = uv_tty_init(uv_default_loop(), &tty_out, ttyout_fd, 0); /* Writable. */ + ASSERT(r == 0); + + bufs[0] = uv_buf_init(dummy, sizeof(dummy)); + + r = uv_try_write((uv_stream_t*) &tty_out, bufs, 1); + ASSERT(r == 10000); + + uv_close((uv_handle_t*) &tty_out, NULL); + + uv_run(loop, UV_RUN_DEFAULT); + + MAKE_VALGRIND_HAPPY(); + return 0; +} #endif diff --git a/doc/api/buffer.md b/doc/api/buffer.md index b9f8369335a0d6..adc9d6b104680b 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -348,15 +348,16 @@ deprecated: v6.0.0 > [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][`Buffer.from(arrayBuffer)`] > instead. -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a [`TypedArray`] or - [`ArrayBuffer`] -* `byteOffset` {Integer} Where to start copying from `arrayBuffer`. **Default:** `0` -* `length` {Integer} How many bytes to copy from `arrayBuffer`. +* `arrayBuffer` {ArrayBuffer} An [`ArrayBuffer`] or the `.buffer` property of a + [`TypedArray`]. +* `byteOffset` {Integer} Index of first byte to expose. **Default:** `0` +* `length` {Integer} Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset` -When passed a reference to the `.buffer` property of a [`TypedArray`] instance, -the newly created `Buffer` will share the same allocated memory as the -[`TypedArray`]. +This creates a view of the [`ArrayBuffer`] without copying the underlying +memory. For example, when passed a reference to the `.buffer` property of a +[`TypedArray`] instance, the newly created `Buffer` will share the same +allocated memory as the [`TypedArray`]. The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. @@ -719,15 +720,16 @@ A `TypeError` will be thrown if `array` is not an `Array`. added: v5.10.0 --> -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a [`TypedArray`] or - [`ArrayBuffer`] -* `byteOffset` {Integer} Where to start copying from `arrayBuffer`. **Default:** `0` -* `length` {Integer} How many bytes to copy from `arrayBuffer`. +* `arrayBuffer` {ArrayBuffer} An [`ArrayBuffer`] or the `.buffer` property of a + [`TypedArray`]. +* `byteOffset` {Integer} Index of first byte to expose. **Default:** `0` +* `length` {Integer} Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset` -When passed a reference to the `.buffer` property of a [`TypedArray`] instance, -the newly created `Buffer` will share the same allocated memory as the -[`TypedArray`]. +This creates a view of the [`ArrayBuffer`] without copying the underlying +memory. For example, when passed a reference to the `.buffer` property of a +[`TypedArray`] instance, the newly created `Buffer` will share the same +allocated memory as the [`TypedArray`]. Example: diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 0147242c5583a0..c541837b91e302 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -91,11 +91,11 @@ const spawn = require('child_process').spawn; const bat = spawn('cmd.exe', ['/c', 'my.bat']); bat.stdout.on('data', (data) => { - console.log(data); + console.log(data.toString()); }); bat.stderr.on('data', (data) => { - console.log(data); + console.log(data.toString()); }); bat.on('exit', (code) => { @@ -113,7 +113,7 @@ exec('my.bat', (err, stdout, stderr) => { }); // Script with spaces in the filename: -const bat = spawn('"my script.cmd"', ['a', 'b'], { shell:true }); +const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true }); // or: exec('"my script.cmd" a b', (err, stdout, stderr) => { // ... @@ -137,7 +137,7 @@ added: v0.1.90 * `timeout` {Number} (Default: `0`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: `200*1024`) - * `killSignal` {String} (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} (Default: `'SIGTERM'`) * `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `callback` {Function} called with the output when process terminates @@ -214,7 +214,7 @@ added: v0.1.91 * `timeout` {Number} (Default: `0`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: `200*1024`) - * `killSignal` {String} (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} (Default: `'SIGTERM'`) * `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `callback` {Function} called with the output when process terminates @@ -391,7 +391,7 @@ ps.on('close', (code) => { }); grep.stdout.on('data', (data) => { - console.log(`${data}`); + console.log(data.toString()); }); grep.stderr.on('data', (data) => { @@ -475,8 +475,8 @@ const out = fs.openSync('./out.log', 'a'); const err = fs.openSync('./out.log', 'a'); const child = spawn('prg', [], { - detached: true, - stdio: [ 'ignore', out, err ] + detached: true, + stdio: [ 'ignore', out, err ] }); child.unref(); @@ -591,8 +591,8 @@ added: v0.11.12 * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) - * `killSignal` {String} The signal value to be used when the spawned process - will be killed. (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} The signal value to be used when the spawned + process will be killed. (Default: `'SIGTERM'`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: `'buffer'`) @@ -633,8 +633,8 @@ added: v0.11.12 * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) - * `killSignal` {String} The signal value to be used when the spawned process - will be killed. (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} The signal value to be used when the spawned + process will be killed. (Default: `'SIGTERM'`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. @@ -675,8 +675,8 @@ added: v0.11.12 * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) - * `killSignal` {String} The signal value to be used when the spawned process - will be killed. (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} The signal value to be used when the spawned + process will be killed. (Default: `'SIGTERM'`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. @@ -876,7 +876,7 @@ as in this example: 'use strict'; const spawn = require('child_process').spawn; -let child = spawn('sh', ['-c', +const child = spawn('sh', ['-c', `node -e "setInterval(() => { console.log(process.pid, 'is alive') }, 500);"` @@ -1123,21 +1123,21 @@ const fs = require('fs'); const child_process = require('child_process'); const child = child_process.spawn('ls', { - stdio: [ - 0, // Use parents stdin for child - 'pipe', // Pipe child's stdout to parent - fs.openSync('err.out', 'w') // Direct child's stderr to a file - ] + stdio: [ + 0, // Use parent's stdin for child + 'pipe', // Pipe child's stdout to parent + fs.openSync('err.out', 'w') // Direct child's stderr to a file + ] }); -assert.equal(child.stdio[0], null); -assert.equal(child.stdio[0], child.stdin); +assert.strictEqual(child.stdio[0], null); +assert.strictEqual(child.stdio[0], child.stdin); assert(child.stdout); -assert.equal(child.stdio[1], child.stdout); +assert.strictEqual(child.stdio[1], child.stdout); -assert.equal(child.stdio[2], null); -assert.equal(child.stdio[2], child.stderr); +assert.strictEqual(child.stdio[2], null); +assert.strictEqual(child.stdio[2], child.stderr); ``` ### child.stdout diff --git a/doc/api/cli.md b/doc/api/cli.md index d868d70533f5f2..30d4c62e52b8a1 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -189,7 +189,7 @@ Track heap object allocations for heap snapshots. ### `--prof-process` Process v8 profiler output generated using the v8 option `--prof`. @@ -287,6 +287,13 @@ added: v0.11.15 Data path for ICU (Intl object) data. Will extend linked-in data when compiled with small-icu support. +### `NODE_NO_WARNINGS=1` + + +When set to `1`, process warnings are silenced. + ### `NODE_PRESERVE_SYMLINKS=1` When set to `1`, writes to `stdout` and `stderr` will be non-blocking and @@ -316,6 +323,9 @@ Setting this will void any guarantee that stdio will not be interleaved or dropped at program exit. **Use of this mode is not recommended.** ### `NODE_EXTRA_CA_CERTS=file` + When set, the well known "root" CAs (like VeriSign) will be extended with the extra certificates in `file`. The file should consist of one or more trusted diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 7f77d3f940768c..9102f2e89c03c4 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -26,7 +26,7 @@ It is possible for Node.js to be built without including support for the error being thrown. ```js -var crypto; +let crypto; try { crypto = require('crypto'); } catch (err) { @@ -132,9 +132,9 @@ Example: Using `Cipher` objects as streams: const crypto = require('crypto'); const cipher = crypto.createCipher('aes192', 'a password'); -var encrypted = ''; +let encrypted = ''; cipher.on('readable', () => { - var data = cipher.read(); + const data = cipher.read(); if (data) encrypted += data.toString('hex'); }); @@ -166,7 +166,7 @@ Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods: const crypto = require('crypto'); const cipher = crypto.createCipher('aes192', 'a password'); -var encrypted = cipher.update('some clear text data', 'utf8', 'hex'); +let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); encrypted += cipher.final('hex'); console.log(encrypted); // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504 @@ -269,9 +269,9 @@ Example: Using `Decipher` objects as streams: const crypto = require('crypto'); const decipher = crypto.createDecipher('aes192', 'a password'); -var decrypted = ''; +let decrypted = ''; decipher.on('readable', () => { - var data = decipher.read(); + const data = decipher.read(); if (data) decrypted += data.toString('utf8'); }); @@ -280,7 +280,7 @@ decipher.on('end', () => { // Prints: some clear text data }); -var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; +const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; decipher.write(encrypted, 'hex'); decipher.end(); ``` @@ -304,8 +304,8 @@ Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods: const crypto = require('crypto'); const decipher = crypto.createDecipher('aes192', 'a password'); -var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; -var decrypted = decipher.update(encrypted, 'hex', 'utf8'); +const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; +let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); console.log(decrypted); // Prints: some clear text data @@ -402,18 +402,18 @@ const assert = require('assert'); // Generate Alice's keys... const alice = crypto.createDiffieHellman(2048); -const alice_key = alice.generateKeys(); +const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator()); -const bob_key = bob.generateKeys(); +const bobKey = bob.generateKeys(); // Exchange and generate the secret... -const alice_secret = alice.computeSecret(bob_key); -const bob_secret = bob.computeSecret(alice_key); +const aliceSecret = alice.computeSecret(bobKey); +const bobSecret = bob.computeSecret(aliceKey); // OK -assert.equal(alice_secret.toString('hex'), bob_secret.toString('hex')); +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding]) @@ -531,17 +531,17 @@ const assert = require('assert'); // Generate Alice's keys... const alice = crypto.createECDH('secp521r1'); -const alice_key = alice.generateKeys(); +const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = crypto.createECDH('secp521r1'); -const bob_key = bob.generateKeys(); +const bobKey = bob.generateKeys(); // Exchange and generate the secret... -const alice_secret = alice.computeSecret(bob_key); -const bob_secret = bob.computeSecret(alice_key); +const aliceSecret = alice.computeSecret(bobKey); +const bobSecret = bob.computeSecret(aliceKey); -assert(alice_secret, bob_secret); +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); // OK ``` @@ -648,13 +648,14 @@ alice.setPrivateKey( ); // Bob uses a newly generated cryptographically strong -// pseudorandom key pair bob.generateKeys(); +// pseudorandom key pair +bob.generateKeys(); -const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); -const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); -// alice_secret and bob_secret should be the same shared secret value -console.log(alice_secret === bob_secret); +// aliceSecret and bobSecret should be the same shared secret value +console.log(aliceSecret === bobSecret); ``` ## Class: Hash @@ -680,7 +681,7 @@ const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.on('readable', () => { - var data = hash.read(); + const data = hash.read(); if (data) console.log(data.toString('hex')); // Prints: @@ -763,7 +764,7 @@ const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', 'a secret'); hmac.on('readable', () => { - var data = hmac.read(); + const data = hmac.read(); if (data) console.log(data.toString('hex')); // Prints: @@ -847,8 +848,8 @@ const sign = crypto.createSign('RSA-SHA256'); sign.write('some data to sign'); sign.end(); -const private_key = getPrivateKeySomehow(); -console.log(sign.sign(private_key, 'hex')); +const privateKey = getPrivateKeySomehow(); +console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature ``` @@ -860,8 +861,8 @@ const sign = crypto.createSign('RSA-SHA256'); sign.update('some data to sign'); -const private_key = getPrivateKeySomehow(); -console.log(sign.sign(private_key, 'hex')); +const privateKey = getPrivateKeySomehow(); +console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature ``` @@ -878,13 +879,14 @@ const sign = crypto.createSign('sha256'); sign.update('some data to sign'); -const private_key = '-----BEGIN EC PRIVATE KEY-----\n' + - 'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' + - 'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' + - 'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' + - '-----END EC PRIVATE KEY-----\n'; +const privateKey = +`-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49 +AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2 +pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng== +-----END EC PRIVATE KEY-----`; -console.log(sign.sign(private_key).toString('hex')); +console.log(sign.sign(privateKey).toString('hex')); ``` ### sign.sign(private_key[, output_format]) @@ -947,9 +949,9 @@ const verify = crypto.createVerify('RSA-SHA256'); verify.write('some data to sign'); verify.end(); -const public_key = getPublicKeySomehow(); +const publicKey = getPublicKeySomehow(); const signature = getSignatureToVerify(); -console.log(verify.verify(public_key, signature)); +console.log(verify.verify(publicKey, signature)); // Prints: true or false ``` @@ -961,9 +963,9 @@ const verify = crypto.createVerify('RSA-SHA256'); verify.update('some data to sign'); -const public_key = getPublicKeySomehow(); +const publicKey = getPublicKeySomehow(); const signature = getSignatureToVerify(); -console.log(verify.verify(public_key, signature)); +console.log(verify.verify(publicKey, signature)); // Prints: true or false ``` @@ -1192,7 +1194,7 @@ const hash = crypto.createHash('sha256'); const input = fs.createReadStream(filename); input.on('readable', () => { - var data = input.read(); + const data = input.read(); if (data) hash.update(data); else { @@ -1226,7 +1228,7 @@ const hmac = crypto.createHmac('sha256', 'a secret'); const input = fs.createReadStream(filename); input.on('readable', () => { - var data = input.read(); + const data = input.read(); if (data) hmac.update(data); else { @@ -1278,7 +1280,7 @@ Example: ```js const curves = crypto.getCurves(); -console.log(curves); // ['secp256k1', 'secp384r1', ...] +console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` ### crypto.getDiffieHellman(group_name) @@ -1307,11 +1309,11 @@ const bob = crypto.getDiffieHellman('modp14'); alice.generateKeys(); bob.generateKeys(); -const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); -const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); -/* alice_secret and bob_secret should be the same */ -console.log(alice_secret == bob_secret); +/* aliceSecret and bobSecret should be the same */ +console.log(aliceSecret === bobSecret); ``` ### crypto.getHashes() @@ -1326,7 +1328,7 @@ Example: ```js const hashes = crypto.getHashes(); -console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...] +console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` ### crypto.pbkdf2(password, salt, iterations, keylen, digest, callback) @@ -1357,7 +1359,7 @@ Example: const crypto = require('crypto'); crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => { if (err) throw err; - console.log(key.toString('hex')); // 'c5e478d...1469e50' + console.log(key.toString('hex')); // '3745e48...aa39b34' }); ``` @@ -1390,7 +1392,7 @@ Example: ```js const crypto = require('crypto'); const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); -console.log(key.toString('hex')); // 'c5e478d...1469e50' +console.log(key.toString('hex')); // '3745e48...aa39b34' ``` An array of supported digest functions can be retrieved using @@ -1938,6 +1940,7 @@ the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. [`crypto.createHash()`]: #crypto_crypto_createhash_algorithm [`crypto.createHmac()`]: #crypto_crypto_createhmac_algorithm_key [`crypto.createSign()`]: #crypto_crypto_createsign_algorithm +[`crypto.createVerify()`]: #crypto_crypto_createverify_algorithm [`crypto.getCurves()`]: #crypto_crypto_getcurves [`crypto.getHashes()`]: #crypto_crypto_gethashes [`crypto.pbkdf2()`]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback diff --git a/doc/api/fs.md b/doc/api/fs.md index 4651e08672dda5..638e8261e36af1 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1832,7 +1832,8 @@ added: v0.0.2 Write `buffer` to the file specified by `fd`. -`offset` and `length` determine the part of the buffer to be written. +`offset` determines the part of the buffer to be written, and `length` is +an integer specifying the number of bytes to write. `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written diff --git a/doc/api/http.md b/doc/api/http.md index fb90123330458c..ea23dad33a8bd8 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -907,9 +907,8 @@ added: v0.4.0 * `name` {String} * Returns: {String} -Reads out a header that's already been queued but not sent to the client. Note -that the name is case insensitive. This can only be called before headers get -implicitly flushed. +Reads out a header that's already been queued but not sent to the client. +Note that the name is case insensitive. Example: diff --git a/doc/api/process.md b/doc/api/process.md index 3e0414e59effc4..4e20399d41fade 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -1651,9 +1651,9 @@ added: v0.2.0 * {Object} The `process.versions` property returns an object listing the version strings of -Node.js and its dependencies. In addition, `process.versions.modules` indicates -the current ABI version, which is increased whenever a C++ API changes. Node.js -will refuse to load native modules built for an older `modules` value. +Node.js and its dependencies. `process.versions.modules` indicates the current +ABI version, which is increased whenever a C++ API changes. Node.js will refuse +to load modules that were compiled against a different module ABI version. ```js console.log(process.versions); @@ -1754,5 +1754,5 @@ cases: [Readable]: stream.html [Child Process]: child_process.html [Cluster]: cluster.html -[`process.exitCode`]: #processexitcode-1 +[`process.exitCode`]: #process_process_exitcode [LTS]: https://github.com/nodejs/LTS/ diff --git a/doc/api/stream.md b/doc/api/stream.md index 291cda735aee3d..1095d8e6ecb5f8 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -440,12 +440,49 @@ occurs, the `callback` *may or may not* be called with the error as its first argument. To reliably detect write errors, add a listener for the `'error'` event. -The return value is `true` if the internal buffer does not exceed +The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. If `false` is returned, further attempts to write data to the stream should -stop until the [`'drain'`][] event is emitted. However, the `false` return -value is only advisory and the writable stream will unconditionally accept and -buffer `chunk` even if it has not not been allowed to drain. +stop until the [`'drain'`][] event is emitted. + +While a stream is not draining, calls to `write()` will buffer `chunk`, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the `'drain'` event will be emitted. +It is recommended that once write() returns false, no more chunks be written +until the `'drain'` event is emitted. While calling `write()` on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability. + +Writing data while the stream is not draining is particularly +problematic for a [Transform][], because the `Transform` streams are paused +by default until they are piped or an `'data'` or `'readable'` event handler +is added. + +If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a [Readable][] and use +[`stream.pipe()`][]. However, if calling `write()` is preferred, it is +possible to respect backpressure and avoid memory issues using the +the [`'drain'`][] event: + +```js +function write (data, cb) { + if (!stream.write(data)) { + stream.once('drain', cb) + } else { + process.nextTick(cb) + } +} + +// Wait for cb to be called before doing any other write. +write('hello', () => { + console.log('write completed, do more writes now') +}) +``` A Writable stream in object mode will always ignore the `encoding` argument. @@ -1306,7 +1343,7 @@ It is recommended that errors occurring during the processing of the `writable._write()` and `writable._writev()` methods are reported by invoking the callback and passing the error as the first argument. This will cause an `'error'` event to be emitted by the Writable. Throwing an Error from within -`writable._write()` can result in expected and inconsistent behavior depending +`writable._write()` can result in unexpected and inconsistent behavior depending on how the stream is being used. Using the callback ensures consistent and predictable handling of errors. diff --git a/doc/api/tls.md b/doc/api/tls.md index c33174f250479a..f83ed1df3e449f 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -483,12 +483,8 @@ added: v0.11.4 will be emitted on the socket before establishing a secure communication * `secureContext`: Optional TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one - will be created by passing the entire `options` object to - `tls.createSecureContext()`. *Note*: In effect, all - [`tls.createSecureContext()`][] options can be provided, but they will be - _completely ignored_ unless the `secureContext` option is missing. - * ...: Optional [`tls.createSecureContext()`][] options can be provided, see - the `secureContext` option for more information. + will be created by calling [`tls.createSecureContext()`][] with no options. + Construct a new `tls.TLSSocket` object from an existing TCP socket. ### Event: 'OCSPResponse' @@ -587,13 +583,16 @@ For Example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }` added: v0.11.4 --> -* `detailed` {boolean} Specify `true` to request that the full certificate - chain with the `issuer` property be returned; `false` to return only the - top certificate without the `issuer` property. +* `detailed` {boolean} Include the full certificate chain if `true`, otherwise + include just the peer's certificate. Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate. +If the full certificate chain was requested, each certificate will include a +`issuerCertificate` property containing an object representing its issuer's +certificate. + For example: ```text @@ -604,15 +603,15 @@ For example: O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, - issuerInfo: + issuer: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, - issuer: - { ... another certificate ... }, + issuerCertificate: + { ... another certificate, possibly with a .issuerCertificate ... }, raw: < RAW DER buffer >, valid_from: 'Nov 11 09:52:22 2009 GMT', valid_to: 'Nov 6 09:52:22 2029 GMT', @@ -620,8 +619,7 @@ For example: serialNumber: 'B9B0D332A1AA5635' } ``` -If the peer does not provide a certificate, `null` or an empty object will be -returned. +If the peer does not provide a certificate, an empty object will be returned. ### tlsSocket.getProtocol() The default curve name to use for ECDH key agreement in a tls server. The default value is `'prime256v1'` (NIST P-256). Consult [RFC 4492] and diff --git a/doc/api/url.md b/doc/api/url.md old mode 100644 new mode 100755 index 40a3440195e69a..50e7433e6110e5 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -250,7 +250,465 @@ properties of URL objects: For example, the ASCII space character (`' '`) is encoded as `%20`. The ASCII forward slash (`/`) character is encoded as `%3C`. +## The WHATWG URL API + +> Stability: 1 - Experimental + +The `url` module provides an *experimental* implementation of the +[WHATWG URL Standard][] as an alternative to the existing `url.parse()` API. + +```js +const URL = require('url').URL; +const myURL = new URL('https://example.org/foo'); + +console.log(myURL.href); // https://example.org/foo +console.log(myURL.protocol); // https: +console.log(myURL.hostname); // example.org +console.log(myURL.pathname); // /foo +``` + +*Note*: Using the `delete` keyword (e.g. `delete myURL.protocol`, +`delete myURL.pathname`, etc) has no effect but will still return `true`. + +### Class: URL +#### Constructor: new URL(input[, base]) + +* `input` {String} The input URL to parse +* `base` {String | URL} The base URL to resolve against if the `input` is not + absolute. + +Creates a new `URL` object by parsing the `input` relative to the `base`. If +`base` is passed as a string, it will be parsed equivalent to `new URL(base)`. + +```js +const myURL = new URL('/foo', 'https://example.org/'); + // https://example.org/foo +``` + +A `TypeError` will be thrown if the `input` or `base` are not valid URLs. Note +that an effort will be made to coerce the given values into strings. For +instance: + +```js +const myURL = new URL({toString: () => 'https://example.org/'}); + // https://example.org/ +``` + +Unicode characters appearing within the hostname of `input` will be +automatically converted to ASCII using the [Punycode][] algorithm. + +```js +const myURL = new URL('https://你好你好'); + // https://xn--6qqa088eba +``` + +Additional [examples of parsed URLs][] may be found in the WHATWG URL Standard. + +#### url.hash + +Gets and sets the fragment portion of the URL. + +```js +const myURL = new URL('https://example.org/foo#bar'); +console.log(myURL.hash); + // Prints #bar + +myURL.hash = 'baz'; +console.log(myURL.href); + // Prints https://example.org/foo#baz +``` + +Invalid URL characters included in the value assigned to the `hash` property +are [percent-encoded](#whatwg-percent-encoding). Note that the selection of +which characters to percent-encode may vary somewhat from what the +[`url.parse()`][] and [`url.format()`][] methods would produce. + +#### url.host + +Gets and sets the host portion of the URL. + +```js +const myURL = new URL('https://example.org:81/foo'); +console.log(myURL.host); + // Prints example.org:81 + +myURL.host = 'example.com:82'; +console.log(myURL.href); + // Prints https://example.com:82/foo +``` + +Invalid host values assigned to the `host` property are ignored. + +#### url.hostname + +Gets and sets the hostname portion of the URL. The key difference between +`url.host` and `url.hostname` is that `url.hostname` does *not* include the +port. + +```js +const myURL = new URL('https://example.org:81/foo'); +console.log(myURL.hostname); + // Prints example.org + +myURL.hostname = 'example.com:82'; +console.log(myURL.href); + // Prints https://example.com:81/foo +``` + +Invalid hostname values assigned to the `hostname` property are ignored. + +#### url.href + +Gets and sets the serialized URL. + +```js +const myURL = new URL('https://example.org/foo'); +console.log(myURL.href); + // Prints https://example.org/foo + +myURL.href = 'https://example.com/bar' + // Prints https://example.com/bar +``` + +Setting the value of the `href` property to a new value is equivalent to +creating a new `URL` object using `new URL(value)`. Each of the `URL` object's +properties will be modified. + +If the value assigned to the `href` property is not a valid URL, a `TypeError` +will be thrown. + +#### url.origin + +Gets the read-only serialization of the URL's origin. Unicode characters that +may be contained within the hostname will be encoded as-is without [Punycode][] +encoding. + +```js +const myURL = new URL('https://example.org/foo/bar?baz'); +console.log(myURL.origin); + // Prints https://example.org +``` + +```js +const idnURL = new URL('https://你好你好'); +console.log(idnURL.origin); + // Prints https://你好你好 + +console.log(idnURL.hostname); + // Prints xn--6qqa088eba +``` + +#### url.password + +Gets and sets the password portion of the URL. + +```js +const myURL = new URL('https://abc:xyz@example.com'); +console.log(myURL.password); + // Prints xyz + +myURL.password = '123'; +console.log(myURL.href); + // Prints https://abc:123@example.com +``` + +Invalid URL characters included in the value assigned to the `password` property +are [percent-encoded](#whatwg-percent-encoding). Note that the selection of +which characters to percent-encode may vary somewhat from what the +[`url.parse()`][] and [`url.format()`][] methods would produce. + +#### url.pathname + +Gets and sets the path portion of the URL. + +```js +const myURL = new URL('https://example.org/abc/xyz?123'); +console.log(myURL.pathname); + // Prints /abc/xyz + +myURL.pathname = '/abcdef'; +console.log(myURL.href); + // Prints https://example.org/abcdef?123 +``` + +Invalid URL characters included in the value assigned to the `pathname` +property are [percent-encoded](#whatwg-percent-encoding). Note that the +selection of which characters to percent-encode may vary somewhat from what the +[`url.parse()`][] and [`url.format()`][] methods would produce. + +#### url.port + +Gets and sets the port portion of the URL. When getting the port, the value +is returned as a String. + +```js +const myURL = new URL('https://example.org:8888'); +console.log(myURL.port); + // Prints 8888 + +myURL.port = 1234; +console.log(myURL.href); + // Prints https://example.org:1234 +``` + +The port value may be set as either a number or as a String containing a number +in the range `0` to `65535` (inclusive). Setting the value to the default port +of the `URL` objects given `protocol` will result in the `port` value becoming +the empty string (`''`). + +Invalid URL port values assigned to the `port` property are ignored. + +#### url.protocol + +Gets and sets the protocol portion of the URL. + +```js +const myURL = new URL('https://example.org'); +console.log(myURL.protocol); + // Prints http: + +myURL.protocol = 'ftp'; +console.log(myURL.href); + // Prints ftp://example.org +``` + +Invalid URL protocol values assigned to the `protocol` property are ignored. + +#### url.search + +Gets and sets the serialized query portion of the URL. + +```js +const myURL = new URL('https://example.org/abc?123'); +console.log(myURL.search); + // Prints ?123 + +myURL.search = 'abc=xyz'; +console.log(myURL.href); + // Prints https://example.org/abc?abc=xyz +``` + +Any invalid URL characters appearing in the value assigned the `search` +property will be [percent-encoded](#whatwg-percent-encoding). Note that the +selection of which characters to percent-encode may vary somewhat from what the +[`url.parse()`][] and [`url.format()`][] methods would produce. + +#### url.searchParams + +Gets a [`URLSearchParams`](#url_class_urlsearchparams) object representing the +query parameters of the URL. + +#### url.username + +Gets and sets the username portion of the URL. + +```js +const myURL = new URL('https://abc:xyz@example.com'); +console.log(myURL.username); + // Prints abc + +myURL.username = '123'; +console.log(myURL.href); + // Prints https://123:xyz@example.com +``` + +Any invalid URL characters appearing in the value assigned the `username` +property will be [percent-encoded](#whatwg-percent-encoding). Note that the +selection of which characters to percent-encode may vary somewhat from what the +[`url.parse()`][] and [`url.format()`][] methods would produce. + +#### url.toString() + +The `toString()` method on the `URL` object returns the serialized URL. The +value returned is equivalent to that of `url.href`. + +### Class: URLSearchParams + +The `URLSearchParams` object provides read and write access to the query of a +`URL`. + +```js +const URL = require('url').URL; +const myURL = new URL('https://example.org/?abc=123'); +console.log(myURL.searchParams.get('abc')); + // Prints 123 + +myURL.searchParams.append('abc', 'xyz'); +console.log(myURL.href); + // Prints https://example.org/?abc=123&abc=xyz + +myURL.searchParams.delete('abc'); +myURL.searchParams.set('a', 'b'); +console.log(myURL.href); + // Prints https://example.org/?a=b +``` + +#### Constructor: new URLSearchParams([init]) + +* `init` {String} The URL query + +#### urlSearchParams.append(name, value) + +* `name` {String} +* `value` {String} + +Append a new name-value pair to the query string. + +#### urlSearchParams.delete(name) + +* `name` {String} + +Remove all name-value pairs whose name is `name`. + +#### urlSearchParams.entries() + +* Returns: {Iterator} + +Returns an ES6 Iterator over each of the name-value pairs in the query. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the `name`, the second item of the Array is the `value`. + +Alias for `urlSearchParams\[\@\@iterator\]()`. + +#### urlSearchParams.forEach(fn) + +* `fn` {Function} Function invoked for each name-value pair in the query. + +Iterates over each name-value pair in the query and invokes the given function. + +```js +const URL = require('url').URL; +const myURL = new URL('https://example.org/?a=b&c=d'); +myURL.searchParams.forEach((value, name) => { + console.log(name, value); +}); +``` + +#### urlSearchParams.get(name) + +* `name` {String} +* Returns: {String} or `null` if there is no name-value pair with the given + `name`. + +Returns the value of the first name-value pair whose name is `name`. + +#### urlSearchParams.getAll(name) + +* `name` {String} +* Returns: {Array} + +Returns the values of all name-value pairs whose name is `name`. + +#### urlSearchParams.has(name) + +* `name` {String} +* Returns: {Boolean} + +Returns `true` if there is at least one name-value pair whose name is `name`. + +#### urlSearchParams.keys() + +* Returns: {Iterator} + +Returns an ES6 Iterator over the names of each name-value pair. + +#### urlSearchParams.set(name, value) + +* `name` {String} +* `value` {String} + +Remove any existing name-value pairs whose name is `name` and append a new +name-value pair. + +#### urlSearchParams.toString() + +* Returns: {String} + +Returns the search parameters serialized as a URL-encoded string. + +#### urlSearchParams.values() + +* Returns: {Iterator} + +Returns an ES6 Iterator over the values of each name-value pair. + +#### urlSearchParams\[\@\@iterator\]() + +* Returns: {Iterator} + +Returns an ES6 Iterator over each of the name-value pairs in the query string. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the `name`, the second item of the Array is the `value`. + +Alias for `urlSearchParams.entries()`. + +### require('url').domainToAscii(domain) + +* `domain` {String} +* Returns: {String} + +Returns the [Punycode][] ASCII serialization of the `domain`. + +*Note*: The `require('url').domainToAscii()` method is introduced as part of +the new `URL` implementation but is not part of the WHATWG URL standard. + +### require('url').domainToUnicode(domain) + +* `domain` {String} +* Returns: {String} + +Returns the Unicode serialization of the `domain`. + +*Note*: The `require('url').domainToUnicode()` API is introduced as part of the +the new `URL` implementation but is not part of the WHATWG URL standard. + + +### Percent-Encoding in the WHATWG URL Standard + +URLs are permitted to only contain a certain range of characters. Any character +falling outside of that range must be encoded. How such characters are encoded, +and which characters to encode depends entirely on where the character is +located within the structure of the URL. The WHATWG URL Standard uses a more +selective and fine grained approach to selecting encoded characters than that +used by the older [`url.parse()`][] and [`url.format()`][] methods. + +The WHATWG algorithm defines three "encoding sets" that describe ranges of +characters that must be percent-encoded: + +* The *simple encode set* includes code points in range U+0000 to U+001F + (inclusive) and all code points greater than U+007E. + +* The *default encode set* includes the *simple encode set* and code points + U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060, U+007B, and U+007D. + +* The *userinfo encode set* includes the *default encode set* and code points + U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D, U+005E, and + U+007C. + +The *simple encode set* is used primary for URL fragments and certain specific +conditions for the path. The *userinfo encode set* is used specifically for +username and passwords encoded within the URL. The *default encode set* is used +for all other cases. + +When non-ASCII characters appear within a hostname, the hostname is encoded +using the [Punycode][] algorithm. Note, however, that a hostname *may* contain +*both* Punycode encoded and percent-encoded characters. For example: + +```js +const URL = require('url').URL; +const myURL = new URL('https://%CF%80.com/foo'); +console.log(myURL.href); + // Prints https://xn--1xa.com/foo +console.log(myURL.origin); + // Prints https://π.com +``` + [`Error`]: errors.html#errors_class_error [`querystring`]: querystring.html [`TypeError`]: errors.html#errors_class_typeerror +[WHATWG URL Standard]: https://url.spec.whatwg.org/ +[examples of parsed URLs]: https://url.spec.whatwg.org/#example-url-parsing +[`url.parse()`]: #url_url_parse_urlstring_parsequerystring_slashesdenotehost +[`url.format()`]: #url_url_format_urlobject +[Punycode]: https://tools.ietf.org/html/rfc5891#section-4.4 diff --git a/doc/api/vm.md b/doc/api/vm.md index 8c49cfb7c31f24..cb0e2fbb76e25d 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -439,9 +439,9 @@ let code = vm.runInThisContext(code)(require); ``` -*Note*: The `require()` in the above case shares the state with context it is -passed from. This may introduce risks when untrusted code is executed, e.g. -altering objects from the calling thread's context in unwanted ways. +*Note*: The `require()` in the above case shares the state with the context it +is passed from. This may introduce risks when untrusted code is executed, e.g. +altering objects in the context in unwanted ways. ## What does it mean to "contextify" an object? diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 73bcf8e0179366..0d79c084acd565 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -388,6 +388,9 @@ Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms. ## zlib.constants + Provides an object enumerating Zlib-related constants. @@ -460,7 +463,7 @@ added: v0.6.0 added: v0.11.12 --> -Compress a Buffer or string with Deflate. +Compress a [Buffer][] or string with [Deflate][]. ### zlib.deflateRaw(buf[, options], callback) -Compress a Buffer or string with DeflateRaw. +Compress a [Buffer][] or string with [DeflateRaw][]. ### zlib.gunzip(buf[, options], callback) -Decompress a Buffer or string with Gunzip. +Decompress a [Buffer][] or string with [Gunzip][]. ### zlib.gzip(buf[, options], callback) -Compress a Buffer or string with Gzip. +Compress a [Buffer][] or string with [Gzip][]. ### zlib.inflate(buf[, options], callback) -Decompress a Buffer or string with Inflate. +Decompress a [Buffer][] or string with [Inflate][]. ### zlib.inflateRaw(buf[, options], callback) -Decompress a Buffer or string with InflateRaw. +Decompress a [Buffer][] or string with [InflateRaw][]. ### zlib.unzip(buf[, options], callback) -Decompress a Buffer or string with Unzip. +Decompress a [Buffer][] or string with [Unzip][]. [`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 [`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 diff --git a/doc/changelogs/CHANGELOG_V7.md b/doc/changelogs/CHANGELOG_V7.md index 1f476b8eae4649..f10ecdcc9c2b12 100644 --- a/doc/changelogs/CHANGELOG_V7.md +++ b/doc/changelogs/CHANGELOG_V7.md @@ -553,7 +553,7 @@ _This is a security release impacting Windows 10 users._ ### Notable changes * **crypto**: The `Decipher` methods `setAuthTag()` and `setAAD` now return `this`. (Kirill Fomichev) [#9398](https://github.com/nodejs/node/pull/9398) -* **dns**: Implemented `{ttl: true}` for `resolve4()` and `resolve6()`. (Ben Noordhuis) [#9296](https://github.com/nodejs/node/pull/9296) & [#9296](https://github.com/nodejs/node/pull/9296) +* **dns**: Implemented `{ttl: true}` for `resolve4()` and `resolve6()`. (Ben Noordhuis) [#9296](https://github.com/nodejs/node/pull/9296) * **libuv**: Upgrade to v1.10.1 (cjihrig) [#9647](https://github.com/nodejs/node/pull/9647) - Fixed a potential buffer overflow when writing data to console on Windows 10. (CVE-2016-9551) * **process**: Added a new `external` property to the data returned by `memoryUsage()`. (Fedor Indutny) [#9587](https://github.com/nodejs/node/pull/9587) @@ -986,8 +986,8 @@ _This is a security release impacting Windows 10 users._ * [[`0301ce9f55`](https://github.com/nodejs/node/commit/0301ce9f55)] - **src**: move IsolateData out of Environment (Ben Noordhuis) [#7082](https://github.com/nodejs/node/pull/7082) * [[`a3c5567eb4`](https://github.com/nodejs/node/commit/a3c5567eb4)] - **(SEMVER-MAJOR)** **src,win**: use correct exit code in old versions (yorkie) [#8204](https://github.com/nodejs/node/pull/8204) * [[`2f05af4c06`](https://github.com/nodejs/node/commit/2f05af4c06)] - **(SEMVER-MAJOR)** **stream**: improve stream error messages (Italo A. Casas) [#8801](https://github.com/nodejs/node/pull/8801) -* [[`9983af0347`](https://github.com/nodejs/node/commit/9983af0347)] - **(SEMVER-MAJOR)** **stream**: improve unimplemented _write() error (ratikesh9) [#7671](https://github.com/nodejs/node/pull/7671) -* [[`0cd0118334`](https://github.com/nodejs/node/commit/0cd0118334)] - **(SEMVER-MAJOR)** **stream**: 'data' argument on callback of Transform._flush() (Jesús Leganés Combarro "piranna) [#3708](https://github.com/nodejs/node/pull/3708) +* [[`9983af0347`](https://github.com/nodejs/node/commit/9983af0347)] - **(SEMVER-MAJOR)** **stream**: improve unimplemented \_write() error (ratikesh9) [#7671](https://github.com/nodejs/node/pull/7671) +* [[`0cd0118334`](https://github.com/nodejs/node/commit/0cd0118334)] - **(SEMVER-MAJOR)** **stream**: 'data' argument on callback of Transform.\_flush() (Jesús Leganés Combarro "piranna) [#3708](https://github.com/nodejs/node/pull/3708) * [[`a717be87a3`](https://github.com/nodejs/node/commit/a717be87a3)] - **test**: fix flaky test-timers-blocking-callback (Rich Trott) [#9198](https://github.com/nodejs/node/pull/9198) * [[`5ba02bf5db`](https://github.com/nodejs/node/commit/5ba02bf5db)] - **test**: remove arbitrary timer (Rich Trott) [#9197](https://github.com/nodejs/node/pull/9197) * [[`1518cc1e70`](https://github.com/nodejs/node/commit/1518cc1e70)] - **test**: remove duplicate required module (Rich Trott) [#9169](https://github.com/nodejs/node/pull/9169) diff --git a/doc/guides/maintaining-V8.md b/doc/guides/maintaining-V8.md index 19ee61fe20c5d7..4bfed3790f5185 100644 --- a/doc/guides/maintaining-V8.md +++ b/doc/guides/maintaining-V8.md @@ -177,8 +177,8 @@ https://crbug.com/v8/5199. From the bug we can see that it was merged by V8 into `v6.x` uses V8 5.1, the fix needed to cherry-picked. To cherry-pick, here's an example workflow: -* Download and apply the commit linked-to in the issue (in this case a51f429). `curl -L https://github.com/v8/v8/commit/a51f429.patch | git apply --directory=deps/v8`. If the branches have diverged significantly, this may not apply cleanly. It may help to try to cherry-pick the merge to the oldest branch that was done upstream in V8. In this example, this would be the patch from the merge to 5.2. The hope is that this would be closer to the V8 5.1, and has a better chance of applying cleanly. If you're stuck, feel free to ping @ofrobots for help. -* Modify the commit message to match the format we use for V8 backports. You may want to add extra description if necessary to indicate the impact of the fix on Node.js. In this case the original issue was descriptive enough. Example: +* Download and apply the commit linked-to in the issue (in this case a51f429). `curl -L https://github.com/v8/v8/commit/a51f429.patch | git am -3 --directory=deps/v8`. If the branches have diverged significantly, this may not apply cleanly. It may help to try to cherry-pick the merge to the oldest branch that was done upstream in V8. In this example, this would be the patch from the merge to 5.2. The hope is that this would be closer to the V8 5.1, and has a better chance of applying cleanly. If you're stuck, feel free to ping @ofrobots for help. +* Modify the commit message to match the format we use for V8 backports and replace yourself as the author. `git commit --amend --reset-author`. You may want to add extra description if necessary to indicate the impact of the fix on Node.js. In this case the original issue was descriptive enough. Example: ``` deps: cherry-pick a51f429 from V8 upstream diff --git a/doc/guides/timers-in-node.md b/doc/guides/timers-in-node.md deleted file mode 100644 index 818cc793437cad..00000000000000 --- a/doc/guides/timers-in-node.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Timers in Node.js -layout: docs.hbs ---- - -# Timers in Node.js and beyond - -The Timers module in Node.js contains functions that execute code after a set -period of time. Timers do not need to be imported via `require()`, since -all the methods are available globally to emulate the browser JavaScript API. -To fully understand when timer functions will be executed, it's a good idea to -read up on the the Node.js -[Event Loop](../topics/event-loop-timers-and-nexttick.md). - -## Controlling the Time Continuum with Node.js - -The Node.js API provides several ways of scheduling code to execute at -some point after the present moment. The functions below may seem familiar, -since they are available in most browsers, but Node.js actually provides -its own implementation of these methods. Timers integrate very closely -with the system, and despite the fact that the API mirrors the browser -API, there are some differences in implementation. - -### "When I say so" Execution ~ *`setTimeout()`* - -`setTimeout()` can be used to schedule code execution after a designated -amount of milliseconds. This function is similar to -[`window.setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout) -from the browser JavaScript API, however a string of code cannot be passed -to be executed. - -`setTimeout()` accepts a function to execute as its first argument and the -millisecond delay defined as a number as the second argument. Additional -arguments may also be included and these will be passed on to the function. Here -is an example of that: - -```js -function myFunc (arg) { - console.log('arg was => ' + arg); -} - -setTimeout(myFunc, 1500, 'funky'); -``` - -The above function `myFunc()` will execute as close to 1500 -milliseconds (or 1.5 seconds) as possible due to the call of `setTimeout()`. - -The timeout interval that is set cannot be relied upon to execute after -that *exact* number of milliseconds. This is because other executing code that -blocks or holds onto the event loop will push the execution of the timeout -back. The *only* guarantee is that the timeout will not execute *sooner* than -the declared timeout interval. - -`setTimeout()` returns a `Timeout` object that can be used to reference the -timeout that was set. This returned object can be used to cancel the timeout ( -see `clearTimeout()` below) as well as change the execution behavior (see -`unref()` below). - -### "Right after this" Execution ~ *`setImmediate()`* - -`setImmediate()` will execute code at the end of the current event loop cycle. -This code will execute *after* any I/O operations in the current event loop and -*before* any timers scheduled for the next event loop. This code execution -could be thought of as happening "right after this", meaning any code following -the `setImmediate()` function call will execute before the `setImmediate()` -function argument. - -The first argument to `setImmediate()` will be the function to execute. Any -subsequent arguments will be passed to the function when it is executed. -Here's an example: - -```js -console.log('before immediate'); - -setImmediate((arg) => { - console.log(`executing immediate: ${arg}`); -}, 'so immediate'); - -console.log('after immediate'); -``` - -The above function passed to `setImmediate()` will execute after all runnable -code has executed, and the console output will be: - -```console -before immediate -after immediate -executing immediate: so immediate -``` - -`setImmediate()` returns and `Immediate` object, which can be used to cancel -the scheduled immediate (see `clearImmediate()` below). - -Note: Don't get `setImmediate()` confused with `process.nextTick()`. There are -some major ways they differ. The first is that `process.nextTick()` will run -*before* any `Immediate`s that are set as well as before any scheduled I/O. -The second is that `process.nextTick()` is non-clearable, meaning once -code has been scheduled to execute with `process.nextTick()`, the execution -cannot be stopped, just like with a normal function. Refer to [this guide](../topics/event-loop-timers-and-nexttick.md#processnexttick) -to better understand the operation of `process.nextTick()`. - -### "Infinite Loop" Execution ~ *`setInterval()`* - -If there is a block of code that should execute multiple times, `setInterval()` -can be used to execute that code. `setInterval()` takes a function -argument that will run an infinite number of times with a given millisecond -delay as the second argument. Just like `setTimeout()`, additional arguments -can be added beyond the delay, and these will be passed on to the function call. -Also like `setTimeout()`, the delay cannot be guaranteed because of operations -that may hold on to the event loop, and therefore should be treated as an -approximate delay. See the below example: - -```js -function intervalFunc () { - console.log('Cant stop me now!'); -} - -setInterval(intervalFunc, 1500); -``` -In the above example, `intervalFunc()` will execute about every 1500 -milliseconds, or 1.5 seconds, until it is stopped (see below). - -Just like `setTimeout()`, `setInterval()` also returns a `Timeout` object which -can be used to reference and modify the interval that was set. - -## Clearing the Future - -What can be done if a `Timeout` or `Immediate` object needs to be cancelled? -`setTimeout()`, `setImmediate()`, and `setInterval()` return a timer object -that can be used to reference the set `Timeout` or `Immediate` object. -By passing said object into the respective `clear` function, execution of -that object will be halted completely. The respective functions are -`clearTimeout()`, `clearImmediate()`, and `clearInterval()`. See the example -below for an example of each: - -```js -let timeoutObj = setTimeout(() => { - console.log('timeout beyond time'); -}, 1500); - -let immediateObj = setImmediate(() => { - console.log('immediately executing immediate'); -}); - -let intervalObj = setInterval(() => { - console.log('interviewing the interval'); -}, 500); - -clearTimeout(timeoutObj); -clearImmediate(immediateObj); -clearInterval(intervalObj); -``` - -## Leaving Timeouts Behind - -Remember that `Timeout` objects are returned by `setTimeout` and `setInterval`. -The `Timeout` object provides two functions intended to augment `Timeout` -behavior with `unref()` and `ref()`. If there is a `Timeout` object scheduled -using a `set` function, `unref()` can be called on that object. This will change -the behavior slightly, and not call the `Timeout` object *if it is the last -code to execute*. The `Timeout` object will not keep the process alive, waiting -to execute. - -In similar fashion, a `Timeout` object that has had `unref()` called on it -can remove that behavior by calling `ref()` on that same `Timeout` object, -which will then ensure its execution. Be aware, however, that this does -not *exactly* restore the initial behavior for performance reasons. See -below for examples of both: - -```js -let timerObj = setTimeout(() => { - console.log('will i run?'); -}); - -// if left alone, this statement will keep the above -// timeout from running, since the timeout will be the only -// thing keeping the program from exiting -timerObj.unref(); - -// we can bring it back to life by calling ref() inside -// an immediate -setImmediate(() => { - timerObj.ref(); -}); -``` -## Further Down the Event Loop - -There's much more to the Event Loop and Timers than this guide -has covered. To learn more about the internals of the Node.js -Event Loop and how Timers operate during execution, check out -this Node.js guide: [The Node.js Event Loop, Timers, and -process.nextTick()](../topics/event-loop-timers-and-nexttick.md). diff --git a/doc/guides/writing-tests.md b/doc/guides/writing-tests.md index d628e3f6f5873c..f27c076590e513 100644 --- a/doc/guides/writing-tests.md +++ b/doc/guides/writing-tests.md @@ -2,26 +2,25 @@ ## What is a test? -A test must be a node script that exercises a specific functionality provided -by node and checks that it behaves as expected. It should exit with code `0` on success, -otherwise it will fail. A test will fail if: +Most tests in Node.js core are JavaScript programs that exercise a functionality +provided by Node.js and check that it behaves as expected. Tests should exit +with code `0` on success. A test will fail if: - It exits by setting `process.exitCode` to a non-zero number. - - This is most often done by having an assertion throw an uncaught - Error. + - This is usually done by having an assertion throw an uncaught Error. - Occasionally, using `process.exit(code)` may be appropriate. - It never exits. In this case, the test runner will terminate the test because it sets a maximum time limit. -Tests can be added for multiple reasons: +Add tests when: -- When adding new functionality. -- When fixing regressions and bugs. -- When expanding test coverage. +- Adding new functionality. +- Fixing regressions and bugs. +- Expanding test coverage. ## Test structure -Let's analyze this very basic test from the Node.js test suite: +Let's analyze this basic test from the Node.js test suite: ```javascript 1 'use strict'; @@ -30,8 +29,8 @@ Let's analyze this very basic test from the Node.js test suite: 4 // This test ensures that the http-parser can handle UTF-8 characters 5 // in the http header. 6 -7 const http = require('http'); -8 const assert = require('assert'); +7 const assert = require('assert'); +8 const http = require('http'); 9 10 const server = http.createServer(common.mustCall((req, res) => { 11 res.end('ok'); @@ -47,7 +46,7 @@ Let's analyze this very basic test from the Node.js test suite: 21 }); ``` -**Lines 1-2** +### **Lines 1-2** ```javascript 'use strict'; @@ -60,17 +59,18 @@ the nature of the test requires that the test run without it. The second line loads the `common` module. The `common` module is a helper module that provides useful tools for the tests. -Even if no functions or other properties exported by `common` are used in a -test, the `common` module should still be included. This is because the `common` -module includes code that will cause tests to fail if variables are leaked into -the global space. In situations where no functions or other properties exported -by `common` are used, it can be included without assigning it to an identifier: +Even if a test uses no functions or other properties exported by `common`, +the test should still include the `common` module before any other modules. This +is because the `common` module includes code that will cause a test to fail if +the test leaks variables into the global space. In situations where a test uses +no functions or other properties exported by `common`, include it without +assigning it to an identifier: ```javascript require('../common'); ``` -**Lines 4-5** +### **Lines 4-5** ```javascript // This test ensures that the http-parser can handle UTF-8 characters @@ -80,32 +80,35 @@ require('../common'); A test should start with a comment containing a brief description of what it is designed to test. -**Lines 7-8** +### **Lines 7-8** ```javascript -const http = require('http'); const assert = require('assert'); +const http = require('http'); ``` -These modules are required for the test to run. Except for special cases, these -modules should only include core modules. -The `assert` module is used by most of the tests to check that the assumptions -for the test are met. +The test checks functionality in the `http` module. + +Most tests use the `assert` module to confirm expectations of the test. + +The require statements are sorted in +[ASCII](http://man7.org/linux/man-pages/man7/ascii.7.html) order (digits, upper +case, `_`, lower case). -**Lines 10-21** +### **Lines 10-21** -This is the body of the test. This test is quite simple, it just tests that an +This is the body of the test. This test is simple, it just tests that an HTTP server accepts `non-ASCII` characters in the headers of an incoming request. Interesting things to notice: -- If the test doesn't depend on a specific port number then always use 0 instead - of an arbitrary value, as it allows tests to be run in parallel safely, as the - operating system will assign a random port. If the test requires a specific - port, for example if the test checks that assigning a specific port works as - expected, then it is ok to assign a specific port number. +- If the test doesn't depend on a specific port number, then always use 0 + instead of an arbitrary value, as it allows tests to run in parallel safely, + as the operating system will assign a random port. If the test requires a + specific port, for example if the test checks that assigning a specific port + works as expected, then it is ok to assign a specific port number. - The use of `common.mustCall` to check that some callbacks/listeners are called. -- The HTTP server is closed once all the checks have run. This way, the test can +- The HTTP server closes once all the checks have run. This way, the test can exit gracefully. Remember that for a test to succeed, it must exit with a status code of 0. @@ -113,20 +116,20 @@ request. Interesting things to notice: ### Timers -The use of timers is discouraged, unless timers are being tested. There are -multiple reasons for this. Mainly, they are a source of flakiness. For a thorough +Avoid timers unless the test is specifically testing timers. There are multiple +reasons for this. Mainly, they are a source of flakiness. For a thorough explanation go [here](https://github.com/nodejs/testing/issues/27). -In the event a timer is needed, it's recommended using the -`common.platformTimeout()` method, that allows setting specific timeouts +In the event a test needs a timer, consider using the +`common.platformTimeout()` method. It allows setting specific timeouts depending on the platform. For example: ```javascript const timer = setTimeout(fail, common.platformTimeout(4000)); ``` -will create a 4-seconds timeout, except for some platforms where the delay will -be multiplied for some factor. +will create a 4-second timeout on most platforms but a longer timeout on slower +platforms. ### The *common* API @@ -191,9 +194,9 @@ var server = http.createServer(common.mustCall(function(req, res) { ### Flags Some tests will require running Node.js with specific command line flags set. To -accomplish this, a `// Flags: ` comment should be added in the preamble of the +accomplish this, add a `// Flags: ` comment in the preamble of the test followed by the flags. For example, to allow a test to require some of the -`internal/*` modules, the `--expose-internals` flag should be added. +`internal/*` modules, add the `--expose-internals` flag. A test that would require `internal/freelist` could start like this: ```javascript @@ -205,3 +208,15 @@ require('../common'); const assert = require('assert'); const freelist = require('internal/freelist'); ``` + +## Naming Test Files + +Test files are named using kebab casing. The first component of the name is +`test`. The second is the module or subsystem being tested. The third is usually +the method or event name being tested. Subsequent components of the name add +more information about what is being tested. + +For example, a test for the `beforeExit` event on the `process` object might be +named `test-process-before-exit.js`. If the test specifically checked that arrow +functions worked correctly with the `beforeExit` event, then it might be named +`test-process-before-exit-arrow-functions.js`. diff --git a/doc/node.1 b/doc/node.1 index e7f6d256ae850e..a2426594c0d381 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -198,6 +198,10 @@ errors are otherwise ignored. Data path for ICU (Intl object) data. Will extend linked-in data when compiled with small\-icu support. +.TP +.BR NODE_NO_WARNINGS =\fI1\fR +When set to \fI1\fR, process warnings are silenced. + .TP .BR NODE_PATH =\fIpath\fR[:\fI...\fR] \':\'\-separated list of directories prefixed to the module search path. diff --git a/doc/onboarding-extras.md b/doc/onboarding-extras.md index 9e1a4a7ed7b14b..1b5d082434fd71 100644 --- a/doc/onboarding-extras.md +++ b/doc/onboarding-extras.md @@ -13,6 +13,7 @@ | `lib/{crypto,tls,https}` | @nodejs/crypto | | `lib/domains` | @misterdjules | | `lib/fs`, `src/{fs|file}` | @nodejs/fs | +| `lib/internal/url`, `src/node_url` | @nodejs/url | | `lib/{_}http{*}` | @nodejs/http | | `lib/net` | @bnoordhuis, @indutny, @nodejs/streams | | `lib/{_}stream{s|*}` | @nodejs/streams | @@ -26,10 +27,11 @@ | `tools/eslint`, `.eslintrc` | @silverwind, @trott | | async_hooks | @nodejs/diagnostics | | upgrading V8 | @nodejs/v8, @nodejs/post-mortem | -| upgrading npm | @fishrock123, @thealphanerd | +| upgrading npm | @fishrock123, @MylesBorins | | upgrading c-ares | @jbergstroem | | upgrading http-parser | @jbergstroem, @nodejs/http | | upgrading libuv | @saghul | +| python code | @nodejs/python | | platform specific | @nodejs/platform-{aix,arm,freebsd,macos,ppc,smartos,s390,windows} | diff --git a/doc/onboarding.md b/doc/onboarding.md index dbe3dfd569b7ae..14e4572890dbbe 100644 --- a/doc/onboarding.md +++ b/doc/onboarding.md @@ -71,6 +71,10 @@ onboarding session. * [**See "Who to CC in issues"**](./onboarding-extras.md#who-to-cc-in-issues) * will also come more naturally over time + * When a discussion gets heated, you can request that other collaborators keep an eye on it by opening an issue at the private [nodejs/moderation](https://github.com/nodejs/moderation) repository. + * This is a repository to which all members of the `nodejs` GitHub organization (not just Collaborators on Node.js core) have access. Its contents should not be shared externally. + * You can find the full moderation policy [here](https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md). + ## Reviewing PRs * The primary goal is for the codebase to improve. * Secondary (but not far off) is for the person submitting code to succeed. diff --git a/doc/topics/blocking-vs-non-blocking.md b/doc/topics/blocking-vs-non-blocking.md deleted file mode 100644 index ffdbcfc918e0e7..00000000000000 --- a/doc/topics/blocking-vs-non-blocking.md +++ /dev/null @@ -1,143 +0,0 @@ -# Overview of Blocking vs Non-Blocking - -This overview covers the difference between **blocking** and **non-blocking** -calls in Node.js. This overview will refer to the event loop and libuv but no -prior knowledge of those topics is required. Readers are assumed to have a -basic understanding of the JavaScript language and Node.js callback pattern. - -> "I/O" refers primarily to interaction with the system's disk and -> network supported by [libuv](http://libuv.org/). - - -## Blocking - -**Blocking** is when the execution of additional JavaScript in the Node.js -process must wait until a non-JavaScript operation completes. This happens -because the event loop is unable to continue running JavaScript while a -**blocking** operation is occurring. - -In Node.js, JavaScript that exhibits poor performance due to being CPU intensive -rather than waiting on a non-JavaScript operation, such as I/O, isn't typically -referred to as **blocking**. Synchronous methods in the Node.js standard library -that use libuv are the most commonly used **blocking** operations. Native -modules may also have **blocking** methods. - -All of the I/O methods in the Node.js standard library provide asynchronous -versions, which are **non-blocking**, and accept callback functions. Some -methods also have **blocking** counterparts, which have names that end with -`Sync`. - - -## Comparing Code - -**Blocking** methods execute **synchronously** and **non-blocking** methods -execute **asynchronously**. - -Using the File System module as an example, this is a **synchronous** file read: - -```js -const fs = require('fs'); -const data = fs.readFileSync('/file.md'); // blocks here until file is read -``` - -And here is an equivalent **asynchronous** example: - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; -}); -``` - -The first example appears simpler than the second but has the disadvantage of -the second line **blocking** the execution of any additional JavaScript until -the entire file is read. Note that in the synchronous version if an error is -thrown it will need to be caught or the process will crash. In the asynchronous -version, it is up to the author to decide whether an error should throw as -shown. - -Let's expand our example a little bit: - -```js -const fs = require('fs'); -const data = fs.readFileSync('/file.md'); // blocks here until file is read -console.log(data); -// moreWork(); will run after console.log -``` - -And here is a similar, but not equivalent asynchronous example: - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; - console.log(data); -}); -// moreWork(); will run before console.log -``` - -In the first example above, `console.log` will be called before `moreWork()`. In -the second example `fs.readFile()` is **non-blocking** so JavaScript execution -can continue and `moreWork()` will be called first. The ability to run -`moreWork()` without waiting for the file read to complete is a key design -choice that allows for higher throughput. - - -## Concurrency and Throughput - -JavaScript execution in Node.js is single threaded, so concurrency refers to the -event loop's capacity to execute JavaScript callback functions after completing -other work. Any code that is expected to run in a concurrent manner must allow -the event loop to continue running as non-JavaScript operations, like I/O, are -occurring. - -As an example, let's consider a case where each request to a web server takes -50ms to complete and 45ms of that 50ms is database I/O that can be done -asynchronously. Choosing **non-blocking** asynchronous operations frees up that -45ms per request to handle other requests. This is a significant difference in -capacity just by choosing to use **non-blocking** methods instead of -**blocking** methods. - -The event loop is different than models in many other languages where additional -threads may be created to handle concurrent work. - - -## Dangers of Mixing Blocking and Non-Blocking Code - -There are some patterns that should be avoided when dealing with I/O. Let's look -at an example: - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; - console.log(data); -}); -fs.unlinkSync('/file.md'); -``` - -In the above example, `fs.unlinkSync()` is likely to be run before -`fs.readFile()`, which would delete `file.md` before it is actually read. A -better way to write this that is completely **non-blocking** and guaranteed to -execute in the correct order is: - - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; - console.log(data); - fs.unlink('/file.md', (err) => { - if (err) throw err; - }); -}); -``` - -The above places a **non-blocking** call to `fs.unlink()` within the callback of -`fs.readFile()` which guarantees the correct order of operations. - - -## Additional Resources - -- [libuv](http://libuv.org/) -- [About Node.js](https://nodejs.org/en/about/) diff --git a/doc/topics/domain-postmortem.md b/doc/topics/domain-postmortem.md deleted file mode 100644 index e03012db926b08..00000000000000 --- a/doc/topics/domain-postmortem.md +++ /dev/null @@ -1,301 +0,0 @@ -# Domain Module Postmortem - -## Usability Issues - -### Implicit Behavior - -It's possible for a developer to create a new domain and then simply run -`domain.enter()`. Which then acts as a catch-all for any exception in the -future that couldn't be observed by the thrower. Allowing a module author to -intercept the exceptions of unrelated code in a different module. Preventing -the originator of the code from knowing about its own exceptions. - -Here's an example of how one indirectly linked modules can affect another: - -```js -// module a.js -const b = require('./b'); -const c = require('./c'); - - -// module b.js -const d = require('domain').create(); -d.on('error', () => { /* silence everything */ }); -d.enter(); - - -// module c.js -const dep = require('some-dep'); -dep.method(); // Uh-oh! This method doesn't actually exist. -``` - -Since module `b` enters the domain but never exits any uncaught exception will -be swallowed. Leaving module `c` in the dark as to why it didn't run the entire -script. Leaving a potentially partially populated `module.exports`. Doing this -is not the same as listening for `'uncaughtException'`. As the latter is -explicitly meant to globally catch errors. The other issue is that domains are -processed prior to any `'uncaughtException'` handlers, and prevent them from -running. - -Another issue is that domains route errors automatically if no `'error'` -handler was set on the event emitter. There is no opt-in mechanism for this, -and automatically propagates across the entire asynchronous chain. This may -seem useful at first, but once asynchronous calls are two or more modules deep -and one of them doesn't include an error handler the creator of the domain will -suddenly be catching unexpected exceptions, and the thrower's exception will go -unnoticed by the author. - -The following is a simple example of how a missing `'error'` handler allows -the active domain to hijack the error: - -```js -const domain = require('domain'); -const net = require('net'); -const d = domain.create(); -d.on('error', (err) => console.error(err.message)); - -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); -``` - -Even manually removing the connection via `d.remove(c)` does not prevent the -connection's error from being automatically intercepted. - -Failures that plagues both error routing and exception handling are the -inconsistencies in how errors are bubbled. The following is an example of how -nested domains will and won't bubble the exception based on when they happen: - -```js -const domain = require('domain'); -const net = require('net'); -const d = domain.create(); -d.on('error', () => console.error('d intercepted an error')); - -d.run(() => { - const server = net.createServer((c) => { - const e = domain.create(); // No 'error' handler being set. - e.run(() => { - // This will not be caught by d's error handler. - setImmediate(() => { - throw new Error('thrown from setImmediate'); - }); - // Though this one will bubble to d's error handler. - throw new Error('immediately thrown'); - }); - }).listen(8080); -}); -``` - -It may be expected that nested domains always remain nested, and will always -propagate the exception up the domain stack. Or that exceptions will never -automatically bubble. Unfortunately both these situations occur, leading to -potentially confusing behavior that may even be prone to difficult to debug -timing conflicts. - - -### API Gaps - -While APIs based on using `EventEmitter` can use `bind()` and errback style -callbacks can use `intercept()`, alternative APIs that implicitly bind to the -active domain must be executed inside of `run()`. Meaning if module authors -wanted to support domains using a mechanism alternative to those mentioned they -must manually implement domain support themselves. Instead of being able to -leverage the implicit mechanisms already in place. - - -### Error Propagation - -Propagating errors across nested domains is not straight forward, if even -possible. Existing documentation shows a simple example of how to `close()` an -`http` server if there is an error in the request handler. What it does not -explain is how to close the server if the request handler creates another -domain instance for another async request. Using the following as a simple -example of the failing of error propagation: - -```js -const d1 = domain.create(); -d1.foo = true; // custom member to make more visible in console -d1.on('error', (er) => { /* handle error */ }); - -d1.run(() => setTimeout(() => { - const d2 = domain.create(); - d2.bar = 43; - d2.on('error', (er) => console.error(er.message, domain._stack)); - d2.run(() => { - setTimeout(() => { - setTimeout(() => { - throw new Error('outer'); - }); - throw new Error('inner') - }); - }); -})); -``` - -Even in the case that the domain instances are being used for local storage so -access to resources are made available there is still no way to allow the error -to continue propagating from `d2` back to `d1`. Quick inspection may tell us -that simply throwing from `d2`'s domain `'error'` handler would allow `d1` to -then catch the exception and execute its own error handler. Though that is not -the case. Upon inspection of `domain._stack` you'll see that the stack only -contains `d2`. - -This may be considered a failing of the API, but even if it did operate in this -way there is still the issue of transmitting the fact that a branch in the -asynchronous execution has failed, and that all further operations in that -branch must cease. In the example of the http request handler, if we fire off -several asynchronous requests and each one then `write()`'s data back to the -client many more errors will arise from attempting to `write()` to a closed -handle. More on this in _Resource Cleanup on Exception_. - - -### Resource Cleanup on Exception - -The script [`domain-resource-cleanup-example.js`][] -contains a more complex example of properly cleaning up in a small resource -dependency tree in the case that an exception occurs in a given connection or -any of its dependencies. Breaking down the script into its basic operations: - -- When a new connection happens, concurrently: - - Open a file on the file system - - Open Pipe to unique socket -- Read a chunk of the file asynchronously -- Write chunk to both the TCP connection and any listening sockets -- If any of these resources error, notify all other attached resources that - they need to clean up and shutdown - -As we can see from this example a lot more must be done to properly clean up -resources when something fails than what can be done strictly through the -domain API. All that domains offer is an exception aggregation mechanism. Even -the potentially useful ability to propagate data with the domain is easily -countered, in this example, by passing the needed resources as a function -argument. - -One problem domains perpetuated was the supposed simplicity of being able to -continue execution, contrary to what the documentation stated, of the -application despite an unexpected exception. This example demonstrates the -fallacy behind that idea. - -Attempting proper resource cleanup on unexpected exception becomes more complex -as the application itself grows in complexity. This example only has 3 basic -resources in play, and all of them with a clear dependency path. If an -application uses something like shared resources or resource reuse the ability -to cleanup, and properly test that cleanup has been done, grows greatly. - -In the end, in terms of handling errors, domains aren't much more than a -glorified `'uncaughtException'` handler. Except with more implicit and -unobservable behavior by third-parties. - - -### Resource Propagation - -Another use case for domains was to use it to propagate data along asynchronous -data paths. One problematic point is the ambiguity of when to expect the -correct domain when there are multiple in the stack (which must be assumed if -the async stack works with other modules). Also the conflict between being -able to depend on a domain for error handling while also having it available to -retrieve the necessary data. - -The following is a involved example demonstrating the failing using domains to -propagate data along asynchronous stacks: - -```js -const domain = require('domain'); -const net = require('net'); - -const server = net.createServer((c) => { - // Use a domain to propagate data across events within the - // connection so that we don't have to pass arguments - // everywhere. - const d = domain.create(); - d.data = { connection: c }; - d.add(c); - // Mock class that does some useless async data transformation - // for demonstration purposes. - const ds = new DataStream(dataTransformed); - c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log(`listening on 8080`)); - -function dataTransformed(chunk) { - // FAIL! Because the DataStream instance also created a - // domain we have now lost the active domain we had - // hoped to use. - domain.active.data.connection.write(chunk); -} - -function DataStream(cb) { - this.cb = cb; - // DataStream wants to use domains for data propagation too! - // Unfortunately this will conflict with any domain that - // already exists. - this.domain = domain.create(); - this.domain.data = { inst: this }; -} - -DataStream.prototype.data = function data(chunk) { - // This code is self contained, but pretend it's a complex - // operation that crosses at least one other module. So - // passing along "this", etc., is not easy. - this.domain.run(function() { - // Simulate an async operation that does the data transform. - setImmediate(() => { - for (var i = 0; i < chunk.length; i++) - chunk[i] = ((chunk[i] + Math.random() * 100) % 96) + 33; - // Grab the instance from the active domain and use that - // to call the user's callback. - const self = domain.active.data.inst; - self.cb.call(self, chunk); - }); - }); -}; -``` - -The above shows that it is difficult to have more than one asynchronous API -attempt to use domains to propagate data. This example could possibly be fixed -by assigning `parent: domain.active` in the `DataStream` constructor. Then -restoring it via `domain.active = domain.active.data.parent` just before the -user's callback is called. Also the instantiation of `DataStream` in the -`'connection'` callback must be run inside `d.run()`, instead of simply using -`d.add(c)`, otherwise there will be no active domain. - -In short, for this to have a prayer of a chance usage would need to strictly -adhere to a set of guidelines that would be difficult to enforce or test. - - -## Performance Issues - -A significant deterrent from using domains is the overhead. Using node's -built-in http benchmark, `http_simple.js`, without domains it can handle over -22,000 requests/second. Whereas if it's run with `NODE_USE_DOMAINS=1` that -number drops down to under 17,000 requests/second. In this case there is only -a single global domain. If we edit the benchmark so the http request callback -creates a new domain instance performance drops further to 15,000 -requests/second. - -While this probably wouldn't affect a server only serving a few hundred or even -a thousand requests per second, the amount of overhead is directly proportional -to the number of asynchronous requests made. So if a single connection needs to -connect to several other services all of those will contribute to the overall -latency of delivering the final product to the client. - -Using `AsyncWrap` and tracking the number of times -`init`/`pre`/`post`/`destroy` are called in the mentioned benchmark we find -that the sum of all events called is over 170,000 times per second. This means -even adding 1 microsecond overhead per call for any type of setup or tear down -will result in a 17% performance loss. Granted, this is for the optimized -scenario of the benchmark, but I believe this demonstrates the necessity for a -mechanism such as domain to be as cheap to run as possible. - - -## Looking Ahead - -The domain module has been soft deprecated since Dec 2014, but has not yet been -removed because node offers no alternative functionality at the moment. As of -this writing there is ongoing work building out the `AsyncWrap` API and a -proposal for Zones being prepared for the TC39. At such time there is suitable -functionality to replace domains it will undergo the full deprecation cycle and -eventually be removed from core. - -[`domain-resource-cleanup-example.js`]: ./domain-resource-cleanup-example.js diff --git a/doc/topics/domain-resource-cleanup-example.js b/doc/topics/domain-resource-cleanup-example.js deleted file mode 100644 index d379d1a00e6695..00000000000000 --- a/doc/topics/domain-resource-cleanup-example.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -const domain = require('domain'); -const EE = require('events'); -const fs = require('fs'); -const net = require('net'); -const util = require('util'); -const print = process._rawDebug; - -const pipeList = []; -const FILENAME = '/tmp/tmp.tmp'; -const PIPENAME = '/tmp/node-domain-example-'; -const FILESIZE = 1024; -var uid = 0; - -// Setting up temporary resources -const buf = Buffer(FILESIZE); -for (var i = 0; i < buf.length; i++) - buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII -fs.writeFileSync(FILENAME, buf); - -function ConnectionResource(c) { - EE.call(this); - this._connection = c; - this._alive = true; - this._domain = domain.create(); - this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); - - this._domain.add(c); - this._domain.on('error', () => { - this._alive = false; - }); -} -util.inherits(ConnectionResource, EE); - -ConnectionResource.prototype.end = function end(chunk) { - this._alive = false; - this._connection.end(chunk); - this.emit('end'); -}; - -ConnectionResource.prototype.isAlive = function isAlive() { - return this._alive; -}; - -ConnectionResource.prototype.id = function id() { - return this._id; -}; - -ConnectionResource.prototype.write = function write(chunk) { - this.emit('data', chunk); - return this._connection.write(chunk); -}; - -// Example begin -net.createServer((c) => { - const cr = new ConnectionResource(c); - - const d1 = domain.create(); - fs.open(FILENAME, 'r', d1.intercept((fd) => { - streamInParts(fd, cr, 0); - })); - - pipeData(cr); - - c.on('close', () => cr.end()); -}).listen(8080); - -function streamInParts(fd, cr, pos) { - const d2 = domain.create(); - var alive = true; - d2.on('error', (er) => { - print('d2 error:', er.message) - cr.end(); - }); - fs.read(fd, new Buffer(10), 0, 10, pos, d2.intercept((bRead, buf) => { - if (!cr.isAlive()) { - return fs.close(fd); - } - if (cr._connection.bytesWritten < FILESIZE) { - // Documentation says callback is optional, but doesn't mention that if - // the write fails an exception will be thrown. - const goodtogo = cr.write(buf); - if (goodtogo) { - setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); - } else { - cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); - } - return; - } - cr.end(buf); - fs.close(fd); - })); -} - -function pipeData(cr) { - const pname = PIPENAME + cr.id(); - const ps = net.createServer(); - const d3 = domain.create(); - const connectionList = []; - d3.on('error', (er) => { - print('d3 error:', er.message); - cr.end(); - }); - d3.add(ps); - ps.on('connection', (conn) => { - connectionList.push(conn); - conn.on('data', () => {}); // don't care about incoming data. - conn.on('close', () => { - connectionList.splice(connectionList.indexOf(conn), 1); - }); - }); - cr.on('data', (chunk) => { - for (var i = 0; i < connectionList.length; i++) { - connectionList[i].write(chunk); - } - }); - cr.on('end', () => { - for (var i = 0; i < connectionList.length; i++) { - connectionList[i].end(); - } - ps.close(); - }); - pipeList.push(pname); - ps.listen(pname); -} - -process.on('SIGINT', () => process.exit()); -process.on('exit', () => { - try { - for (var i = 0; i < pipeList.length; i++) { - fs.unlinkSync(pipeList[i]); - } - fs.unlinkSync(FILENAME); - } catch (e) { } -}); diff --git a/doc/topics/event-loop-timers-and-nexttick.md b/doc/topics/event-loop-timers-and-nexttick.md deleted file mode 100644 index d7d0ee96e9c438..00000000000000 --- a/doc/topics/event-loop-timers-and-nexttick.md +++ /dev/null @@ -1,486 +0,0 @@ -# The Node.js Event Loop, Timers, and `process.nextTick()` - -## What is the Event Loop? - -The event loop is what allows Node.js to perform non-blocking I/O -operations — despite the fact that JavaScript is single-threaded — by -offloading operations to the system kernel whenever possible. - -Since most modern kernels are multi-threaded, they can handle multiple -operations executing in the background. When one of these operations -completes, the kernel tells Node.js so that the appropriate callback -may be added to the **poll** queue to eventually be executed. We'll explain -this in further detail later in this topic. - -## Event Loop Explained - -When Node.js starts, it initializes the event loop, processes the -provided input script (or drops into the [REPL][], which is not covered in -this document) which may make async API calls, schedule timers, or call -`process.nextTick()`, then begins processing the event loop. - -The following diagram shows a simplified overview of the event loop's -order of operations. - -```txt - ┌───────────────────────┐ -┌─>│ timers │ -│ └──────────┬────────────┘ -│ ┌──────────┴────────────┐ -│ │ I/O callbacks │ -│ └──────────┬────────────┘ -│ ┌──────────┴────────────┐ -│ │ idle, prepare │ -│ └──────────┬────────────┘ ┌───────────────┐ -│ ┌──────────┴────────────┐ │ incoming: │ -│ │ poll │<─────┤ connections, │ -│ └──────────┬────────────┘ │ data, etc. │ -│ ┌──────────┴────────────┐ └───────────────┘ -│ │ check │ -│ └──────────┬────────────┘ -│ ┌──────────┴────────────┐ -└──┤ close callbacks │ - └───────────────────────┘ -``` - -*note: each box will be referred to as a "phase" of the event loop.* - -Each phase has a FIFO queue of callbacks to execute. While each phase is -special in its own way, generally, when the event loop enters a given -phase, it will perform any operations specific to that phase, then -execute callbacks in that phase's queue until the queue has been -exhausted or the maximum number of callbacks has executed. When the -queue has been exhausted or the callback limit is reached, the event -loop will move to the next phase, and so on. - -Since any of these operations may schedule _more_ operations and new -events processed in the **poll** phase are queued by the kernel, poll -events can be queued while polling events are being processed. As a -result, long running callbacks can allow the poll phase to run much -longer than a timer's threshold. See the [**timers**](#timers) and -[**poll**](#poll) sections for more details. - -_**NOTE:** There is a slight discrepancy between the Windows and the -Unix/Linux implementation, but that's not important for this -demonstration. The most important parts are here. There are actually -seven or eight steps, but the ones we care about — ones that Node.js -actually uses - are those above._ - - -## Phases Overview - -* **timers**: this phase executes callbacks scheduled by `setTimeout()` - and `setInterval()`. -* **I/O callbacks**: executes almost all callbacks with the exception of - close callbacks, the ones scheduled by timers, and `setImmediate()`. -* **idle, prepare**: only used internally. -* **poll**: retrieve new I/O events; node will block here when appropriate. -* **check**: `setImmediate()` callbacks are invoked here. -* **close callbacks**: e.g. `socket.on('close', ...)`. - -Between each run of the event loop, Node.js checks if it is waiting for -any asynchronous I/O or timers and shuts down cleanly if there are not -any. - -## Phases in Detail - -### timers - -A timer specifies the **threshold** _after which_ a provided callback -_may be executed_ rather than the **exact** time a person _wants it to -be executed_. Timers callbacks will run as early as they can be -scheduled after the specified amount of time has passed; however, -Operating System scheduling or the running of other callbacks may delay -them. - -_**Note**: Technically, the [**poll** phase](#poll) controls when timers -are executed._ - -For example, say you schedule a timeout to execute after a 100 ms -threshold, then your script starts asynchronously reading a file which -takes 95 ms: - -```js - -var fs = require('fs'); - -function someAsyncOperation (callback) { - // Assume this takes 95ms to complete - fs.readFile('/path/to/file', callback); -} - -var timeoutScheduled = Date.now(); - -setTimeout(function () { - - var delay = Date.now() - timeoutScheduled; - - console.log(delay + "ms have passed since I was scheduled"); -}, 100); - - -// do someAsyncOperation which takes 95 ms to complete -someAsyncOperation(function () { - - var startCallback = Date.now(); - - // do something that will take 10ms... - while (Date.now() - startCallback < 10) { - ; // do nothing - } - -}); -``` - -When the event loop enters the **poll** phase, it has an empty queue -(`fs.readFile()` has not completed), so it will wait for the number of ms -remaining until the soonest timer's threshold is reached. While it is -waiting 95 ms pass, `fs.readFile()` finishes reading the file and its -callback which takes 10 ms to complete is added to the **poll** queue and -executed. When the callback finishes, there are no more callbacks in the -queue, so the event loop will see that the threshold of the soonest -timer has been reached then wrap back to the **timers** phase to execute -the timer's callback. In this example, you will see that the total delay -between the timer being scheduled and its callback being executed will -be 105ms. - -Note: To prevent the **poll** phase from starving the event loop, [libuv] -(http://libuv.org/) (the C library that implements the Node.js -event loop and all of the asynchronous behaviors of the platform) -also has a hard maximum (system dependent) before it stops polling for -more events. - -### I/O callbacks - -This phase executes callbacks for some system operations such as types -of TCP errors. For example if a TCP socket receives `ECONNREFUSED` when -attempting to connect, some \*nix systems want to wait to report the -error. This will be queued to execute in the **I/O callbacks** phase. - -### poll - -The **poll** phase has two main functions: - -1. Executing scripts for timers whose threshold has elapsed, then -2. Processing events in the **poll** queue. - -When the event loop enters the **poll** phase _and there are no timers -scheduled_, one of two things will happen: - -* _If the **poll** queue **is not empty**_, the event loop will iterate -through its queue of callbacks executing them synchronously until -either the queue has been exhausted, or the system-dependent hard limit -is reached. - -* _If the **poll** queue **is empty**_, one of two more things will -happen: - * If scripts have been scheduled by `setImmediate()`, the event loop - will end the **poll** phase and continue to the **check** phase to - execute those scheduled scripts. - - * If scripts **have not** been scheduled by `setImmediate()`, the - event loop will wait for callbacks to be added to the queue, then - execute them immediately. - -Once the **poll** queue is empty the event loop will check for timers -_whose time thresholds have been reached_. If one or more timers are -ready, the event loop will wrap back to the **timers** phase to execute -those timers' callbacks. - -### check - -This phase allows a person to execute callbacks immediately after the -**poll** phase has completed. If the **poll** phase becomes idle and -scripts have been queued with `setImmediate()`, the event loop may -continue to the **check** phase rather than waiting. - -`setImmediate()` is actually a special timer that runs in a separate -phase of the event loop. It uses a libuv API that schedules callbacks to -execute after the **poll** phase has completed. - -Generally, as the code is executed, the event loop will eventually hit -the **poll** phase where it will wait for an incoming connection, request, -etc. However, if a callback has been scheduled with `setImmediate()` -and the **poll** phase becomes idle, it will end and continue to the -**check** phase rather than waiting for **poll** events. - -### close callbacks - -If a socket or handle is closed abruptly (e.g. `socket.destroy()`), the -`'close'` event will be emitted in this phase. Otherwise it will be -emitted via `process.nextTick()`. - -## `setImmediate()` vs `setTimeout()` - -`setImmediate` and `setTimeout()` are similar, but behave in different -ways depending on when they are called. - -* `setImmediate()` is designed to execute a script once the current -**poll** phase completes. -* `setTimeout()` schedules a script to be run after a minimum threshold -in ms has elapsed. - -The order in which the timers are executed will vary depending on the -context in which they are called. If both are called from within the -main module, then timing will be bound by the performance of the process -(which can be impacted by other applications running on the machine). - -For example, if we run the following script which is not within an I/O -cycle (i.e. the main module), the order in which the two timers are -executed is non-deterministic, as it is bound by the performance of the -process: - - -```js -// timeout_vs_immediate.js -setTimeout(function timeout () { - console.log('timeout'); -},0); - -setImmediate(function immediate () { - console.log('immediate'); -}); -``` - -```console -$ node timeout_vs_immediate.js -timeout -immediate - -$ node timeout_vs_immediate.js -immediate -timeout -``` - -However, if you move the two calls within an I/O cycle, the immediate -callback is always executed first: - -```js -// timeout_vs_immediate.js -var fs = require('fs') - -fs.readFile(__filename, () => { - setTimeout(() => { - console.log('timeout') - }, 0) - setImmediate(() => { - console.log('immediate') - }) -}) -``` - -```console -$ node timeout_vs_immediate.js -immediate -timeout - -$ node timeout_vs_immediate.js -immediate -timeout -``` - -The main advantage to using `setImmediate()` over `setTimeout()` is -`setImmediate()` will always be executed before any timers if scheduled -within an I/O cycle, independently of how many timers are present. - -## `process.nextTick()` - -### Understanding `process.nextTick()` - -You may have noticed that `process.nextTick()` was not displayed in the -diagram, even though it's a part of the asynchronous API. This is because -`process.nextTick()` is not technically part of the event loop. Instead, -the `nextTickQueue` will be processed after the current operation -completes, regardless of the current phase of the event loop. - -Looking back at our diagram, any time you call `process.nextTick()` in a -given phase, all callbacks passed to `process.nextTick()` will be -resolved before the event loop continues. This can create some bad -situations because **it allows you to "starve" your I/O by making -recursive `process.nextTick()` calls**, which prevents the event loop -from reaching the **poll** phase. - -### Why would that be allowed? - -Why would something like this be included in Node.js? Part of it is a -design philosophy where an API should always be asynchronous even where -it doesn't have to be. Take this code snippet for example: - -```js -function apiCall (arg, callback) { - if (typeof arg !== 'string') - return process.nextTick(callback, - new TypeError('argument should be string')); -} -``` - -The snippet does an argument check and if it's not correct, it will pass -the error to the callback. The API updated fairly recently to allow -passing arguments to `process.nextTick()` allowing it to take any -arguments passed after the callback to be propagated as the arguments to -the callback so you don't have to nest functions. - -What we're doing is passing an error back to the user but only *after* -we have allowed the rest of the user's code to execute. By using -`process.nextTick()` we guarantee that `apiCall()` always runs its -callback *after* the rest of the user's code and *before* the event loop -is allowed to proceed. To achieve this, the JS call stack is allowed to -unwind then immediately execute the provided callback which allows a -person to make recursive calls to `process.nextTick()` without reaching a -`RangeError: Maximum call stack size exceeded from v8`. - -This philosophy can lead to some potentially problematic situations. -Take this snippet for example: - -```js -// this has an asynchronous signature, but calls callback synchronously -function someAsyncApiCall (callback) { callback(); }; - -// the callback is called before `someAsyncApiCall` completes. -someAsyncApiCall(() => { - - // since someAsyncApiCall has completed, bar hasn't been assigned any value - console.log('bar', bar); // undefined - -}); - -var bar = 1; -``` - -The user defines `someAsyncApiCall()` to have an asynchronous signature, -but it actually operates synchronously. When it is called, the callback -provided to `someAsyncApiCall()` is called in the same phase of the -event loop because `someAsyncApiCall()` doesn't actually do anything -asynchronously. As a result, the callback tries to reference `bar` even -though it may not have that variable in scope yet, because the script has not -been able to run to completion. - -By placing the callback in a `process.nextTick()`, the script still has the -ability to run to completion, allowing all the variables, functions, -etc., to be initialized prior to the callback being called. It also has -the advantage of not allowing the event loop to continue. It may be -useful for the user to be alerted to an error before the event loop is -allowed to continue. Here is the previous example using `process.nextTick()`: - -```js -function someAsyncApiCall (callback) { - process.nextTick(callback); -}; - -someAsyncApiCall(() => { - console.log('bar', bar); // 1 -}); - -var bar = 1; -``` - -Here's another real world example: - -```js -const server = net.createServer(() => {}).listen(8080); - -server.on('listening', () => {}); -``` - -When only a port is passed the port is bound immediately. So the -`'listening'` callback could be called immediately. Problem is that the -`.on('listening')` will not have been set by that time. - -To get around this the `'listening'` event is queued in a `nextTick()` -to allow the script to run to completion. Which allows the user to set -any event handlers they want. - -## `process.nextTick()` vs `setImmediate()` - -We have two calls that are similar as far as users are concerned, but -their names are confusing. - -* `process.nextTick()` fires immediately on the same phase -* `setImmediate()` fires on the following iteration or 'tick' of the -event loop - -In essence, the names should be swapped. `process.nextTick()` fires more -immediately than `setImmediate()` but this is an artifact of the past -which is unlikely to change. Making this switch would break a large -percentage of the packages on npm. Every day more new modules are being -added, which mean every day we wait, more potential breakages occur. -While they are confusing, the names themselves won't change. - -*We recommend developers use `setImmediate()` in all cases because it's -easier to reason about (and it leads to code that's compatible with a -wider variety of environments, like browser JS.)* - -## Why use `process.nextTick()`? - -There are two main reasons: - -1. Allow users to handle errors, cleanup any then unneeded resources, or -perhaps try the request again before the event loop continues. - -2. At times it's necessary to allow a callback to run after the call -stack has unwound but before the event loop continues. - -One example is to match the user's expectations. Simple example: - -```js -var server = net.createServer(); -server.on('connection', function(conn) { }); - -server.listen(8080); -server.on('listening', function() { }); -``` - -Say that `listen()` is run at the beginning of the event loop, but the -listening callback is placed in a `setImmediate()`. Now, unless a -hostname is passed binding to the port will happen immediately. Now for -the event loop to proceed it must hit the **poll** phase, which means -there is a non-zero chance that a connection could have been received -allowing the connection event to be fired before the listening event. - -Another example is running a function constructor that was to, say, -inherit from `EventEmitter` and it wanted to call an event within the -constructor: - -```js -const EventEmitter = require('events'); -const util = require('util'); - -function MyEmitter() { - EventEmitter.call(this); - this.emit('event'); -} -util.inherits(MyEmitter, EventEmitter); - -const myEmitter = new MyEmitter(); -myEmitter.on('event', function() { - console.log('an event occurred!'); -}); -``` - -You can't emit an event from the constructor immediately -because the script will not have processed to the point where the user -assigns a callback to that event. So, within the constructor itself, -you can use `process.nextTick()` to set a callback to emit the event -after the constructor has finished, which provides the expected results: - -```js -const EventEmitter = require('events'); -const util = require('util'); - -function MyEmitter() { - EventEmitter.call(this); - - // use nextTick to emit the event once a handler is assigned - process.nextTick(function () { - this.emit('event'); - }.bind(this)); -} -util.inherits(MyEmitter, EventEmitter); - -const myEmitter = new MyEmitter(); -myEmitter.on('event', function() { - console.log('an event occurred!'); -}); -``` - -[REPL]: https://nodejs.org/api/repl.html#repl_repl diff --git a/lib/.eslintrc b/lib/.eslintrc.yaml similarity index 100% rename from lib/.eslintrc rename to lib/.eslintrc.yaml diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 2a07cd25e26dd9..eebdb242463b5d 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -206,36 +206,40 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) { } self.sockets[name].push(s); debug('sockets', name, self.sockets[name].length); - - function onFree() { - self.emit('free', s, options); - } - s.on('free', onFree); - - function onClose(err) { - debug('CLIENT socket onClose'); - // This is the only place where sockets get removed from the Agent. - // If you want to remove a socket from the pool, just close it. - // All socket errors end in a close event anyway. - self.removeSocket(s, options); - } - s.on('close', onClose); - - function onRemove() { - // We need this function for cases like HTTP 'upgrade' - // (defined by WebSockets) where we need to remove a socket from the - // pool because it'll be locked up indefinitely - debug('CLIENT socket onRemove'); - self.removeSocket(s, options); - s.removeListener('close', onClose); - s.removeListener('free', onFree); - s.removeListener('agentRemove', onRemove); - } - s.on('agentRemove', onRemove); + installListeners(self, s, options); cb(null, s); } }; +function installListeners(agent, s, options) { + function onFree() { + debug('CLIENT socket onFree'); + agent.emit('free', s, options); + } + s.on('free', onFree); + + function onClose(err) { + debug('CLIENT socket onClose'); + // This is the only place where sockets get removed from the Agent. + // If you want to remove a socket from the pool, just close it. + // All socket errors end in a close event anyway. + agent.removeSocket(s, options); + } + s.on('close', onClose); + + function onRemove() { + // We need this function for cases like HTTP 'upgrade' + // (defined by WebSockets) where we need to remove a socket from the + // pool because it'll be locked up indefinitely + debug('CLIENT socket onRemove'); + agent.removeSocket(s, options); + s.removeListener('close', onClose); + s.removeListener('free', onFree); + s.removeListener('agentRemove', onRemove); + } + s.on('agentRemove', onRemove); +} + Agent.prototype.removeSocket = function removeSocket(s, options) { var name = this.getName(options); debug('removeSocket', name, 'writable:', s.writable); diff --git a/lib/_http_client.js b/lib/_http_client.js index 1846e36e12bf88..ade344cee245dc 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -15,6 +15,34 @@ const Agent = require('_http_agent'); const Buffer = require('buffer').Buffer; +// The actual list of disallowed characters in regexp form is more like: +// /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/ +// with an additional rule for ignoring percentage-escaped characters, but +// that's a) hard to capture in a regular expression that performs well, and +// b) possibly too restrictive for real-world usage. So instead we restrict the +// filter to just control characters and spaces. +// +// This function is used in the case of small paths, where manual character code +// checks can greatly outperform the equivalent regexp (tested in V8 5.4). +function isInvalidPath(s) { + var i = 0; + if (s.charCodeAt(0) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(1) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(2) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(3) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(4) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(5) <= 32) return true; + ++i; + for (; i < s.length; ++i) + if (s.charCodeAt(i) <= 32) return true; + return false; +} + function ClientRequest(options, cb) { var self = this; OutgoingMessage.call(self); @@ -43,14 +71,20 @@ function ClientRequest(options, cb) { if (self.agent && self.agent.protocol) expectedProtocol = self.agent.protocol; - if (options.path && /[\u0000-\u0020]/.test(options.path)) { - // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/ - // with an additional rule for ignoring percentage-escaped characters - // but that's a) hard to capture in a regular expression that performs - // well, and b) possibly too restrictive for real-world usage. - // Restrict the filter to control characters and spaces. - throw new TypeError('Request path contains unescaped characters'); - } else if (protocol !== expectedProtocol) { + var path; + if (options.path) { + path = '' + options.path; + var invalidPath; + if (path.length <= 39) { // Determined experimentally in V8 5.4 + invalidPath = isInvalidPath(path); + } else { + invalidPath = /[\u0000-\u0020]/.test(path); + } + if (invalidPath) + throw new TypeError('Request path contains unescaped characters'); + } + + if (protocol !== expectedProtocol) { throw new Error('Protocol "' + protocol + '" not supported. ' + 'Expected "' + expectedProtocol + '"'); } @@ -61,9 +95,7 @@ function ClientRequest(options, cb) { var port = options.port = options.port || defaultPort || 80; var host = options.host = options.hostname || options.host || 'localhost'; - if (options.setHost === undefined) { - var setHost = true; - } + var setHost = (options.setHost === undefined); self.socketPath = options.socketPath; self.timeout = options.timeout; @@ -77,10 +109,11 @@ function ClientRequest(options, cb) { self.once('response', cb); } - if (!Array.isArray(options.headers)) { + var headersArray = Array.isArray(options.headers); + if (!headersArray) { if (options.headers) { var keys = Object.keys(options.headers); - for (var i = 0, l = keys.length; i < l; i++) { + for (var i = 0; i < keys.length; i++) { var key = keys[i]; self.setHeader(key, options.headers[key]); } @@ -106,7 +139,6 @@ function ClientRequest(options, cb) { } if (options.auth && !this.getHeader('Authorization')) { - //basic auth this.setHeader('Authorization', 'Basic ' + Buffer.from(options.auth).toString('base64')); } @@ -121,7 +153,7 @@ function ClientRequest(options, cb) { self.useChunkedEncodingByDefault = true; } - if (Array.isArray(options.headers)) { + if (headersArray) { self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', options.headers); } else if (self.getHeader('expect')) { @@ -129,6 +161,14 @@ function ClientRequest(options, cb) { self._renderHeaders()); } + this._ended = false; + this.res = null; + this.aborted = undefined; + this.timeoutCb = null; + this.upgradeOrConnect = false; + this.parser = null; + this.maxHeadersCount = null; + var called = false; if (self.socketPath) { self._last = true; @@ -196,16 +236,12 @@ function ClientRequest(options, cb) { self._flush(); self = null; }); - - this._ended = false; } util.inherits(ClientRequest, OutgoingMessage); exports.ClientRequest = ClientRequest; -ClientRequest.prototype.aborted = undefined; - ClientRequest.prototype._finish = function _finish() { DTRACE_HTTP_CLIENT_REQUEST(this, this.connection); LTTNG_HTTP_CLIENT_REQUEST(this, this.connection); @@ -219,7 +255,7 @@ ClientRequest.prototype._implicitHeader = function _implicitHeader() { }; ClientRequest.prototype.abort = function abort() { - if (this.aborted === undefined) { + if (!this.aborted) { process.nextTick(emitAbortNT, this); } // Mark as aborting so we can avoid sending queued request data @@ -448,7 +484,7 @@ function parserOnIncomingClient(res, shouldKeepAlive) { if (res.statusCode === 100) { // restart the parser, as this is a continue message. - delete req.res; // Clear res so that we don't hit double-responses. + req.res = null; // Clear res so that we don't hit double-responses. req.emit('continue'); return true; } diff --git a/lib/_http_server.js b/lib/_http_server.js index 21113fc37a9f5b..bd726f83e3e638 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -248,6 +248,7 @@ function Server(requestListener) { this.timeout = 2 * 60 * 1000; this._pendingResponseData = 0; + this.maxHeadersCount = null; } util.inherits(Server, net.Server); diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index b20fe8d2ea91ed..ba56225d974fe9 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -194,23 +194,18 @@ function writeAfterEnd(stream, cb) { process.nextTick(cb, er); } -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. + if (chunk === null) { er = new TypeError('May not write null values to stream'); - } else if (!(chunk instanceof Buffer) && - typeof chunk !== 'string' && - chunk !== undefined && - !state.objectMode) { + } else if (typeof chunk !== 'string' && + chunk !== undefined && + !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { @@ -224,13 +219,14 @@ function validChunk(stream, state, chunk, cb) { Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; var ret = false; + var isBuf = (chunk instanceof Buffer); if (typeof encoding === 'function') { cb = encoding; encoding = null; } - if (chunk instanceof Buffer) + if (isBuf) encoding = 'buffer'; else if (!encoding) encoding = state.defaultEncoding; @@ -240,9 +236,9 @@ Writable.prototype.write = function(chunk, encoding, cb) { if (state.ended) writeAfterEnd(this, cb); - else if (validChunk(this, state, chunk, cb)) { + else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; @@ -291,11 +287,12 @@ function decodeChunk(state, chunk, encoding) { // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - - if (chunk instanceof Buffer) - encoding = 'buffer'; +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + chunk = decodeChunk(state, chunk, encoding); + if (chunk instanceof Buffer) + encoding = 'buffer'; + } var len = state.objectMode ? 1 : chunk.length; state.length += len; diff --git a/lib/_tls_common.js b/lib/_tls_common.js index 85ae71f8d15cc1..107c3bb2ea7c67 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -134,7 +134,9 @@ exports.createSecureContext = function createSecureContext(options, context) { } } - // Do not keep read/write buffers in free list + // Do not keep read/write buffers in free list for OpenSSL < 1.1.0. (For + // OpenSSL 1.1.0, buffers are malloced and freed without the use of a + // freelist.) if (options.singleUse) { c.singleUse = true; c.context.setFreeListLength(0); diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index f974b0cfc05575..e765b2507e7502 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -1,6 +1,6 @@ 'use strict'; -require('internal/util').assertCrypto(exports); +require('internal/util').assertCrypto(); const assert = require('assert'); const EventEmitter = require('events'); diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 434384cec81595..721cdde142519c 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -1,6 +1,6 @@ 'use strict'; -require('internal/util').assertCrypto(exports); +require('internal/util').assertCrypto(); const assert = require('assert'); const crypto = require('crypto'); diff --git a/lib/assert.js b/lib/assert.js index 04c5cb5ad436e1..892df6d9a0f4e2 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -30,16 +30,16 @@ const util = require('util'); const Buffer = require('buffer').Buffer; const pToString = (obj) => Object.prototype.toString.call(obj); -// 1. The assert module provides functions that throw +// The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. const assert = module.exports = ok; -// 2. The AssertionError is defined in assert. +// The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, -// expected: expected }) +// expected: expected }); assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; @@ -75,7 +75,7 @@ function getMessage(self) { // other keys to the AssertionError's constructor - they will be // ignored. -// 3. All of the following functions must throw an AssertionError +// All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for @@ -94,7 +94,7 @@ function fail(actual, expected, message, operator, stackStartFunction) { // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; -// 4. Pure assertion tests whether a value is truthy, as determined +// Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, @@ -106,7 +106,7 @@ function ok(value, message) { } assert.ok = ok; -// 5. The equality assertion tests shallow, coercive equality with +// The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); @@ -114,8 +114,9 @@ assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); +// The non-equality assertion tests for whether two objects are not +// equal with !=. +// assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { @@ -123,7 +124,7 @@ assert.notEqual = function notEqual(actual, expected, message) { } }; -// 7. The equivalence assertion tests a deep equality relation. +// The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); /* eslint-disable no-restricted-properties */ @@ -141,18 +142,22 @@ assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { }; function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. + // All identical values are equivalent, as determined by ===. if (actual === expected) { return true; + + // If both values are instances of buffers, equivalence is + // determined by comparing the values and ensuring the result + // === 0. } else if (actual instanceof Buffer && expected instanceof Buffer) { return compare(actual, expected) === 0; - // 7.2. If the expected value is a Date object, the actual value is + // If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); - // 7.3 If the expected value is a RegExp object, the actual value is + // If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { @@ -162,18 +167,18 @@ function _deepEqual(actual, expected, strict, memos) { actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. + // If both values are primitives, equivalence is determined by + // == or, if checking for strict equivalence, ===. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance + // ArrayBuffers in a Buffer to increase performance. // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. + // Object.prototype.toString (pToString). Never perform binary + // comparisons for Float*Arrays, though, since +0 === -0 is true despite the + // two values' bit patterns not being identical. } else if (ArrayBuffer.isView(actual) && ArrayBuffer.isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || @@ -185,7 +190,7 @@ function _deepEqual(actual, expected, strict, memos) { expected.byteOffset, expected.byteLength)) === 0; - // 7.5 For all other Object pairs, including Array objects, equivalence is + // For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every @@ -215,7 +220,8 @@ function isArguments(object) { function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; - // if one is a primitive, the other must be same + + // If one is a primitive, the other must be the same. if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) @@ -227,20 +233,23 @@ function objEquiv(a, b, strict, actualVisitedObjects) { const ka = Object.keys(a); const kb = Object.keys(b); var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) + + // The pair must have the same number of owned properties (keys + // incorporates hasOwnProperty). if (ka.length !== kb.length) return false; - //the same set of keys (although not necessarily the same order), + + // The pair must have the same set of keys (although not + // necessarily in the same order). ka.sort(); kb.sort(); - //~~~cheap key test + // Cheap key test: for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test + // The pair must have equivalent values for every corresponding key. + // Possibly expensive deep test: for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) @@ -249,7 +258,7 @@ function objEquiv(a, b, strict, actualVisitedObjects) { return true; } -// 8. The non-equivalence assertion tests for any deep inequality. +// The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { @@ -266,7 +275,7 @@ function notDeepStrictEqual(actual, expected, message) { } -// 9. The strict equality assertion tests strict equality, as determined by ===. +// The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { @@ -275,8 +284,9 @@ assert.strictEqual = function strictEqual(actual, expected, message) { } }; -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); +// The strict non-equality assertion tests for strict inequality, as +// determined by !==. +// assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { @@ -298,7 +308,7 @@ function expectedException(actual, expected) { return true; } } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. + // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { @@ -356,7 +366,7 @@ function _throws(shouldThrow, block, expected, message) { } } -// 11. Expected to throw an error: +// Expected to throw an error. // assert.throws(block, Error_opt, message_opt); assert.throws = function throws(block, /*optional*/error, /*optional*/message) { diff --git a/lib/buffer.js b/lib/buffer.js index a6a0d59f74f52f..2349474952c462 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -793,10 +793,14 @@ Buffer.prototype.write = function(string, offset, length, encoding) { Buffer.prototype.toJSON = function() { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this, 0) - }; + if (this.length) { + const data = []; + for (var i = 0; i < this.length; ++i) + data[i] = this[i]; + return { type: 'Buffer', data }; + } else { + return { type: 'Buffer', data: [] }; + } }; diff --git a/lib/cluster.js b/lib/cluster.js index e95e19bcc672d4..a12b83cd0c34c0 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -31,14 +31,12 @@ function Worker(options) { this.exitedAfterDisconnect = undefined; Object.defineProperty(this, 'suicide', { - get: internalUtil.deprecate(() => { - return this.exitedAfterDisconnect; - }, 'worker.suicide is deprecated. ' + - 'Please use worker.exitedAfterDisconnect.'), - set: internalUtil.deprecate((val) => { - this.exitedAfterDisconnect = val; - }, 'worker.suicide is deprecated. ' + - 'Please use worker.exitedAfterDisconnect.'), + get: internalUtil.deprecate( + () => this.exitedAfterDisconnect, + 'worker.suicide is deprecated. Please use worker.exitedAfterDisconnect.'), + set: internalUtil.deprecate( + (val) => { this.exitedAfterDisconnect = val; }, + 'worker.suicide is deprecated. Please use worker.exitedAfterDisconnect.'), enumerable: true }); diff --git a/lib/crypto.js b/lib/crypto.js index 6b2a04711a868a..9180ce70dce12e 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -4,7 +4,7 @@ 'use strict'; const internalUtil = require('internal/util'); -internalUtil.assertCrypto(exports); +internalUtil.assertCrypto(); exports.DEFAULT_ENCODING = 'buffer'; @@ -637,17 +637,17 @@ exports.randomBytes = exports.pseudoRandomBytes = randomBytes; exports.rng = exports.prng = randomBytes; -exports.getCiphers = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(getCiphers()); -}); +exports.getCiphers = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(getCiphers()) +); -exports.getHashes = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(getHashes()); -}); +exports.getHashes = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(getHashes()) +); -exports.getCurves = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(getCurves()); -}); +exports.getCurves = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(getCurves()) +); Object.defineProperty(exports, 'fips', { get: getFipsCrypto, diff --git a/lib/events.js b/lib/events.js index 6a8345ab7bc516..000fa98d5a88c5 100644 --- a/lib/events.js +++ b/lib/events.js @@ -148,7 +148,8 @@ EventEmitter.prototype.emit = function emit(type) { // If there is no 'error' event listener then throw. if (doError) { - er = arguments[1]; + if (arguments.length > 1) + er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); @@ -360,6 +361,8 @@ EventEmitter.prototype.removeListener = } else { delete events[type]; } + } else if (position === 0) { + list.shift(); } else { spliceOne(list, position); } diff --git a/lib/fs.js b/lib/fs.js index d407cf1479eac0..da67f2742cb892 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1453,8 +1453,8 @@ const splitRootRe = isWindows ? /^(?:[a-zA-Z]:|[\\/]{2}[^\\/]+[\\/][^\\/]+)?[\\/]*/ : /^[/]*/; -function encodeRealpathResult(result, options, err) { - if (!options || !options.encoding || options.encoding === 'utf8' || err) +function encodeRealpathResult(result, options) { + if (!options || !options.encoding || options.encoding === 'utf8') return result; const asBuffer = Buffer.from(result); if (options.encoding === 'buffer') { diff --git a/lib/https.js b/lib/https.js index 26b6cbf279a15f..e05be20b4d6d5a 100644 --- a/lib/https.js +++ b/lib/https.js @@ -1,6 +1,6 @@ 'use strict'; -require('internal/util').assertCrypto(exports); +require('internal/util').assertCrypto(); const tls = require('tls'); const url = require('url'); @@ -143,6 +143,10 @@ Agent.prototype.getName = function getName(options) { if (options.servername && options.servername !== options.host) name += options.servername; + name += ':'; + if (options.secureProtocol) + name += options.secureProtocol; + return name; }; diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index 4e1e2aa9018b5a..71a6c529041b47 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -393,9 +393,7 @@ } function isDebugBreak() { - return process.execArgv.some((arg) => { - return arg.match(/^--debug-brk(=[0-9]*)?$/); - }); + return process.execArgv.some((arg) => /^--debug-brk(=[0-9]+)?$/.test(arg)); } function run(entryFunction) { diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 5bdc53fd192073..3017cd5889a037 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -446,14 +446,20 @@ function setupChannel(target, channel) { channel.onread = function(nread, pool, recvHandle) { // TODO(bnoordhuis) Check that nread > 0. if (pool) { - jsonBuffer += decoder.write(pool); - - var i, start = 0; + // Linebreak is used as a message end sign + var chunks = decoder.write(pool).split('\n'); + var numCompleteChunks = chunks.length - 1; + // Last line does not have trailing linebreak + var incompleteChunk = chunks[numCompleteChunks]; + if (numCompleteChunks === 0) { + jsonBuffer += incompleteChunk; + this.buffering = jsonBuffer.length !== 0; + return; + } + chunks[0] = jsonBuffer + chunks[0]; - //Linebreak is used as a message end sign - while ((i = jsonBuffer.indexOf('\n', start)) >= 0) { - var json = jsonBuffer.slice(start, i); - var message = JSON.parse(json); + for (var i = 0; i < numCompleteChunks; i++) { + var message = JSON.parse(chunks[i]); // There will be at most one NODE_HANDLE message in every chunk we // read because SCM_RIGHTS messages don't get coalesced. Make sure @@ -462,10 +468,8 @@ function setupChannel(target, channel) { handleMessage(target, message, recvHandle); else handleMessage(target, message, undefined); - - start = i + 1; } - jsonBuffer = jsonBuffer.slice(start); + jsonBuffer = incompleteChunk; this.buffering = jsonBuffer.length !== 0; } else { @@ -494,9 +498,10 @@ function setupChannel(target, channel) { var queue = target._handleQueue; target._handleQueue = null; - queue.forEach(function(args) { + for (var i = 0; i < queue.length; i++) { + var args = queue[i]; target._send(args.message, args.handle, args.options, args.callback); - }); + } // Process a pending disconnect (if any). if (!target.connected && target.channel && !target._handleQueue) diff --git a/lib/internal/module.js b/lib/internal/module.js index a12af12f3e3d7e..2f38618daac5f7 100644 --- a/lib/internal/module.js +++ b/lib/internal/module.js @@ -51,10 +51,12 @@ function stripBOM(content) { return content; } -exports.builtinLibs = ['assert', 'buffer', 'child_process', 'cluster', - 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'net', - 'os', 'path', 'punycode', 'querystring', 'readline', 'repl', 'stream', - 'string_decoder', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib']; +exports.builtinLibs = [ + 'assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns', + 'domain', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode', + 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'tls', 'tty', + 'url', 'util', 'v8', 'vm', 'zlib' +]; function addBuiltinLibsToObject(object) { // Make built-in modules available directly (loaded lazily). diff --git a/lib/internal/process/warning.js b/lib/internal/process/warning.js index 74a74aa916dd91..f98f7f69ddae23 100644 --- a/lib/internal/process/warning.js +++ b/lib/internal/process/warning.js @@ -5,7 +5,7 @@ const prefix = `(${process.release.name}:${process.pid}) `; exports.setup = setupProcessWarnings; function setupProcessWarnings() { - if (!process.noProcessWarnings) { + if (!process.noProcessWarnings && process.env.NODE_NO_WARNINGS !== '1') { process.on('warning', (warning) => { if (!(warning instanceof Error)) return; const isDeprecation = warning.name === 'DeprecationWarning'; diff --git a/lib/internal/url.js b/lib/internal/url.js index e1e1c515f842d2..995e533013249c 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -8,6 +8,7 @@ function getPunycode() { } } const punycode = getPunycode(); +const util = require('util'); const binding = process.binding('url'); const context = Symbol('context'); const cannotBeBase = Symbol('cannot-be-base'); @@ -66,7 +67,8 @@ class TupleOrigin { return this[kDomain] || this[kHost]; } - toString(unicode = false) { + // https://url.spec.whatwg.org/#dom-url-origin + toString(unicode = true) { var result = this[kScheme]; result += '://'; result += unicode ? domainToUnicode(this[kHost]) : this[kHost]; @@ -284,7 +286,8 @@ Object.defineProperties(URL.prototype, { if (ctx.host !== undefined) { ret += '//'; const has_username = typeof ctx.username === 'string'; - const has_password = typeof ctx.password === 'string'; + const has_password = typeof ctx.password === 'string' && + ctx.password !== ''; if (has_username || has_password) { if (has_username) ret += ctx.username; @@ -325,7 +328,7 @@ Object.defineProperties(URL.prototype, { enumerable: true, configurable: true, get() { - return originFor(this).toString(true); + return originFor(this).toString(); } }, protocol: { @@ -491,7 +494,7 @@ Object.defineProperties(URL.prototype, { ctx.query = ''; binding.parse(search, binding.kQuery, null, ctx, onParseSearchComplete.bind(this)); - this[searchParams][searchParams] = querystring.parse(search); + initSearchParams(this[searchParams], search); } }, searchParams: { // readonly @@ -608,8 +611,13 @@ function update(url, params) { } } -function getSearchParamPairs(target) { - const obj = target[searchParams]; +// Reused by the URL parse function invoked by +// the href setter, and the URLSearchParams constructor +function initSearchParams(url, init) { + url[searchParams] = getParamsFromObject(querystring.parse(init)); +} + +function getParamsFromObject(obj) { const keys = Object.keys(obj); const values = []; for (var i = 0; i < keys.length; i++) { @@ -617,25 +625,33 @@ function getSearchParamPairs(target) { const value = obj[name]; if (Array.isArray(value)) { for (const item of value) - values.push([name, item]); + values.push(name, item); } else { - values.push([name, value]); + values.push(name, value); } } return values; } -// Reused by the URL parse function invoked by -// the href setter, and the URLSearchParams constructor -function initSearchParams(url, init) { - url[searchParams] = querystring.parse(init); +function getObjectFromParams(array) { + const obj = new StorageObject(); + for (var i = 0; i < array.length; i += 2) { + const name = array[i]; + const value = array[i + 1]; + if (obj[name]) { + obj[name].push(value); + } else { + obj[name] = [value]; + } + } + return obj; } class URLSearchParams { constructor(init = '') { if (init instanceof URLSearchParams) { const childParams = init[searchParams]; - this[searchParams] = Object.assign(Object.create(null), childParams); + this[searchParams] = childParams.slice(); } else { init = String(init); if (init[0] === '?') init = init.slice(1); @@ -656,21 +672,12 @@ class URLSearchParams { throw new TypeError('Value of `this` is not a URLSearchParams'); } if (arguments.length < 2) { - throw new TypeError( - 'Both `name` and `value` arguments need to be specified'); + throw new TypeError('"name" and "value" arguments must be specified'); } - const obj = this[searchParams]; name = String(name); value = String(value); - var existing = obj[name]; - if (existing === undefined) { - obj[name] = value; - } else if (Array.isArray(existing)) { - existing.push(value); - } else { - obj[name] = [existing, value]; - } + this[searchParams].push(name, value); update(this[context], this); } @@ -679,12 +686,19 @@ class URLSearchParams { throw new TypeError('Value of `this` is not a URLSearchParams'); } if (arguments.length < 1) { - throw new TypeError('The `name` argument needs to be specified'); + throw new TypeError('"name" argument must be specified'); } - const obj = this[searchParams]; + const list = this[searchParams]; name = String(name); - delete obj[name]; + for (var i = 0; i < list.length;) { + const cur = list[i]; + if (cur === name) { + list.splice(i, 2); + } else { + i += 2; + } + } update(this[context], this); } @@ -693,14 +707,38 @@ class URLSearchParams { throw new TypeError('Value of `this` is not a URLSearchParams'); } if (arguments.length < 2) { - throw new TypeError( - 'Both `name` and `value` arguments need to be specified'); + throw new TypeError('"name" and "value" arguments must be specified'); } - const obj = this[searchParams]; + const list = this[searchParams]; name = String(name); value = String(value); - obj[name] = value; + + // If there are any name-value pairs whose name is `name`, in `list`, set + // the value of the first such name-value pair to `value` and remove the + // others. + var found = false; + for (var i = 0; i < list.length;) { + const cur = list[i]; + if (cur === name) { + if (!found) { + list[i + 1] = value; + found = true; + i += 2; + } else { + list.splice(i, 2); + } + } else { + i += 2; + } + } + + // Otherwise, append a new name-value pair whose name is `name` and value + // is `value`, to `list`. + if (!found) { + list.push(name, value); + } + update(this[context], this); } @@ -709,13 +747,17 @@ class URLSearchParams { throw new TypeError('Value of `this` is not a URLSearchParams'); } if (arguments.length < 1) { - throw new TypeError('The `name` argument needs to be specified'); + throw new TypeError('"name" argument must be specified'); } - const obj = this[searchParams]; + const list = this[searchParams]; name = String(name); - var value = obj[name]; - return value === undefined ? null : Array.isArray(value) ? value[0] : value; + for (var i = 0; i < list.length; i += 2) { + if (list[i] === name) { + return list[i + 1]; + } + } + return null; } getAll(name) { @@ -723,13 +765,18 @@ class URLSearchParams { throw new TypeError('Value of `this` is not a URLSearchParams'); } if (arguments.length < 1) { - throw new TypeError('The `name` argument needs to be specified'); + throw new TypeError('"name" argument must be specified'); } - const obj = this[searchParams]; + const list = this[searchParams]; + const values = []; name = String(name); - var value = obj[name]; - return value === undefined ? [] : Array.isArray(value) ? value : [value]; + for (var i = 0; i < list.length; i += 2) { + if (list[i] === name) { + values.push(list[i + 1]); + } + } + return values; } has(name) { @@ -737,12 +784,17 @@ class URLSearchParams { throw new TypeError('Value of `this` is not a URLSearchParams'); } if (arguments.length < 1) { - throw new TypeError('The `name` argument needs to be specified'); + throw new TypeError('"name" argument must be specified'); } - const obj = this[searchParams]; + const list = this[searchParams]; name = String(name); - return name in obj; + for (var i = 0; i < list.length; i += 2) { + if (list[i] === name) { + return true; + } + } + return false; } // https://heycam.github.io/webidl/#es-iterators @@ -760,18 +812,20 @@ class URLSearchParams { if (!this || !(this instanceof URLSearchParams)) { throw new TypeError('Value of `this` is not a URLSearchParams'); } - if (arguments.length < 1) { - throw new TypeError('The `callback` argument needs to be specified'); + if (typeof callback !== 'function') { + throw new TypeError('"callback" argument must be a function'); } - let pairs = getSearchParamPairs(this); + let list = this[searchParams]; var i = 0; - while (i < pairs.length) { - const [key, value] = pairs[i]; + while (i < list.length) { + const key = list[i]; + const value = list[i + 1]; callback.call(thisArg, value, key, this); - pairs = getSearchParamPairs(this); - i++; + // in case the URL object's `search` is updated + list = this[searchParams]; + i += 2; } } @@ -798,12 +852,38 @@ class URLSearchParams { throw new TypeError('Value of `this` is not a URLSearchParams'); } - return querystring.stringify(this[searchParams]); + return querystring.stringify(getObjectFromParams(this[searchParams])); } } // https://heycam.github.io/webidl/#es-iterable-entries URLSearchParams.prototype[Symbol.iterator] = URLSearchParams.prototype.entries; +URLSearchParams.prototype[util.inspect.custom] = + function inspect(recurseTimes, ctx) { + const innerOpts = Object.assign({}, ctx); + if (recurseTimes !== null) { + innerOpts.depth = recurseTimes - 1; + } + const innerInspect = (v) => util.inspect(v, innerOpts); + + const list = this[searchParams]; + const output = []; + for (var i = 0; i < list.length; i += 2) + output.push(`${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`); + + const colorRe = /\u001b\[\d\d?m/g; + const length = output.reduce((prev, cur) => { + return prev + cur.replace(colorRe, '').length + ', '.length; + }, -', '.length); + if (length > ctx.breakLength) { + return `${this.constructor.name} {\n ${output.join(',\n ')} }`; + } else if (output.length) { + return `${this.constructor.name} { ${output.join(', ')} }`; + } else { + return `${this.constructor.name} {}`; + } + }; + // https://heycam.github.io/webidl/#dfn-default-iterator-object function createSearchParamsIterator(target, kind) { const iterator = Object.create(URLSearchParamsIteratorPrototype); @@ -828,7 +908,7 @@ const URLSearchParamsIteratorPrototype = Object.setPrototypeOf({ kind, index } = this[context]; - const values = getSearchParamPairs(target); + const values = target[searchParams]; const len = values.length; if (index >= len) { return { @@ -837,22 +917,54 @@ const URLSearchParamsIteratorPrototype = Object.setPrototypeOf({ }; } - const pair = values[index]; - this[context].index = index + 1; + const name = values[index]; + const value = values[index + 1]; + this[context].index = index + 2; let result; if (kind === 'key') { - result = pair[0]; + result = name; } else if (kind === 'value') { - result = pair[1]; + result = value; } else { - result = pair; + result = [name, value]; } return { value: result, done: false }; + }, + [util.inspect.custom]: function inspect(recurseTimes, ctx) { + const innerOpts = Object.assign({}, ctx); + if (recurseTimes !== null) { + innerOpts.depth = recurseTimes - 1; + } + const { + target, + kind, + index + } = this[context]; + const output = target[searchParams].slice(index).reduce((prev, cur, i) => { + const key = i % 2 === 0; + if (kind === 'key' && key) { + prev.push(cur); + } else if (kind === 'value' && !key) { + prev.push(cur); + } else if (kind === 'key+value' && !key) { + prev.push([target[searchParams][index + i - 1], cur]); + } + return prev; + }, []); + const breakLn = util.inspect(output, innerOpts).includes('\n'); + const outputStrs = output.map((p) => util.inspect(p, innerOpts)); + let outputStr; + if (breakLn) { + outputStr = `\n ${outputStrs.join(',\n ')}`; + } else { + outputStr = ` ${outputStrs.join(', ')}`; + } + return `${this[Symbol.toStringTag]} {${outputStr} }`; } }, IteratorPrototype); @@ -908,6 +1020,7 @@ function domainToUnicode(domain) { } exports.URL = URL; +exports.URLSearchParams = URLSearchParams; exports.originFor = originFor; exports.domainToASCII = domainToASCII; exports.domainToUnicode = domainToUnicode; diff --git a/lib/internal/util.js b/lib/internal/util.js index 238eb65891365c..42a0922d304970 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -97,16 +97,22 @@ exports.objectToString = function objectToString(o) { }; const noCrypto = !process.versions.openssl; -exports.assertCrypto = function(exports) { +exports.assertCrypto = function() { if (noCrypto) throw new Error('Node.js is not compiled with openssl crypto support'); }; exports.kIsEncodingSymbol = Symbol('node.isEncoding'); + +// The loop should only run at most twice, retrying with lowercased enc +// if there is no match in the first pass. +// We use a loop instead of branching to retry with a helper +// function in order to avoid the performance hit. +// Return undefined if there is no match. exports.normalizeEncoding = function normalizeEncoding(enc) { if (!enc) return 'utf8'; - var low; - for (;;) { + var retried; + while (true) { switch (enc) { case 'utf8': case 'utf-8': @@ -124,9 +130,9 @@ exports.normalizeEncoding = function normalizeEncoding(enc) { case 'hex': return enc; default: - if (low) return; // undefined + if (retried) return; // undefined enc = ('' + enc).toLowerCase(); - low = true; + retried = true; } } }; @@ -134,20 +140,14 @@ exports.normalizeEncoding = function normalizeEncoding(enc) { // Filters duplicate strings. Used to support functions in crypto and tls // modules. Implemented specifically to maintain existing behaviors in each. exports.filterDuplicateStrings = function filterDuplicateStrings(items, low) { - if (!Array.isArray(items)) - return []; - const len = items.length; - if (len <= 1) - return items; const map = new Map(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < items.length; i++) { const item = items[i]; const key = item.toLowerCase(); if (low) { map.set(key, key); } else { - if (!map.has(key) || map.get(key) <= item) - map.set(key, item); + map.set(key, item); } } return Array.from(map.values()).sort(); @@ -158,7 +158,7 @@ exports.cachedResult = function cachedResult(fn) { return () => { if (result === undefined) result = fn(); - return result; + return result.slice(); }; }; diff --git a/lib/os.js b/lib/os.js index cab148581a9db3..a59cc49bae8c51 100644 --- a/lib/os.js +++ b/lib/os.js @@ -51,8 +51,9 @@ exports.tmpdir = function() { return path; }; -exports.tmpDir = internalUtil.deprecate(exports.tmpdir, - 'os.tmpDir() is deprecated. Use os.tmpdir() instead.'); +const tmpDirDeprecationMsg = + 'os.tmpDir() is deprecated. Use os.tmpdir() instead.'; +exports.tmpDir = internalUtil.deprecate(exports.tmpdir, tmpDirDeprecationMsg); exports.getNetworkInterfaces = internalUtil.deprecate(function() { return exports.networkInterfaces(); diff --git a/lib/readline.js b/lib/readline.js index 9b925a6d990d8b..8200771ec4b39f 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -23,22 +23,13 @@ const stripVTControlCharacters = internalReadline.stripVTControlCharacters; exports.createInterface = function(input, output, completer, terminal) { - var rl; - if (arguments.length === 1) { - rl = new Interface(input); - } else { - rl = new Interface(input, output, completer, terminal); - } - return rl; + return new Interface(input, output, completer, terminal); }; function Interface(input, output, completer, terminal) { if (!(this instanceof Interface)) { - // call the constructor preserving original number of arguments - const self = Object.create(Interface.prototype); - Interface.apply(self, arguments); - return self; + return new Interface(input, output, completer, terminal); } this._sawReturnAt = 0; @@ -51,7 +42,7 @@ function Interface(input, output, completer, terminal) { let crlfDelay; let prompt = '> '; - if (arguments.length === 1) { + if (input && input.input) { // an options object was given output = input.output; completer = input.completer; diff --git a/lib/repl.js b/lib/repl.js index 858ccd883850d3..302e79f9a2752c 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -39,13 +39,13 @@ const debug = util.debuglog('repl'); const parentModule = module; const replMap = new WeakMap(); -const GLOBAL_OBJECT_PROPERTIES = ['NaN', 'Infinity', 'undefined', - 'eval', 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'decodeURI', - 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', - 'Object', 'Function', 'Array', 'String', 'Boolean', 'Number', - 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError', - 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', - 'Math', 'JSON']; +const GLOBAL_OBJECT_PROPERTIES = [ + 'NaN', 'Infinity', 'undefined', 'eval', 'parseInt', 'parseFloat', 'isNaN', + 'isFinite', 'decodeURI', 'decodeURIComponent', 'encodeURI', + 'encodeURIComponent', 'Object', 'Function', 'Array', 'String', 'Boolean', + 'Number', 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError', + 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'Math', 'JSON' +]; const GLOBAL_OBJECT_PROPERTY_MAP = {}; GLOBAL_OBJECT_PROPERTIES.forEach((p) => GLOBAL_OBJECT_PROPERTY_MAP[p] = p); @@ -322,13 +322,7 @@ function REPLServer(prompt, if (!err) { // Unset raw mode during evaluation so that Ctrl+C raises a signal. let previouslyInRawMode; - - // Temporarily disabled on Windows due to output problems that likely - // result from the raw mode switches here, see - // https://github.com/nodejs/node/issues/7837 - // Setting NODE_REPL_CTRLC is meant as a temporary opt-in for debugging. - if (self.breakEvalOnSigint && - (process.platform !== 'win32' || process.env.NODE_REPL_CTRLC)) { + if (self.breakEvalOnSigint) { // Start the SIGINT watchdog before entering raw mode so that a very // quick Ctrl+C doesn’t lead to aborting the process completely. utilBinding.startSigintWatchdog(); @@ -348,8 +342,7 @@ function REPLServer(prompt, result = script.runInContext(context, scriptOptions); } } finally { - if (self.breakEvalOnSigint && - (process.platform !== 'win32' || process.env.NODE_REPL_CTRLC)) { + if (self.breakEvalOnSigint) { // Reset terminal mode to its previous value. self._setRawMode(previouslyInRawMode); @@ -728,9 +721,7 @@ REPLServer.prototype.createContext = function() { Object.defineProperty(context, '_', { configurable: true, - get: () => { - return this.last; - }, + get: () => this.last, set: (value) => { this.last = value; if (!this.underscoreAssigned) { @@ -1223,12 +1214,13 @@ function addStandardGlobals(completionGroups, filter) { // Common keywords. Exclude for completion on the empty string, b/c // they just get in the way. if (filter) { - completionGroups.push(['break', 'case', 'catch', 'const', - 'continue', 'debugger', 'default', 'delete', 'do', 'else', - 'export', 'false', 'finally', 'for', 'function', 'if', - 'import', 'in', 'instanceof', 'let', 'new', 'null', 'return', - 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'undefined', - 'var', 'void', 'while', 'with', 'yield']); + completionGroups.push([ + 'break', 'case', 'catch', 'const', 'continue', 'debugger', 'default', + 'delete', 'do', 'else', 'export', 'false', 'finally', 'for', 'function', + 'if', 'import', 'in', 'instanceof', 'let', 'new', 'null', 'return', + 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'undefined', 'var', + 'void', 'while', 'with', 'yield' + ]); } } @@ -1272,9 +1264,10 @@ function defineDefaultCommands(repl) { help: 'Print this help message', action: function() { const names = Object.keys(this.commands).sort(); - const longestNameLength = names.reduce((max, name) => { - return Math.max(max, name.length); - }, 0); + const longestNameLength = names.reduce( + (max, name) => Math.max(max, name.length), + 0 + ); names.forEach((name) => { const cmd = this.commands[name]; const spaces = ' '.repeat(longestNameLength - name.length + 3); diff --git a/lib/tls.js b/lib/tls.js index 32c0319754be2a..bb4719d9b02c93 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -1,7 +1,7 @@ 'use strict'; const internalUtil = require('internal/util'); -internalUtil.assertCrypto(exports); +internalUtil.assertCrypto(); const net = require('net'); const url = require('url'); @@ -22,9 +22,9 @@ exports.DEFAULT_CIPHERS = exports.DEFAULT_ECDH_CURVE = 'prime256v1'; -exports.getCiphers = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(binding.getSSLCiphers(), true); -}); +exports.getCiphers = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(binding.getSSLCiphers(), true) +); // Convert protocols array into valid OpenSSL protocols list // ("\x06spdy/2\x08http/1.1\x08http/1.0") diff --git a/lib/url.js b/lib/url.js index 1dfab2eaaf7fca..933ffe13b4d9e4 100644 --- a/lib/url.js +++ b/lib/url.js @@ -17,6 +17,7 @@ exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.URL = internalUrl.URL; +exports.URLSearchParams = internalUrl.URLSearchParams; exports.originFor = internalUrl.originFor; exports.domainToASCII = internalUrl.domainToASCII; exports.domainToUnicode = internalUrl.domainToUnicode; diff --git a/lib/util.js b/lib/util.js index 37008b2d176062..9d5909cdc7ce30 100644 --- a/lib/util.js +++ b/lib/util.js @@ -27,16 +27,13 @@ var simdFormatters; if (typeof global.SIMD === 'object' && global.SIMD !== null) { simdFormatters = new Map(); - const make = (extractLane, count) => { - return (ctx, value, recurseTimes, visibleKeys, keys) => { + const make = + (extractLane, count) => (ctx, value, recurseTimes, visibleKeys, keys) => { const output = new Array(count); for (var i = 0; i < count; i += 1) output[i] = formatPrimitive(ctx, extractLane(value, i)); return output; }; - }; - - const SIMD = global.SIMD; // Pacify eslint. const countPerType = { Bool16x8: 8, @@ -52,7 +49,7 @@ if (typeof global.SIMD === 'object' && global.SIMD !== null) { }; for (const key in countPerType) { - const type = SIMD[key]; + const type = global.SIMD[key]; simdFormatters.set(type, make(type.extractLane, countPerType[key])); } } @@ -173,8 +170,12 @@ function inspect(obj, opts) { stylize: stylizeNoColor }; // legacy... - if (arguments[2] !== undefined) ctx.depth = arguments[2]; - if (arguments[3] !== undefined) ctx.colors = arguments[3]; + if (arguments.length >= 3 && arguments[2] !== undefined) { + ctx.depth = arguments[2]; + } + if (arguments.length >= 4 && arguments[3] !== undefined) { + ctx.colors = arguments[3]; + } if (typeof opts === 'boolean') { // legacy... ctx.showHidden = opts; @@ -403,7 +404,7 @@ function formatValue(ctx, value, recurseTimes) { if (keys.length === 0) { if (typeof value === 'function') { return ctx.stylize(`[Function${value.name ? `: ${value.name}` : ''}]`, - 'special'); + 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); @@ -663,7 +664,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { for (var i = 0; i < maxLength; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); + String(i), true)); } else { output.push(''); } @@ -674,7 +675,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { keys.forEach(function(key) { if (typeof key === 'symbol' || !key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); + key, true)); } }); return output; diff --git a/lib/v8.js b/lib/v8.js index 90abc627a45af0..415aed593eb799 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -18,7 +18,7 @@ const v8binding = process.binding('v8'); // Properties for heap statistics buffer extraction. const heapStatisticsBuffer = - new Uint32Array(v8binding.heapStatisticsArrayBuffer); + new Float64Array(v8binding.heapStatisticsArrayBuffer); const kTotalHeapSizeIndex = v8binding.kTotalHeapSizeIndex; const kTotalHeapSizeExecutableIndex = v8binding.kTotalHeapSizeExecutableIndex; const kTotalPhysicalSizeIndex = v8binding.kTotalPhysicalSizeIndex; @@ -31,7 +31,7 @@ const kPeakMallocedMemoryIndex = v8binding.kPeakMallocedMemoryIndex; // Properties for heap space statistics buffer extraction. const heapSpaceStatisticsBuffer = - new Uint32Array(v8binding.heapSpaceStatisticsArrayBuffer); + new Float64Array(v8binding.heapSpaceStatisticsArrayBuffer); const kHeapSpaces = v8binding.kHeapSpaces; const kNumberOfHeapSpaces = kHeapSpaces.length; const kHeapSpaceStatisticsPropertiesCount = diff --git a/lib/vm.js b/lib/vm.js index 4869d368807665..cf672fbbc14871 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -17,22 +17,17 @@ const realRunInThisContext = Script.prototype.runInThisContext; const realRunInContext = Script.prototype.runInContext; Script.prototype.runInThisContext = function(options) { - if (options && options.breakOnSigint) { - const realRunInThisContextScript = () => { - return realRunInThisContext.call(this, options); - }; - return sigintHandlersWrap(realRunInThisContextScript); + if (options && options.breakOnSigint && process._events.SIGINT) { + return sigintHandlersWrap(realRunInThisContext, this, [options]); } else { return realRunInThisContext.call(this, options); } }; Script.prototype.runInContext = function(contextifiedSandbox, options) { - if (options && options.breakOnSigint) { - const realRunInContextScript = () => { - return realRunInContext.call(this, contextifiedSandbox, options); - }; - return sigintHandlersWrap(realRunInContextScript); + if (options && options.breakOnSigint && process._events.SIGINT) { + return sigintHandlersWrap(realRunInContext, this, + [contextifiedSandbox, options]); } else { return realRunInContext.call(this, contextifiedSandbox, options); } @@ -83,19 +78,20 @@ exports.isContext = binding.isContext; // Remove all SIGINT listeners and re-attach them after the wrapped function // has executed, so that caught SIGINT are handled by the listeners again. -function sigintHandlersWrap(fn) { +function sigintHandlersWrap(fn, thisArg, argsArray) { // Using the internal list here to make sure `.once()` wrappers are used, // not the original ones. let sigintListeners = process._events.SIGINT; - if (!Array.isArray(sigintListeners)) - sigintListeners = sigintListeners ? [sigintListeners] : []; - else + + if (Array.isArray(sigintListeners)) sigintListeners = sigintListeners.slice(); + else + sigintListeners = [sigintListeners]; process.removeAllListeners('SIGINT'); try { - return fn(); + return fn.apply(thisArg, argsArray); } finally { // Add using the public methods so that the `newListener` handler of // process can re-attach the listeners. diff --git a/node.gyp b/node.gyp index 2b720a46791b73..3da08d5187f8e9 100644 --- a/node.gyp +++ b/node.gyp @@ -171,6 +171,7 @@ 'src/signal_wrap.cc', 'src/spawn_sync.cc', 'src/string_bytes.cc', + 'src/string_search.cc', 'src/stream_base.cc', 'src/stream_wrap.cc', 'src/tcp_wrap.cc', @@ -178,6 +179,7 @@ 'src/tty_wrap.cc', 'src/process_wrap.cc', 'src/udp_wrap.cc', + 'src/util.cc', 'src/uv.cc', # headers to make for a more pleasant IDE experience 'src/async-wrap.h', @@ -218,8 +220,6 @@ 'src/tree.h', 'src/util.h', 'src/util-inl.h', - 'src/util.cc', - 'src/string_search.cc', 'deps/http_parser/http_parser.h', 'deps/v8/include/v8.h', 'deps/v8/include/v8-debug.h', diff --git a/src/connection_wrap.cc b/src/connection_wrap.cc index 41571946b22e4f..020fe8b4c9508c 100644 --- a/src/connection_wrap.cc +++ b/src/connection_wrap.cc @@ -99,11 +99,10 @@ void ConnectionWrap::AfterConnect(uv_connect_t* req, writable = uv_is_writable(req->handle) != 0; } - Local req_wrap_obj = req_wrap->object(); Local argv[5] = { Integer::New(env->isolate(), status), wrap->object(), - req_wrap_obj, + req_wrap->object(), Boolean::New(env->isolate(), readable), Boolean::New(env->isolate(), writable) }; diff --git a/src/env-inl.h b/src/env-inl.h index 83db3d33b6d18f..1a17e2947d0597 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -207,6 +207,19 @@ inline Environment::~Environment() { delete hc; } + while (handle_cleanup_waiting_ != 0) + uv_run(event_loop(), UV_RUN_ONCE); + + // Closing the destroy_ids_idle_handle_ within the handle cleanup queue + // prevents the async wrap destroy hook from being called. + uv_handle_t* handle = + reinterpret_cast(&destroy_ids_idle_handle_); + handle->data = this; + handle_cleanup_waiting_ = 1; + uv_close(handle, [](uv_handle_t* handle) { + static_cast(handle->data)->FinishHandleCleanup(handle); + }); + while (handle_cleanup_waiting_ != 0) uv_run(event_loop(), UV_RUN_ONCE); @@ -316,22 +329,22 @@ inline std::vector* Environment::destroy_ids_list() { return &destroy_ids_list_; } -inline uint32_t* Environment::heap_statistics_buffer() const { +inline double* Environment::heap_statistics_buffer() const { CHECK_NE(heap_statistics_buffer_, nullptr); return heap_statistics_buffer_; } -inline void Environment::set_heap_statistics_buffer(uint32_t* pointer) { +inline void Environment::set_heap_statistics_buffer(double* pointer) { CHECK_EQ(heap_statistics_buffer_, nullptr); // Should be set only once. heap_statistics_buffer_ = pointer; } -inline uint32_t* Environment::heap_space_statistics_buffer() const { +inline double* Environment::heap_space_statistics_buffer() const { CHECK_NE(heap_space_statistics_buffer_, nullptr); return heap_space_statistics_buffer_; } -inline void Environment::set_heap_space_statistics_buffer(uint32_t* pointer) { +inline void Environment::set_heap_space_statistics_buffer(double* pointer) { CHECK_EQ(heap_space_statistics_buffer_, nullptr); // Should be set only once. heap_space_statistics_buffer_ = pointer; } diff --git a/src/env.h b/src/env.h index b99bb45f819e59..8c256ca9c7faa4 100644 --- a/src/env.h +++ b/src/env.h @@ -469,11 +469,11 @@ class Environment { // List of id's that have been destroyed and need the destroy() cb called. inline std::vector* destroy_ids_list(); - inline uint32_t* heap_statistics_buffer() const; - inline void set_heap_statistics_buffer(uint32_t* pointer); + inline double* heap_statistics_buffer() const; + inline void set_heap_statistics_buffer(double* pointer); - inline uint32_t* heap_space_statistics_buffer() const; - inline void set_heap_space_statistics_buffer(uint32_t* pointer); + inline double* heap_space_statistics_buffer() const; + inline void set_heap_space_statistics_buffer(double* pointer); inline char* http_parser_buffer() const; inline void set_http_parser_buffer(char* buffer); @@ -581,8 +581,8 @@ class Environment { &HandleCleanup::handle_cleanup_queue_> handle_cleanup_queue_; int handle_cleanup_waiting_; - uint32_t* heap_statistics_buffer_ = nullptr; - uint32_t* heap_space_statistics_buffer_ = nullptr; + double* heap_statistics_buffer_ = nullptr; + double* heap_space_statistics_buffer_ = nullptr; char* http_parser_buffer_; diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index fc478c49a09d61..8e72b3643c872c 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -129,7 +129,6 @@ class InspectorAgentDelegate: public node::inspector::SocketServerDelegate { class AgentImpl { public: explicit AgentImpl(node::Environment* env); - ~AgentImpl(); // Start the inspector agent thread bool Start(v8::Platform* platform, const char* path, int port, bool wait); @@ -183,7 +182,6 @@ class AgentImpl { State state_; node::Environment* parent_env_; - uv_async_t* data_written_; uv_async_t io_thread_req_; V8NodeInspector* inspector_; v8::Platform* platform_; @@ -323,7 +321,6 @@ AgentImpl::AgentImpl(Environment* env) : delegate_(nullptr), shutting_down_(false), state_(State::kNew), parent_env_(env), - data_written_(new uv_async_t()), inspector_(nullptr), platform_(nullptr), dispatching_messages_(false), @@ -331,16 +328,6 @@ AgentImpl::AgentImpl(Environment* env) : delegate_(nullptr), server_(nullptr) { CHECK_EQ(0, uv_sem_init(&start_sem_, 0)); memset(&io_thread_req_, 0, sizeof(io_thread_req_)); - CHECK_EQ(0, uv_async_init(env->event_loop(), data_written_, nullptr)); - uv_unref(reinterpret_cast(data_written_)); -} - -AgentImpl::~AgentImpl() { - auto close_cb = [](uv_handle_t* handle) { - delete reinterpret_cast(handle); - }; - uv_close(reinterpret_cast(data_written_), close_cb); - data_written_ = nullptr; } void InspectorConsoleCall(const v8::FunctionCallbackInfo& info) { @@ -606,7 +593,6 @@ void AgentImpl::PostIncomingMessage(int session_id, platform_->CallOnForegroundThread(isolate, new DispatchOnInspectorBackendTask(this)); isolate->RequestInterrupt(InterruptCallback, this); - uv_async_send(data_written_); } NotifyMessageReceived(); } @@ -662,7 +648,6 @@ void AgentImpl::DispatchMessages() { } } } while (!tasks.empty()); - uv_async_send(data_written_); dispatching_messages_ = false; } diff --git a/src/inspector_socket_server.cc b/src/inspector_socket_server.cc index 4bd35ae8bed4fb..5308e9bcf0b924 100644 --- a/src/inspector_socket_server.cc +++ b/src/inspector_socket_server.cc @@ -74,22 +74,27 @@ void OnBufferAlloc(uv_handle_t* handle, size_t len, uv_buf_t* buf) { buf->len = len; } -void PrintDebuggerReadyMessage(int port, const std::vector& ids) { - fprintf(stderr, +void PrintDebuggerReadyMessage(int port, + const std::vector& ids, + FILE* out) { + if (out == NULL) { + return; + } + fprintf(out, "Debugger listening on port %d.\n" "Warning: This is an experimental feature " "and could change at any time.\n", port); if (ids.size() == 1) - fprintf(stderr, "To start debugging, open the following URL in Chrome:\n"); + fprintf(out, "To start debugging, open the following URL in Chrome:\n"); if (ids.size() > 1) - fprintf(stderr, "To start debugging, open the following URLs in Chrome:\n"); + fprintf(out, "To start debugging, open the following URLs in Chrome:\n"); for (const std::string& id : ids) { - fprintf(stderr, + fprintf(out, " chrome-devtools://devtools/bundled/inspector.html?" "experiments=true&v8only=true&ws=%s\n", GetWsUrl(port, id).c_str()); } - fflush(stderr); + fflush(out); } void SendHttpResponse(InspectorSocket* socket, const std::string& response) { @@ -132,6 +137,23 @@ void SendProtocolJson(InspectorSocket* socket) { SendHttpResponse(socket, data); } +int GetPort(uv_tcp_t* socket, int* out_port) { + sockaddr_storage addr; + int len = sizeof(addr); + int err = uv_tcp_getsockname(socket, + reinterpret_cast(&addr), + &len); + if (err != 0) + return err; + int port; + if (addr.ss_family == AF_INET6) + port = reinterpret_cast(&addr)->sin6_port; + else + port = reinterpret_cast(&addr)->sin_port; + *out_port = ntohs(port); + return err; +} + } // namespace @@ -207,12 +229,14 @@ class SocketSession { }; InspectorSocketServer::InspectorSocketServer(SocketServerDelegate* delegate, - int port) : loop_(nullptr), - delegate_(delegate), - port_(port), - server_(uv_tcp_t()), - closer_(nullptr), - next_session_id_(0) { } + int port, + FILE* out) : loop_(nullptr), + delegate_(delegate), + port_(port), + server_(uv_tcp_t()), + closer_(nullptr), + next_session_id_(0), + out_(out) { } // static @@ -260,7 +284,7 @@ void InspectorSocketServer::SessionTerminated(int session_id) { delegate_->EndSession(session_id); if (connected_sessions_.empty() && uv_is_active(reinterpret_cast(&server_))) { - PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds()); + PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds(), out_); } } @@ -332,15 +356,19 @@ bool InspectorSocketServer::Start(uv_loop_t* loop) { uv_ip4_addr("0.0.0.0", port_, &addr); int err = uv_tcp_bind(&server_, reinterpret_cast(&addr), 0); + if (err == 0) + err = GetPort(&server_, &port_); if (err == 0) { err = uv_listen(reinterpret_cast(&server_), 1, SocketConnectedCallback); } if (err == 0 && connected_sessions_.empty()) { - PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds()); + PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds(), out_); } if (err != 0 && connected_sessions_.empty()) { - fprintf(stderr, "Unable to open devtools socket: %s\n", uv_strerror(err)); + if (out_ != NULL) { + fprintf(out_, "Unable to open devtools socket: %s\n", uv_strerror(err)); + } uv_close(reinterpret_cast(&server_), nullptr); return false; } diff --git a/src/inspector_socket_server.h b/src/inspector_socket_server.h index 4c139e138f7547..48ebc5353f123d 100644 --- a/src/inspector_socket_server.h +++ b/src/inspector_socket_server.h @@ -32,11 +32,16 @@ class SocketServerDelegate { class InspectorSocketServer { public: using ServerCallback = void (*)(InspectorSocketServer*); - InspectorSocketServer(SocketServerDelegate* delegate, int port); + InspectorSocketServer(SocketServerDelegate* delegate, + int port, + FILE* out = stderr); bool Start(uv_loop_t* loop); void Stop(ServerCallback callback); void Send(int session_id, const std::string& message); void TerminateConnections(ServerCallback callback); + int port() { + return port_; + } private: static bool HandshakeCallback(InspectorSocket* socket, @@ -60,12 +65,13 @@ class InspectorSocketServer { uv_loop_t* loop_; SocketServerDelegate* const delegate_; - const int port_; + int port_; std::string path_; uv_tcp_t server_; Closer* closer_; std::map connected_sessions_; int next_session_id_; + FILE* out_; friend class SocketSession; friend class Closer; diff --git a/src/node.cc b/src/node.cc index 0280eb696c1b84..75f3078db5b4f9 100644 --- a/src/node.cc +++ b/src/node.cc @@ -2198,7 +2198,7 @@ static void WaitForInspectorDisconnect(Environment* env) { if (env->inspector_agent()->IsConnected()) { // Restore signal dispositions, the app is done and is no longer // capable of handling signals. -#ifdef __POSIX__ +#if defined(__POSIX__) && !defined(NODE_SHARED_MODE) struct sigaction act; memset(&act, 0, sizeof(act)); for (unsigned nr = 1; nr < kMaxSignal; nr += 1) { @@ -4166,6 +4166,7 @@ inline void PlatformInit() { CHECK_EQ(err, 0); +#ifndef NODE_SHARED_MODE // Restore signal dispositions, the parent process may have changed them. struct sigaction act; memset(&act, 0, sizeof(act)); @@ -4179,6 +4180,7 @@ inline void PlatformInit() { act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL; CHECK_EQ(0, sigaction(nr, &act, nullptr)); } +#endif // !NODE_SHARED_MODE RegisterSignalHandler(SIGINT, SignalExit, true); RegisterSignalHandler(SIGTERM, SignalExit, true); diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 8e1319269e8ed7..cd485c63ab4a53 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -123,7 +123,7 @@ const char* const root_certs[] = { std::string extra_root_certs_file; // NOLINT(runtime/string) X509_STORE* root_cert_store; -std::vector* root_certs_vector; +std::vector root_certs_vector; // Just to generate static methods template class SSLWrap; @@ -693,9 +693,7 @@ static int X509_up_ref(X509* cert) { static X509_STORE* NewRootCertStore() { - if (!root_certs_vector) { - root_certs_vector = new std::vector; - + if (root_certs_vector.empty()) { for (size_t i = 0; i < arraysize(root_certs); i++) { BIO* bp = NodeBIO::NewFixed(root_certs[i], strlen(root_certs[i])); X509 *x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr); @@ -704,15 +702,19 @@ static X509_STORE* NewRootCertStore() { // Parse errors from the built-in roots are fatal. CHECK_NE(x509, nullptr); - root_certs_vector->push_back(x509); + root_certs_vector.push_back(x509); } } X509_STORE* store = X509_STORE_new(); - for (auto& cert : *root_certs_vector) { +#if defined(NODE_OPENSSL_CERT_STORE) + X509_STORE_set_default_paths(store); +#else + for (X509 *cert : root_certs_vector) { X509_up_ref(cert); X509_STORE_add_cert(store, cert); } +#endif return store; } @@ -1147,10 +1149,14 @@ void SecureContext::SetTicketKeys(const FunctionCallbackInfo& args) { void SecureContext::SetFreeListLength(const FunctionCallbackInfo& args) { +#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(OPENSSL_IS_BORINGSSL) + // |freelist_max_len| was removed in OpenSSL 1.1.0. In that version OpenSSL + // mallocs and frees buffers directly, without the use of a freelist. SecureContext* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); wrap->ctx_->freelist_max_len = args[0]->Int32Value(); +#endif } diff --git a/src/node_os.cc b/src/node_os.cc index f8b53e45d8e669..97b1a1d08da6ed 100644 --- a/src/node_os.cc +++ b/src/node_os.cc @@ -69,7 +69,7 @@ static void GetOSType(const FunctionCallbackInfo& args) { } rval = info.sysname; #else // __MINGW32__ - rval ="Windows_NT"; + rval = "Windows_NT"; #endif // __POSIX__ args.GetReturnValue().Set(OneByteString(env->isolate(), rval)); diff --git a/src/node_url.cc b/src/node_url.cc index 11a03ea5211a89..92cb8efbb84389 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -96,50 +96,50 @@ using v8::Value; namespace url { #if defined(NODE_HAVE_I18N_SUPPORT) - static int ToUnicode(std::string* input, std::string* output) { + static bool ToUnicode(std::string* input, std::string* output) { MaybeStackBuffer buf; if (i18n::ToUnicode(&buf, input->c_str(), input->length()) < 0) - return -1; + return false; output->assign(*buf, buf.length()); - return 0; + return true; } - static int ToASCII(std::string* input, std::string* output) { + static bool ToASCII(std::string* input, std::string* output) { MaybeStackBuffer buf; if (i18n::ToASCII(&buf, input->c_str(), input->length()) < 0) - return -1; + return false; output->assign(*buf, buf.length()); - return 0; + return true; } // Unfortunately there's not really a better way to do this. // Iterate through each encoded codepoint and verify that // it is a valid unicode codepoint. - static int IsValidUTF8(std::string* input) { + static bool IsValidUTF8(std::string* input) { const char* p = input->c_str(); int32_t len = input->length(); for (int32_t i = 0; i < len;) { UChar32 c; U8_NEXT_UNSAFE(p, i, c); if (!U_IS_UNICODE_CHAR(c)) - return -1; + return false; } - return 0; + return true; } #else // Intentional non-ops if ICU is not present. - static int ToUnicode(std::string* input, std::string* output) { - output->reserve(input->length()); - *output = input->c_str(); + static bool ToUnicode(std::string* input, std::string* output) { + *output = *input; + return true; } - static int ToASCII(std::string* input, std::string* output) { - output->reserve(input->length()); - *output = input->c_str(); + static bool ToASCII(std::string* input, std::string* output) { + *output = *input; + return true; } - static int IsValidUTF8(std::string* input) { - return 0; + static bool IsValidUTF8(std::string* input) { + return true; } #endif @@ -381,11 +381,11 @@ namespace url { // If there are any invalid UTF8 byte sequences, we have to fail. // Unfortunately this means iterating through the string and checking // each decoded codepoint. - if (IsValidUTF8(&decoded) < 0) + if (!IsValidUTF8(&decoded)) goto end; // Then we have to punycode toASCII - if (ToASCII(&decoded, &decoded) < 0) + if (!ToASCII(&decoded, &decoded)) goto end; // If any of the following characters are still present, we have to fail @@ -405,7 +405,7 @@ namespace url { goto end; // If the unicode flag is set, run the result through punycode ToUnicode - if (unicode && ToUnicode(&decoded, &decoded) < 0) + if (unicode && !ToUnicode(&decoded, &decoded)) goto end; // It's not an IPv4 or IPv6 address, it must be a domain @@ -499,17 +499,17 @@ namespace url { return host->type; } - static int ParseHost(std::string* input, - std::string* output, - bool unicode = false) { + static bool ParseHost(std::string* input, + std::string* output, + bool unicode = false) { if (input->length() == 0) - return 0; + return true; url_host host{{""}, HOST_TYPE_DOMAIN}; ParseHost(&host, input->c_str(), input->length(), unicode); if (host.type == HOST_TYPE_FAILED) - return -1; + return false; WriteHost(&host, output); - return 0; + return true; } static inline void Copy(Isolate* isolate, @@ -996,7 +996,7 @@ namespace url { if (special && buffer.size() == 0) URL_FAILED() SET_HAVE_HOST() - if (ParseHost(&buffer, &url.host) < 0) + if (!ParseHost(&buffer, &url.host)) URL_FAILED() buffer.clear(); state = kPort; @@ -1011,7 +1011,7 @@ namespace url { if (special && buffer.size() == 0) URL_FAILED() SET_HAVE_HOST() - if (ParseHost(&buffer, &url.host) < 0) + if (!ParseHost(&buffer, &url.host)) URL_FAILED() buffer.clear(); state = kPathStart; @@ -1161,7 +1161,7 @@ namespace url { } else { if (buffer != "localhost") { SET_HAVE_HOST() - if (ParseHost(&buffer, &url.host) < 0) + if (!ParseHost(&buffer, &url.host)) URL_FAILED() } buffer.clear(); @@ -1214,12 +1214,7 @@ namespace url { state = kFragment; } } else { - if (ch == '%' && p[1] == '2' && TO_LOWER(p[2]) == 'e') { - buffer += '.'; - p += 2; - } else { - AppendOrEscape(&buffer, ch, DefaultEncodeSet); - } + AppendOrEscape(&buffer, ch, DefaultEncodeSet); } break; case kCannotBeBase: diff --git a/src/node_v8.cc b/src/node_v8.cc index a033c48a7c98be..7059922607089d 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -57,8 +57,8 @@ void UpdateHeapStatisticsArrayBuffer(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); HeapStatistics s; env->isolate()->GetHeapStatistics(&s); - uint32_t* const buffer = env->heap_statistics_buffer(); -#define V(index, name, _) buffer[index] = static_cast(s.name()); + double* const buffer = env->heap_statistics_buffer(); +#define V(index, name, _) buffer[index] = static_cast(s.name()); HEAP_STATISTICS_PROPERTIES(V) #undef V } @@ -68,13 +68,13 @@ void UpdateHeapSpaceStatisticsBuffer(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); HeapSpaceStatistics s; Isolate* const isolate = env->isolate(); - uint32_t* buffer = env->heap_space_statistics_buffer(); + double* buffer = env->heap_space_statistics_buffer(); for (size_t i = 0; i < number_of_heap_spaces; i++) { isolate->GetHeapSpaceStatistics(&s, i); size_t const property_offset = i * kHeapSpaceStatisticsPropertiesCount; #define V(index, name, _) buffer[property_offset + index] = \ - static_cast(s.name()); + static_cast(s.name()); HEAP_SPACE_STATISTICS_PROPERTIES(V) #undef V } @@ -103,7 +103,7 @@ void InitializeV8Bindings(Local target, "updateHeapStatisticsArrayBuffer", UpdateHeapStatisticsArrayBuffer); - env->set_heap_statistics_buffer(new uint32_t[kHeapStatisticsPropertiesCount]); + env->set_heap_statistics_buffer(new double[kHeapStatisticsPropertiesCount]); const size_t heap_statistics_buffer_byte_length = sizeof(*env->heap_statistics_buffer()) * kHeapStatisticsPropertiesCount; @@ -149,7 +149,7 @@ void InitializeV8Bindings(Local target, UpdateHeapSpaceStatisticsBuffer); env->set_heap_space_statistics_buffer( - new uint32_t[kHeapSpaceStatisticsPropertiesCount * number_of_heap_spaces]); + new double[kHeapSpaceStatisticsPropertiesCount * number_of_heap_spaces]); const size_t heap_space_statistics_buffer_byte_length = sizeof(*env->heap_space_statistics_buffer()) * diff --git a/src/pipe_wrap.cc b/src/pipe_wrap.cc index 8fd2f8f5f3bbce..5f47dadddb4d96 100644 --- a/src/pipe_wrap.cc +++ b/src/pipe_wrap.cc @@ -53,7 +53,11 @@ void PipeWrap::Initialize(Local target, env->SetProtoMethod(t, "ref", HandleWrap::Ref); env->SetProtoMethod(t, "hasRef", HandleWrap::HasRef); +#ifdef _WIN32 StreamWrap::AddMethods(env, t); +#else + StreamWrap::AddMethods(env, t, StreamBase::kFlagHasWritev); +#endif env->SetProtoMethod(t, "bind", Bind); env->SetProtoMethod(t, "listen", Listen); diff --git a/test/.eslintrc b/test/.eslintrc.yaml similarity index 100% rename from test/.eslintrc rename to test/.eslintrc.yaml diff --git a/test/README.md b/test/README.md index 8d8cec44919720..94f77eda5148f2 100644 --- a/test/README.md +++ b/test/README.md @@ -163,6 +163,13 @@ A stream to push an array into a REPL Blocks for `time` amount of time. +### canCreateSymLink +API to indicate whether the current running process can create +symlinks. On Windows, this returns false if the process running +doesn't have privileges to create symlinks (specifically +[SeCreateSymbolicLinkPrivilege](https://msdn.microsoft.com/en-us/library/windows/desktop/bb530716(v=vs.85).aspx)). +On non-Windows platforms, this currently returns true. + ### ddCommand(filename, kilobytes) * return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -366,7 +373,7 @@ Synchronous version of `spawnPwd`. ### tmpDir * return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -Path to the 'tmp' directory. +The realpath of the 'tmp' directory. ### tmpDirName * return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/test/cctest/test_inspector_socket_server.cc b/test/cctest/test_inspector_socket_server.cc index 2bbc3811390fe6..e1e9f6f66865d3 100644 --- a/test/cctest/test_inspector_socket_server.cc +++ b/test/cctest/test_inspector_socket_server.cc @@ -6,7 +6,6 @@ #include #include -static const int PORT = 9229; static uv_loop_t loop; static const char CLIENT_CLOSE_FRAME[] = "\x88\x80\x2D\x0E\x1E\xFA"; @@ -70,7 +69,7 @@ class Timeout { class InspectorSocketServerTest : public ::testing::Test { protected: void SetUp() override { - uv_loop_init(&loop); + EXPECT_EQ(0, uv_loop_init(&loop)); } void TearDown() override { @@ -165,7 +164,7 @@ class SocketWrapper { contents_.clear(); uv_tcp_init(loop_, &socket_); sockaddr_in addr; - uv_ip4_addr(host.c_str(), PORT, &addr); + uv_ip4_addr(host.c_str(), port, &addr); int err = uv_tcp_connect(&connect_, &socket_, reinterpret_cast(&addr), Connected_); @@ -183,7 +182,7 @@ class SocketWrapper { contents_.clear(); uv_tcp_init(loop_, &socket_); sockaddr_in addr; - uv_ip4_addr(host.c_str(), PORT, &addr); + uv_ip4_addr(host.c_str(), port, &addr); int err = uv_tcp_connect(&connect_, &socket_, reinterpret_cast(&addr), ConnectionMustFail_); @@ -300,9 +299,9 @@ class SocketWrapper { class ServerHolder { public: template - ServerHolder(Delegate* delegate, int port) + ServerHolder(Delegate* delegate, int port, FILE* out = NULL) : closed(false), paused(false), sessions_terminated(false), - server_(delegate, port) { + server_(delegate, port, out) { delegate->Connect(&server_); } @@ -310,6 +309,10 @@ class ServerHolder { return &server_; } + int port() { + return server_.port(); + } + static void CloseCallback(InspectorSocketServer* server) { ServerHolder* holder = node::ContainerOf(&ServerHolder::server_, server); holder->closed = true; @@ -377,12 +380,12 @@ static const std::string WsHandshakeRequest(const std::string& target_id) { TEST_F(InspectorSocketServerTest, InspectorSessions) { TestInspectorServerDelegate delegate; - ServerHolder server(&delegate, PORT); + ServerHolder server(&delegate, 0); ASSERT_TRUE(server->Start(&loop)); SocketWrapper well_behaved_socket(&loop); // Regular connection - well_behaved_socket.Connect("0.0.0.0", PORT); + well_behaved_socket.Connect("0.0.0.0", server.port()); well_behaved_socket.Write(WsHandshakeRequest(MAIN_TARGET_ID)); well_behaved_socket.Expect(WS_HANDSHAKE_RESPONSE); @@ -405,7 +408,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Declined connection SocketWrapper declined_target_socket(&loop); - declined_target_socket.Connect("127.0.0.1", PORT); + declined_target_socket.Connect("127.0.0.1", server.port()); declined_target_socket.Write(WsHandshakeRequest(UNCONNECTABLE_TARGET_ID)); declined_target_socket.Expect("HTTP/1.0 400 Bad Request"); declined_target_socket.ExpectEOF(); @@ -414,7 +417,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Bogus target - start session callback should not even be invoked SocketWrapper bogus_target_socket(&loop); - bogus_target_socket.Connect("127.0.0.1", PORT); + bogus_target_socket.Connect("127.0.0.1", server.port()); bogus_target_socket.Write(WsHandshakeRequest("bogus_target")); bogus_target_socket.Expect("HTTP/1.0 400 Bad Request"); bogus_target_socket.ExpectEOF(); @@ -423,7 +426,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Drop connection (no proper close frames) SocketWrapper dropped_connection_socket(&loop); - dropped_connection_socket.Connect("127.0.0.1", PORT); + dropped_connection_socket.Connect("127.0.0.1", server.port()); dropped_connection_socket.Write(WsHandshakeRequest(MAIN_TARGET_ID)); dropped_connection_socket.Expect(WS_HANDSHAKE_RESPONSE); @@ -437,7 +440,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Reconnect regular connection SocketWrapper stays_till_termination_socket(&loop); - stays_till_termination_socket.Connect("127.0.0.1", PORT); + stays_till_termination_socket.Connect("127.0.0.1", server.port()); stays_till_termination_socket.Write(WsHandshakeRequest(MAIN_TARGET_ID)); stays_till_termination_socket.Expect(WS_HANDSHAKE_RESPONSE); @@ -464,7 +467,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { TEST_F(InspectorSocketServerTest, ServerDoesNothing) { TestInspectorServerDelegate delegate; - ServerHolder server(&delegate, PORT); + ServerHolder server(&delegate, 0); ASSERT_TRUE(server->Start(&loop)); server->Stop(ServerHolder::CloseCallback); @@ -474,14 +477,14 @@ TEST_F(InspectorSocketServerTest, ServerDoesNothing) { TEST_F(InspectorSocketServerTest, ServerWithoutTargets) { ServerDelegateNoTargets delegate; - ServerHolder server(&delegate, PORT); + ServerHolder server(&delegate, 0); ASSERT_TRUE(server->Start(&loop)); - TestHttpRequest(PORT, "/json/list", "[ ]"); - TestHttpRequest(PORT, "/json", "[ ]"); + TestHttpRequest(server.port(), "/json/list", "[ ]"); + TestHttpRequest(server.port(), "/json", "[ ]"); // Declined connection SocketWrapper socket(&loop); - socket.Connect("0.0.0.0", PORT); + socket.Connect("0.0.0.0", server.port()); socket.Write(WsHandshakeRequest(UNCONNECTABLE_TARGET_ID)); socket.Expect("HTTP/1.0 400 Bad Request"); socket.ExpectEOF(); @@ -492,9 +495,9 @@ TEST_F(InspectorSocketServerTest, ServerWithoutTargets) { TEST_F(InspectorSocketServerTest, ServerCannotStart) { ServerDelegateNoTargets delegate1, delegate2; - ServerHolder server1(&delegate1, PORT); + ServerHolder server1(&delegate1, 0); ASSERT_TRUE(server1->Start(&loop)); - ServerHolder server2(&delegate2, PORT); + ServerHolder server2(&delegate2, server1.port()); ASSERT_FALSE(server2->Start(&loop)); server1->Stop(ServerHolder::CloseCallback); server1->TerminateConnections(ServerHolder::ConnectionsTerminated); @@ -506,10 +509,10 @@ TEST_F(InspectorSocketServerTest, ServerCannotStart) { TEST_F(InspectorSocketServerTest, StoppingServerDoesNotKillConnections) { ServerDelegateNoTargets delegate; - ServerHolder server(&delegate, PORT); + ServerHolder server(&delegate, 0); ASSERT_TRUE(server->Start(&loop)); SocketWrapper socket1(&loop); - socket1.Connect("0.0.0.0", PORT); + socket1.Connect("0.0.0.0", server.port()); socket1.TestHttpRequest("/json/list", "[ ]"); server->Stop(ServerHolder::CloseCallback); SPIN_WHILE(!server.closed); diff --git a/test/common.js b/test/common.js index 0fff06bfc0944d..5ee9a5ce314793 100644 --- a/test/common.js +++ b/test/common.js @@ -8,9 +8,10 @@ const child_process = require('child_process'); const stream = require('stream'); const util = require('util'); const Timer = process.binding('timer_wrap').Timer; +const execSync = require('child_process').execSync; const testRoot = process.env.NODE_TEST_DIR ? - path.resolve(process.env.NODE_TEST_DIR) : __dirname; + fs.realpathSync(process.env.NODE_TEST_DIR) : __dirname; exports.fixturesDir = path.join(__dirname, 'fixtures'); exports.tmpDirName = 'tmp'; @@ -202,6 +203,28 @@ exports.hasIPv6 = Object.keys(ifaces).some(function(name) { }); }); +/* + * Check that when running a test with + * `$node --abort-on-uncaught-exception $file child` + * the process aborts. + */ +exports.childShouldThrowAndAbort = function() { + var testCmd = ''; + if (!exports.isWindows) { + // Do not create core files, as it can take a lot of disk space on + // continuous testing and developers' machines + testCmd += 'ulimit -c 0 && '; + } + testCmd += `${process.argv[0]} --abort-on-uncaught-exception `; + testCmd += `${process.argv[1]} child`; + const child = child_process.exec(testCmd); + child.on('exit', function onExit(exitCode, signal) { + const errMsg = 'Test should have aborted ' + + `but instead exited with exit code ${exitCode}` + + ` and signal ${signal}`; + assert(exports.nodeProcessAborted(exitCode, signal), errMsg); + }); +}; exports.ddCommand = function(filename, kilobytes) { if (exports.isWindows) { @@ -398,7 +421,10 @@ function runCallChecks(exitCode) { exports.mustCall = function(fn, expected) { - if (typeof expected !== 'number') expected = 1; + if (expected === undefined) + expected = 1; + else if (typeof expected !== 'number') + throw new TypeError(`Invalid expected value: ${expected}`); const context = { expected: expected, @@ -435,6 +461,34 @@ exports.fileExists = function(pathname) { } }; +exports.canCreateSymLink = function() { + // On Windows, creating symlinks requires admin privileges. + // We'll only try to run symlink test if we have enough privileges. + // On other platforms, creating symlinks shouldn't need admin privileges + if (exports.isWindows) { + // whoami.exe needs to be the one from System32 + // If unix tools are in the path, they can shadow the one we want, + // so use the full path while executing whoami + const whoamiPath = path.join(process.env['SystemRoot'], + 'System32', 'whoami.exe'); + + let err = false; + let output = ''; + + try { + output = execSync(whoamiPath + ' /priv', { timout: 1000 }); + } catch (e) { + err = true; + } finally { + if (err || !output.includes('SeCreateSymbolicLinkPrivilege')) { + return false; + } + } + } + + return true; +}; + function fail(msg) { assert.fail(null, null, msg); } diff --git a/test/disabled/test-dgram-send-error.js b/test/disabled/test-dgram-send-error.js index 271e6689046a00..7da60de3581ff3 100644 --- a/test/disabled/test-dgram-send-error.js +++ b/test/disabled/test-dgram-send-error.js @@ -34,7 +34,7 @@ function onMessage(message, info) { } function afterSend(err) { - if (err) throw err; + assert.ifError(err); packetsSent++; } diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index bd21e21d9563d2..1745c8fea3df5c 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -74,7 +74,7 @@ const testData = [ }, ]; -testData.forEach(function(item) { +testData.forEach((item) => { // Normalize expected data by stripping whitespace const expected = item.html.replace(/\s/g, ''); diff --git a/test/doctool/test-doctool-json.js b/test/doctool/test-doctool-json.js index 520c79bef8bcda..ae7b2007b7d2ef 100644 --- a/test/doctool/test-doctool-json.js +++ b/test/doctool/test-doctool-json.js @@ -18,7 +18,7 @@ const json = require('../../tools/doc/json.js'); // Test data is a list of objects with two properties. // The file property is the file path. // The json property is some json which will be generated by the doctool. -var testData = [ +const testData = [ { file: path.join(common.fixturesDir, 'sample_document.md'), json: { @@ -136,10 +136,10 @@ var testData = [ } ]; -testData.forEach(function(item) { - fs.readFile(item.file, 'utf8', common.mustCall(function(err, input) { +testData.forEach((item) => { + fs.readFile(item.file, 'utf8', common.mustCall((err, input) => { assert.ifError(err); - json(input, 'foo', common.mustCall(function(err, output) { + json(input, 'foo', common.mustCall((err, output) => { assert.ifError(err); assert.deepStrictEqual(output, item.json); })); diff --git a/test/fixtures/tls-connect.js b/test/fixtures/tls-connect.js new file mode 100644 index 00000000000000..72f83736bf370e --- /dev/null +++ b/test/fixtures/tls-connect.js @@ -0,0 +1,101 @@ +// One shot call to connect a TLS client and server based on options to +// tls.createServer() and tls.connect(), so assertions can be made on both ends +// of the connection. +'use strict'; + +const common = require('../common'); +const fs = require('fs'); +const join = require('path').join; +const tls = require('tls'); +const util = require('util'); + +module.exports = exports = checkCrypto; + +function checkCrypto() { + if (!common.hasCrypto) { + common.skip('missing crypto'); + process.exit(0); + } + return exports; +} + +exports.assert = require('assert'); +exports.debug = util.debuglog('test'); +exports.tls = tls; + +// Pre-load keys from common fixtures for ease of use by tests. +const keys = exports.keys = { + agent1: load('agent1', 'ca1'), + agent2: load('agent2', 'agent2'), + agent3: load('agent3', 'ca2'), + agent4: load('agent4', 'ca2'), + agent5: load('agent5', 'ca2'), + agent6: load('agent6', 'ca1'), + agent7: load('agent7', 'fake-cnnic-root'), + ec: load('ec', 'ec'), +}; + +function load(cert, issuer) { + issuer = issuer || cert; // Assume self-signed if no issuer + const id = { + key: read(cert + '-key.pem'), + cert: read(cert + '-cert.pem'), + ca: read(issuer + '-cert.pem'), + }; + return id; +} + +function read(file) { + return fs.readFileSync(join(common.fixturesDir, 'keys', file), 'binary'); +} + +exports.connect = function connect(options, callback) { + callback = common.mustCall(callback); + + const server = {}; + const client = {}; + const pair = { + server: server, + client: client, + }; + + tls.createServer(options.server, function(conn) { + server.conn = conn; + conn.pipe(conn); + maybeCallback() + }).listen(0, function() { + server.server = this; + + const optClient = util._extend({ + port: this.address().port, + }, options.client); + + tls.connect(optClient) + .on('secureConnect', function() { + client.conn = this; + maybeCallback(); + }) + .on('error', function(err) { + client.err = err; + client.conn = this; + maybeCallback(); + }); + }); + + function maybeCallback() { + if (!callback) + return; + if (server.conn && (client.conn || client.err)) { + const err = pair.client.err || pair.server.err; + callback(err, pair, cleanup); + callback = null; + + function cleanup() { + if (server.server) + server.server.close(); + if (client.conn) + client.conn.end(); + } + } + } +} diff --git a/test/fixtures/url-setter-tests.json b/test/fixtures/url-setter-tests.json index e3a163e788301e..56a1c00a86fd45 100644 --- a/test/fixtures/url-setter-tests.json +++ b/test/fixtures/url-setter-tests.json @@ -953,8 +953,8 @@ "href": "view-source+http://example.net/home?lang=fr#nav", "new_value": "\\a\\%2E\\b\\%2e.\\c", "expected": { - "href": "view-source+http://example.net/\\a\\.\\b\\..\\c?lang=fr#nav", - "pathname": "/\\a\\.\\b\\..\\c" + "href": "view-source+http://example.net/\\a\\%2E\\b\\%2e.\\c?lang=fr#nav", + "pathname": "/\\a\\%2E\\b\\%2e.\\c" } }, { @@ -967,12 +967,12 @@ } }, { - "comment": "Bytes already percent-encoded are left as-is, except %2E.", + "comment": "Bytes already percent-encoded are left as-is, including %2E outside dotted segments.", "href": "http://example.net", "new_value": "%2e%2E%c3%89té", "expected": { - "href": "http://example.net/..%c3%89t%C3%A9", - "pathname": "/..%c3%89t%C3%A9" + "href": "http://example.net/%2e%2E%c3%89t%C3%A9", + "pathname": "/%2e%2E%c3%89t%C3%A9" } }, { diff --git a/test/fixtures/url-tests.json b/test/fixtures/url-tests.json index 44d665b99f5bb6..634a8e3f663985 100644 --- a/test/fixtures/url-tests.json +++ b/test/fixtures/url-tests.json @@ -32,6 +32,66 @@ "search": "?b", "hash": "#c" }, + { + "input": "https://test:@test", + "base": "about:blank", + "href": "https://test@test/", + "origin": "https://test", + "protocol": "https:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://:@test", + "base": "about:blank", + "href": "https://test/", + "origin": "https://test", + "protocol": "https:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://test:@test/x", + "base": "about:blank", + "href": "non-special://test@test/x", + "origin": "null", + "protocol": "non-special:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "non-special://:@test/x", + "base": "about:blank", + "href": "non-special://test/x", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, { "input": "http:foo.com", "base": "http://example.org/foo/bar", @@ -1787,7 +1847,7 @@ { "input": "http://example.com/foo/%2e%2", "base": "about:blank", - "href": "http://example.com/foo/.%2", + "href": "http://example.com/foo/%2e%2", "origin": "http://example.com", "protocol": "http:", "username": "", @@ -1795,14 +1855,14 @@ "host": "example.com", "hostname": "example.com", "port": "", - "pathname": "/foo/.%2", + "pathname": "/foo/%2e%2", "search": "", "hash": "" }, { "input": "http://example.com/foo/%2e./%2e%2e/.%2e/%2e.bar", "base": "about:blank", - "href": "http://example.com/..bar", + "href": "http://example.com/%2e.bar", "origin": "http://example.com", "protocol": "http:", "username": "", @@ -1810,7 +1870,7 @@ "host": "example.com", "hostname": "example.com", "port": "", - "pathname": "/..bar", + "pathname": "/%2e.bar", "search": "", "hash": "" }, @@ -2228,7 +2288,7 @@ { "input": "http://www/foo%2Ehtml", "base": "about:blank", - "href": "http://www/foo.html", + "href": "http://www/foo%2Ehtml", "origin": "http://www", "protocol": "http:", "username": "", @@ -2236,7 +2296,7 @@ "host": "www", "hostname": "www", "port": "", - "pathname": "/foo.html", + "pathname": "/foo%2Ehtml", "search": "", "hash": "" }, @@ -3098,7 +3158,7 @@ { "input": "http:a:@www.example.com", "base": "about:blank", - "href": "http://a:@www.example.com/", + "href": "http://a@www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "a", @@ -3113,7 +3173,7 @@ { "input": "http:/a:@www.example.com", "base": "about:blank", - "href": "http://a:@www.example.com/", + "href": "http://a@www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "a", @@ -3128,7 +3188,7 @@ { "input": "http://a:@www.example.com", "base": "about:blank", - "href": "http://a:@www.example.com/", + "href": "http://a@www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "a", @@ -3173,7 +3233,7 @@ { "input": "http://:@www.example.com", "base": "about:blank", - "href": "http://:@www.example.com/", + "href": "http://www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "", diff --git a/test/gc/node_modules/nan/tools/1to2.js b/test/gc/node_modules/nan/tools/1to2.js index b7498e438ccd83..15d156481873f7 100755 --- a/test/gc/node_modules/nan/tools/1to2.js +++ b/test/gc/node_modules/nan/tools/1to2.js @@ -57,7 +57,7 @@ groups.push([1, ['(', [ /* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */ groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']); -/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ +/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); /* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */ diff --git a/test/gc/test-net-timeout.js b/test/gc/test-net-timeout.js index 2d9bc134a30347..9bc19a04256108 100644 --- a/test/gc/test-net-timeout.js +++ b/test/gc/test-net-timeout.js @@ -36,7 +36,7 @@ function getall() { if (count >= todo) return; - const req = net.connect(server.address().port, server.address().address); + const req = net.connect(server.address().port); req.resume(); req.setTimeout(10, function() { req.destroy(); diff --git a/test/inspector/test-inspector.js b/test/inspector/test-inspector.js index 7e53eaa55fffb7..a1c69cb6fbb2fe 100644 --- a/test/inspector/test-inspector.js +++ b/test/inspector/test-inspector.js @@ -114,10 +114,10 @@ function testSetBreakpointAndResume(session) { const commands = [ { 'method': 'Debugger.setBreakpointByUrl', 'params': { 'lineNumber': 5, - 'url': session.mainScriptPath, - 'columnNumber': 0, - 'condition': '' - } + 'url': session.mainScriptPath, + 'columnNumber': 0, + 'condition': '' + } }, { 'method': 'Debugger.resume'}, [ { 'method': 'Debugger.getScriptSource', diff --git a/test/internet/test-dgram-broadcast-multi-process.js b/test/internet/test-dgram-broadcast-multi-process.js index c05d0cf5b9512e..da3bd8cceb74e3 100644 --- a/test/internet/test-dgram-broadcast-multi-process.js +++ b/test/internet/test-dgram-broadcast-multi-process.js @@ -179,7 +179,7 @@ if (process.argv[2] !== 'child') { common.PORT, LOCAL_BROADCAST_HOST, function(err) { - if (err) throw err; + assert.ifError(err); console.error('[PARENT] sent %s to %s:%s', util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT); diff --git a/test/internet/test-dgram-multicast-multi-process.js b/test/internet/test-dgram-multicast-multi-process.js index 307549bba870b6..de6bf874ed874c 100644 --- a/test/internet/test-dgram-multicast-multi-process.js +++ b/test/internet/test-dgram-multicast-multi-process.js @@ -160,7 +160,7 @@ if (process.argv[2] !== 'child') { common.PORT, LOCAL_BROADCAST_HOST, function(err) { - if (err) throw err; + assert.ifError(err); console.error('[PARENT] sent "%s" to %s:%s', buf.toString(), LOCAL_BROADCAST_HOST, common.PORT); diff --git a/test/internet/test-dns-ipv4.js b/test/internet/test-dns-ipv4.js index a86c863cc443c9..c4f2d00df886d9 100644 --- a/test/internet/test-dns-ipv4.js +++ b/test/internet/test-dns-ipv4.js @@ -36,61 +36,61 @@ function checkWrap(req) { TEST(function test_resolve4(done) { const req = dns.resolve4('www.google.com', - common.mustCall((err, ips) => { - assert.ifError(err); + common.mustCall((err, ips) => { + assert.ifError(err); - assert.ok(ips.length > 0); + assert.ok(ips.length > 0); - for (let i = 0; i < ips.length; i++) { - assert.ok(isIPv4(ips[i])); - } + for (let i = 0; i < ips.length; i++) { + assert.ok(isIPv4(ips[i])); + } - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_reverse_ipv4(done) { const req = dns.reverse('8.8.8.8', - common.mustCall((err, domains) => { - assert.ifError(err); + common.mustCall((err, domains) => { + assert.ifError(err); - assert.ok(domains.length > 0); + assert.ok(domains.length > 0); - for (let i = 0; i < domains.length; i++) { - assert.ok(domains[i]); - assert.ok(typeof domains[i] === 'string'); - } + for (let i = 0; i < domains.length; i++) { + assert.ok(domains[i]); + assert.ok(typeof domains[i] === 'string'); + } - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_ipv4_explicit(done) { const req = dns.lookup('www.google.com', 4, - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(net.isIPv4(ip)); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(net.isIPv4(ip)); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_ipv4_implicit(done) { const req = dns.lookup('www.google.com', - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(net.isIPv4(ip)); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(net.isIPv4(ip)); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); @@ -125,26 +125,26 @@ TEST(function test_lookup_ipv4_hint_addrconfig(done) { TEST(function test_lookup_ip_ipv4(done) { const req = dns.lookup('127.0.0.1', - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.strictEqual(ip, '127.0.0.1'); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.strictEqual(ip, '127.0.0.1'); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_localhost_ipv4(done) { const req = dns.lookup('localhost', 4, - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.strictEqual(ip, '127.0.0.1'); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.strictEqual(ip, '127.0.0.1'); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); @@ -164,21 +164,23 @@ TEST(function test_lookup_all_ipv4(done) { }); done(); - } - )); + }) + ); checkWrap(req); }); TEST(function test_lookupservice_ip_ipv4(done) { - const req = dns.lookupService('127.0.0.1', 80, + const req = dns.lookupService( + '127.0.0.1', 80, common.mustCall((err, host, service) => { assert.ifError(err); assert.strictEqual(typeof host, 'string'); assert(host); assert(['http', 'www', '80'].includes(service)); done(); - })); + }) + ); checkWrap(req); }); diff --git a/test/internet/test-dns-ipv6.js b/test/internet/test-dns-ipv6.js index b2cdd14c53a60c..34382660f24423 100644 --- a/test/internet/test-dns-ipv6.js +++ b/test/internet/test-dns-ipv6.js @@ -41,45 +41,45 @@ function checkWrap(req) { TEST(function test_resolve6(done) { const req = dns.resolve6('ipv6.google.com', - common.mustCall((err, ips) => { - assert.ifError(err); + common.mustCall((err, ips) => { + assert.ifError(err); - assert.ok(ips.length > 0); + assert.ok(ips.length > 0); - for (let i = 0; i < ips.length; i++) - assert.ok(isIPv6(ips[i])); + for (let i = 0; i < ips.length; i++) + assert.ok(isIPv6(ips[i])); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_reverse_ipv6(done) { const req = dns.reverse('2001:4860:4860::8888', - common.mustCall((err, domains) => { - assert.ifError(err); + common.mustCall((err, domains) => { + assert.ifError(err); - assert.ok(domains.length > 0); + assert.ok(domains.length > 0); - for (let i = 0; i < domains.length; i++) - assert.ok(typeof domains[i] === 'string'); + for (let i = 0; i < domains.length; i++) + assert.ok(typeof domains[i] === 'string'); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_ipv6_explicit(done) { const req = dns.lookup('ipv6.google.com', 6, - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(isIPv6(ip)); - assert.strictEqual(family, 6); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(isIPv6(ip)); + assert.strictEqual(family, 6); - done(); - })); + done(); + })); checkWrap(req); }); @@ -87,7 +87,7 @@ TEST(function test_lookup_ipv6_explicit(done) { /* This ends up just being too problematic to test TEST(function test_lookup_ipv6_implicit(done) { var req = dns.lookup('ipv6.google.com', function(err, ip, family) { - if (err) throw err; + assert.ifError(err); assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); @@ -142,13 +142,13 @@ TEST(function test_lookup_ipv6_hint(done) { TEST(function test_lookup_ip_ipv6(done) { const req = dns.lookup('::1', - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(isIPv6(ip)); - assert.strictEqual(family, 6); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(isIPv6(ip)); + assert.strictEqual(family, 6); - done(); - })); + done(); + })); checkWrap(req); }); @@ -169,14 +169,15 @@ TEST(function test_lookup_all_ipv6(done) { }); done(); - } - )); + }) + ); checkWrap(req); }); TEST(function test_lookupservice_ip_ipv6(done) { - const req = dns.lookupService('::1', 80, + const req = dns.lookupService( + '::1', 80, common.mustCall((err, host, service) => { if (err) { // Not skipping the test, rather checking an alternative result, @@ -188,7 +189,8 @@ TEST(function test_lookupservice_ip_ipv6(done) { assert(host); assert(['http', 'www', '80'].includes(service)); done(); - })); + }) + ); checkWrap(req); }); @@ -196,7 +198,7 @@ TEST(function test_lookupservice_ip_ipv6(done) { /* Disabled because it appears to be not working on linux. */ /* TEST(function test_lookup_localhost_ipv6(done) { var req = dns.lookup('localhost', 6, function(err, ip, family) { - if (err) throw err; + assert.ifError(err); assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index db3449dc727516..be3f9b0469ed2e 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -104,8 +104,7 @@ TEST(function test_resolve6_ttl(done) { TEST(function test_resolveMx(done) { var req = dns.resolveMx('gmail.com', function(err, result) { - if (err) throw err; - + assert.ifError(err); assert.ok(result.length > 0); for (var i = 0; i < result.length; i++) { @@ -140,8 +139,7 @@ TEST(function test_resolveMx_failure(done) { TEST(function test_resolveNs(done) { var req = dns.resolveNs('rackspace.com', function(err, names) { - if (err) throw err; - + assert.ifError(err); assert.ok(names.length > 0); for (var i = 0; i < names.length; i++) { @@ -171,8 +169,7 @@ TEST(function test_resolveNs_failure(done) { TEST(function test_resolveSrv(done) { var req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { - if (err) throw err; - + assert.ifError(err); assert.ok(result.length > 0); for (var i = 0; i < result.length; i++) { @@ -209,8 +206,7 @@ TEST(function test_resolveSrv_failure(done) { TEST(function test_resolvePtr(done) { var req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) { - if (err) throw err; - + assert.ifError(err); assert.ok(result.length > 0); for (var i = 0; i < result.length; i++) { @@ -240,8 +236,7 @@ TEST(function test_resolvePtr_failure(done) { TEST(function test_resolveNaptr(done) { var req = dns.resolveNaptr('sip2sip.info', function(err, result) { - if (err) throw err; - + assert.ifError(err); assert.ok(result.length > 0); for (var i = 0; i < result.length; i++) { @@ -278,8 +273,7 @@ TEST(function test_resolveNaptr_failure(done) { TEST(function test_resolveSoa(done) { var req = dns.resolveSoa('nodejs.org', function(err, result) { - if (err) throw err; - + assert.ifError(err); assert.ok(result); assert.strictEqual(typeof result, 'object'); @@ -325,8 +319,7 @@ TEST(function test_resolveSoa_failure(done) { TEST(function test_resolveCname(done) { var req = dns.resolveCname('www.microsoft.com', function(err, names) { - if (err) throw err; - + assert.ifError(err); assert.ok(names.length > 0); for (var i = 0; i < names.length; i++) { @@ -357,7 +350,7 @@ TEST(function test_resolveCname_failure(done) { TEST(function test_resolveTxt(done) { var req = dns.resolveTxt('google.com', function(err, records) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(records.length, 1); assert.ok(util.isArray(records[0])); assert.strictEqual(records[0][0].indexOf('v=spf1'), 0); @@ -398,7 +391,7 @@ TEST(function test_lookup_failure(done) { TEST(function test_lookup_null(done) { var req = dns.lookup(null, function(err, ip, family) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(ip, null); assert.strictEqual(family, 4); @@ -411,7 +404,7 @@ TEST(function test_lookup_null(done) { TEST(function test_lookup_ip_all(done) { var req = dns.lookup('127.0.0.1', {all: true}, function(err, ips, family) { - if (err) throw err; + assert.ifError(err); assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); assert.strictEqual(ips[0].address, '127.0.0.1'); @@ -426,7 +419,7 @@ TEST(function test_lookup_ip_all(done) { TEST(function test_lookup_null_all(done) { var req = dns.lookup(null, {all: true}, function(err, ips, family) { - if (err) throw err; + assert.ifError(err); assert.ok(Array.isArray(ips)); assert.strictEqual(ips.length, 0); @@ -439,7 +432,7 @@ TEST(function test_lookup_null_all(done) { TEST(function test_lookup_all_mixed(done) { var req = dns.lookup('www.google.com', {all: true}, function(err, ips) { - if (err) throw err; + assert.ifError(err); assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); diff --git a/test/internet/test-tls-add-ca-cert.js b/test/internet/test-tls-add-ca-cert.js new file mode 100644 index 00000000000000..05f3b4dc10e36c --- /dev/null +++ b/test/internet/test-tls-add-ca-cert.js @@ -0,0 +1,55 @@ +'use strict'; +const common = require('../common'); + +if (!common.hasCrypto) { + common.skip('missing crypto'); + return; +} + +// Test interaction of compiled-in CAs with user-provided CAs. + +const assert = require('assert'); +const fs = require('fs'); +const tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +const caCert = loadPEM('ca1-cert'); + +const opts = { + host: 'www.nodejs.org', + port: 443, + rejectUnauthorized: true +}; + +// Success relies on the compiled in well-known root CAs +tls.connect(opts, common.mustCall(end)); + +// The .ca option replaces the well-known roots, so connection fails. +opts.ca = caCert; +tls.connect(opts, fail).on('error', common.mustCall((err) => { + assert.strictEqual(err.message, 'unable to get local issuer certificate'); +})); + +function fail() { + assert(false, 'should fail to connect'); +} + +// New secure contexts have the well-known root CAs. +opts.secureContext = tls.createSecureContext(); +tls.connect(opts, common.mustCall(end)); + +// Explicit calls to addCACert() add to the default well-known roots, instead +// of replacing, so connection still succeeds. +opts.secureContext.context.addCACert(caCert); +tls.connect(opts, common.mustCall(end)); + +function end() { + this.end(); +} diff --git a/test/message/timeout_throw.js b/test/message/timeout_throw.js index 14291fabd12565..4008f306fe58be 100644 --- a/test/message/timeout_throw.js +++ b/test/message/timeout_throw.js @@ -4,4 +4,4 @@ require('../common'); setTimeout(function() { // eslint-disable-next-line no-undef undefined_reference_error_maker; -}); +}, 1); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index eb983345418637..3d2481ef4ec49b 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -64,7 +64,7 @@ assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), // deepEqual joy! // 7.2 assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14), - new Date(2000, 3, 14)), + new Date(2000, 3, 14)), 'deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'); assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), @@ -81,7 +81,7 @@ assert.doesNotThrow(makeBlock( a.notDeepEqual, new Date(), new Date(2000, 3, 14)), - 'notDeepEqual(new Date(), new Date(2000, 3, 14))' + 'notDeepEqual(new Date(), new Date(2000, 3, 14))' ); // 7.3 @@ -90,11 +90,16 @@ assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g)); assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i)); assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m)); assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm)); -assert.throws(makeBlock(a.deepEqual, /ab/, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/g, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/i, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/m, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im)); +assert.throws(makeBlock(a.deepEqual, /ab/, /a/), + /^AssertionError: \/ab\/ deepEqual \/a\/$/); +assert.throws(makeBlock(a.deepEqual, /a/g, /a/), + /^AssertionError: \/a\/g deepEqual \/a\/$/); +assert.throws(makeBlock(a.deepEqual, /a/i, /a/), + /^AssertionError: \/a\/i deepEqual \/a\/$/); +assert.throws(makeBlock(a.deepEqual, /a/m, /a/), + /^AssertionError: \/a\/m deepEqual \/a\/$/); +assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im), + /^AssertionError: \/a\/gim deepEqual \/a\/im$/); { const re1 = /a/; @@ -209,11 +214,26 @@ assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/g, /a/g)); assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/i, /a/i)); assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/m, /a/m)); assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/igm, /a/igm)); -assert.throws(makeBlock(a.deepStrictEqual, /ab/, /a/)); -assert.throws(makeBlock(a.deepStrictEqual, /a/g, /a/)); -assert.throws(makeBlock(a.deepStrictEqual, /a/i, /a/)); -assert.throws(makeBlock(a.deepStrictEqual, /a/m, /a/)); -assert.throws(makeBlock(a.deepStrictEqual, /a/igm, /a/im)); +assert.throws( + makeBlock(a.deepStrictEqual, /ab/, /a/), + /^AssertionError: \/ab\/ deepStrictEqual \/a\/$/ +); +assert.throws( + makeBlock(a.deepStrictEqual, /a/g, /a/), + /^AssertionError: \/a\/g deepStrictEqual \/a\/$/ +); +assert.throws( + makeBlock(a.deepStrictEqual, /a/i, /a/), + /^AssertionError: \/a\/i deepStrictEqual \/a\/$/ +); +assert.throws( + makeBlock(a.deepStrictEqual, /a/m, /a/), + /^AssertionError: \/a\/m deepStrictEqual \/a\/$/ +); +assert.throws( + makeBlock(a.deepStrictEqual, /a/igm, /a/im), + /^AssertionError: \/a\/gim deepStrictEqual \/a\/im$/ +); { const re1 = /a/; @@ -365,7 +385,7 @@ assert.doesNotThrow(function() { assert.ifError(); }); assert.throws(() => { assert.doesNotThrow(makeBlock(thrower, Error), 'user message'); }, /Got unwanted exception. user message/, - 'a.doesNotThrow ignores user message'); + 'a.doesNotThrow ignores user message'); // make sure that validating using constructor really works threw = false; @@ -489,7 +509,7 @@ testAssertionMessage({}, '{}'); testAssertionMessage(circular, '{ y: 1, x: [Circular] }'); testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }'); testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, - '{ a: NaN, b: Infinity, c: -Infinity }'); + '{ a: NaN, b: Infinity, c: -Infinity }'); // #2893 try { diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index 2245c9843a5edd..1426bd80ebc4ab 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -988,9 +988,7 @@ assert.throws(() => Buffer.from('', 'buffer'), TypeError); // Regression test for #6111. Constructing a buffer from another buffer // should a) work, and b) not corrupt the source buffer. { - let a = [0]; - for (let i = 0; i < 7; ++i) a = a.concat(a); - a = a.map((_, i) => { return i; }); + const a = [...Array(128).keys()]; // [0, 1, 2, 3, ... 126, 127] const b = Buffer.from(a); const c = Buffer.from(b); assert.strictEqual(b.length, a.length); diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index eecb14abb06001..8cfeeabe91eebe 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -184,20 +184,20 @@ deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, -1]), [0, 0, 0, 0]); assert.throws(() => buf1.fill(0, -1), /^RangeError: Out of range index$/); assert.throws(() => buf1.fill(0, 0, buf1.length + 1), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); assert.throws(() => buf1.fill('', -1), /^RangeError: Out of range index$/); assert.throws(() => buf1.fill('', 0, buf1.length + 1), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); assert.throws(() => buf1.fill('a', 0, buf1.length, 'node rocks!'), - /^TypeError: Unknown encoding: node rocks!$/); + /^TypeError: Unknown encoding: node rocks!$/); assert.throws(() => buf1.fill('a', 0, 0, NaN), - /^TypeError: encoding must be a string$/); + /^TypeError: encoding must be a string$/); assert.throws(() => buf1.fill('a', 0, 0, null), - /^TypeError: encoding must be a string$/); + /^TypeError: encoding must be a string$/); assert.throws(() => buf1.fill('a', 0, 0, 'foo'), /^TypeError: Unknown encoding: foo$/); @@ -271,10 +271,10 @@ function testBufs(string, offset, length, encoding) { // Make sure these throw. assert.throws(() => Buffer.allocUnsafe(8).fill('a', -1), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); assert.throws(() => Buffer.allocUnsafe(8).fill('a', 0, 9), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); // Make sure this doesn't hang indefinitely. Buffer.allocUnsafe(8).fill(''); diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 22ba1e6b7e1735..15e1eedeb54d15 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -159,10 +159,10 @@ assert( 6, mixedByteStringUcs2.includes(Buffer.from('bc', 'ucs2'), 0, 'ucs2')); assert( 10, mixedByteStringUcs2.includes(Buffer.from('\u03a3', 'ucs2'), - 0, 'ucs2')); + 0, 'ucs2')); assert( -1, mixedByteStringUcs2.includes(Buffer.from('\u0396', 'ucs2'), - 0, 'ucs2')); + 0, 'ucs2')); twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); diff --git a/test/parallel/test-buffer-read-noassert.js b/test/parallel/test-buffer-read-noassert.js new file mode 100644 index 00000000000000..83d533a32031cb --- /dev/null +++ b/test/parallel/test-buffer-read-noassert.js @@ -0,0 +1,59 @@ +'use strict'; +require('../common'); +const assert = require('assert'); + +// testing basic buffer read functions +const buf = Buffer.from([0xa4, 0xfd, 0x48, 0xea, 0xcf, 0xff, 0xd9, 0x01, 0xde]); + +function read(buff, funx, args, expected) { + + assert.strictEqual(buff[funx](...args), expected); + assert.throws( + () => buff[funx](-1), + /^RangeError: Index out of range$/ + ); + + assert.doesNotThrow( + () => assert.strictEqual(buff[funx](...args, true), expected), + 'noAssert does not change return value for valid ranges' +); + +} + +// testing basic functionality of readDoubleBE() and readDOubleLE() +read(buf, 'readDoubleBE', [1], -3.1827727774563287e+295); +read(buf, 'readDoubleLE', [1], -6.966010051009108e+144); + +// testing basic functionality of readFLoatBE() and readFloatLE() +read(buf, 'readFloatBE', [1], -1.6691549692541768e+37); +read(buf, 'readFloatLE', [1], -7861303808); + +// testing basic functionality of readInt8() +read(buf, 'readInt8', [1], -3); + +// testing basic functionality of readInt16BE() and readInt16LE() +read(buf, 'readInt16BE', [1], -696); +read(buf, 'readInt16LE', [1], 0x48fd); + +// testing basic functionality of readInt32BE() and readInt32LE() +read(buf, 'readInt32BE', [1], -45552945); +read(buf, 'readInt32LE', [1], -806729475); + +// testing basic functionality of readIntBE() and readIntLE() +read(buf, 'readIntBE', [1, 1], -3); +read(buf, 'readIntLE', [2, 1], 0x48); + +// testing basic functionality of readUInt8() +read(buf, 'readUInt8', [1], 0xfd); + +// testing basic functionality of readUInt16BE() and readUInt16LE() +read(buf, 'readUInt16BE', [2], 0x48ea); +read(buf, 'readUInt16LE', [2], 0xea48); + +// testing basic functionality of readUInt32BE() and readUInt32LE() +read(buf, 'readUInt32BE', [1], 0xfd48eacf); +read(buf, 'readUInt32LE', [1], 0xcfea48fd); + +// testing basic functionality of readUIntBE() and readUIntLE() +read(buf, 'readUIntBE', [2, 0], 0xfd); +read(buf, 'readUIntLE', [2, 0], 0x48); diff --git a/test/parallel/test-buffer-readuintbe.js b/test/parallel/test-buffer-readuintbe.js deleted file mode 100644 index 162e9fea27a14f..00000000000000 --- a/test/parallel/test-buffer-readuintbe.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; -require('../common'); -const assert = require('assert'); - -// testing basic functionality of readUIntBE() - -const buf = Buffer.from([42, 84, 168, 127]); -const result = buf.readUIntBE(2); - -assert.strictEqual(result, 84); - -assert.throws( - () => { - buf.readUIntBE(5); - }, - /Index out of range/ -); - -assert.doesNotThrow( - () => { - buf.readUIntBE(5, 0, true); - }, - 'readUIntBE() should not throw if noAssert is true' -); diff --git a/test/parallel/test-buffer-readuintle.js b/test/parallel/test-buffer-readuintle.js deleted file mode 100644 index 982adb8607eaa1..00000000000000 --- a/test/parallel/test-buffer-readuintle.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; -require('../common'); -const assert = require('assert'); - -// testing basic functionality of readUIntLE() - -const buf = Buffer.from([42, 84, 168, 127]); -const result = buf.readUIntLE(2); - -assert.strictEqual(result, 168); - -assert.throws( - () => { - buf.readUIntLE(5); - }, - /Index out of range/ -); - -assert.doesNotThrow( - () => { - buf.readUIntLE(5, 0, true); - }, - 'readUIntLE() should not throw if noAssert is true' -); diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js index 2489420c33e6e9..b43654b952de0b 100644 --- a/test/parallel/test-buffer-slice.js +++ b/test/parallel/test-buffer-slice.js @@ -8,54 +8,54 @@ assert.strictEqual(0, Buffer('hello', 'utf8').slice(0, 0).length); const buf = Buffer.from('0123456789', 'utf8'); assert.strictEqual(0, Buffer.compare(buf.slice(-10, 10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-20, 10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-20, -10), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, 0), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(undefined), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('foobar'), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(undefined, undefined), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(2), - Buffer.from('23456789', 'utf8'))); + Buffer.from('23456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(5), - Buffer.from('56789', 'utf8'))); + Buffer.from('56789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(10), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(5, 8), - Buffer.from('567', 'utf8'))); + Buffer.from('567', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(8, -1), - Buffer.from('8', 'utf8'))); + Buffer.from('8', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, -9), - Buffer.from('0', 'utf8'))); + Buffer.from('0', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, -10), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, -1), - Buffer.from('012345678', 'utf8'))); + Buffer.from('012345678', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(2, -2), - Buffer.from('234567', 'utf8'))); + Buffer.from('234567', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, 65536), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(65536, 0), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-5, -8), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-5, -3), - Buffer.from('56', 'utf8'))); + Buffer.from('56', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-10, 10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); for (let i = 0, s = buf; i < buf.length; ++i) { assert.strictEqual(0, Buffer.compare(buf.slice(i), s.slice(i))); assert.strictEqual(0, Buffer.compare(buf.slice(0, i), s.slice(0, i))); @@ -67,19 +67,19 @@ const utf16Buf = Buffer.from('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); assert.strictEqual(0, Buffer.compare(buf.slice('0', '1'), - Buffer.from('0', 'utf8'))); + Buffer.from('0', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-5', '10'), - Buffer.from('56789', 'utf8'))); + Buffer.from('56789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-10', '10'), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-10', '-5'), - Buffer.from('01234', 'utf8'))); + Buffer.from('01234', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-10', '-0'), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('111'), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('0', '-111'), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); // try to slice a zero length Buffer // see https://github.com/joyent/node/issues/5881 diff --git a/test/parallel/test-child-process-fork-dgram.js b/test/parallel/test-child-process-fork-dgram.js index 8bdf006a743e0d..b25cf07ef6ff81 100644 --- a/test/parallel/test-child-process-fork-dgram.js +++ b/test/parallel/test-child-process-fork-dgram.js @@ -76,7 +76,7 @@ if (process.argv[2] === 'child') { serverPort, '127.0.0.1', function(err) { - if (err) throw err; + assert.ifError(err); } ); } diff --git a/test/parallel/test-child-process-spawnsync-shell.js b/test/parallel/test-child-process-spawnsync-shell.js index 620a01c4532203..fc42d56d105eaf 100644 --- a/test/parallel/test-child-process-spawnsync-shell.js +++ b/test/parallel/test-child-process-spawnsync-shell.js @@ -35,3 +35,59 @@ const env = cp.spawnSync(`"${process.execPath}" -pe process.env.BAZ`, { }); assert.strictEqual(env.stdout.toString().trim(), 'buzz'); + +// Verify that the shell internals work properly across platforms. +{ + const originalComspec = process.env.comspec; + + // Enable monkey patching process.platform. + const originalPlatform = process.platform; + let platform = null; + Object.defineProperty(process, 'platform', { get: () => platform }); + + function test(testPlatform, shell, shellOutput) { + platform = testPlatform; + + const cmd = 'not_a_real_command'; + const shellFlags = platform === 'win32' ? ['/d', '/s', '/c'] : ['-c']; + const outputCmd = platform === 'win32' ? `"${cmd}"` : cmd; + const windowsVerbatim = platform === 'win32' ? true : undefined; + const result = cp.spawnSync(cmd, { shell }); + + assert.strictEqual(result.file, shellOutput); + assert.deepStrictEqual(result.args, + [shellOutput, ...shellFlags, outputCmd]); + assert.strictEqual(result.options.shell, shell); + assert.strictEqual(result.options.file, result.file); + assert.deepStrictEqual(result.options.args, result.args); + assert.strictEqual(result.options.windowsVerbatimArguments, + windowsVerbatim); + } + + // Test Unix platforms with the default shell. + test('darwin', true, '/bin/sh'); + + // Test Unix platforms with a user specified shell. + test('darwin', '/bin/csh', '/bin/csh'); + + // Test Android platforms. + test('android', true, '/system/bin/sh'); + + // Test Windows platforms with a user specified shell. + test('win32', 'powershell.exe', 'powershell.exe'); + + // Test Windows platforms with the default shell and no comspec. + delete process.env.comspec; + test('win32', true, 'cmd.exe'); + + // Test Windows platforms with the default shell and a comspec value. + process.env.comspec = 'powershell.exe'; + test('win32', true, process.env.comspec); + + // Restore the original value of process.platform. + platform = originalPlatform; + + // Restore the original comspec environment variable if necessary. + if (originalComspec) + process.env.comspec = originalComspec; +} diff --git a/test/parallel/test-child-process-uid-gid.js b/test/parallel/test-child-process-uid-gid.js index 1ee7661227701e..ec2cb9a31956c1 100644 --- a/test/parallel/test-child-process-uid-gid.js +++ b/test/parallel/test-child-process-uid-gid.js @@ -2,18 +2,16 @@ const common = require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; - -if (!common.isWindows && process.getuid() === 0) { - common.skip('as this test should not be run as `root`'); - return; -} - const expectedError = common.isWindows ? /\bENOTSUP\b/ : /\bEPERM\b/; -assert.throws(() => { - spawn('echo', ['fhqwhgads'], {uid: 0}); -}, expectedError); +if (common.isWindows || process.getuid() !== 0) { + assert.throws(() => { + spawn('echo', ['fhqwhgads'], {uid: 0}); + }, expectedError); +} -assert.throws(() => { - spawn('echo', ['fhqwhgads'], {gid: 0}); -}, expectedError); +if (common.isWindows || !process.getgroups().some((gid) => gid === 0)) { + assert.throws(() => { + spawn('echo', ['fhqwhgads'], {gid: 0}); + }, expectedError); +} diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 0198a0f1beda48..8db7ad30872223 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -18,27 +18,27 @@ var filename = __filename.replace(/\\/g, '/'); // assert that nothing is written to stdout child.exec(nodejs + ' --eval 42', - function(err, stdout, stderr) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); + }); // assert that "42\n" is written to stderr child.exec(nodejs + ' --eval "console.error(42)"', - function(err, stdout, stderr) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, '42\n'); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, '42\n'); + }); // assert that the expected output is written to stdout ['--print', '-p -e', '-pe', '-p'].forEach(function(s) { var cmd = nodejs + ' ' + s + ' '; child.exec(cmd + '42', - function(err, stdout, stderr) { - assert.strictEqual(stdout, '42\n'); - assert.strictEqual(stderr, ''); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, '42\n'); + assert.strictEqual(stderr, ''); + }); child.exec(cmd + "'[]'", common.mustCall( function(err, stdout, stderr) { @@ -49,22 +49,22 @@ child.exec(nodejs + ' --eval "console.error(42)"', // assert that module loading works child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', - function(status, stdout, stderr) { - assert.strictEqual(status.code, 42); - }); + function(status, stdout, stderr) { + assert.strictEqual(status.code, 42); + }); // Check that builtin modules are pre-defined. child.exec(nodejs + ' --print "os.platform()"', - function(status, stdout, stderr) { - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout.trim(), require('os').platform()); - }); + function(status, stdout, stderr) { + assert.strictEqual(stderr, ''); + assert.strictEqual(stdout.trim(), require('os').platform()); + }); // module path resolve bug, regression test child.exec(nodejs + ' --eval "require(\'./test/parallel/test-cli-eval.js\')"', - function(status, stdout, stderr) { - assert.strictEqual(status.code, 42); - }); + function(status, stdout, stderr) { + assert.strictEqual(status.code, 42); + }); // Missing argument should not crash child.exec(nodejs + ' -e', common.mustCall(function(status, stdout, stderr) { @@ -80,24 +80,25 @@ child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { // "\\-42" should be interpreted as an escaped expression, not a switch child.exec(nodejs + ' -p "\\-42"', - function(err, stdout, stderr) { - assert.strictEqual(stdout, '-42\n'); - assert.strictEqual(stderr, ''); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, '-42\n'); + assert.strictEqual(stderr, ''); + }); child.exec(nodejs + ' --use-strict -p process.execArgv', - function(status, stdout, stderr) { - assert.strictEqual(stdout, - "[ '--use-strict', '-p', 'process.execArgv' ]\n"); - }); + function(status, stdout, stderr) { + assert.strictEqual( + stdout, "[ '--use-strict', '-p', 'process.execArgv' ]\n" + ); + }); // Regression test for https://github.com/nodejs/node/issues/3574 const emptyFile = path.join(common.fixturesDir, 'empty.js'); child.exec(nodejs + ` -e 'require("child_process").fork("${emptyFile}")'`, - function(status, stdout, stderr) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); + function(status, stdout, stderr) { + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); + }); // Regression test for https://github.com/nodejs/node/issues/8534. { diff --git a/test/parallel/test-cluster-worker-deprecated.js b/test/parallel/test-cluster-worker-deprecated.js new file mode 100644 index 00000000000000..2f433aae797ccc --- /dev/null +++ b/test/parallel/test-cluster-worker-deprecated.js @@ -0,0 +1,18 @@ +'use strict'; +require('../common'); + +const assert = require('assert'); +const cluster = require('cluster'); + +const worker = new cluster.Worker(); + +assert.strictEqual(worker.exitedAfterDisconnect, undefined); +assert.strictEqual(worker.suicide, undefined); + +worker.exitedAfterDisconnect = 'recommended'; +assert.strictEqual(worker.exitedAfterDisconnect, 'recommended'); +assert.strictEqual(worker.suicide, 'recommended'); + +worker.suicide = 'deprecated'; +assert.strictEqual(worker.exitedAfterDisconnect, 'deprecated'); +assert.strictEqual(worker.suicide, 'deprecated'); diff --git a/test/parallel/test-cluster-worker-exit.js b/test/parallel/test-cluster-worker-exit.js index 1c0ec509c468ad..1cd7b1d0f222c7 100644 --- a/test/parallel/test-cluster-worker-exit.js +++ b/test/parallel/test-cluster-worker-exit.js @@ -32,8 +32,9 @@ if (cluster.isWorker) { worker_emitExit: [1, "the worker did not emit 'exit'"], worker_state: ['disconnected', 'the worker state is incorrect'], worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], - worker_exitedAfterDisconnect: [false, - 'the .exitedAfterDisconnect flag is incorrect'], + worker_exitedAfterDisconnect: [ + false, 'the .exitedAfterDisconnect flag is incorrect' + ], worker_died: [true, 'the worker is still running'], worker_exitCode: [EXIT_CODE, 'the worker exited w/ incorrect exitCode'], worker_signalCode: [null, 'the worker exited w/ incorrect signalCode'] diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index 5ffe2c351503c1..59485eec4a327f 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -5,3 +5,11 @@ var assert = require('assert'); common.globalCheck = false; global.gc = 42; // Not a valid global unless --expose_gc is set. assert.deepStrictEqual(common.leakedGlobals(), ['gc']); + +assert.throws(function() { + common.mustCall(function() {}, 'foo'); +}, /^TypeError: Invalid expected value: foo$/); + +assert.throws(function() { + common.mustCall(function() {}, /foo/); +}, /^TypeError: Invalid expected value: \/foo\/$/); diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index 4bed5aa665b64d..245783fb1b4275 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -312,7 +312,7 @@ const ciphers = crypto.getCiphers(); for (const i in TEST_CASES) { const test = TEST_CASES[i]; - if (ciphers.indexOf(test.algo) === -1) { + if (!ciphers.includes(test.algo)) { common.skip('unsupported ' + test.algo + ' test'); continue; } @@ -324,7 +324,8 @@ for (const i in TEST_CASES) { { const encrypt = crypto.createCipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); if (test.aad) encrypt.setAAD(Buffer.from(test.aad, 'hex')); @@ -342,7 +343,8 @@ for (const i in TEST_CASES) { { const decrypt = crypto.createDecipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) decrypt.setAAD(Buffer.from(test.aad, 'hex')); @@ -401,7 +403,8 @@ for (const i in TEST_CASES) { { // trying to get tag before inputting all data: const encrypt = crypto.createCipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); encrypt.update('blah', 'ascii'); assert.throws(function() { encrypt.getAuthTag(); }, / state/); } @@ -409,7 +412,8 @@ for (const i in TEST_CASES) { { // trying to set tag on encryption object: const encrypt = crypto.createCipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, / state/); } @@ -417,7 +421,8 @@ for (const i in TEST_CASES) { { // trying to read tag from decryption object: const decrypt = crypto.createDecipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); assert.throws(function() { decrypt.getAuthTag(); }, / state/); } diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index 9e212443453203..79353ede3b49dc 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -109,9 +109,9 @@ h3.digest(); assert.throws(function() { h3.digest(); }, - /Digest already called/); + /Digest already called/); assert.throws(function() { h3.update('foo'); }, - /Digest already called/); + /Digest already called/); diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index 5307ea4f6f9e05..eeb8cd152567f8 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -8,6 +8,14 @@ if (!common.hasCrypto) { } var crypto = require('crypto'); +// Test for binding layer robustness +{ + const binding = process.binding('crypto'); + const h = new binding.Hmac(); + // Fail to init the Hmac with an algorithm. + assert.throws(() => h.update('hello'), /^TypeError: HmacUpdate fail$/); +} + // Test HMAC var h1 = crypto.createHmac('sha1', 'Node') .update('some data') @@ -115,7 +123,7 @@ var rfc4231 = [ key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), + 'hex'), hmac: { sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', sha256: @@ -132,10 +140,10 @@ var rfc4231 = [ }, { key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), + 'hex'), data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', - 'hex'), + 'hex'), hmac: { sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', sha256: @@ -256,16 +264,16 @@ var rfc2202_md5 = [ key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), + 'hex'), hmac: '56be34521d144c88dbb8c733f0e8b3f6' }, { key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), + 'hex'), data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', - 'hex'), + 'hex'), hmac: '697eaf0aca3a3aea3a75164746ffaa79' }, { @@ -278,7 +286,7 @@ var rfc2202_md5 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' }, @@ -287,7 +295,7 @@ var rfc2202_md5 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', @@ -310,16 +318,16 @@ var rfc2202_sha1 = [ data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddd' + 'dddddddddd', - 'hex'), + 'hex'), hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' }, { key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), + 'hex'), data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', - 'hex'), + 'hex'), hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' }, { @@ -332,7 +340,7 @@ var rfc2202_sha1 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' }, @@ -341,7 +349,7 @@ var rfc2202_sha1 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', diff --git a/test/parallel/test-crypto-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js index e835867d61d005..7fd2e98de617cf 100644 --- a/test/parallel/test-crypto-padding-aes256.js +++ b/test/parallel/test-crypto-padding-aes256.js @@ -11,18 +11,18 @@ var crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'buffer'; function aes256(decipherFinal) { - var iv = Buffer.from('00000000000000000000000000000000', 'hex'); - var key = Buffer.from('0123456789abcdef0123456789abcdef' + - '0123456789abcdef0123456789abcdef', 'hex'); + const iv = Buffer.from('00000000000000000000000000000000', 'hex'); + const key = Buffer.from('0123456789abcdef0123456789abcdef' + + '0123456789abcdef0123456789abcdef', 'hex'); function encrypt(val, pad) { - var c = crypto.createCipheriv('aes256', key, iv); + const c = crypto.createCipheriv('aes256', key, iv); c.setAutoPadding(pad); return c.update(val, 'utf8', 'latin1') + c.final('latin1'); } function decrypt(val, pad) { - var c = crypto.createDecipheriv('aes256', key, iv); + const c = crypto.createDecipheriv('aes256', key, iv); c.setAutoPadding(pad); return c.update(val, 'latin1', 'utf8') + c[decipherFinal]('utf8'); } @@ -30,10 +30,10 @@ function aes256(decipherFinal) { // echo 0123456789abcdef0123456789abcdef \ // | openssl enc -e -aes256 -nopad -K -iv \ // | openssl enc -d -aes256 -nopad -K -iv - var plaintext = '0123456789abcdef0123456789abcdef'; // multiple of block size - var encrypted = encrypt(plaintext, false); - var decrypted = decrypt(encrypted, false); - assert.equal(decrypted, plaintext); + let plaintext = '0123456789abcdef0123456789abcdef'; // multiple of block size + let encrypted = encrypt(plaintext, false); + let decrypted = decrypt(encrypted, false); + assert.strictEqual(decrypted, plaintext); // echo 0123456789abcdef0123456789abcde \ // | openssl enc -e -aes256 -K -iv \ @@ -41,7 +41,7 @@ function aes256(decipherFinal) { plaintext = '0123456789abcdef0123456789abcde'; // not a multiple encrypted = encrypt(plaintext, true); decrypted = decrypt(encrypted, true); - assert.equal(decrypted, plaintext); + assert.strictEqual(decrypted, plaintext); } aes256('final'); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 396717ef742a95..118117547cae32 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -14,15 +14,15 @@ var crypto = require('crypto'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', - 'ascii'); + 'ascii'); var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', - 'ascii'); + 'ascii'); var rsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_encrypted.pem', 'ascii'); var dsaPubPem = fs.readFileSync(common.fixturesDir + '/test_dsa_pubkey.pem', - 'ascii'); + 'ascii'); var dsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_dsa_privkey.pem', - 'ascii'); + 'ascii'); var dsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index 13401e4ac594ab..2e94397c8f22f9 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -53,23 +53,33 @@ assert.throws(function() { }, /^TypeError: Data must be a string or a buffer$/); -function assertSorted(list) { +function validateList(list) { + // The list must not be empty + assert(list.length > 0); + + // The list should be sorted. // Array#sort() modifies the list in place so make a copy. - const sorted = list.slice().sort(); + const sorted = [...list].sort(); assert.deepStrictEqual(list, sorted); + + // Each element should be unique. + assert.strictEqual([...new Set(list)].length, list.length); + + // Each element should be a string. + assert(list.every((value) => typeof value === 'string')); } // Assume that we have at least AES-128-CBC. -assert.notStrictEqual(0, crypto.getCiphers().length); +const cryptoCiphers = crypto.getCiphers(); assert(crypto.getCiphers().includes('aes-128-cbc')); -assert(!crypto.getCiphers().includes('AES-128-CBC')); -assertSorted(crypto.getCiphers()); +validateList(cryptoCiphers); // Assume that we have at least AES256-SHA. -assert.notStrictEqual(0, tls.getCiphers().length); +const tlsCiphers = tls.getCiphers(); assert(tls.getCiphers().includes('aes256-sha')); -assert(!tls.getCiphers().includes('AES256-SHA')); -assertSorted(tls.getCiphers()); +// There should be no capital letters in any element. +assert(tlsCiphers.every((value) => /^[^A-Z]+$/.test(value))); +validateList(tlsCiphers); // Assert that we have sha and sha1 but not SHA and SHA1. assert.notStrictEqual(0, crypto.getHashes().length); @@ -79,13 +89,27 @@ assert(!crypto.getHashes().includes('SHA1')); assert(!crypto.getHashes().includes('SHA')); assert(crypto.getHashes().includes('RSA-SHA1')); assert(!crypto.getHashes().includes('rsa-sha1')); -assertSorted(crypto.getHashes()); +validateList(crypto.getHashes()); // Assume that we have at least secp384r1. assert.notStrictEqual(0, crypto.getCurves().length); assert(crypto.getCurves().includes('secp384r1')); assert(!crypto.getCurves().includes('SECP384R1')); -assertSorted(crypto.getCurves()); +validateList(crypto.getCurves()); + +// Modifying return value from get* functions should not mutate subsequent +// return values. +function testImmutability(fn) { + const list = fn(); + const copy = [...list]; + list.push('some-arbitrary-value'); + assert.deepStrictEqual(fn(), copy); +} + +testImmutability(crypto.getCiphers); +testImmutability(tls.getCiphers); +testImmutability(crypto.getHashes); +testImmutability(crypto.getCurves); // Regression tests for #5725: hex input that's not a power of two should // throw, not assert in C++ land. diff --git a/test/parallel/test-dgram-sendto.js b/test/parallel/test-dgram-sendto.js new file mode 100644 index 00000000000000..350f488f12af0d --- /dev/null +++ b/test/parallel/test-dgram-sendto.js @@ -0,0 +1,24 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const dgram = require('dgram'); +const socket = dgram.createSocket('udp4'); + +const errorMessage = + /^Error: Send takes "offset" and "length" as args 2 and 3$/; + +assert.throws(() => { + socket.sendto(); +}, errorMessage); + +assert.throws(() => { + socket.sendto('buffer', 1, 'offset', 'port', 'address', 'cb'); +}, errorMessage); + +assert.throws(() => { + socket.sendto('buffer', 'offset', 1, 'port', 'address', 'cb'); +}, errorMessage); + +assert.throws(() => { + socket.sendto('buffer', 1, 1, 10, false, 'cb'); +}, /^Error: udp4 sockets must send to port, address$/); diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js index 9ee2e9f974f625..27b9b81d7d14a2 100644 --- a/test/parallel/test-dns.js +++ b/test/parallel/test-dns.js @@ -112,7 +112,7 @@ assert.doesNotThrow(() => dns.lookup(NaN, noop)); */ assert.throws(() => { dns.lookup('www.google.com', { hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1 }, - noop); + noop); }, /^TypeError: Invalid argument: hints must use valid flags$/); assert.throws(() => dns.lookup('www.google.com'), diff --git a/test/parallel/test-domain-implicit-fs.js b/test/parallel/test-domain-implicit-fs.js index a92653aff1de1c..01a7026ac9bad4 100644 --- a/test/parallel/test-domain-implicit-fs.js +++ b/test/parallel/test-domain-implicit-fs.js @@ -31,7 +31,7 @@ d.run(function() { var fs = require('fs'); fs.readdir(__dirname, function() { fs.open('this file does not exist', 'r', function(er) { - if (er) throw er; + assert.ifError(er); throw new Error('should not get here!'); }); }); diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.js new file mode 100644 index 00000000000000..6a3a670b9204c2 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.js @@ -0,0 +1,18 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + throw new Error('boom!'); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js new file mode 100644 index 00000000000000..e32245176571ef --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js @@ -0,0 +1,21 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.run(function() { + d2.run(function() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js new file mode 100644 index 00000000000000..ff0fd5eec35f6b --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + setTimeout(function() { + throw new Error('boom!'); + }, 1); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js new file mode 100644 index 00000000000000..cbe5f3ed8dc4a1 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + setImmediate(function() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js new file mode 100644 index 00000000000000..4d0dd39454d2b2 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + process.nextTick(function() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js new file mode 100644 index 00000000000000..78ef3662a20229 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js @@ -0,0 +1,21 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + var fs = require('fs'); + fs.exists('/non/existing/file', function onExists() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js new file mode 100644 index 00000000000000..c3a91379319db5 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + setTimeout(function() { + throw new Error('boom!'); + }, 1); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js new file mode 100644 index 00000000000000..9debc754cea3d1 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + setImmediate(function() { + throw new Error('boom!'); + }); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js new file mode 100644 index 00000000000000..f1670cbd300bdf --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + process.nextTick(function() { + throw new Error('boom!'); + }); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js new file mode 100644 index 00000000000000..a4eebd50e96388 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js @@ -0,0 +1,27 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + var fs = require('fs'); + fs.exists('/non/existing/file', function onExists() { + throw new Error('boom!'); + }); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught.js deleted file mode 100644 index 833e7374d7f2ab..00000000000000 --- a/test/parallel/test-domain-no-error-handler-abort-on-uncaught.js +++ /dev/null @@ -1,168 +0,0 @@ -'use strict'; - -/* - * This test makes sure that when using --abort-on-uncaught-exception and - * when throwing an error from within a domain that does not have an error - * handler setup, the process aborts. - */ -const common = require('../common'); -const assert = require('assert'); -const domain = require('domain'); -const child_process = require('child_process'); - -const tests = [ - function() { - const d = domain.create(); - - d.run(function() { - throw new Error('boom!'); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.run(function() { - d2.run(function() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - setTimeout(function() { - throw new Error('boom!'); - }, 1); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - setImmediate(function() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - process.nextTick(function() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - var fs = require('fs'); - fs.exists('/non/existing/file', function onExists() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - setTimeout(function() { - throw new Error('boom!'); - }, 1); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - setImmediate(function() { - throw new Error('boom!'); - }); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - process.nextTick(function() { - throw new Error('boom!'); - }); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - var fs = require('fs'); - fs.exists('/non/existing/file', function onExists() { - throw new Error('boom!'); - }); - }); - }); - }, -]; - -if (process.argv[2] === 'child') { - const testIndex = +process.argv[3]; - tests[testIndex](); -} else { - - tests.forEach(function(test, testIndex) { - var testCmd = ''; - if (!common.isWindows) { - // Do not create core files, as it can take a lot of disk space on - // continuous testing and developers' machines - testCmd += 'ulimit -c 0 && '; - } - - testCmd += process.argv[0]; - testCmd += ' ' + '--abort-on-uncaught-exception'; - testCmd += ' ' + process.argv[1]; - testCmd += ' ' + 'child'; - testCmd += ' ' + testIndex; - - var child = child_process.exec(testCmd); - - child.on('exit', function onExit(exitCode, signal) { - const errMsg = 'Test at index ' + testIndex + ' should have aborted ' + - 'but instead exited with exit code ' + exitCode + - ' and signal ' + signal; - assert(common.nodeProcessAborted(exitCode, signal), errMsg); - }); - }); -} diff --git a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js index fc6a93ccdca8ef..a45f7d17a83a2c 100644 --- a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js +++ b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js @@ -49,22 +49,23 @@ if (process.argv[2] === 'child') { } function runTestWithoutAbortOnUncaughtException() { - child_process.exec(createTestCmdLine(), - function onTestDone(err, stdout, stderr) { - // When _not_ passing --abort-on-uncaught-exception, the process' - // uncaughtException handler _must_ be called, and thus the error - // message must include only the message of the error thrown from the - // process' uncaughtException handler. - assert(stderr.includes(uncaughtExceptionHandlerErrMsg), - 'stderr output must include proper uncaughtException ' + - 'handler\'s error\'s message'); - assert(!stderr.includes(domainErrMsg), 'stderr output must not ' + - 'include domain\'s error\'s message'); - - assert.notEqual(err.code, 0, - 'child process should have exited with a non-zero ' + - 'exit code, but did not'); - }); + child_process.exec( + createTestCmdLine(), + function onTestDone(err, stdout, stderr) { + // When _not_ passing --abort-on-uncaught-exception, the process' + // uncaughtException handler _must_ be called, and thus the error + // message must include only the message of the error thrown from the + // process' uncaughtException handler. + assert(stderr.includes(uncaughtExceptionHandlerErrMsg), + 'stderr output must include proper uncaughtException ' + + 'handler\'s error\'s message'); + assert(!stderr.includes(domainErrMsg), + 'stderr output must not include domain\'s error\'s message'); + assert.notStrictEqual(err.code, 0, + 'child process should have exited with a ' + + 'non-zero exit code, but did not'); + } + ); } function runTestWithAbortOnUncaughtException() { diff --git a/test/parallel/test-env-var-no-warnings.js b/test/parallel/test-env-var-no-warnings.js new file mode 100644 index 00000000000000..53b7d302683cf4 --- /dev/null +++ b/test/parallel/test-env-var-no-warnings.js @@ -0,0 +1,41 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const cp = require('child_process'); + +if (process.argv[2] === 'child') { + process.emitWarning('foo'); +} else { + function test(env) { + const cmd = `${process.execPath} ${__filename} child`; + + cp.exec(cmd, { env }, common.mustCall((err, stdout, stderr) => { + assert.strictEqual(err, null); + assert.strictEqual(stdout, ''); + + if (env.NODE_NO_WARNINGS === '1') + assert.strictEqual(stderr, ''); + else + assert(/Warning: foo$/.test(stderr.trim())); + })); + } + + test({}); + test(process.env); + test({ NODE_NO_WARNINGS: undefined }); + test({ NODE_NO_WARNINGS: null }); + test({ NODE_NO_WARNINGS: 'foo' }); + test({ NODE_NO_WARNINGS: true }); + test({ NODE_NO_WARNINGS: false }); + test({ NODE_NO_WARNINGS: {} }); + test({ NODE_NO_WARNINGS: [] }); + test({ NODE_NO_WARNINGS: function() {} }); + test({ NODE_NO_WARNINGS: 0 }); + test({ NODE_NO_WARNINGS: -1 }); + test({ NODE_NO_WARNINGS: '0' }); + test({ NODE_NO_WARNINGS: '01' }); + test({ NODE_NO_WARNINGS: '2' }); + // Don't test the number 1 because it will come through as a string in the + // the child process environment. + test({ NODE_NO_WARNINGS: '1' }); +} diff --git a/test/parallel/test-event-emitter-modify-in-emit.js b/test/parallel/test-event-emitter-modify-in-emit.js index 7864438fff4df6..c13fad4347d617 100644 --- a/test/parallel/test-event-emitter-modify-in-emit.js +++ b/test/parallel/test-event-emitter-modify-in-emit.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const events = require('events'); -var callbacks_called = []; +let callbacks_called = []; const e = new events.EventEmitter(); @@ -25,27 +25,27 @@ function callback3() { } e.on('foo', callback1); -assert.equal(1, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 1); e.emit('foo'); -assert.equal(2, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 2); assert.deepStrictEqual(['callback1'], callbacks_called); e.emit('foo'); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 0); assert.deepStrictEqual(['callback1', 'callback2', 'callback3'], callbacks_called); e.emit('foo'); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 0); assert.deepStrictEqual(['callback1', 'callback2', 'callback3'], callbacks_called); e.on('foo', callback1); e.on('foo', callback2); -assert.equal(2, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 2); e.removeAllListeners('foo'); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 0); // Verify that removing callbacks while in emit allows emits to propagate to // all listeners @@ -53,7 +53,7 @@ callbacks_called = []; e.on('foo', callback2); e.on('foo', callback3); -assert.equal(2, e.listeners('foo').length); +assert.strictEqual(2, e.listeners('foo').length); e.emit('foo'); assert.deepStrictEqual(['callback2', 'callback3'], callbacks_called); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(0, e.listeners('foo').length); diff --git a/test/parallel/test-fs-buffer.js b/test/parallel/test-fs-buffer.js index 6f142310f5e418..1452143a91c238 100644 --- a/test/parallel/test-fs-buffer.js +++ b/test/parallel/test-fs-buffer.js @@ -9,14 +9,14 @@ common.refreshTmpDir(); assert.doesNotThrow(() => { fs.access(Buffer.from(common.tmpDir), common.mustCall((err) => { - if (err) throw err; + assert.ifError(err); })); }); assert.doesNotThrow(() => { const buf = Buffer.from(path.join(common.tmpDir, 'a.txt')); fs.open(buf, 'w+', common.mustCall((err, fd) => { - if (err) throw err; + assert.ifError(err); assert(fd); fs.close(fd, common.mustCall(() => { fs.unlinkSync(buf); @@ -30,12 +30,12 @@ assert.throws(() => { const dir = Buffer.from(common.fixturesDir); fs.readdir(dir, 'hex', common.mustCall((err, list) => { - if (err) throw err; + assert.ifError(err); list = list.map((i) => { return Buffer.from(i, 'hex').toString(); }); fs.readdir(dir, common.mustCall((err, list2) => { - if (err) throw err; + assert.ifError(err); assert.deepStrictEqual(list, list2); })); })); diff --git a/test/parallel/test-fs-link.js b/test/parallel/test-fs-link.js index 2cba47bfec83df..d110ff80fe0341 100644 --- a/test/parallel/test-fs-link.js +++ b/test/parallel/test-fs-link.js @@ -12,7 +12,7 @@ const dstPath = path.join(common.tmpDir, 'link1.js'); fs.writeFileSync(srcPath, 'hello world'); const callback = function(err) { - if (err) throw err; + assert.ifError(err); const dstContent = fs.readFileSync(dstPath, 'utf8'); assert.strictEqual('hello world', dstContent); }; diff --git a/test/parallel/test-fs-make-callback.js b/test/parallel/test-fs-make-callback.js index 6e4572ee352197..40c9aa42995f9a 100644 --- a/test/parallel/test-fs-make-callback.js +++ b/test/parallel/test-fs-make-callback.js @@ -2,6 +2,7 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); +const cbTypeError = /^TypeError: "callback" argument must be a function$/; function test(cb) { return function() { @@ -26,13 +27,13 @@ process.once('warning', common.mustCall((warning) => { assert.doesNotThrow(test()); function invalidArgumentsTests() { - assert.throws(test(null)); - assert.throws(test(true)); - assert.throws(test(false)); - assert.throws(test(1)); - assert.throws(test(0)); - assert.throws(test('foo')); - assert.throws(test(/foo/)); - assert.throws(test([])); - assert.throws(test({})); + assert.throws(test(null), cbTypeError); + assert.throws(test(true), cbTypeError); + assert.throws(test(false), cbTypeError); + assert.throws(test(1), cbTypeError); + assert.throws(test(0), cbTypeError); + assert.throws(test('foo'), cbTypeError); + assert.throws(test(/foo/), cbTypeError); + assert.throws(test([]), cbTypeError); + assert.throws(test({}), cbTypeError); } diff --git a/test/parallel/test-fs-non-number-arguments-throw.js b/test/parallel/test-fs-non-number-arguments-throw.js index b13041ca3eecb6..3e40a5fd41be38 100644 --- a/test/parallel/test-fs-non-number-arguments-throw.js +++ b/test/parallel/test-fs-non-number-arguments-throw.js @@ -16,17 +16,17 @@ const saneEmitter = fs.createReadStream(tempFile, { start: 4, end: 6 }); assert.throws(function() { fs.createReadStream(tempFile, { start: '4', end: 6 }); }, /^TypeError: "start" option must be a Number$/, - "start as string didn't throw an error for createReadStream"); + "start as string didn't throw an error for createReadStream"); assert.throws(function() { fs.createReadStream(tempFile, { start: 4, end: '6' }); }, /^TypeError: "end" option must be a Number$/, - "end as string didn't throw an error for createReadStream"); + "end as string didn't throw an error for createReadStream"); assert.throws(function() { fs.createWriteStream(tempFile, { start: '4' }); }, /^TypeError: "start" option must be a Number$/, - "start as string didn't throw an error for createWriteStream"); + "start as string didn't throw an error for createWriteStream"); saneEmitter.on('data', common.mustCall(function(data) { assert.strictEqual(sanity, data.toString('utf8'), 'read ' + diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js index 3c70d2953ca0f4..e04aa1cb76cb6f 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -4,16 +4,15 @@ var assert = require('assert'); var fs = require('fs'); function check(async, sync) { - var expected = /Path must be a string without null bytes/; - var argsSync = Array.prototype.slice.call(arguments, 2); - var argsAsync = argsSync.concat(function(er) { + const expected = /Path must be a string without null bytes/; + const argsSync = Array.prototype.slice.call(arguments, 2); + const argsAsync = argsSync.concat((er) => { assert(er && er.message.match(expected)); - assert.equal(er.code, 'ENOENT'); + assert.strictEqual(er.code, 'ENOENT'); }); if (sync) - assert.throws(function() { - console.error(sync.name, argsSync); + assert.throws(() => { sync.apply(null, argsSync); }, expected); @@ -51,7 +50,7 @@ check(fs.writeFile, fs.writeFileSync, 'foo\u0000bar'); // an 'error' for exists means that it doesn't exist. // one of many reasons why this file is the absolute worst. -fs.exists('foo\u0000bar', function(exists) { +fs.exists('foo\u0000bar', common.mustCall((exists) => { assert(!exists); -}); +})); assert(!fs.existsSync('foo\u0000bar')); diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index ce7eaad580c008..2002d5a448a830 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -34,20 +34,27 @@ assert.equal(stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); ('+ +a +r +w rw wa war raw r++ a++ w++ x +x x+ rx rx+ wxx wax xwx xxx') .split(' ') .forEach(function(flags) { - assert.throws(function() { stringToFlags(flags); }); + assert.throws( + () => stringToFlags(flags), + new RegExp(`^Error: Unknown file open flag: ${escapeRegExp(flags)}`) + ); }); assert.throws( () => stringToFlags({}), - /Unknown file open flag: \[object Object\]/ + /^Error: Unknown file open flag: \[object Object\]$/ ); assert.throws( () => stringToFlags(true), - /Unknown file open flag: true/ + /^Error: Unknown file open flag: true$/ ); assert.throws( () => stringToFlags(null), - /Unknown file open flag: null/ + /^Error: Unknown file open flag: null$/ ); + +function escapeRegExp(string) { + return string.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); +} diff --git a/test/parallel/test-fs-options-immutable.js b/test/parallel/test-fs-options-immutable.js index 47796a94a5e79e..185d14c4721d74 100644 --- a/test/parallel/test-fs-options-immutable.js +++ b/test/parallel/test-fs-options-immutable.js @@ -29,7 +29,7 @@ common.refreshTmpDir(); assert.doesNotThrow(() => fs.readdirSync(__dirname, options)); } -{ +if (common.canCreateSymLink()) { const sourceFile = path.resolve(common.tmpDir, 'test-readlink'); const linkFile = path.resolve(common.tmpDir, 'test-readlink-link'); diff --git a/test/parallel/test-fs-read-buffer.js b/test/parallel/test-fs-read-buffer.js index 82fb3c284fb98a..733be5ba0db4c6 100644 --- a/test/parallel/test-fs-read-buffer.js +++ b/test/parallel/test-fs-read-buffer.js @@ -16,6 +16,7 @@ function test(bufferAsync, bufferSync, expected) { expected.length, 0, common.mustCall((err, bytesRead) => { + assert.ifError(err); assert.strictEqual(bytesRead, expected.length); assert.deepStrictEqual(bufferAsync, Buffer.from(expected)); })); diff --git a/test/parallel/test-fs-readdir-ucs2.js b/test/parallel/test-fs-readdir-ucs2.js index 916758fe943f86..53b16de4b9bea0 100644 --- a/test/parallel/test-fs-readdir-ucs2.js +++ b/test/parallel/test-fs-readdir-ucs2.js @@ -19,7 +19,7 @@ const fullpath = Buffer.concat([root, filebuff]); fs.closeSync(fs.openSync(fullpath, 'w+')); fs.readdir(common.tmpDir, 'ucs2', (err, list) => { - if (err) throw err; + assert.ifError(err); assert.equal(1, list.length); const fn = list[0]; assert.deepStrictEqual(filebuff, Buffer.from(fn, 'ucs2')); diff --git a/test/parallel/test-fs-readfile-fd.js b/test/parallel/test-fs-readfile-fd.js index 6420dbfdd004e5..190a10fc538fd6 100644 --- a/test/parallel/test-fs-readfile-fd.js +++ b/test/parallel/test-fs-readfile-fd.js @@ -29,11 +29,10 @@ tempFdSync(function(fd) { function tempFd(callback) { fs.open(fn, 'r', function(err, fd) { - if (err) throw err; - + assert.ifError(err); callback(fd, function() { fs.close(fd, function(err) { - if (err) throw err; + assert.ifError(err); }); }); }); diff --git a/test/parallel/test-fs-readfile-pipe-large.js b/test/parallel/test-fs-readfile-pipe-large.js index 1b1523cb132e4c..926cc318c4f63a 100644 --- a/test/parallel/test-fs-readfile-pipe-large.js +++ b/test/parallel/test-fs-readfile-pipe-large.js @@ -14,7 +14,7 @@ const fs = require('fs'); if (process.argv[2] === 'child') { fs.readFile('/dev/stdin', function(er, data) { - if (er) throw er; + assert.ifError(er); process.stdout.write(data); }); return; @@ -30,8 +30,7 @@ const f = JSON.stringify(__filename); const node = JSON.stringify(process.execPath); const cmd = `cat ${filename} | ${node} ${f} child`; exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) { - if (err) console.error(err); - assert(!err, 'it exits normally'); + assert.ifError(err); assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); assert.strictEqual(stderr, '', 'it does not write to stderr'); console.log('ok'); diff --git a/test/parallel/test-fs-readfile-pipe.js b/test/parallel/test-fs-readfile-pipe.js index 54fb1fbe104fae..91465a261c8f96 100644 --- a/test/parallel/test-fs-readfile-pipe.js +++ b/test/parallel/test-fs-readfile-pipe.js @@ -26,8 +26,7 @@ const f = JSON.stringify(__filename); const node = JSON.stringify(process.execPath); const cmd = `cat ${f} | ${node} ${f} child`; exec(cmd, function(err, stdout, stderr) { - if (err) console.error(err); - assert(!err, 'it exits normally'); + assert.ifError(err); assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); assert.strictEqual(stderr, '', 'it does not write to stderr'); console.log('ok'); diff --git a/test/parallel/test-fs-readfile-zero-byte-liar.js b/test/parallel/test-fs-readfile-zero-byte-liar.js index 283a986f8a038a..c3887979bb0b4a 100644 --- a/test/parallel/test-fs-readfile-zero-byte-liar.js +++ b/test/parallel/test-fs-readfile-zero-byte-liar.js @@ -3,29 +3,29 @@ const common = require('../common'); var assert = require('assert'); var fs = require('fs'); -var dataExpected = fs.readFileSync(__filename, 'utf8'); +const dataExpected = fs.readFileSync(__filename, 'utf8'); // sometimes stat returns size=0, but it's a lie. fs._fstat = fs.fstat; fs._fstatSync = fs.fstatSync; -fs.fstat = function(fd, cb) { - fs._fstat(fd, function(er, st) { +fs.fstat = (fd, cb) => { + fs._fstat(fd, (er, st) => { if (er) return cb(er); st.size = 0; return cb(er, st); }); }; -fs.fstatSync = function(fd) { - var st = fs._fstatSync(fd); +fs.fstatSync = (fd) => { + const st = fs._fstatSync(fd); st.size = 0; return st; }; -var d = fs.readFileSync(__filename, 'utf8'); -assert.equal(d, dataExpected); +const d = fs.readFileSync(__filename, 'utf8'); +assert.strictEqual(d, dataExpected); -fs.readFile(__filename, 'utf8', common.mustCall(function(er, d) { - assert.equal(d, dataExpected); +fs.readFile(__filename, 'utf8', common.mustCall((er, d) => { + assert.strictEqual(d, dataExpected); })); diff --git a/test/parallel/test-fs-readfilesync-pipe-large.js b/test/parallel/test-fs-readfilesync-pipe-large.js index 9108118b87e2e6..e791618b4999fe 100644 --- a/test/parallel/test-fs-readfilesync-pipe-large.js +++ b/test/parallel/test-fs-readfilesync-pipe-large.js @@ -27,8 +27,7 @@ const f = JSON.stringify(__filename); const node = JSON.stringify(process.execPath); const cmd = `cat ${filename} | ${node} ${f} child`; exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) { - if (err) console.error(err); - assert(!err, 'it exits normally'); + assert.ifError(err); assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); assert.strictEqual(stderr, '', 'it does not write to stderr'); console.log('ok'); diff --git a/test/parallel/test-fs-realpath-buffer-encoding.js b/test/parallel/test-fs-realpath-buffer-encoding.js index 78ec02549bbd27..fd7b0d5c3d42f3 100644 --- a/test/parallel/test-fs-realpath-buffer-encoding.js +++ b/test/parallel/test-fs-realpath-buffer-encoding.js @@ -50,39 +50,39 @@ for (encoding in expected) { const expected_value = expected[encoding]; fs.realpath(string_dir, {encoding: encoding}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); fs.realpath(string_dir, encoding, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); fs.realpath(buffer_dir, {encoding: encoding}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); fs.realpath(buffer_dir, encoding, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); } fs.realpath(string_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); fs.realpath(string_dir, 'buffer', common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); fs.realpath(buffer_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); fs.realpath(buffer_dir, 'buffer', common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); diff --git a/test/parallel/test-fs-realpath-on-substed-drive.js b/test/parallel/test-fs-realpath-on-substed-drive.js index c9109362691845..ae2895553ed2f6 100644 --- a/test/parallel/test-fs-realpath-on-substed-drive.js +++ b/test/parallel/test-fs-realpath-on-substed-drive.js @@ -42,12 +42,12 @@ assert(Buffer.isBuffer(result)); assert(result.equals(filenameBuffer)); fs.realpath(filename, common.mustCall(function(err, result) { - assert(!err); + assert.ifError(err); assert.strictEqual(result, filename); })); fs.realpath(filename, 'buffer', common.mustCall(function(err, result) { - assert(!err); + assert.ifError(err); assert(Buffer.isBuffer(result)); assert(result.equals(filenameBuffer)); })); diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index dcaf8177c9499c..986e2089b44ab9 100644 --- a/test/parallel/test-fs-realpath.js +++ b/test/parallel/test-fs-realpath.js @@ -137,13 +137,13 @@ function test_deep_relative_file_symlink(callback) { .relative(path.join(targetsAbsDir, 'nested-index', 'one'), expected); const linkPath1 = path.join(targetsAbsDir, - 'nested-index', 'one', 'symlink1.js'); + 'nested-index', 'one', 'symlink1.js'); try { fs.unlinkSync(linkPath1); } catch (e) {} fs.symlinkSync(linkData1, linkPath1, 'file'); const linkData2 = '../one/symlink1.js'; const entry = path.join(targetsAbsDir, - 'nested-index', 'two', 'symlink1-b.js'); + 'nested-index', 'two', 'symlink1-b.js'); try { fs.unlinkSync(entry); } catch (e) {} fs.symlinkSync(linkData2, entry, 'file'); unlink.push(linkPath1); @@ -170,7 +170,7 @@ function test_deep_relative_dir_symlink(callback) { const linkData2b = '../one/symlink1-dir'; const entry = path.join(targetsAbsDir, - 'nested-index', 'two', 'symlink12-dir'); + 'nested-index', 'two', 'symlink12-dir'); try { fs.unlinkSync(entry); } catch (e) {} fs.symlinkSync(linkData2b, entry, 'dir'); unlink.push(linkPath1b); @@ -237,7 +237,7 @@ function test_relative_input_cwd(callback) { // we need to calculate the relative path to the tmp dir from cwd const entrydir = process.cwd(); const entry = path.relative(entrydir, - path.join(common.tmpDir + '/cycles/realpath-3a')); + path.join(common.tmpDir + '/cycles/realpath-3a')); const expected = common.tmpDir + '/cycles/root.js'; [ [entry, '../cycles/realpath-3b'], @@ -292,14 +292,14 @@ function test_deep_symlink_mix(callback) { [ [entry, common.tmpDir + '/node-test-realpath-d1/foo'], [tmp('node-test-realpath-d1'), - common.tmpDir + '/node-test-realpath-d2'], + common.tmpDir + '/node-test-realpath-d2'], [tmp('node-test-realpath-d2/foo'), '../node-test-realpath-f2'], [tmp('node-test-realpath-f2'), targetsAbsDir + '/nested-index/one/realpath-c'], [targetsAbsDir + '/nested-index/one/realpath-c', targetsAbsDir + '/nested-index/two/realpath-c'], [targetsAbsDir + '/nested-index/two/realpath-c', - common.tmpDir + '/cycles/root.js'] + common.tmpDir + '/cycles/root.js'] ].forEach(function(t) { try { fs.unlinkSync(t[0]); } catch (e) {} fs.symlinkSync(t[1], t[0]); @@ -361,7 +361,7 @@ function test_up_multiple(cb) { } function cleanup() { ['a/b', - 'a' + 'a' ].forEach(function(folder) { try { fs.rmdirSync(tmp(folder)); } catch (ex) {} }); @@ -386,10 +386,10 @@ function test_up_multiple(cb) { assertEqualPath(fs.realpathSync(abedabeda), abedabeda_real); assertEqualPath(fs.realpathSync(abedabed), abedabed_real); fs.realpath(abedabeda, function(er, real) { - if (er) throw er; + assert.ifError(er); assertEqualPath(abedabeda_real, real); fs.realpath(abedabed, function(er, real) { - if (er) throw er; + assert.ifError(er); assertEqualPath(abedabed_real, real); cb(); cleanup(); @@ -418,14 +418,14 @@ function test_abs_with_kids(cb) { const root = tmpAbsDir + '/node-test-realpath-abs-kids'; function cleanup() { ['/a/b/c/x.txt', - '/a/link' + '/a/link' ].forEach(function(file) { try { fs.unlinkSync(root + file); } catch (ex) {} }); ['/a/b/c', - '/a/b', - '/a', - '' + '/a/b', + '/a', + '' ].forEach(function(folder) { try { fs.rmdirSync(root + folder); } catch (ex) {} }); @@ -433,9 +433,9 @@ function test_abs_with_kids(cb) { function setup() { cleanup(); ['', - '/a', - '/a/b', - '/a/b/c' + '/a', + '/a/b', + '/a/b/c' ].forEach(function(folder) { console.log('mkdir ' + root + folder); fs.mkdirSync(root + folder, 0o700); @@ -476,7 +476,7 @@ const tests = [ const numtests = tests.length; var testsRun = 0; function runNextTest(err) { - if (err) throw err; + assert.ifError(err); const test = tests.shift(); if (!test) { return console.log(numtests + diff --git a/test/parallel/test-fs-symlink.js b/test/parallel/test-fs-symlink.js index ab52ba22923f3d..69b78dad3d2797 100644 --- a/test/parallel/test-fs-symlink.js +++ b/test/parallel/test-fs-symlink.js @@ -3,20 +3,13 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); const fs = require('fs'); -const exec = require('child_process').exec; var linkTime; var fileTime; -if (common.isWindows) { - // On Windows, creating symlinks requires admin privileges. - // We'll only try to run symlink test if we have enough privileges. - exec('whoami /priv', function(err, o) { - if (err || !o.includes('SeCreateSymbolicLinkPrivilege')) { - common.skip('insufficient privileges'); - return; - } - }); +if (!common.canCreateSymLink()) { + common.skip('insufficient privileges'); + return; } common.refreshTmpDir(); diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 1ba0db7f012fe4..80c938b8d43a03 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -43,9 +43,9 @@ fs.closeSync(fd); // async tests testTruncate(common.mustCall(function(er) { - if (er) throw er; + assert.ifError(er); testFtruncate(common.mustCall(function(er) { - if (er) throw er; + assert.ifError(er); })); })); diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index f245a7962da0f4..108ca7c7d71c03 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -4,11 +4,11 @@ var assert = require('assert'); var util = require('util'); var fs = require('fs'); -var tests_ok = 0; -var tests_run = 0; +let tests_ok = 0; +let tests_run = 0; function stat_resource(resource) { - if (typeof resource == 'string') { + if (typeof resource === 'string') { return fs.statSync(resource); } else { // ensure mtime has been written to disk @@ -19,8 +19,8 @@ function stat_resource(resource) { function check_mtime(resource, mtime) { mtime = fs._toUnixTimestamp(mtime); - var stats = stat_resource(resource); - var real_mtime = fs._toUnixTimestamp(stats.mtime); + const stats = stat_resource(resource); + const real_mtime = fs._toUnixTimestamp(stats.mtime); // check up to single-second precision // sub-second precision is OS and fs dependant return mtime - real_mtime < 2; @@ -46,9 +46,9 @@ function expect_ok(syscall, resource, err, atime, mtime) { // the tests assume that __filename belongs to the user running the tests // this should be a fairly safe assumption; testing against a temp file // would be even better though (node doesn't have such functionality yet) -function runTest(atime, mtime, callback) { +function testIt(atime, mtime, callback) { - var fd; + let fd; // // test synchronized code paths, these functions throw on failure // @@ -67,8 +67,7 @@ function runTest(atime, mtime, callback) { expect_errno('futimesSync', fd, ex, 'ENOSYS'); } - var err; - err = undefined; + let err = undefined; try { fs.utimesSync('foobarbaz', atime, mtime); } catch (ex) { @@ -90,10 +89,10 @@ function runTest(atime, mtime, callback) { // // test async code paths // - fs.utimes(__filename, atime, mtime, function(err) { + fs.utimes(__filename, atime, mtime, common.mustCall(function(err) { expect_ok('utimes', __filename, err, atime, mtime); - fs.utimes('foobarbaz', atime, mtime, function(err) { + fs.utimes('foobarbaz', atime, mtime, common.mustCall(function(err) { expect_errno('utimes', 'foobarbaz', err, 'ENOENT'); // don't close this fd @@ -103,34 +102,36 @@ function runTest(atime, mtime, callback) { fd = fs.openSync(__filename, 'r'); } - fs.futimes(fd, atime, mtime, function(err) { + fs.futimes(fd, atime, mtime, common.mustCall(function(err) { expect_ok('futimes', fd, err, atime, mtime); - fs.futimes(-1, atime, mtime, function(err) { + fs.futimes(-1, atime, mtime, common.mustCall(function(err) { expect_errno('futimes', -1, err, 'EBADF'); syncTests(); callback(); - }); + })); tests_run++; - }); + })); tests_run++; - }); + })); tests_run++; - }); + })); tests_run++; } -var stats = fs.statSync(__filename); +const stats = fs.statSync(__filename); // run tests +const runTest = common.mustCall(testIt, 6); + runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { runTest(new Date(), new Date(), function() { runTest(123456.789, 123456.789, function() { runTest(stats.mtime, stats.mtime, function() { runTest(NaN, Infinity, function() { - runTest('123456', -1, function() { + runTest('123456', -1, common.mustCall(function() { // done - }); + })); }); }); }); @@ -140,5 +141,5 @@ runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { process.on('exit', function() { console.log('Tests run / ok:', tests_run, '/', tests_ok); - assert.equal(tests_ok, tests_run); + assert.strictEqual(tests_ok, tests_run); }); diff --git a/test/parallel/test-fs-write-buffer.js b/test/parallel/test-fs-write-buffer.js index 0e24f33872825f..927ebb15412bc8 100644 --- a/test/parallel/test-fs-write-buffer.js +++ b/test/parallel/test-fs-write-buffer.js @@ -10,17 +10,17 @@ common.refreshTmpDir(); // fs.write with all parameters provided: { const filename = path.join(common.tmpDir, 'write1.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(expected.length, written); fs.closeSync(fd); var found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual(expected.toString(), found); + assert.strictEqual(expected.toString(), found); }); fs.write(fd, expected, 0, expected.length, null, cb); @@ -30,17 +30,17 @@ common.refreshTmpDir(); // fs.write with a buffer, without the length parameter: { const filename = path.join(common.tmpDir, 'write2.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(2, written); fs.closeSync(fd); const found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual('lo', found); + assert.strictEqual('lo', found); }); fs.write(fd, Buffer.from('hello'), 3, cb); @@ -90,17 +90,17 @@ common.refreshTmpDir(); // fs.write with offset and length passed as undefined followed by the callback: { const filename = path.join(common.tmpDir, 'write5.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(expected.length, written); fs.closeSync(fd); const found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual(expected.toString(), found); + assert.strictEqual(expected.toString(), found); }); fs.write(fd, expected, undefined, undefined, cb); @@ -110,17 +110,17 @@ common.refreshTmpDir(); // fs.write with a Uint8Array, without the offset and length parameters: { const filename = path.join(common.tmpDir, 'write6.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(expected.length, written); fs.closeSync(fd); const found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual(expected.toString(), found); + assert.strictEqual(expected.toString(), found); }); fs.write(fd, Uint8Array.from(expected), cb); diff --git a/test/parallel/test-fs-write-stream-autoclose-option.js b/test/parallel/test-fs-write-stream-autoclose-option.js index c7d21db2b4b531..4bfa4ba5341e1e 100644 --- a/test/parallel/test-fs-write-stream-autoclose-option.js +++ b/test/parallel/test-fs-write-stream-autoclose-option.js @@ -32,7 +32,7 @@ function next() { function next2() { // This will test if after reusing the fd data is written properly fs.readFile(file, function(err, data) { - assert(!err); + assert.ifError(err); assert.strictEqual(data.toString(), 'Test2'); process.nextTick(common.mustCall(next3)); }); diff --git a/test/parallel/test-fs-write-stream-throw-type-error.js b/test/parallel/test-fs-write-stream-throw-type-error.js index 996b22119cda5e..940def65b30b01 100644 --- a/test/parallel/test-fs-write-stream-throw-type-error.js +++ b/test/parallel/test-fs-write-stream-throw-type-error.js @@ -4,32 +4,44 @@ const assert = require('assert'); const fs = require('fs'); const path = require('path'); +const numberError = new RegExp('^TypeError: "options" must be a string ' + + 'or an object, got number instead.$'); + +const booleanError = new RegExp('^TypeError: "options" must be a string ' + + 'or an object, got boolean instead.$'); + const example = path.join(common.tmpDir, 'dummy'); common.refreshTmpDir(); -assert.doesNotThrow(function() { +assert.doesNotThrow(() => { fs.createWriteStream(example, undefined); }); -assert.doesNotThrow(function() { + +assert.doesNotThrow(() => { fs.createWriteStream(example, null); }); -assert.doesNotThrow(function() { + +assert.doesNotThrow(() => { fs.createWriteStream(example, 'utf8'); }); -assert.doesNotThrow(function() { + +assert.doesNotThrow(() => { fs.createWriteStream(example, {encoding: 'utf8'}); }); -assert.throws(function() { +assert.throws(() => { fs.createWriteStream(example, 123); -}, /"options" must be a string or an object/); -assert.throws(function() { +}, numberError); + +assert.throws(() => { fs.createWriteStream(example, 0); -}, /"options" must be a string or an object/); -assert.throws(function() { +}, numberError); + +assert.throws(() => { fs.createWriteStream(example, true); -}, /"options" must be a string or an object/); -assert.throws(function() { +}, booleanError); + +assert.throws(() => { fs.createWriteStream(example, false); -}, /"options" must be a string or an object/); +}, booleanError); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index 5c7999e9b1158c..75f689b94b2c47 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -12,11 +12,11 @@ var data = true; var expected = data + ''; fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { - if (err) throw err; + assert.ifError(err); console.log('open done'); fs.write(fd, data, 0, 'utf8', common.mustCall(function(err, written) { console.log('write done'); - if (err) throw err; + assert.ifError(err); assert.equal(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn, 'utf8'); diff --git a/test/parallel/test-fs-write.js b/test/parallel/test-fs-write.js index 9960a91a4f7515..81f5cf707bf00a 100644 --- a/test/parallel/test-fs-write.js +++ b/test/parallel/test-fs-write.js @@ -12,14 +12,14 @@ const constants = fs.constants; common.refreshTmpDir(); fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { - if (err) throw err; + assert.ifError(err); console.log('open done'); fs.write(fd, '', 0, 'utf8', function(err, written) { assert.strictEqual(0, written); }); fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) { console.log('write done'); - if (err) throw err; + assert.ifError(err); assert.strictEqual(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn, 'utf8'); @@ -33,14 +33,14 @@ fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644, common.mustCall((err, fd) => { - if (err) throw err; + assert.ifError(err); console.log('open done'); fs.write(fd, '', 0, 'utf8', (err, written) => { assert.strictEqual(0, written); }); fs.write(fd, expected, 0, 'utf8', common.mustCall((err, written) => { console.log('write done'); - if (err) throw err; + assert.ifError(err); assert.strictEqual(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn2, 'utf8'); diff --git a/test/parallel/test-handle-wrap-close-abort.js b/test/parallel/test-handle-wrap-close-abort.js index 5355e65df60821..e9f69195ad29cd 100644 --- a/test/parallel/test-handle-wrap-close-abort.js +++ b/test/parallel/test-handle-wrap-close-abort.js @@ -13,4 +13,4 @@ setTimeout(function() { setTimeout(function() { throw new Error('setTimeout'); }, 1); -}); +}, 1); diff --git a/test/parallel/test-http-chunk-problem.js b/test/parallel/test-http-chunk-problem.js index 9bb004dc973f5c..82e8534af9e334 100644 --- a/test/parallel/test-http-chunk-problem.js +++ b/test/parallel/test-http-chunk-problem.js @@ -51,7 +51,7 @@ function executeRequest(cb) { __filename, 'shasum' ].join(' '), (err, stdout, stderr) => { - if (err) throw err; + assert.ifError(err); assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', stdout.slice(0, 40)); cb(); @@ -65,7 +65,7 @@ common.refreshTmpDir(); const ddcmd = common.ddCommand(filename, 10240); cp.exec(ddcmd, function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); server = http.createServer(function(req, res) { res.writeHead(200); diff --git a/test/parallel/test-http-chunked-304.js b/test/parallel/test-http-chunked-304.js index 5ea1912b72dfee..82fe138fd926da 100644 --- a/test/parallel/test-http-chunked-304.js +++ b/test/parallel/test-http-chunked-304.js @@ -12,32 +12,35 @@ var net = require('net'); // Likewise for 304 responses. Verify that no empty chunk is sent when // the user explicitly sets a Transfer-Encoding header. -test(204, function() { - test(304); -}); +test(204); +test(304); -function test(statusCode, next) { - var server = http.createServer(function(req, res) { +function test(statusCode) { + const server = http.createServer(common.mustCall((req, res) => { res.writeHead(statusCode, { 'Transfer-Encoding': 'chunked' }); res.end(); server.close(); - }); + })); - server.listen(0, function() { - var conn = net.createConnection(this.address().port, function() { - conn.write('GET / HTTP/1.1\r\n\r\n'); + server.listen(0, common.mustCall(() => { + const conn = net.createConnection( + server.address().port, + common.mustCall(() => { + conn.write('GET / HTTP/1.1\r\n\r\n'); - var resp = ''; - conn.setEncoding('utf8'); - conn.on('data', function(data) { - resp += data; - }); + let resp = ''; + conn.setEncoding('utf8'); + conn.on('data', common.mustCall((data) => { + resp += data; + })); - conn.on('end', common.mustCall(function() { - assert.equal(/^Connection: close\r\n$/m.test(resp), true); - assert.equal(/^0\r\n$/m.test(resp), false); - if (next) process.nextTick(next); - })); - }); - }); + conn.on('end', common.mustCall(() => { + // Connection: close should be in the response + assert.strictEqual(/^Connection: close\r\n$/m.test(resp), true); + // Make sure this doesn't end with 0\r\n\r\n + assert.strictEqual(/^0\r\n$/m.test(resp), false); + })); + }) + ); + })); } diff --git a/test/parallel/test-http-client-defaults.js b/test/parallel/test-http-client-defaults.js new file mode 100644 index 00000000000000..d277a60e3df55e --- /dev/null +++ b/test/parallel/test-http-client-defaults.js @@ -0,0 +1,24 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const ClientRequest = require('http').ClientRequest; + +function noop() {} + +{ + const req = new ClientRequest({ createConnection: noop }); + assert.strictEqual(req.path, '/'); + assert.strictEqual(req.method, 'GET'); +} + +{ + const req = new ClientRequest({ method: '', createConnection: noop }); + assert.strictEqual(req.path, '/'); + assert.strictEqual(req.method, 'GET'); +} + +{ + const req = new ClientRequest({ path: '', createConnection: noop }); + assert.strictEqual(req.path, '/'); + assert.strictEqual(req.method, 'GET'); +} diff --git a/test/parallel/test-http-common.js b/test/parallel/test-http-common.js new file mode 100644 index 00000000000000..1629856ce57d09 --- /dev/null +++ b/test/parallel/test-http-common.js @@ -0,0 +1,33 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const httpCommon = require('_http_common'); +const checkIsHttpToken = httpCommon._checkIsHttpToken; +const checkInvalidHeaderChar = httpCommon._checkInvalidHeaderChar; + +// checkIsHttpToken +assert(checkIsHttpToken('t')); +assert(checkIsHttpToken('tt')); +assert(checkIsHttpToken('ttt')); +assert(checkIsHttpToken('tttt')); +assert(checkIsHttpToken('ttttt')); + +assert.strictEqual(checkIsHttpToken(''), false); +assert.strictEqual(checkIsHttpToken(' '), false); +assert.strictEqual(checkIsHttpToken('あ'), false); +assert.strictEqual(checkIsHttpToken('あa'), false); +assert.strictEqual(checkIsHttpToken('aaaaあaaaa'), false); + +// checkInvalidHeaderChar +assert(checkInvalidHeaderChar('あ')); +assert(checkInvalidHeaderChar('aaaaあaaaa')); + +assert.strictEqual(checkInvalidHeaderChar(''), false); +assert.strictEqual(checkInvalidHeaderChar(1), false); +assert.strictEqual(checkInvalidHeaderChar(' '), false); +assert.strictEqual(checkInvalidHeaderChar(false), false); +assert.strictEqual(checkInvalidHeaderChar('t'), false); +assert.strictEqual(checkInvalidHeaderChar('tt'), false); +assert.strictEqual(checkInvalidHeaderChar('ttt'), false); +assert.strictEqual(checkInvalidHeaderChar('tttt'), false); +assert.strictEqual(checkInvalidHeaderChar('ttttt'), false); diff --git a/test/parallel/test-http-double-content-length.js b/test/parallel/test-http-double-content-length.js index a73cf49854ed35..f6c13becfd83dd 100644 --- a/test/parallel/test-http-double-content-length.js +++ b/test/parallel/test-http-double-content-length.js @@ -22,9 +22,9 @@ server.listen(0, () => { port: server.address().port, // Send two content-length header values. headers: {'Content-Length': [1, 2]}}, - (res) => { - common.fail('an error should have occurred'); - } + (res) => { + common.fail('an error should have occurred'); + } ); req.on('error', common.mustCall(() => { server.close(); diff --git a/test/parallel/test-http-host-headers.js b/test/parallel/test-http-host-headers.js index a9f12d6819314e..0adf5716b7e776 100644 --- a/test/parallel/test-http-host-headers.js +++ b/test/parallel/test-http-host-headers.js @@ -39,9 +39,7 @@ function testHttp() { httpServer.listen(0, function(er) { console.error(`test http server listening on ${this.address().port}`); - - if (er) throw er; - + assert.ifError(er); http.get({ method: 'GET', path: '/' + (counter++), diff --git a/test/parallel/test-http-incoming-matchKnownFields.js b/test/parallel/test-http-incoming-matchKnownFields.js new file mode 100644 index 00000000000000..7411be4e847d73 --- /dev/null +++ b/test/parallel/test-http-incoming-matchKnownFields.js @@ -0,0 +1,90 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const IncomingMessage = require('http').IncomingMessage; + +function checkDest(field, result, value) { + const dest = {}; + + if (value) dest[field] = 'test'; + const incomingMessage = new IncomingMessage(field); + // dest is changed by IncomingMessage._addHeaderLine + incomingMessage._addHeaderLine(field, value, dest); + assert.deepStrictEqual(dest, result); +} + +checkDest('', {'': undefined}); +checkDest('Content-Type', {'content-type': undefined}); +checkDest('content-type', {'content-type': 'test'}, 'value'); +checkDest('User-Agent', {'user-agent': undefined}); +checkDest('user-agent', {'user-agent': 'test'}, 'value'); +checkDest('Referer', {referer: undefined}); +checkDest('referer', {referer: 'test'}, 'value'); +checkDest('Host', {host: undefined}); +checkDest('host', {host: 'test'}, 'value'); +checkDest('Authorization', {authorization: undefined}, undefined); +checkDest('authorization', {authorization: 'test'}, 'value'); +checkDest('Proxy-Authorization', {'proxy-authorization': undefined}); +checkDest('proxy-authorization', {'proxy-authorization': 'test'}, 'value'); +checkDest('If-Modified-Since', {'if-modified-since': undefined}); +checkDest('if-modified-since', {'if-modified-since': 'test'}, 'value'); +checkDest('If-Unmodified-Since', {'if-unmodified-since': undefined}); +checkDest('if-unmodified-since', {'if-unmodified-since': 'test'}, 'value'); +checkDest('Form', {form: undefined}); +checkDest('form', {form: 'test, value'}, 'value'); +checkDest('Location', {location: undefined}); +checkDest('location', {location: 'test'}, 'value'); +checkDest('Max-Forwards', {'max-forwards': undefined}); +checkDest('max-forwards', {'max-forwards': 'test'}, 'value'); +checkDest('Retry-After', {'retry-after': undefined}); +checkDest('retry-after', {'retry-after': 'test'}, 'value'); +checkDest('Etag', {etag: undefined}); +checkDest('etag', {etag: 'test'}, 'value'); +checkDest('Last-Modified', {'last-modified': undefined}); +checkDest('last-modified', {'last-modified': 'test'}, 'value'); +checkDest('Server', {server: undefined}); +checkDest('server', {server: 'test'}, 'value'); +checkDest('Age', {age: undefined}); +checkDest('age', {age: 'test'}, 'value'); +checkDest('Expires', {expires: undefined}); +checkDest('expires', {expires: 'test'}, 'value'); +checkDest('Set-Cookie', {'set-cookie': [undefined]}); +checkDest('set-cookie', {'set-cookie': [undefined]}); +checkDest('Transfer-Encoding', {'transfer-encoding': undefined}); +checkDest('transfer-encoding', {'transfer-encoding': 'test, value'}, 'value'); +checkDest('Date', {date: undefined}); +checkDest('date', {date: 'test, value'}, 'value'); +checkDest('Connection', {connection: undefined}); +checkDest('connection', {connection: 'test, value'}, 'value'); +checkDest('Cache-Control', {'cache-control': undefined}); +checkDest('cache-control', {'cache-control': 'test, value'}, 'value'); +checkDest('Transfer-Encoding', {'transfer-encoding': undefined}); +checkDest('transfer-encoding', {'transfer-encoding': 'test, value'}, 'value'); +checkDest('Vary', {vary: undefined}); +checkDest('vary', {vary: 'test, value'}, 'value'); +checkDest('Content-Encoding', {'content-encoding': undefined}, undefined); +checkDest('content-encoding', {'content-encoding': 'test, value'}, 'value'); +checkDest('Cookies', {cookies: undefined}); +checkDest('cookies', {cookies: 'test, value'}, 'value'); +checkDest('Origin', {origin: undefined}); +checkDest('origin', {origin: 'test, value'}, 'value'); +checkDest('Upgrade', {upgrade: undefined}); +checkDest('upgrade', {upgrade: 'test, value'}, 'value'); +checkDest('Expect', {expect: undefined}); +checkDest('expect', {expect: 'test, value'}, 'value'); +checkDest('If-Match', {'if-match': undefined}); +checkDest('if-match', {'if-match': 'test, value'}, 'value'); +checkDest('If-None-Match', {'if-none-match': undefined}); +checkDest('if-none-match', {'if-none-match': 'test, value'}, 'value'); +checkDest('Accept', {accept: undefined}); +checkDest('accept', {accept: 'test, value'}, 'value'); +checkDest('Accept-Encoding', {'accept-encoding': undefined}); +checkDest('accept-encoding', {'accept-encoding': 'test, value'}, 'value'); +checkDest('Accept-Language', {'accept-language': undefined}); +checkDest('accept-language', {'accept-language': 'test, value'}, 'value'); +checkDest('X-Forwarded-For', {'x-forwarded-for': undefined}); +checkDest('x-forwarded-for', {'x-forwarded-for': 'test, value'}, 'value'); +checkDest('X-Forwarded-Host', {'x-forwarded-host': undefined}); +checkDest('x-forwarded-host', {'x-forwarded-host': 'test, value'}, 'value'); +checkDest('X-Forwarded-Proto', {'x-forwarded-proto': undefined}); +checkDest('x-forwarded-proto', {'x-forwarded-proto': 'test, value'}, 'value'); diff --git a/test/parallel/test-http-localaddress.js b/test/parallel/test-http-localaddress.js index fd38f8a901fe81..d507d12ec89e25 100644 --- a/test/parallel/test-http-localaddress.js +++ b/test/parallel/test-http-localaddress.js @@ -21,10 +21,10 @@ var server = http.createServer(function(req, res) { server.listen(0, '127.0.0.1', function() { var options = { host: 'localhost', - port: this.address().port, - path: '/', - method: 'GET', - localAddress: '127.0.0.2' }; + port: this.address().port, + path: '/', + method: 'GET', + localAddress: '127.0.0.2' }; var req = http.request(options, function(res) { res.on('end', function() { diff --git a/test/parallel/test-http-outgoing-proto.js b/test/parallel/test-http-outgoing-proto.js index 738e1d2c8cfe4e..53198708b42b68 100644 --- a/test/parallel/test-http-outgoing-proto.js +++ b/test/parallel/test-http-outgoing-proto.js @@ -12,3 +12,63 @@ assert.strictEqual( typeof ClientRequest.prototype._implicitHeader, 'function'); assert.strictEqual( typeof ServerResponse.prototype._implicitHeader, 'function'); + +// validateHeader +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.setHeader(); +}, /^TypeError: Header name must be a valid HTTP Token \["undefined"\]$/); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.setHeader('test'); +}, /^Error: "value" required in setHeader\("test", value\)$/); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.setHeader(404); +}, /^TypeError: Header name must be a valid HTTP Token \["404"\]$/); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.setHeader.call({_header: 'test'}, 'test', 'value'); +}, /^Error: Can't set headers after they are sent.$/); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.setHeader('200', 'あ'); +}, /^TypeError: The header content contains invalid characters$/); + +// write +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.write(); +}, /^Error: _implicitHeader\(\) method is not implemented$/); + +assert(OutgoingMessage.prototype.write.call({_header: 'test'})); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.write.call({_header: 'test', _hasBody: 'test'}); +}, /^TypeError: First argument must be a string or Buffer$/); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.write.call({_header: 'test', _hasBody: 'test'}, 1); +}, /^TypeError: First argument must be a string or Buffer$/); + +// addTrailers +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.addTrailers(); +}, /^TypeError: Cannot convert undefined or null to object$/); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.addTrailers({'あ': 'value'}); +}, /^TypeError: Trailer name must be a valid HTTP Token \["あ"\]$/); + +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.addTrailers({404: 'あ'}); +}, /^TypeError: The trailer content contains invalid characters$/); diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index 43feb1e3b3838c..48367caaa7d89e 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -10,8 +10,8 @@ var cookies = [ ]; var headers = {'content-type': 'text/plain', - 'set-cookie': cookies, - 'hello': 'world' }; + 'set-cookie': cookies, + 'hello': 'world' }; var backend = http.createServer(function(req, res) { console.error('backend request'); diff --git a/test/parallel/test-http-response-statuscode.js b/test/parallel/test-http-response-statuscode.js index 3314506339b564..57256db6032324 100644 --- a/test/parallel/test-http-response-statuscode.js +++ b/test/parallel/test-http-response-statuscode.js @@ -11,62 +11,62 @@ const server = http.Server(common.mustCall(function(req, res) { case 0: assert.throws(common.mustCall(() => { res.writeHead(-1); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 1: assert.throws(common.mustCall(() => { res.writeHead(Infinity); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 2: assert.throws(common.mustCall(() => { res.writeHead(NaN); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 3: assert.throws(common.mustCall(() => { res.writeHead({}); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 4: assert.throws(common.mustCall(() => { res.writeHead(99); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 5: assert.throws(common.mustCall(() => { res.writeHead(1000); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 6: assert.throws(common.mustCall(() => { res.writeHead('1000'); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 7: assert.throws(common.mustCall(() => { res.writeHead(null); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 8: assert.throws(common.mustCall(() => { res.writeHead(true); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 9: assert.throws(common.mustCall(() => { res.writeHead([]); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 10: assert.throws(common.mustCall(() => { res.writeHead('this is not valid'); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 11: assert.throws(common.mustCall(() => { res.writeHead('404 this is not valid either'); - }, /invalid status code/i)); + }), /invalid status code/i); this.close(); break; default: diff --git a/test/parallel/test-http-status-reason-invalid-chars.js b/test/parallel/test-http-status-reason-invalid-chars.js index 9950eeeee9cdd2..75ccb2c2430c53 100644 --- a/test/parallel/test-http-status-reason-invalid-chars.js +++ b/test/parallel/test-http-status-reason-invalid-chars.js @@ -3,7 +3,6 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -const net = require('net'); function explicit(req, res) { assert.throws(() => { @@ -34,8 +33,7 @@ const server = http.createServer((req, res) => { implicit(req, res); } }).listen(0, common.mustCall(() => { - const addr = server.address().address; - const hostname = net.isIPv6(addr) ? `[${addr}1]` : addr; + const hostname = 'localhost'; const url = `http://${hostname}:${server.address().port}`; let left = 2; const check = common.mustCall((res) => { diff --git a/test/parallel/test-https-agent-getname.js b/test/parallel/test-https-agent-getname.js index 49c1dcef4fb5fb..9b4f29602b79c6 100644 --- a/test/parallel/test-https-agent-getname.js +++ b/test/parallel/test-https-agent-getname.js @@ -14,7 +14,7 @@ const agent = new https.Agent(); // empty options assert.strictEqual( agent.getName({}), - 'localhost:::::::::' + 'localhost::::::::::' ); // pass all options arguments @@ -33,5 +33,5 @@ const options = { assert.strictEqual( agent.getName(options), - '0.0.0.0:443:192.168.1.1:ca:cert:ciphers:key:pfx:false:localhost' + '0.0.0.0:443:192.168.1.1:ca:cert:ciphers:key:pfx:false:localhost:' ); diff --git a/test/parallel/test-https-agent-secure-protocol.js b/test/parallel/test-https-agent-secure-protocol.js new file mode 100644 index 00000000000000..7cca682101fa0b --- /dev/null +++ b/test/parallel/test-https-agent-secure-protocol.js @@ -0,0 +1,60 @@ +'use strict'; +const assert = require('assert'); +const common = require('../common'); + +if (!common.hasCrypto) { + common.skip('missing crypto'); + return; +} + +const https = require('https'); +const fs = require('fs'); + +const options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), + ca: fs.readFileSync(common.fixturesDir + '/keys/ca1-cert.pem') +}; + +const server = https.Server(options, function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(0, common.mustCall(function() { + const port = this.address().port; + const globalAgent = https.globalAgent; + globalAgent.keepAlive = true; + https.get({ + path: '/', + port: port, + ca: options.ca, + rejectUnauthorized: true, + servername: 'agent1', + secureProtocol: 'SSLv23_method' + }, common.mustCall(function(res) { + res.resume(); + globalAgent.once('free', common.mustCall(function() { + https.get({ + path: '/', + port: port, + ca: options.ca, + rejectUnauthorized: true, + servername: 'agent1', + secureProtocol: 'TLSv1_method' + }, common.mustCall(function(res) { + res.resume(); + globalAgent.once('free', common.mustCall(function() { + // Verify that two keep-alived connections are created + // due to the different secureProtocol settings: + const keys = Object.keys(globalAgent.freeSockets); + assert.strictEqual(keys.length, 2); + assert.ok(keys[0].includes(':SSLv23_method')); + assert.ok(keys[1].includes(':TLSv1_method')); + globalAgent.destroy(); + server.close(); + })); + })); + })); + })); +})); diff --git a/test/parallel/test-https-host-headers.js b/test/parallel/test-https-host-headers.js index e4fd6dfe92ef15..3e998d470487ef 100644 --- a/test/parallel/test-https-host-headers.js +++ b/test/parallel/test-https-host-headers.js @@ -51,9 +51,7 @@ function testHttps() { httpsServer.listen(0, function(er) { console.log(`test https server listening on port ${this.address().port}`); - - if (er) throw er; - + assert.ifError(er); https.get({ method: 'GET', path: '/' + (counter++), diff --git a/test/parallel/test-https-strict.js b/test/parallel/test-https-strict.js index 871d9ef94e6960..ff9c1790824429 100644 --- a/test/parallel/test-https-strict.js +++ b/test/parallel/test-https-strict.js @@ -23,60 +23,60 @@ function read(fname) { } // key1 is signed by ca1. -var key1 = read('agent1-key.pem'); -var cert1 = read('agent1-cert.pem'); +const key1 = read('agent1-key.pem'); +const cert1 = read('agent1-cert.pem'); // key2 has a self signed cert -var key2 = read('agent2-key.pem'); -var cert2 = read('agent2-cert.pem'); +const key2 = read('agent2-key.pem'); +const cert2 = read('agent2-cert.pem'); // key3 is signed by ca2. -var key3 = read('agent3-key.pem'); -var cert3 = read('agent3-cert.pem'); +const key3 = read('agent3-key.pem'); +const cert3 = read('agent3-cert.pem'); -var ca1 = read('ca1-cert.pem'); -var ca2 = read('ca2-cert.pem'); +const ca1 = read('ca1-cert.pem'); +const ca2 = read('ca2-cert.pem'); // different agents to use different CA lists. // this api is beyond bad. -var agent0 = new https.Agent(); -var agent1 = new https.Agent({ ca: [ca1] }); -var agent2 = new https.Agent({ ca: [ca2] }); -var agent3 = new https.Agent({ ca: [ca1, ca2] }); +const agent0 = new https.Agent(); +const agent1 = new https.Agent({ ca: [ca1] }); +const agent2 = new https.Agent({ ca: [ca2] }); +const agent3 = new https.Agent({ ca: [ca1, ca2] }); -var options1 = { +const options1 = { key: key1, cert: cert1 }; -var options2 = { +const options2 = { key: key2, cert: cert2 }; -var options3 = { +const options3 = { key: key3, cert: cert3 }; -var server1 = server(options1); -var server2 = server(options2); -var server3 = server(options3); +const server1 = server(options1); +const server2 = server(options2); +const server3 = server(options3); -var listenWait = 0; +let listenWait = 0; server1.listen(0, listening()); server2.listen(0, listening()); server3.listen(0, listening()); -var responseErrors = {}; -var expectResponseCount = 0; -var responseCount = 0; -var pending = 0; +const responseErrors = {}; +let expectResponseCount = 0; +let responseCount = 0; +let pending = 0; -function server(options, port) { - var s = https.createServer(options, handler); +function server(options) { + const s = https.createServer(options, handler); s.requests = []; s.expectCount = 0; return s; @@ -91,7 +91,7 @@ function handler(req, res) { function listening() { listenWait++; - return function() { + return () => { listenWait--; if (listenWait === 0) { allListening(); @@ -101,7 +101,7 @@ function listening() { function makeReq(path, port, error, host, ca) { pending++; - var options = { + const options = { port: port, path: path, ca: ca @@ -125,9 +125,9 @@ function makeReq(path, port, error, host, ca) { if (host) { options.headers = { host: host }; } - var req = https.get(options); + const req = https.get(options); expectResponseCount++; - var server = port === server1.address().port ? server1 : + const server = port === server1.address().port ? server1 : port === server2.address().port ? server2 : port === server3.address().port ? server3 : null; @@ -135,9 +135,9 @@ function makeReq(path, port, error, host, ca) { if (!server) throw new Error('invalid port: ' + port); server.expectCount++; - req.on('response', function(res) { + req.on('response', (res) => { responseCount++; - assert.equal(res.connection.authorizationError, error); + assert.strictEqual(res.connection.authorizationError, error); responseErrors[path] = res.connection.authorizationError; pending--; if (pending === 0) { @@ -195,10 +195,9 @@ function allListening() { } -process.on('exit', function() { - console.error(responseErrors); - assert.equal(server1.requests.length, server1.expectCount); - assert.equal(server2.requests.length, server2.expectCount); - assert.equal(server3.requests.length, server3.expectCount); - assert.equal(responseCount, expectResponseCount); +process.on('exit', () => { + assert.strictEqual(server1.requests.length, server1.expectCount); + assert.strictEqual(server2.requests.length, server2.expectCount); + assert.strictEqual(server3.requests.length, server3.expectCount); + assert.strictEqual(responseCount, expectResponseCount); }); diff --git a/test/parallel/test-https-truncate.js b/test/parallel/test-https-truncate.js index 4101a8c974e736..c96b385fc37fde 100644 --- a/test/parallel/test-https-truncate.js +++ b/test/parallel/test-https-truncate.js @@ -1,11 +1,12 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } + +const assert = require('assert'); const https = require('https'); const fs = require('fs'); @@ -14,7 +15,7 @@ const key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); const cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); // number of bytes discovered empirically to trigger the bug -const data = Buffer.allocUnsafe(1024 * 32 + 1); +const data = Buffer.alloc(1024 * 32 + 1); httpsTest(); @@ -36,12 +37,11 @@ function httpsTest() { } -function test(res) { - res.on('end', function() { +const test = common.mustCall(function(res) { + res.on('end', common.mustCall(function() { assert.strictEqual(res._readableState.length, 0); assert.strictEqual(bytes, data.length); - console.log('ok'); - }); + })); // Pause and then resume on each chunk, to ensure that there will be // a lone byte hanging out at the very end. @@ -49,6 +49,6 @@ function test(res) { res.on('data', function(chunk) { bytes += chunk.length; this.pause(); - setTimeout(this.resume.bind(this)); + setTimeout(this.resume.bind(this), 1); }); -} +}); diff --git a/test/parallel/test-icu-punycode.js b/test/parallel/test-icu-punycode.js index d9b36e7df78882..62508bc9f78f49 100644 --- a/test/parallel/test-icu-punycode.js +++ b/test/parallel/test-icu-punycode.js @@ -1,6 +1,11 @@ 'use strict'; - const common = require('../common'); + +if (!common.hasIntl) { + common.skip('missing Intl'); + return; +} + const icu = getPunycode(); const assert = require('assert'); @@ -12,11 +17,6 @@ function getPunycode() { } } -if (!icu) { - common.skip('icu punycode tests because ICU is not present.'); - return; -} - // Credit for list: http://www.i18nguy.com/markup/idna-examples.html const tests = [ 'افغانستا.icom.museum', diff --git a/test/parallel/test-icu-stringwidth.js b/test/parallel/test-icu-stringwidth.js index 5b66f00c32840c..80e798b13af154 100644 --- a/test/parallel/test-icu-stringwidth.js +++ b/test/parallel/test-icu-stringwidth.js @@ -1,15 +1,15 @@ // Flags: --expose_internals 'use strict'; - const common = require('../common'); -const assert = require('assert'); -const readline = require('internal/readline'); -if (!process.binding('config').hasIntl) { - common.skip('missing intl... skipping test'); +if (!common.hasIntl) { + common.skip('missing Intl'); return; } +const assert = require('assert'); +const readline = require('internal/readline'); + // Test column width assert.strictEqual(readline.getStringWidth('a'), 1); assert.strictEqual(readline.getStringWidth('丁'), 2); diff --git a/test/parallel/test-icu-transcode.js b/test/parallel/test-icu-transcode.js index c099e754ca55d6..463b2fca9188ba 100644 --- a/test/parallel/test-icu-transcode.js +++ b/test/parallel/test-icu-transcode.js @@ -1,9 +1,14 @@ 'use strict'; -require('../common'); +const common = require('../common'); + +if (!common.hasIntl) { + common.skip('missing Intl'); + return; +} + const buffer = require('buffer'); const assert = require('assert'); - const orig = Buffer.from('tést €', 'utf8'); // Test Transcoding diff --git a/test/parallel/test-intl-v8BreakIterator.js b/test/parallel/test-intl-v8BreakIterator.js index 4af3452b576f84..70f0f782bbc7e7 100644 --- a/test/parallel/test-intl-v8BreakIterator.js +++ b/test/parallel/test-intl-v8BreakIterator.js @@ -1,11 +1,11 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); if (!common.hasIntl || Intl.v8BreakIterator === undefined) { - return common.skip('no Intl'); + return common.skip('missing Intl'); } +const assert = require('assert'); const warning = 'Intl.v8BreakIterator is deprecated and will be removed soon.'; common.expectWarning('DeprecationWarning', warning); diff --git a/test/parallel/test-os.js b/test/parallel/test-os.js index 5a0a9f6ad14cbc..ce0d2ee054d1f9 100644 --- a/test/parallel/test-os.js +++ b/test/parallel/test-os.js @@ -107,8 +107,8 @@ switch (platform) { const filter = function(e) { return e.address === '127.0.0.1'; }; const actual = interfaces.lo.filter(filter); const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', - mac: '00:00:00:00:00:00', family: 'IPv4', - internal: true }]; + mac: '00:00:00:00:00:00', family: 'IPv4', + internal: true }]; assert.deepStrictEqual(actual, expected); break; } @@ -117,8 +117,8 @@ switch (platform) { const filter = function(e) { return e.address === '127.0.0.1'; }; const actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', - mac: '00:00:00:00:00:00', family: 'IPv4', - internal: true }]; + mac: '00:00:00:00:00:00', family: 'IPv4', + internal: true }]; assert.deepStrictEqual(actual, expected); break; } diff --git a/test/parallel/test-pipe-file-to-http.js b/test/parallel/test-pipe-file-to-http.js index f72cfe7d793348..0ea9244ff76946 100644 --- a/test/parallel/test-pipe-file-to-http.js +++ b/test/parallel/test-pipe-file-to-http.js @@ -38,7 +38,7 @@ server.on('listening', function() { const cmd = common.ddCommand(filename, 10240); cp.exec(cmd, function(err) { - if (err) throw err; + assert.ifError(err); makeRequest(); }); }); diff --git a/test/parallel/test-pipe-writev.js b/test/parallel/test-pipe-writev.js new file mode 100644 index 00000000000000..6440b5f623761d --- /dev/null +++ b/test/parallel/test-pipe-writev.js @@ -0,0 +1,46 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +if (common.isWindows) { + common.skip('Unix-specific test'); + return; +} + +common.refreshTmpDir(); + +const server = net.createServer((connection) => { + connection.on('error', (err) => { + throw err; + }); + + const writev = connection._writev.bind(connection); + connection._writev = common.mustCall(writev); + + connection.cork(); + connection.write('pi'); + connection.write('ng'); + connection.end(); +}); + +server.on('error', (err) => { + throw err; +}); + +server.listen(common.PIPE, () => { + const client = net.connect(common.PIPE); + + client.on('error', (err) => { + throw err; + }); + + client.on('data', common.mustCall((data) => { + assert.strictEqual(data.toString(), 'ping'); + })); + + client.on('end', () => { + server.close(); + }); +}); diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index 4ee564f0520cc5..bf3c4a09cf5600 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -32,43 +32,41 @@ const fixtureD = fixture('define-global.js'); const fixtureThrows = fixture('throws_error4.js'); // test preloading a single module works -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA]) + ' ' + - fixtureB, - function(err, stdout, stderr) { - if (err) throw err; - assert.strictEqual(stdout, 'A\nB\n'); - }); +childProcess.exec(nodeBinary + ' ' + preloadOption([fixtureA]) + ' ' + fixtureB, + function(err, stdout, stderr) { + if (err) throw err; + assert.strictEqual(stdout, 'A\nB\n'); + }); // test preloading multiple modules works -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA, fixtureB]) + ' ' + - fixtureC, +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA, fixtureB]) + ' ' + fixtureC, function(err, stdout, stderr) { if (err) throw err; assert.strictEqual(stdout, 'A\nB\nC\n'); - }); + } +); // test that preloading a throwing module aborts -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA, fixtureThrows]) + ' ' + - fixtureB, +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA, fixtureThrows]) + ' ' + fixtureB, function(err, stdout, stderr) { if (err) { assert.strictEqual(stdout, 'A\n'); } else { throw new Error('Preload should have failed'); } - }); + } +); // test that preload can be used with --eval -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA]) + - '-e "console.log(\'hello\');"', +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA]) + '-e "console.log(\'hello\');"', function(err, stdout, stderr) { if (err) throw err; assert.strictEqual(stdout, 'A\nhello\n'); - }); + } +); // test that preload can be used with stdin const stdinProc = childProcess.spawn( @@ -108,42 +106,43 @@ replProc.on('close', function(code) { // test that preload placement at other points in the cmdline // also test that duplicated preload only gets loaded once -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA]) + - '-e "console.log(\'hello\');" ' + - preloadOption([fixtureA, fixtureB]), +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA]) + + '-e "console.log(\'hello\');" ' + preloadOption([fixtureA, fixtureB]), function(err, stdout, stderr) { if (err) throw err; assert.strictEqual(stdout, 'A\nB\nhello\n'); - }); + } +); // test that preload works with -i -const interactive = childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureD]) + - '-i', +const interactive = childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureD]) + '-i', common.mustCall(function(err, stdout, stderr) { assert.ifError(err); assert.strictEqual(stdout, "> 'test'\n> "); - })); + }) +); interactive.stdin.write('a\n'); interactive.stdin.write('process.exit()\n'); -childProcess.exec(nodeBinary + ' ' + - '--require ' + fixture('cluster-preload.js') + ' ' + - fixture('cluster-preload-test.js'), +childProcess.exec( + nodeBinary + ' ' + '--require ' + fixture('cluster-preload.js') + ' ' + + fixture('cluster-preload-test.js'), function(err, stdout, stderr) { if (err) throw err; assert.ok(/worker terminated with code 43/.test(stdout)); - }); + } +); // https://github.com/nodejs/node/issues/1691 process.chdir(common.fixturesDir); -childProcess.exec(nodeBinary + ' ' + - '--expose_debug_as=v8debug ' + - '--require ' + fixture('cluster-preload.js') + ' ' + - 'cluster-preload-test.js', +childProcess.exec( + nodeBinary + ' ' + '--expose_debug_as=v8debug ' + '--require ' + + fixture('cluster-preload.js') + ' ' + 'cluster-preload-test.js', function(err, stdout, stderr) { if (err) throw err; assert.ok(/worker terminated with code 43/.test(stdout)); - }); + } +); diff --git a/test/parallel/test-process-cpuUsage.js b/test/parallel/test-process-cpuUsage.js index 92dc71918585c3..0c553c576a1f25 100644 --- a/test/parallel/test-process-cpuUsage.js +++ b/test/parallel/test-process-cpuUsage.js @@ -33,27 +33,57 @@ for (let i = 0; i < 10; i++) { assert(diffUsage.system >= 0); } +const invalidUserArgument = + /^TypeError: value of user property of argument is invalid$/; +const invalidSystemArgument = + /^TypeError: value of system property of argument is invalid$/; + // Ensure that an invalid shape for the previous value argument throws an error. -assert.throws(function() { process.cpuUsage(1); }); -assert.throws(function() { process.cpuUsage({}); }); -assert.throws(function() { process.cpuUsage({ user: 'a' }); }); -assert.throws(function() { process.cpuUsage({ system: 'b' }); }); -assert.throws(function() { process.cpuUsage({ user: null, system: 'c' }); }); -assert.throws(function() { process.cpuUsage({ user: 'd', system: null }); }); -assert.throws(function() { process.cpuUsage({ user: -1, system: 2 }); }); -assert.throws(function() { process.cpuUsage({ user: 3, system: -2 }); }); -assert.throws(function() { +assert.throws(() => { + process.cpuUsage(1); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({}); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: 'a' }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ system: 'b' }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: null, system: 'c' }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: 'd', system: null }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: -1, system: 2 }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: 3, system: -2 }); +}, invalidSystemArgument); + +assert.throws(() => { process.cpuUsage({ user: Number.POSITIVE_INFINITY, system: 4 }); -}); -assert.throws(function() { +}, invalidUserArgument); + +assert.throws(() => { process.cpuUsage({ user: 5, system: Number.NEGATIVE_INFINITY }); -}); +}, invalidSystemArgument); // Ensure that the return value is the expected shape. function validateResult(result) { diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js index 002ec7c1ab4c7c..1e1bd016966842 100644 --- a/test/parallel/test-process-getgroups.js +++ b/test/parallel/test-process-getgroups.js @@ -13,7 +13,7 @@ if (typeof process.getgroups === 'function') { assert(Array.isArray(groups)); assert(groups.length > 0); exec('id -G', function(err, stdout) { - if (err) throw err; + assert.ifError(err); var real_groups = stdout.match(/\d+/g).map(Number); assert.equal(groups.length, real_groups.length); check(groups, real_groups); diff --git a/test/parallel/test-process-hrtime.js b/test/parallel/test-process-hrtime.js index db16be0ad9e812..9280b671f316d6 100644 --- a/test/parallel/test-process-hrtime.js +++ b/test/parallel/test-process-hrtime.js @@ -3,7 +3,7 @@ require('../common'); var assert = require('assert'); // the default behavior, return an Array "tuple" of numbers -var tuple = process.hrtime(); +const tuple = process.hrtime(); // validate the default behavior validateTuple(tuple); @@ -12,16 +12,16 @@ validateTuple(tuple); validateTuple(process.hrtime(tuple)); // test that only an Array may be passed to process.hrtime() -assert.throws(function() { +assert.throws(() => { process.hrtime(1); -}); +}, /^TypeError: process.hrtime\(\) only accepts an Array tuple$/); function validateTuple(tuple) { assert(Array.isArray(tuple)); - assert.equal(2, tuple.length); - tuple.forEach(function(v) { - assert.equal('number', typeof v); - assert(isFinite(v)); + assert.strictEqual(tuple.length, 2); + tuple.forEach((v) => { + assert.strictEqual(typeof v, 'number'); + assert.strictEqual(isFinite(v), true); }); } diff --git a/test/parallel/test-punycode.js b/test/parallel/test-punycode.js index 7d969c66ee4e13..60175557042ff9 100644 --- a/test/parallel/test-punycode.js +++ b/test/parallel/test-punycode.js @@ -6,18 +6,33 @@ const assert = require('assert'); assert.strictEqual(punycode.encode('ü'), 'tda'); assert.strictEqual(punycode.encode('Goethe'), 'Goethe-'); assert.strictEqual(punycode.encode('Bücher'), 'Bcher-kva'); -assert.strictEqual(punycode.encode( - 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'), - 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'); +assert.strictEqual( + punycode.encode( + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres' + ), + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal' +); assert.strictEqual(punycode.encode('日本語'), 'wgv71a119e'); assert.strictEqual(punycode.decode('tda'), 'ü'); assert.strictEqual(punycode.decode('Goethe-'), 'Goethe'); assert.strictEqual(punycode.decode('Bcher-kva'), 'Bücher'); -assert.strictEqual(punycode.decode( - 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'), - 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'); +assert.strictEqual( + punycode.decode( + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal' + ), + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres' +); assert.strictEqual(punycode.decode('wgv71a119e'), '日本語'); +assert.throws(() => { + punycode.decode(' '); +}, /^RangeError: Invalid input$/); +assert.throws(() => { + punycode.decode('α-'); +}, /^RangeError: Illegal input >= 0x80 \(not a basic code point\)$/); +assert.throws(() => { + punycode.decode('あ'); +}, /^RangeError: Overflow: input needs wider integers to process$/); // http://tools.ietf.org/html/rfc3492#section-7.1 const tests = [ diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 37cf66705d56d7..ced2b3a3e6d9c3 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -44,11 +44,11 @@ var qsTestCases = [ ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], // See: https://github.com/joyent/node/issues/1707 ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', - 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', - { hasOwnProperty: 'x', - toString: 'foo', - valueOf: 'bar', - __defineGetter__: 'baz' }], + 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + { hasOwnProperty: 'x', + toString: 'foo', + valueOf: 'bar', + __defineGetter__: 'baz' }], // See: https://github.com/joyent/node/issues/3058 ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }], [null, '', {}], diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 59b75cd0a86231..509995bc9ad619 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -62,7 +62,7 @@ function isWarned(emitter) { // disable history fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal, - historySize: 0 }); + historySize: 0 }); assert.strictEqual(rli.historySize, 0); fi.emit('data', 'asdf\n'); diff --git a/test/parallel/test-regress-GH-3739.js b/test/parallel/test-regress-GH-3739.js index aef54c3ea6c7c4..11caddae0847aa 100644 --- a/test/parallel/test-regress-GH-3739.js +++ b/test/parallel/test-regress-GH-3739.js @@ -27,5 +27,5 @@ assert(common.fileExists(dir), 'Directory is not accessible'); // Test if file exists asynchronously fs.access(dir, function(err) { - assert(!err, 'Directory is not accessible'); + assert.ifError(err); }); diff --git a/test/parallel/test-regress-GH-897.js b/test/parallel/test-regress-GH-897.js new file mode 100644 index 00000000000000..911ad6b6b2e112 --- /dev/null +++ b/test/parallel/test-regress-GH-897.js @@ -0,0 +1,20 @@ +'use strict'; + +// Test for bug where a timer duration greater than 0 ms but less than 1 ms +// resulted in the duration being set for 1000 ms. The expected behavior is +// that the timeout would be set for 1 ms, and thus fire before timers set +// with values greater than 1ms. +// +// Ref: https://github.com/nodejs/node-v0.x-archive/pull/897 + +const common = require('../common'); + +let timer; + +setTimeout(function() { + clearTimeout(timer); +}, 0.1); // 0.1 should be treated the same as 1, not 1000... + +timer = setTimeout(function() { + common.fail('timers fired out of order'); +}, 2); // ...so this timer should fire second. diff --git a/test/parallel/test-repl-envvars.js b/test/parallel/test-repl-envvars.js index b08f6cbaf621e6..e8c369b244c607 100644 --- a/test/parallel/test-repl-envvars.js +++ b/test/parallel/test-repl-envvars.js @@ -45,7 +45,7 @@ function run(test) { }; REPL.createInternalRepl(env, opts, function(err, repl) { - if (err) throw err; + assert.ifError(err); // The REPL registers 'module' and 'require' globals common.allowGlobals(repl.context.module, repl.context.require); diff --git a/test/parallel/test-repl-history-perm.js b/test/parallel/test-repl-history-perm.js index 4a374cb0ab12e8..16732a44296f1d 100644 --- a/test/parallel/test-repl-history-perm.js +++ b/test/parallel/test-repl-history-perm.js @@ -33,8 +33,7 @@ common.refreshTmpDir(); const replHistoryPath = path.join(common.tmpDir, '.node_repl_history'); const checkResults = common.mustCall(function(err, r) { - if (err) - throw err; + assert.ifError(err); // The REPL registers 'module' and 'require' globals common.allowGlobals(r.context.module, r.context.require); diff --git a/test/parallel/test-repl-tab-complete.js b/test/parallel/test-repl-tab-complete.js index b5f1d3856d3c71..4e05714ab5fc56 100644 --- a/test/parallel/test-repl-tab-complete.js +++ b/test/parallel/test-repl-tab-complete.js @@ -231,6 +231,7 @@ putIn.run([ testMe.complete('proxy.', common.mustCall(function(error, data) { assert.strictEqual(error, null); + assert(Array.isArray(data)); })); // Make sure tab completion does not include integer members of an Array @@ -290,7 +291,7 @@ const testNonGlobal = repl.start({ }); const builtins = [['Infinity', '', 'Int16Array', 'Int32Array', - 'Int8Array'], 'I']; + 'Int8Array'], 'I']; if (common.hasIntl) { builtins[0].push('Intl'); @@ -307,9 +308,7 @@ const testCustomCompleterSyncMode = repl.start({ input: putIn, output: putIn, completer: function completer(line) { - const hits = customCompletions.filter((c) => { - return c.indexOf(line) === 0; - }); + const hits = customCompletions.filter((c) => c.startsWith(line)); // Show all completions if none found. return [hits.length ? hits : customCompletions, line]; } @@ -339,9 +338,7 @@ const testCustomCompleterAsyncMode = repl.start({ input: putIn, output: putIn, completer: function completer(line, callback) { - const hits = customCompletions.filter((c) => { - return c.indexOf(line) === 0; - }); + const hits = customCompletions.filter((c) => c.startsWith(line)); // Show all completions if none found. callback(null, [hits.length ? hits : customCompletions, line]); } diff --git a/test/parallel/test-repl-underscore.js b/test/parallel/test-repl-underscore.js index 97fc508ad9eee4..91f32223e180b9 100644 --- a/test/parallel/test-repl-underscore.js +++ b/test/parallel/test-repl-underscore.js @@ -8,6 +8,7 @@ const stream = require('stream'); testSloppyMode(); testStrictMode(); testResetContext(); +testResetContextGlobal(); testMagicMode(); function testSloppyMode() { @@ -131,7 +132,28 @@ function testResetContext() { ]); } -function initRepl(mode) { +function testResetContextGlobal() { + const r = initRepl(repl.REPL_MODE_STRICT, true); + + r.write(`_ = 10; // explicitly set to 10 + _; // 10 from user input + .clear // No output because useGlobal is true + _; // remains 10 + `); + + assertOutput(r.output, [ + 'Expression assignment to _ now disabled.', + '10', + '10', + '10', + ]); + + // delete globals leaked by REPL when `useGlobal` is `true` + delete global.module; + delete global.require; +} + +function initRepl(mode, useGlobal) { const inputStream = new stream.PassThrough(); const outputStream = new stream.PassThrough(); outputStream.accum = ''; @@ -146,7 +168,8 @@ function initRepl(mode) { useColors: false, terminal: false, prompt: '', - replMode: mode + replMode: mode, + useGlobal: useGlobal }); } diff --git a/test/parallel/test-require-symlink.js b/test/parallel/test-require-symlink.js index 0792bc13bb70a7..4e74606bedeed6 100644 --- a/test/parallel/test-require-symlink.js +++ b/test/parallel/test-require-symlink.js @@ -11,13 +11,15 @@ const util = require('util'); common.refreshTmpDir(); const linkTarget = path.join(common.fixturesDir, - '/module-require-symlink/node_modules/dep2/'); + '/module-require-symlink/node_modules/dep2/'); -const linkDir = path.join(common.fixturesDir, - '/module-require-symlink/node_modules/dep1/node_modules/dep2'); +const linkDir = path.join( + common.fixturesDir, + '/module-require-symlink/node_modules/dep1/node_modules/dep2' +); const linkScriptTarget = path.join(common.fixturesDir, - '/module-require-symlink/symlinked.js'); + '/module-require-symlink/symlinked.js'); const linkScript = path.join(common.tmpDir, 'module-require-symlink.js'); diff --git a/test/parallel/test-spawn-cmd-named-pipe.js b/test/parallel/test-spawn-cmd-named-pipe.js index c463bf6140053f..b4264880165d39 100644 --- a/test/parallel/test-spawn-cmd-named-pipe.js +++ b/test/parallel/test-spawn-cmd-named-pipe.js @@ -43,7 +43,7 @@ if (!process.argv[2]) { } const args = ['/c', process.execPath, __filename, 'child', - '<', stdinPipeName, '>', stdoutPipeName]; + '<', stdinPipeName, '>', stdoutPipeName]; const child = spawn(comspec, args); diff --git a/test/parallel/test-stdio-closed.js b/test/parallel/test-stdio-closed.js index a85467f76a6d0f..98e4f980d50dd6 100644 --- a/test/parallel/test-stdio-closed.js +++ b/test/parallel/test-stdio-closed.js @@ -2,6 +2,7 @@ const common = require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; +const fs = require('fs'); if (common.isWindows) { common.skip('platform not supported.'); @@ -9,21 +10,7 @@ if (common.isWindows) { } if (process.argv[2] === 'child') { - try { - process.stdout.write('stdout', function() { - try { - process.stderr.write('stderr', function() { - process.exit(42); - }); - } catch (e) { - process.exit(84); - } - }); - } catch (e) { - assert.strictEqual(e.code, 'EBADF'); - assert.strictEqual(e.message, 'EBADF: bad file descriptor, write'); - process.exit(126); - } + [0, 1, 2].forEach((i) => assert.doesNotThrow(() => fs.fstatSync(i))); return; } @@ -32,5 +19,5 @@ const cmd = `"${process.execPath}" "${__filename}" child 1>&- 2>&-`; const proc = spawn('/bin/sh', ['-c', cmd], { stdio: 'inherit' }); proc.on('exit', common.mustCall(function(exitCode) { - assert.strictEqual(exitCode, common.isAix ? 126 : 42); + assert.strictEqual(exitCode, 0); })); diff --git a/test/parallel/test-stdout-to-file.js b/test/parallel/test-stdout-to-file.js index 10391c481a826d..80093160212f9a 100644 --- a/test/parallel/test-stdout-to-file.js +++ b/test/parallel/test-stdout-to-file.js @@ -28,8 +28,7 @@ function test(size, useBuffer, cb) { console.log(`${size} chars to ${tmpFile}...`); childProcess.exec(cmd, common.mustCall(function(err) { - if (err) throw err; - + assert.ifError(err); console.log('done!'); var stat = fs.statSync(tmpFile); diff --git a/test/parallel/test-stream-end-paused.js b/test/parallel/test-stream-end-paused.js index 3c46d49ea65d65..4b585fdb999890 100644 --- a/test/parallel/test-stream-end-paused.js +++ b/test/parallel/test-stream-end-paused.js @@ -21,7 +21,7 @@ stream.pause(); setTimeout(common.mustCall(function() { stream.on('end', common.mustCall(function() {})); stream.resume(); -})); +}), 1); process.on('exit', function() { assert(calledRead); diff --git a/test/parallel/test-stream-pipe-await-drain-manual-resume.js b/test/parallel/test-stream-pipe-await-drain-manual-resume.js index 33540b47b3d5e3..96360429e58856 100644 --- a/test/parallel/test-stream-pipe-await-drain-manual-resume.js +++ b/test/parallel/test-stream-pipe-await-drain-manual-resume.js @@ -1,6 +1,7 @@ 'use strict'; const common = require('../common'); const stream = require('stream'); +const assert = require('assert'); // A consumer stream with a very low highWaterMark, which starts in a state // where it buffers the chunk it receives rather than indicating that they @@ -26,6 +27,11 @@ const readable = new stream.Readable({ readable.pipe(writable); readable.once('pause', common.mustCall(() => { + assert.strictEqual( + readable._readableState.awaitDrain, + 1, + 'awaitDrain doesn\'t increase' + ); // First pause, resume manually. The next write() to writable will still // return false, because chunks are still being buffered, so it will increase // the awaitDrain counter again. @@ -34,6 +40,11 @@ readable.once('pause', common.mustCall(() => { })); readable.once('pause', common.mustCall(() => { + assert.strictEqual( + readable._readableState.awaitDrain, + 1, + '.resume() does not reset counter' + ); // Second pause, handle all chunks from now on. Once all callbacks that // are currently queued up are handled, the awaitDrain drain counter should // fall back to 0 and all chunks that are pending on the readable side @@ -50,5 +61,10 @@ readable.push(Buffer.alloc(100)); // Should get through to the writable. readable.push(null); writable.on('finish', common.mustCall(() => { + assert.strictEqual( + readable._readableState.awaitDrain, + 0, + 'awaitDrain not 0 after all chunks are written' + ); // Everything okay, all chunks were written. })); diff --git a/test/parallel/test-stream-pipe-await-drain-push-while-write.js b/test/parallel/test-stream-pipe-await-drain-push-while-write.js index 1dfdfdb80c8d71..67a8f304c31614 100644 --- a/test/parallel/test-stream-pipe-await-drain-push-while-write.js +++ b/test/parallel/test-stream-pipe-await-drain-push-while-write.js @@ -1,16 +1,34 @@ 'use strict'; const common = require('../common'); const stream = require('stream'); +const assert = require('assert'); + +const awaitDrainStates = [ + 1, // after first chunk before callback + 1, // after second chunk before callback + 0 // resolving chunk pushed after first chunk, awaitDrain is decreased +]; // A writable stream which pushes data onto the stream which pipes into it, // but only the first time it's written to. Since it's not paused at this time, // a second write will occur. If the pipe increases awaitDrain twice, we'll // never get subsequent chunks because 'drain' is only emitted once. const writable = new stream.Writable({ - write: common.mustCall((chunk, encoding, cb) => { + write: common.mustCall(function(chunk, encoding, cb) { if (chunk.length === 32 * 1024) { // first chunk - readable.push(new Buffer(33 * 1024)); // above hwm + const beforePush = readable._readableState.awaitDrain; + readable.push(new Buffer(34 * 1024)); // above hwm + // We should check if awaitDrain counter is increased. + const afterPush = readable._readableState.awaitDrain; + assert.strictEqual(afterPush - beforePush, 1, + 'Counter is not increased for awaitDrain'); } + + assert.strictEqual( + awaitDrainStates.shift(), + readable._readableState.awaitDrain, + 'State variable awaitDrain is not correct.' + ); cb(); }, 3) }); diff --git a/test/parallel/test-stream-pipe-await-drain.js b/test/parallel/test-stream-pipe-await-drain.js index fba99ed4563c14..fc822bb60b7aa8 100644 --- a/test/parallel/test-stream-pipe-await-drain.js +++ b/test/parallel/test-stream-pipe-await-drain.js @@ -1,12 +1,14 @@ 'use strict'; const common = require('../common'); const stream = require('stream'); +const assert = require('assert'); // This is very similar to test-stream-pipe-cleanup-pause.js. const reader = new stream.Readable(); const writer1 = new stream.Writable(); const writer2 = new stream.Writable(); +const writer3 = new stream.Writable(); // 560000 is chosen here because it is larger than the (default) highWaterMark // and will cause `.write()` to return false @@ -19,7 +21,10 @@ writer1._write = common.mustCall(function(chunk, encoding, cb) { this.emit('chunk-received'); cb(); }, 1); + writer1.once('chunk-received', function() { + assert.strictEqual(reader._readableState.awaitDrain, 0, + 'initial value is not 0'); setImmediate(function() { // This one should *not* get through to writer1 because writer2 is not // "done" processing. @@ -29,12 +34,26 @@ writer1.once('chunk-received', function() { // A "slow" consumer: writer2._write = common.mustCall(function(chunk, encoding, cb) { + assert.strictEqual( + reader._readableState.awaitDrain, 1, + 'awaitDrain isn\'t 1 after first push' + ); // Not calling cb here to "simulate" slow stream. + // This should be called exactly once, since the first .write() call + // will return false. +}, 1); +writer3._write = common.mustCall(function(chunk, encoding, cb) { + assert.strictEqual( + reader._readableState.awaitDrain, 2, + 'awaitDrain isn\'t 2 after second push' + ); + // Not calling cb here to "simulate" slow stream. // This should be called exactly once, since the first .write() call // will return false. }, 1); reader.pipe(writer1); reader.pipe(writer2); +reader.pipe(writer3); reader.push(buffer); diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index a20fc2ee732d0f..a8536bdcbab861 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -20,7 +20,7 @@ const Readable = require('stream').Readable; // we're testing what we think we are assert(!r._readableState.reading); r.on('readable', common.mustCall(function() {})); - }); + }, 1); } { @@ -40,7 +40,7 @@ const Readable = require('stream').Readable; // assert we're testing what we think we are assert(r._readableState.reading); r.on('readable', common.mustCall(function() {})); - }); + }, 1); } { @@ -60,5 +60,5 @@ const Readable = require('stream').Readable; // assert we're testing what we think we are assert(!r._readableState.reading); r.on('readable', common.mustCall(function() {})); - }); + }, 1); } diff --git a/test/parallel/test-stream-transform-objectmode-falsey-value.js b/test/parallel/test-stream-transform-objectmode-falsey-value.js index 429cc1c960eefb..9a05034b206421 100644 --- a/test/parallel/test-stream-transform-objectmode-falsey-value.js +++ b/test/parallel/test-stream-transform-objectmode-falsey-value.js @@ -1,33 +1,30 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var stream = require('stream'); -var PassThrough = stream.PassThrough; +const stream = require('stream'); +const PassThrough = stream.PassThrough; -var src = new PassThrough({ objectMode: true }); -var tx = new PassThrough({ objectMode: true }); -var dest = new PassThrough({ objectMode: true }); +const src = new PassThrough({ objectMode: true }); +const tx = new PassThrough({ objectMode: true }); +const dest = new PassThrough({ objectMode: true }); -var expect = [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; -var results = []; -process.on('exit', function() { - assert.deepStrictEqual(results, expect); - console.log('ok'); -}); +const expect = [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; +const results = []; -dest.on('data', function(x) { +dest.on('data', common.mustCall(function(x) { results.push(x); -}); +}, expect.length)); src.pipe(tx).pipe(dest); -var i = -1; -var int = setInterval(function() { - if (i > 10) { +let i = -1; +const int = setInterval(common.mustCall(function() { + if (results.length === expect.length) { src.end(); clearInterval(int); + assert.deepStrictEqual(results, expect); } else { src.write(i++); } -}); +}, expect.length + 1), 1); diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 92479fc88f2958..d024abbceb7f59 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -31,8 +31,7 @@ function test(decode, uncork, multi, next) { expectCount++; var expect = expectCount; return function(er) { - if (er) - throw er; + assert.ifError(er); counter++; assert.equal(counter, expect); }; diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 823407d396afb6..a2ae3f5174272d 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -46,7 +46,7 @@ function push() { console.error(' push #%d', pushes); if (r.push(Buffer.allocUnsafe(PUSHSIZE))) - setTimeout(push); + setTimeout(push, 1); } process.on('exit', function() { diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index c08cc287ce1cbf..dd2cb8d51055c7 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -16,7 +16,7 @@ test._read = function(size) { var chunk = chunks[n++]; setTimeout(function() { test.push(chunk === undefined ? null : chunk); - }); + }, 1); }; test.on('end', thrower); @@ -31,7 +31,7 @@ test.on('readable', function() { if (res) { bytesread += res.length; console.error('br=%d len=%d', bytesread, len); - setTimeout(next); + setTimeout(next, 1); } test.read(0); }); diff --git a/test/parallel/test-stream2-readable-wrap.js b/test/parallel/test-stream2-readable-wrap.js index 0cbd106d5b4b35..aa091dc3d806f0 100644 --- a/test/parallel/test-stream2-readable-wrap.js +++ b/test/parallel/test-stream2-readable-wrap.js @@ -1,77 +1,63 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); +const Readable = require('_stream_readable'); +const Writable = require('_stream_writable'); +const EE = require('events').EventEmitter; -var Readable = require('_stream_readable'); -var Writable = require('_stream_writable'); -var EE = require('events').EventEmitter; - -var testRuns = 0, completedRuns = 0; function runTest(highWaterMark, objectMode, produce) { - testRuns++; - var old = new EE(); - var r = new Readable({ highWaterMark: highWaterMark, - objectMode: objectMode }); - assert.equal(r, r.wrap(old)); + const old = new EE(); + const r = new Readable({ highWaterMark: highWaterMark, + objectMode: objectMode }); + assert.strictEqual(r, r.wrap(old)); - var ended = false; - r.on('end', function() { - ended = true; - }); + r.on('end', common.mustCall(function() {})); old.pause = function() { - console.error('old.pause()'); old.emit('pause'); flowing = false; }; old.resume = function() { - console.error('old.resume()'); old.emit('resume'); flow(); }; - var flowing; - var chunks = 10; - var oldEnded = false; - var expected = []; + let flowing; + let chunks = 10; + let oldEnded = false; + const expected = []; function flow() { flowing = true; while (flowing && chunks-- > 0) { - var item = produce(); + const item = produce(); expected.push(item); - console.log('old.emit', chunks, flowing); old.emit('data', item); - console.log('after emit', chunks, flowing); } if (chunks <= 0) { oldEnded = true; - console.log('old end', chunks, flowing); old.emit('end'); } } - var w = new Writable({ highWaterMark: highWaterMark * 2, - objectMode: objectMode }); - var written = []; + const w = new Writable({ highWaterMark: highWaterMark * 2, + objectMode: objectMode }); + const written = []; w._write = function(chunk, encoding, cb) { - console.log('_write', chunk); written.push(chunk); - setTimeout(cb); + setTimeout(cb, 1); }; - w.on('finish', function() { - completedRuns++; + w.on('finish', common.mustCall(function() { performAsserts(); - }); + })); r.pipe(w); flow(); function performAsserts() { - assert(ended); assert(oldEnded); assert.deepStrictEqual(written, expected); } @@ -81,10 +67,5 @@ runTest(100, false, function() { return Buffer.allocUnsafe(100); }); runTest(10, false, function() { return Buffer.from('xxxxxxxxxx'); }); runTest(1, true, function() { return { foo: 'bar' }; }); -var objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; +const objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; runTest(1, true, function() { return objectChunks.shift(); }); - -process.on('exit', function() { - assert.equal(testRuns, completedRuns); - console.log('ok'); -}); diff --git a/test/parallel/test-tls-addca.js b/test/parallel/test-tls-addca.js index 0e9571efdf0abf..7a6f9a77516e22 100644 --- a/test/parallel/test-tls-addca.js +++ b/test/parallel/test-tls-addca.js @@ -1,62 +1,50 @@ 'use strict'; const common = require('../common'); -const fs = require('fs'); -if (!common.hasCrypto) { - common.skip('missing crypto'); - return; -} -const tls = require('tls'); - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} +// Adding a CA certificate to contextWithCert should not also add it to +// contextWithoutCert. This is tested by trying to connect to a server that +// depends on that CA using contextWithoutCert. -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} +const join = require('path').join; +const { + assert, connect, keys, tls +} = require(join(common.fixturesDir, 'tls-connect'))(); -const caCert = loadPEM('ca1-cert'); const contextWithoutCert = tls.createSecureContext({}); const contextWithCert = tls.createSecureContext({}); -// Adding a CA certificate to contextWithCert should not also add it to -// contextWithoutCert. This is tested by trying to connect to a server that -// depends on that CA using contextWithoutCert. -contextWithCert.context.addCACert(caCert); +contextWithCert.context.addCACert(keys.agent1.ca); const serverOptions = { - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert'), + key: keys.agent1.key, + cert: keys.agent1.cert, }; -const server = tls.createServer(serverOptions, function() {}); const clientOptions = { - port: undefined, - ca: [caCert], + ca: [keys.agent1.ca], servername: 'agent1', rejectUnauthorized: true, }; -function startTest() { - // This client should fail to connect because it doesn't trust the CA +// This client should fail to connect because it doesn't trust the CA +// certificate. +clientOptions.secureContext = contextWithoutCert; + +connect({ + client: clientOptions, + server: serverOptions, +}, function(err, pair, cleanup) { + assert(err); + assert.strictEqual(err.message, 'unable to verify the first certificate'); + cleanup(); + + // This time it should connect because contextWithCert includes the needed CA // certificate. - clientOptions.secureContext = contextWithoutCert; - clientOptions.port = server.address().port; - const client = tls.connect(clientOptions, common.fail); - client.on('error', common.mustCall(() => { - client.destroy(); - - // This time it should connect because contextWithCert includes the needed - // CA certificate. - clientOptions.secureContext = contextWithCert; - const client2 = tls.connect(clientOptions, common.mustCall(() => { - client2.destroy(); - server.close(); - })); - client2.on('error', (e) => { - console.log(e); - }); - })); -} - -server.listen(0, startTest); + clientOptions.secureContext = contextWithCert; + connect({ + client: clientOptions, + server: serverOptions, + }, function(err, pair, cleanup) { + assert.ifError(err); + cleanup(); + }); +}); diff --git a/test/parallel/test-tls-ca-concat.js b/test/parallel/test-tls-ca-concat.js new file mode 100644 index 00000000000000..65c837bed9dc37 --- /dev/null +++ b/test/parallel/test-tls-ca-concat.js @@ -0,0 +1,24 @@ +'use strict'; +const common = require('../common'); + +// Check ca option can contain concatenated certs by prepending an unrelated +// non-CA cert and showing that agent6's CA root is still found. + +const join = require('path').join; +const { + assert, connect, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); + +connect({ + client: { + checkServerIdentity: (servername, cert) => { }, + ca: keys.agent1.cert + '\n' + keys.agent6.ca, + }, + server: { + cert: keys.agent6.cert, + key: keys.agent6.key, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + return cleanup(); +}); diff --git a/test/parallel/test-tls-cert-chains-concat.js b/test/parallel/test-tls-cert-chains-concat.js new file mode 100644 index 00000000000000..d53edef89842b9 --- /dev/null +++ b/test/parallel/test-tls-cert-chains-concat.js @@ -0,0 +1,50 @@ +'use strict'; +const common = require('../common'); + +// Check cert chain is received by client, and is completed with the ca cert +// known to the client. + +const join = require('path').join; +const { + assert, connect, debug, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); + +// agent6-cert.pem includes cert for agent6 and ca3 +connect({ + client: { + checkServerIdentity: (servername, cert) => { }, + ca: keys.agent6.ca, + }, + server: { + cert: keys.agent6.cert, + key: keys.agent6.key, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + + const peer = pair.client.conn.getPeerCertificate(); + debug('peer:\n', peer); + assert.strictEqual(peer.subject.emailAddress, 'adam.lippai@tresorit.com'); + assert.strictEqual(peer.subject.CN, 'Ádám Lippai'), + assert.strictEqual(peer.issuer.CN, 'ca3'); + assert.strictEqual(peer.serialNumber, 'C4CD893EF9A75DCC'); + + const next = pair.client.conn.getPeerCertificate(true).issuerCertificate; + const root = next.issuerCertificate; + delete next.issuerCertificate; + debug('next:\n', next); + assert.strictEqual(next.subject.CN, 'ca3'); + assert.strictEqual(next.issuer.CN, 'ca1'); + assert.strictEqual(next.serialNumber, '9A84ABCFB8A72ABF'); + + debug('root:\n', root); + assert.strictEqual(root.subject.CN, 'ca1'); + assert.strictEqual(root.issuer.CN, 'ca1'); + assert.strictEqual(root.serialNumber, '8DF21C01468AF393'); + + // No client cert, so empty object returned. + assert.deepStrictEqual(pair.server.conn.getPeerCertificate(), {}); + assert.deepStrictEqual(pair.server.conn.getPeerCertificate(true), {}); + + return cleanup(); +}); diff --git a/test/parallel/test-tls-cert-chains-in-ca.js b/test/parallel/test-tls-cert-chains-in-ca.js new file mode 100644 index 00000000000000..69f62c3f72d859 --- /dev/null +++ b/test/parallel/test-tls-cert-chains-in-ca.js @@ -0,0 +1,46 @@ +'use strict'; +const common = require('../common'); + +// Check cert chain is received by client, and is completed with the ca cert +// known to the client. + +const join = require('path').join; +const { + assert, connect, debug, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); + + +// agent6-cert.pem includes cert for agent6 and ca3, split it apart and +// provide ca3 in the .ca property. +const agent6Chain = keys.agent6.cert.split('-----END CERTIFICATE-----') + .map((c) => { return c + '-----END CERTIFICATE-----'; }); +const agent6End = agent6Chain[0]; +const agent6Middle = agent6Chain[1]; +connect({ + client: { + checkServerIdentity: (servername, cert) => { }, + ca: keys.agent6.ca, + }, + server: { + cert: agent6End, + key: keys.agent6.key, + ca: agent6Middle, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + + const peer = pair.client.conn.getPeerCertificate(); + debug('peer:\n', peer); + assert.strictEqual(peer.serialNumber, 'C4CD893EF9A75DCC'); + + const next = pair.client.conn.getPeerCertificate(true).issuerCertificate; + const root = next.issuerCertificate; + delete next.issuerCertificate; + debug('next:\n', next); + assert.strictEqual(next.serialNumber, '9A84ABCFB8A72ABF'); + + debug('root:\n', root); + assert.strictEqual(root.serialNumber, '8DF21C01468AF393'); + + return cleanup(); +}); diff --git a/test/parallel/test-tls-client-getephemeralkeyinfo.js b/test/parallel/test-tls-client-getephemeralkeyinfo.js index c1e6597245a612..fb42991e149548 100644 --- a/test/parallel/test-tls-client-getephemeralkeyinfo.js +++ b/test/parallel/test-tls-client-getephemeralkeyinfo.js @@ -46,7 +46,7 @@ function test(size, type, name, next) { }); server.on('close', common.mustCall(function(err) { - assert(!err); + assert.ifError(err); if (next) next(); })); diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index 983d88296eb26f..a1fa35acf3c124 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -12,36 +12,36 @@ const fs = require('fs'); const hosterr = /Hostname\/IP doesn't match certificate's altnames/g; const testCases = - [{ ca: ['ca1-cert'], - key: 'agent2-key', - cert: 'agent2-cert', - servers: [ + [{ ca: ['ca1-cert'], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent3-key', cert: 'agent3-cert' } - ] - }, + ] + }, - { ca: [], - key: 'agent2-key', - cert: 'agent2-cert', - servers: [ + { ca: [], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ { ok: false, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent3-key', cert: 'agent3-cert' } - ] - }, + ] + }, - { ca: ['ca1-cert', 'ca2-cert'], - key: 'agent2-key', - cert: 'agent2-cert', - servers: [ + { ca: ['ca1-cert', 'ca2-cert'], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: true, key: 'agent3-key', cert: 'agent3-cert' } - ] - } - ]; + ] + } + ]; function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); diff --git a/test/parallel/test-tls-connect-secure-context.js b/test/parallel/test-tls-connect-secure-context.js index 9e1059f169cf62..d1552a62169207 100644 --- a/test/parallel/test-tls-connect-secure-context.js +++ b/test/parallel/test-tls-connect-secure-context.js @@ -1,37 +1,25 @@ 'use strict'; const common = require('../common'); -if (!common.hasCrypto) { - common.skip('missing crypto'); - return; -} -const tls = require('tls'); +// Verify connection with explicitly created client SecureContext. -const fs = require('fs'); -const path = require('path'); +const join = require('path').join; +const { + assert, connect, keys, tls +} = require(join(common.fixturesDir, 'tls-connect'))(); -const keysDir = path.join(common.fixturesDir, 'keys'); - -const ca = fs.readFileSync(path.join(keysDir, 'ca1-cert.pem')); -const cert = fs.readFileSync(path.join(keysDir, 'agent1-cert.pem')); -const key = fs.readFileSync(path.join(keysDir, 'agent1-key.pem')); - -const server = tls.createServer({ - cert: cert, - key: key -}, function(c) { - c.end(); -}).listen(0, function() { - const secureContext = tls.createSecureContext({ - ca: ca - }); - - const socket = tls.connect({ - secureContext: secureContext, +connect({ + client: { servername: 'agent1', - port: this.address().port - }, common.mustCall(function() { - server.close(); - socket.end(); - })); + secureContext: tls.createSecureContext({ + ca: keys.agent1.ca, + }), + }, + server: { + cert: keys.agent1.cert, + key: keys.agent1.key, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + return cleanup(); }); diff --git a/test/parallel/test-tls-dhe.js b/test/parallel/test-tls-dhe.js index 92ab415e3ba0a6..196f5eb497fc4f 100644 --- a/test/parallel/test-tls-dhe.js +++ b/test/parallel/test-tls-dhe.js @@ -36,7 +36,7 @@ function test(keylen, expectedCipher, cb) { }); server.on('close', function(err) { - assert(!err); + assert.ifError(err); if (cb) cb(); }); diff --git a/test/parallel/test-tls-ecdh.js b/test/parallel/test-tls-ecdh.js index 99c6e108ab736a..2c68e3d706406e 100644 --- a/test/parallel/test-tls-ecdh.js +++ b/test/parallel/test-tls-ecdh.js @@ -33,7 +33,7 @@ server.listen(0, '127.0.0.1', common.mustCall(function() { cmd += ' -no_rand_screen'; exec(cmd, common.mustCall(function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert(stdout.includes(reply)); server.close(); })); diff --git a/test/parallel/test-tls-no-sslv3.js b/test/parallel/test-tls-no-sslv3.js index 16a722ef85b9da..fbc7a629611b0d 100644 --- a/test/parallel/test-tls-no-sslv3.js +++ b/test/parallel/test-tls-no-sslv3.js @@ -25,8 +25,8 @@ let stderr = ''; server.listen(0, '127.0.0.1', function() { const address = this.address().address + ':' + this.address().port; const args = ['s_client', - '-ssl3', - '-connect', address]; + '-ssl3', + '-connect', address]; // for the performance and stability issue in s_client on Windows if (common.isWindows) diff --git a/test/parallel/test-tls-peer-certificate.js b/test/parallel/test-tls-peer-certificate.js index ddbbf72a6309e7..eb5be6dcb2241b 100644 --- a/test/parallel/test-tls-peer-certificate.js +++ b/test/parallel/test-tls-peer-certificate.js @@ -1,53 +1,39 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); -if (!common.hasCrypto) { - common.skip('missing crypto'); - return; -} -const tls = require('tls'); +// Verify that detailed getPeerCertificate() return value has all certs. -const fs = require('fs'); -const util = require('util'); const join = require('path').join; +const { + assert, connect, debug, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); -const options = { - key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-key.pem')), - cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-cert.pem')), - ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca1-cert.pem')) ] -}; +connect({ + client: {rejectUnauthorized: false}, + server: keys.agent1, +}, function(err, pair, cleanup) { + assert.ifError(err); + const socket = pair.client.conn; + let peerCert = socket.getPeerCertificate(); + assert.ok(!peerCert.issuerCertificate); -const server = tls.createServer(options, function(cleartext) { - cleartext.end('World'); -}); -server.listen(0, common.mustCall(function() { - const socket = tls.connect({ - port: this.address().port, - rejectUnauthorized: false - }, common.mustCall(function() { - let peerCert = socket.getPeerCertificate(); - assert.ok(!peerCert.issuerCertificate); + peerCert = socket.getPeerCertificate(true); + debug('peerCert:\n', peerCert); - // Verify that detailed return value has all certs - peerCert = socket.getPeerCertificate(true); - assert.ok(peerCert.issuerCertificate); + assert.ok(peerCert.issuerCertificate); + assert.strictEqual(peerCert.subject.emailAddress, 'ry@tinyclouds.org'); + assert.strictEqual(peerCert.serialNumber, '9A84ABCFB8A72AC0'); + assert.strictEqual(peerCert.exponent, '0x10001'); + assert.strictEqual( + peerCert.fingerprint, + '8D:06:3A:B3:E5:8B:85:29:72:4F:7D:1B:54:CD:95:19:3C:EF:6F:AA' + ); + assert.deepStrictEqual(peerCert.infoAccess['OCSP - URI'], + [ 'http://ocsp.nodejs.org/' ]); - console.error(util.inspect(peerCert)); - assert.strictEqual(peerCert.subject.emailAddress, 'ry@tinyclouds.org'); - assert.strictEqual(peerCert.serialNumber, '9A84ABCFB8A72AC0'); - assert.strictEqual(peerCert.exponent, '0x10001'); - assert.strictEqual( - peerCert.fingerprint, - '8D:06:3A:B3:E5:8B:85:29:72:4F:7D:1B:54:CD:95:19:3C:EF:6F:AA' - ); - assert.deepStrictEqual(peerCert.infoAccess['OCSP - URI'], - [ 'http://ocsp.nodejs.org/' ]); + const issuer = peerCert.issuerCertificate; + assert.strictEqual(issuer.issuerCertificate, issuer); + assert.strictEqual(issuer.serialNumber, '8DF21C01468AF393'); - const issuer = peerCert.issuerCertificate; - assert.strictEqual(issuer.issuerCertificate, issuer); - assert.strictEqual(issuer.serialNumber, '8DF21C01468AF393'); - server.close(); - })); - socket.end('Hello'); -})); + return cleanup(); +}); diff --git a/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js b/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js index bd92dc28904183..1ff7decf3cf9cc 100644 --- a/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js +++ b/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js @@ -23,7 +23,7 @@ const server = tls.createServer({}) 'Instance of Error should be passed to error handler'); assert.ok(e.message.match( /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/), - 'Expecting SSL unknown protocol'); + 'Expecting SSL unknown protocol'); server.close(); })); diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js index 04c1547384c61e..58a58324fb383f 100644 --- a/test/parallel/test-tls-server-verify.js +++ b/test/parallel/test-tls-server-verify.js @@ -15,88 +15,88 @@ if (!common.opensslCli) { // - accepted and "authorized". const testCases = - [{ title: 'Do not request certs. Everyone is unauthorized.', - requestCert: false, - rejectUnauthorized: false, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: false }, + [{ title: 'Do not request certs. Everyone is unauthorized.', + requestCert: false, + rejectUnauthorized: false, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: false }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Allow both authed and unauthed connections with CA1', - requestCert: true, - rejectUnauthorized: false, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Allow both authed and unauthed connections with CA1', + requestCert: true, + rejectUnauthorized: false, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Do not request certs at connection. Do that later', - requestCert: false, - rejectUnauthorized: false, - renegotiate: true, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Do not request certs at connection. Do that later', + requestCert: false, + rejectUnauthorized: false, + renegotiate: true, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Allow only authed connections with CA1', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Allow only authed connections with CA1', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: true }, { name: 'agent3', shouldReject: true }, { name: 'nocert', shouldReject: true } - ] - }, - - { title: 'Allow only authed connections with CA1 and CA2', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca1-cert', 'ca2-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Allow only authed connections with CA1 and CA2', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca1-cert', 'ca2-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: true }, { name: 'agent3', shouldReject: false, shouldAuth: true }, { name: 'nocert', shouldReject: true } - ] - }, + ] + }, - { title: 'Allow only certs signed by CA2 but not in the CRL', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca2-cert'], - crl: 'ca2-crl', - clients: [ + { title: 'Allow only certs signed by CA2 but not in the CRL', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca2-cert'], + crl: 'ca2-crl', + clients: [ { name: 'agent1', shouldReject: true, shouldAuth: false }, { name: 'agent2', shouldReject: true, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: true }, // Agent4 has a cert in the CRL. { name: 'agent4', shouldReject: true, shouldAuth: false }, { name: 'nocert', shouldReject: true } - ] - } - ]; + ] + } + ]; if (!common.hasCrypto) { common.skip('missing crypto'); @@ -282,7 +282,7 @@ function runTest(port, testIndex) { requestCert: true, rejectUnauthorized: false }, function(err) { - assert(!err); + assert.ifError(err); c.write('\n_renegotiated\n'); handleConnection(c); }); diff --git a/test/parallel/test-tls-set-ciphers.js b/test/parallel/test-tls-set-ciphers.js index 5a85e3b22e4c62..e61f8448be2923 100644 --- a/test/parallel/test-tls-set-ciphers.js +++ b/test/parallel/test-tls-set-ciphers.js @@ -42,7 +42,7 @@ server.listen(0, '127.0.0.1', function() { cmd += ' -no_rand_screen'; exec(cmd, function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); response = stdout; server.close(); }); diff --git a/test/parallel/test-tls-socket-failed-handshake-emits-error.js b/test/parallel/test-tls-socket-failed-handshake-emits-error.js index f655dc97b5a99b..ffeb42c8ebd8da 100644 --- a/test/parallel/test-tls-socket-failed-handshake-emits-error.js +++ b/test/parallel/test-tls-socket-failed-handshake-emits-error.js @@ -23,7 +23,7 @@ const server = net.createServer(function(c) { 'Instance of Error should be passed to error handler'); assert.ok(e.message.match( /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/), - 'Expecting SSL unknown protocol'); + 'Expecting SSL unknown protocol'); })); s.on('close', function() { diff --git a/test/parallel/test-util-inspect-simd.js b/test/parallel/test-util-inspect-simd.js index ec4ccc1875a817..5e0a2740840c93 100644 --- a/test/parallel/test-util-inspect-simd.js +++ b/test/parallel/test-util-inspect-simd.js @@ -1,12 +1,11 @@ // Flags: --harmony_simd +/* global SIMD */ 'use strict'; require('../common'); const assert = require('assert'); const inspect = require('util').inspect; -const SIMD = global.SIMD; // Pacify eslint. - assert.strictEqual( inspect(SIMD.Bool16x8()), 'Bool16x8 [ false, false, false, false, false, false, false, false ]'); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 1118065f1a09da..b0f89333d25a9b 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -42,7 +42,7 @@ assert.strictEqual(util.inspect({'a': {'b': { 'c': 2}}}, false, 1), '{ a: { b: [Object] } }'); assert.strictEqual(util.inspect(Object.create({}, {visible: {value: 1, enumerable: true}, hidden: {value: 2}})), - '{ visible: 1 }' + '{ visible: 1 }' ); { @@ -206,8 +206,9 @@ for (const showHidden of [true, false]) { // Objects without prototype { const out = util.inspect(Object.create(null, - { name: {value: 'Tim', enumerable: true}, - hidden: {value: 'secret'}}), true); + { name: {value: 'Tim', + enumerable: true}, + hidden: {value: 'secret'}}), true); if (out !== "{ [hidden]: 'secret', name: 'Tim' }" && out !== "{ name: 'Tim', [hidden]: 'secret' }") { common.fail(`unexpected value for out ${out}`); @@ -216,8 +217,8 @@ for (const showHidden of [true, false]) { assert.strictEqual( util.inspect(Object.create(null, - {name: {value: 'Tim', enumerable: true}, - hidden: {value: 'secret'}})), + {name: {value: 'Tim', enumerable: true}, + hidden: {value: 'secret'}})), '{ name: \'Tim\' }' ); diff --git a/test/parallel/test-util-sigint-watchdog.js b/test/parallel/test-util-sigint-watchdog.js index 42e4048bd74a36..207f44b011c3a2 100644 --- a/test/parallel/test-util-sigint-watchdog.js +++ b/test/parallel/test-util-sigint-watchdog.js @@ -16,41 +16,41 @@ if (common.isWindows) { assert.strictEqual(hadPendingSignals, false); next(); }, -(next) => { + (next) => { // Test with one call to the watchdog, one signal. - binding.startSigintWatchdog(); - process.kill(process.pid, 'SIGINT'); - waitForPendingSignal(common.mustCall(() => { - const hadPendingSignals = binding.stopSigintWatchdog(); - assert.strictEqual(hadPendingSignals, true); - next(); - })); -}, -(next) => { + binding.startSigintWatchdog(); + process.kill(process.pid, 'SIGINT'); + waitForPendingSignal(common.mustCall(() => { + const hadPendingSignals = binding.stopSigintWatchdog(); + assert.strictEqual(hadPendingSignals, true); + next(); + })); + }, + (next) => { // Nested calls are okay. - binding.startSigintWatchdog(); - binding.startSigintWatchdog(); - process.kill(process.pid, 'SIGINT'); - waitForPendingSignal(common.mustCall(() => { - const hadPendingSignals1 = binding.stopSigintWatchdog(); - const hadPendingSignals2 = binding.stopSigintWatchdog(); - assert.strictEqual(hadPendingSignals1, true); - assert.strictEqual(hadPendingSignals2, false); - next(); - })); -}, -() => { + binding.startSigintWatchdog(); + binding.startSigintWatchdog(); + process.kill(process.pid, 'SIGINT'); + waitForPendingSignal(common.mustCall(() => { + const hadPendingSignals1 = binding.stopSigintWatchdog(); + const hadPendingSignals2 = binding.stopSigintWatchdog(); + assert.strictEqual(hadPendingSignals1, true); + assert.strictEqual(hadPendingSignals2, false); + next(); + })); + }, + () => { // Signal comes in after first call to stop. - binding.startSigintWatchdog(); - binding.startSigintWatchdog(); - const hadPendingSignals1 = binding.stopSigintWatchdog(); - process.kill(process.pid, 'SIGINT'); - waitForPendingSignal(common.mustCall(() => { - const hadPendingSignals2 = binding.stopSigintWatchdog(); - assert.strictEqual(hadPendingSignals1, false); - assert.strictEqual(hadPendingSignals2, true); - })); -}].reduceRight((a, b) => common.mustCall(b).bind(null, a))(); + binding.startSigintWatchdog(); + binding.startSigintWatchdog(); + const hadPendingSignals1 = binding.stopSigintWatchdog(); + process.kill(process.pid, 'SIGINT'); + waitForPendingSignal(common.mustCall(() => { + const hadPendingSignals2 = binding.stopSigintWatchdog(); + assert.strictEqual(hadPendingSignals1, false); + assert.strictEqual(hadPendingSignals2, true); + })); + }].reduceRight((a, b) => common.mustCall(b).bind(null, a))(); function waitForPendingSignal(cb) { if (binding.watchdogHasPendingSigint()) diff --git a/test/parallel/test-whatwg-url-origin-for.js b/test/parallel/test-whatwg-url-origin-for.js deleted file mode 100644 index 9e015f80510148..00000000000000 --- a/test/parallel/test-whatwg-url-origin-for.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const common = require('../common'); - -const originFor = require('url').originFor; -const path = require('path'); -const assert = require('assert'); -const tests = require(path.join(common.fixturesDir, 'url-tests.json')); - -for (const test of tests) { - if (typeof test === 'string') - continue; - - if (test.origin) { - const origin = originFor(test.input, test.base); - // Pass true to origin.toString() to enable unicode serialization. - assert.strictEqual(origin.toString(true), test.origin); - } -} diff --git a/test/parallel/test-whatwg-url-parsing.js b/test/parallel/test-whatwg-url-parsing.js index ae14d1ff5060bf..9ea6cc74bff5e6 100644 --- a/test/parallel/test-whatwg-url-parsing.js +++ b/test/parallel/test-whatwg-url-parsing.js @@ -4,7 +4,7 @@ const common = require('../common'); if (!common.hasIntl) { // A handful of the tests fail when ICU is not included. - common.skip('missing Intl... skipping test'); + common.skip('missing Intl'); return; } @@ -13,17 +13,30 @@ const path = require('path'); const assert = require('assert'); const tests = require(path.join(common.fixturesDir, 'url-tests.json')); +function verifyURL(url, test) { + if (test.href) assert.strictEqual(url.href, test.href); + if (test.origin) assert.strictEqual(url.origin, test.origin); + if (test.protocol) assert.strictEqual(url.protocol, test.protocol); + if (test.username) assert.strictEqual(url.username, test.username); + if (test.password) assert.strictEqual(url.password, test.password); + if (test.hostname) assert.strictEqual(url.hostname, test.hostname); + if (test.host) assert.strictEqual(url.host, test.host); + if (test.port !== undefined) assert.strictEqual(url.port, test.port); + if (test.pathname) assert.strictEqual(url.pathname, test.pathname); + if (test.search) assert.strictEqual(url.search, test.search); + if (test.hash) assert.strictEqual(url.hash, test.hash); +} + for (const test of tests) { if (typeof test === 'string') continue; if (test.failure) { - assert.throws(() => new URL(test.input, test.base), /Invalid URL/); + assert.throws(() => new URL(test.input, test.base), + /^TypeError: Invalid URL$/); } else { - assert.doesNotThrow(() => { - const url = new URL(test.input, test.base); - assert.strictEqual(url.href, test.href); - }); + const url = new URL(test.input, test.base); + verifyURL(url, test); } } @@ -115,18 +128,10 @@ const additional_tests = [ } ]; -additional_tests.forEach((test) => { - const u = new URL(test.url); - if (test.protocol) assert.strictEqual(test.protocol, u.protocol); - if (test.username) assert.strictEqual(test.username, u.username); - if (test.password) assert.strictEqual(test.password, u.password); - if (test.hostname) assert.strictEqual(test.hostname, u.hostname); - if (test.host) assert.strictEqual(test.host, u.host); - if (test.port !== undefined) assert.strictEqual(test.port, u.port); - if (test.pathname) assert.strictEqual(test.pathname, u.pathname); - if (test.search) assert.strictEqual(test.search, u.search); - if (test.hash) assert.strictEqual(test.hash, u.hash); -}); +for (const test of additional_tests) { + const url = new URL(test.url); + verifyURL(url, test); +} // test inspect const allTests = additional_tests.slice(); diff --git a/test/parallel/test-whatwg-url-properties.js b/test/parallel/test-whatwg-url-properties.js index 60cf581ad8da4d..340a51525e33bf 100644 --- a/test/parallel/test-whatwg-url-properties.js +++ b/test/parallel/test-whatwg-url-properties.js @@ -19,9 +19,9 @@ for (const prop in url) { // https://heycam.github.io/webidl/#es-attributes // https://heycam.github.io/webidl/#es-stringifier const expected = ['toString', - 'href', 'origin', 'protocol', - 'username', 'password', 'host', 'hostname', 'port', - 'pathname', 'search', 'searchParams', 'hash']; + 'href', 'origin', 'protocol', + 'username', 'password', 'host', 'hostname', 'port', + 'pathname', 'search', 'searchParams', 'hash']; assert.deepStrictEqual(props, expected); diff --git a/test/parallel/test-whatwg-url-searchparams-append.js b/test/parallel/test-whatwg-url-searchparams-append.js index 1f61cb0d11bb6b..5ef92252be5d9e 100644 --- a/test/parallel/test-whatwg-url-searchparams-append.js +++ b/test/parallel/test-whatwg-url-searchparams-append.js @@ -2,13 +2,9 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; +const URLSearchParams = require('url').URLSearchParams; -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +let params; // Append same name params = new URLSearchParams(); diff --git a/test/parallel/test-whatwg-url-searchparams-constructor.js b/test/parallel/test-whatwg-url-searchparams-constructor.js index 98349021586f1a..0b42eca5032d53 100644 --- a/test/parallel/test-whatwg-url-searchparams-constructor.js +++ b/test/parallel/test-whatwg-url-searchparams-constructor.js @@ -2,13 +2,9 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; +const URLSearchParams = require('url').URLSearchParams; -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +let params; // Basic URLSearchParams construction params = new URLSearchParams(); diff --git a/test/parallel/test-whatwg-url-searchparams-delete.js b/test/parallel/test-whatwg-url-searchparams-delete.js index b08a3b76867572..71bb7487a75087 100644 --- a/test/parallel/test-whatwg-url-searchparams-delete.js +++ b/test/parallel/test-whatwg-url-searchparams-delete.js @@ -2,13 +2,11 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; +const url = require('url'); +const URL = url.URL; +const URLSearchParams = url.URLSearchParams; -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +let params; // Delete basics params = new URLSearchParams('a=b&c=d'); diff --git a/test/parallel/test-whatwg-url-searchparams-foreach.js b/test/parallel/test-whatwg-url-searchparams-foreach.js index b6d684b06743b0..199d01b8fdfbcc 100644 --- a/test/parallel/test-whatwg-url-searchparams-foreach.js +++ b/test/parallel/test-whatwg-url-searchparams-foreach.js @@ -2,18 +2,14 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; - -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +const url = require('url'); +const URL = url.URL; +const URLSearchParams = url.URLSearchParams; let a, b, i; // ForEach Check -params = new URLSearchParams('a=1&b=2&c=3'); +const params = new URLSearchParams('a=1&b=2&c=3'); const keys = []; const values = []; params.forEach(function(value, key) { diff --git a/test/parallel/test-whatwg-url-searchparams-get.js b/test/parallel/test-whatwg-url-searchparams-get.js index 667738f817b707..aa3a0d9929bf52 100644 --- a/test/parallel/test-whatwg-url-searchparams-get.js +++ b/test/parallel/test-whatwg-url-searchparams-get.js @@ -2,13 +2,9 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; +const URLSearchParams = require('url').URLSearchParams; -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +let params; // Get basics params = new URLSearchParams('a=b&c=d'); diff --git a/test/parallel/test-whatwg-url-searchparams-getall.js b/test/parallel/test-whatwg-url-searchparams-getall.js index 8333982d688c3b..34805164ab1b38 100644 --- a/test/parallel/test-whatwg-url-searchparams-getall.js +++ b/test/parallel/test-whatwg-url-searchparams-getall.js @@ -2,14 +2,9 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; - -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +const URLSearchParams = require('url').URLSearchParams; +let params; let matches; // getAll() basics diff --git a/test/parallel/test-whatwg-url-searchparams-has.js b/test/parallel/test-whatwg-url-searchparams-has.js index c884227e0b0f1d..cd8901da2398b7 100644 --- a/test/parallel/test-whatwg-url-searchparams-has.js +++ b/test/parallel/test-whatwg-url-searchparams-has.js @@ -2,13 +2,9 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; +const URLSearchParams = require('url').URLSearchParams; -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +let params; // Has basics params = new URLSearchParams('a=b&c=d'); diff --git a/test/parallel/test-whatwg-url-searchparams-inspect.js b/test/parallel/test-whatwg-url-searchparams-inspect.js new file mode 100644 index 00000000000000..12472e1df0601a --- /dev/null +++ b/test/parallel/test-whatwg-url-searchparams-inspect.js @@ -0,0 +1,30 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); +const util = require('util'); +const URL = require('url').URL; + +// Until we export URLSearchParams +const m = new URL('http://example.org'); +const URLSearchParams = m.searchParams.constructor; + +const sp = new URLSearchParams('?a=a&b=b&b=c'); +assert.strictEqual(util.inspect(sp), + "URLSearchParams { 'a' => 'a', 'b' => 'b', 'b' => 'c' }"); +assert.strictEqual(util.inspect(sp.keys()), + "URLSearchParamsIterator { 'a', 'b', 'b' }"); +assert.strictEqual(util.inspect(sp.values()), + "URLSearchParamsIterator { 'a', 'b', 'c' }"); + +const iterator = sp.entries(); +assert.strictEqual(util.inspect(iterator), + "URLSearchParamsIterator { [ 'a', 'a' ], [ 'b', 'b' ], " + + "[ 'b', 'c' ] }"); +iterator.next(); +assert.strictEqual(util.inspect(iterator), + "URLSearchParamsIterator { [ 'b', 'b' ], [ 'b', 'c' ] }"); +iterator.next(); +iterator.next(); +assert.strictEqual(util.inspect(iterator), + 'URLSearchParamsIterator { }'); diff --git a/test/parallel/test-whatwg-url-searchparams-set.js b/test/parallel/test-whatwg-url-searchparams-set.js index 2d9ae8aaa8d021..5ab2bbe8d8ac39 100644 --- a/test/parallel/test-whatwg-url-searchparams-set.js +++ b/test/parallel/test-whatwg-url-searchparams-set.js @@ -2,13 +2,9 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; +const URLSearchParams = require('url').URLSearchParams; -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +let params; // Set basics params = new URLSearchParams('a=b&c=d'); diff --git a/test/parallel/test-whatwg-url-searchparams-stringifier.js b/test/parallel/test-whatwg-url-searchparams-stringifier.js index 0a53df634454b6..c591425461a9d1 100644 --- a/test/parallel/test-whatwg-url-searchparams-stringifier.js +++ b/test/parallel/test-whatwg-url-searchparams-stringifier.js @@ -2,13 +2,9 @@ require('../common'); const assert = require('assert'); -const URL = require('url').URL; +const URLSearchParams = require('url').URLSearchParams; -const m = new URL('http://example.org'); -let params = m.searchParams; - -// Until we export URLSearchParams -const URLSearchParams = params.constructor; +let params; // Serialize space // querystring does not currently handle spaces intelligently diff --git a/test/parallel/test-whatwg-url-searchparams.js b/test/parallel/test-whatwg-url-searchparams.js index 54743b97a31da9..9a9fbb0452155d 100644 --- a/test/parallel/test-whatwg-url-searchparams.js +++ b/test/parallel/test-whatwg-url-searchparams.js @@ -44,6 +44,20 @@ n = 0; for (val of sp.values()) { assert.strictEqual(val, String(values[n++])); } +n = 0; +sp.forEach(function(val, key, obj) { + assert.strictEqual(this, undefined); + assert.strictEqual(key, 'a'); + assert.strictEqual(val, String(values[n++])); + assert.strictEqual(obj, sp); +}); +sp.forEach(function() { + assert.strictEqual(this, m); +}, m); +assert.throws(() => sp.forEach(), + /^TypeError: "callback" argument must be a function$/); +assert.throws(() => sp.forEach(1), + /^TypeError: "callback" argument must be a function$/); m.search = '?a=a&b=b'; assert.strictEqual(sp.toString(), 'a=a&b=b'); diff --git a/test/parallel/test-whatwg-url-setters.js b/test/parallel/test-whatwg-url-setters.js index 3b2aca2afd89d7..236737e18177fe 100644 --- a/test/parallel/test-whatwg-url-setters.js +++ b/test/parallel/test-whatwg-url-setters.js @@ -4,7 +4,7 @@ const common = require('../common'); if (!common.hasIntl) { // A handful of the tests fail when ICU is not included. - common.skip('missing Intl... skipping test'); + common.skip('missing Intl'); return; } diff --git a/test/parallel/test-writeint.js b/test/parallel/test-writeint.js index 43784fb390a1f9..9fce2bc410e1be 100644 --- a/test/parallel/test-writeint.js +++ b/test/parallel/test-writeint.js @@ -4,6 +4,7 @@ */ require('../common'); const assert = require('assert'); +const errorOutOfBounds = /^TypeError: "value" argument is out of bounds$/; function test8(clazz) { var buffer = new clazz(2); @@ -17,10 +18,10 @@ function test8(clazz) { /* Make sure we handle truncation correctly */ assert.throws(function() { buffer.writeInt8(0xabc, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt8(0xabc, 0); - }); + }, errorOutOfBounds); /* Make sure we handle min/max correctly */ buffer.writeInt8(0x7f, 0); @@ -30,10 +31,10 @@ function test8(clazz) { assert.equal(0x80, buffer[1]); assert.throws(function() { buffer.writeInt8(0x7f + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt8(-0x80 - 1, 0); - }); + }, errorOutOfBounds); } @@ -70,10 +71,10 @@ function test16(clazz) { assert.equal(0x00, buffer[3]); assert.throws(function() { buffer.writeInt16BE(0x7fff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt16BE(-0x8000 - 1, 0); - }); + }, errorOutOfBounds); buffer.writeInt16LE(0x7fff, 0); buffer.writeInt16LE(-0x8000, 2); @@ -83,10 +84,10 @@ function test16(clazz) { assert.equal(0x80, buffer[3]); assert.throws(function() { buffer.writeInt16LE(0x7fff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt16LE(-0x8000 - 1, 0); - }); + }, errorOutOfBounds); } @@ -139,10 +140,10 @@ function test32(clazz) { assert.equal(0x00, buffer[7]); assert.throws(function() { buffer.writeInt32BE(0x7fffffff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt32BE(-0x80000000 - 1, 0); - }); + }, errorOutOfBounds); buffer.writeInt32LE(0x7fffffff, 0); buffer.writeInt32LE(-0x80000000, 4); @@ -156,10 +157,10 @@ function test32(clazz) { assert.equal(0x80, buffer[7]); assert.throws(function() { buffer.writeInt32LE(0x7fffffff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt32LE(-0x80000000 - 1, 0); - }); + }, errorOutOfBounds); } diff --git a/test/parallel/test-zerolengthbufferbug.js b/test/parallel/test-zerolengthbufferbug.js index 9e2cde6b2fadae..056fc725ff5593 100644 --- a/test/parallel/test-zerolengthbufferbug.js +++ b/test/parallel/test-zerolengthbufferbug.js @@ -8,7 +8,7 @@ var server = http.createServer(function(req, res) { var buffer = Buffer.alloc(0); // FIXME: WTF gjslint want this? res.writeHead(200, {'Content-Type': 'text/html', - 'Content-Length': buffer.length}); + 'Content-Length': buffer.length}); res.end(buffer); }); diff --git a/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js b/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js index 37f89f5b94bf08..872c2581c53b90 100644 --- a/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js +++ b/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js @@ -12,11 +12,15 @@ let data = Buffer.concat([ Buffer(10).fill(0) ]); -assert.equal(zlib.gunzipSync(data).toString(), 'abcdef'); +assert.strictEqual(zlib.gunzipSync(data).toString(), 'abcdef'); zlib.gunzip(data, common.mustCall((err, result) => { assert.ifError(err); - assert.equal(result, 'abcdef', 'result should match original string'); + assert.strictEqual( + result.toString(), + 'abcdef', + 'result should match original string' + ); })); // if the trailing garbage happens to look like a gzip header, it should @@ -28,10 +32,16 @@ data = Buffer.concat([ Buffer(10).fill(0) ]); -assert.throws(() => zlib.gunzipSync(data)); +assert.throws( + () => zlib.gunzipSync(data), + /^Error: unknown compression method$/ +); zlib.gunzip(data, common.mustCall((err, result) => { - assert(err); + assert(err instanceof Error); + assert.strictEqual(err.code, 'Z_DATA_ERROR'); + assert.strictEqual(err.message, 'unknown compression method'); + assert.strictEqual(result, undefined); })); // In this case the trailing junk is too short to be a gzip segment @@ -42,8 +52,14 @@ data = Buffer.concat([ Buffer([0x1f, 0x8b, 0xff, 0xff]) ]); -assert.throws(() => zlib.gunzipSync(data)); +assert.throws( + () => zlib.gunzipSync(data), + /^Error: unknown compression method$/ +); zlib.gunzip(data, common.mustCall((err, result) => { - assert(err); + assert(err instanceof Error); + assert.strictEqual(err.code, 'Z_DATA_ERROR'); + assert.strictEqual(err.message, 'unknown compression method'); + assert.strictEqual(result, undefined); })); diff --git a/test/parallel/test-zlib-invalid-input.js b/test/parallel/test-zlib-invalid-input.js index ee2ee85d73ff09..eb9cd334c11b84 100644 --- a/test/parallel/test-zlib-invalid-input.js +++ b/test/parallel/test-zlib-invalid-input.js @@ -21,9 +21,9 @@ nonStringInputs.forEach(function(input) { console.error('Doing the unzips'); // zlib.Unzip classes need to get valid data, or else they'll throw. const unzips = [ zlib.Unzip(), - zlib.Gunzip(), - zlib.Inflate(), - zlib.InflateRaw() ]; + zlib.Gunzip(), + zlib.Inflate(), + zlib.InflateRaw() ]; var hadError = []; unzips.forEach(function(uz, i) { console.error('Error for ' + uz.constructor.name); diff --git a/test/parallel/test-zlib-truncated.js b/test/parallel/test-zlib-truncated.js index 92a18a538c1ee4..c7b84c0d703711 100644 --- a/test/parallel/test-zlib-truncated.js +++ b/test/parallel/test-zlib-truncated.js @@ -22,7 +22,7 @@ const inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing eli' { comp: 'deflateRaw', decomp: 'inflateRaw', decompSync: 'inflateRawSync' } ].forEach(function(methods) { zlib[methods.comp](inputString, function(err, compressed) { - assert(!err); + assert.ifError(err); const truncated = compressed.slice(0, compressed.length / 2); const toUTF8 = (buffer) => buffer.toString('utf-8'); diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index ea158ded48b5c1..54a4bc473631a0 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -150,9 +150,9 @@ Object.keys(tests).forEach(function(file) { var Def = pair[0]; var Inf = pair[1]; var opts = { level: level, - windowBits: windowBits, - memLevel: memLevel, - strategy: strategy }; + windowBits: windowBits, + memLevel: memLevel, + strategy: strategy }; total++; diff --git a/test/pseudo-tty/pseudo-tty.status b/test/pseudo-tty/pseudo-tty.status index e16bb28cd7be61..50f54de029d874 100644 --- a/test/pseudo-tty/pseudo-tty.status +++ b/test/pseudo-tty/pseudo-tty.status @@ -4,3 +4,5 @@ prefix pseudo-tty # test issue only, covered under https://github.com/nodejs/node/issues/7973 no_dropped_stdio : SKIP no_interleaved_stdio : SKIP +# being investigated under https://github.com/nodejs/node/issues/9728 +test-tty-wrap : FAIL, PASS diff --git a/test/pummel/test-child-process-spawn-loop.js b/test/pummel/test-child-process-spawn-loop.js index 7e686cada244b3..7a3cf114b4e8e9 100644 --- a/test/pummel/test-child-process-spawn-loop.js +++ b/test/pummel/test-child-process-spawn-loop.js @@ -4,26 +4,26 @@ var assert = require('assert'); var spawn = require('child_process').spawn; -var SIZE = 1000 * 1024; -var N = 40; -var finished = false; +const SIZE = 1000 * 1024; +const N = 40; +let finished = false; function doSpawn(i) { - var child = spawn('python', ['-c', 'print ' + SIZE + ' * "C"']); - var count = 0; + const child = spawn('python', ['-c', 'print ' + SIZE + ' * "C"']); + let count = 0; child.stdout.setEncoding('ascii'); - child.stdout.on('data', function(chunk) { + child.stdout.on('data', (chunk) => { count += chunk.length; }); - child.stderr.on('data', function(chunk) { + child.stderr.on('data', (chunk) => { console.log('stderr: ' + chunk); }); - child.on('close', function() { + child.on('close', () => { // + 1 for \n or + 2 for \r\n on Windows - assert.equal(SIZE + (common.isWindows ? 2 : 1), count); + assert.strictEqual(SIZE + (common.isWindows ? 2 : 1), count); if (i < N) { doSpawn(i + 1); } else { @@ -34,6 +34,6 @@ function doSpawn(i) { doSpawn(0); -process.on('exit', function() { +process.on('exit', () => { assert.ok(finished); }); diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index 6f6e1511b14442..18404373318917 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -63,6 +63,8 @@ exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { assert.ok(err); assert.ok(err.killed); assert.strictEqual(err.signal, 'SIGTERM'); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); }); @@ -85,6 +87,8 @@ function killMeTwiceCallback(err, stdout, stderr) { assert.ok(err); assert.ok(err.killed); assert.strictEqual(err.signal, 'SIGTERM'); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); // the timeout should still be in effect console.log('\'sleep 3\' was already killed. Took %d ms', diff); @@ -96,6 +100,8 @@ exec('python -c "print 200000*\'C\'"', {maxBuffer: 1000}, function(err, stdout, stderr) { assert.ok(err); assert.ok(/maxBuffer/.test(err.message)); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); }); diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 4e08e9e9d1cc9b..fc291cfe64c618 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -41,13 +41,13 @@ assert.throws( fs.watchFile(filepathOne); }, function(e) { - return e.message === 'watchFile requires a listener function'; + return e.message === '"watchFile()" requires a listener function'; } ); assert.doesNotThrow( function() { - fs.watchFile(filepathOne, function(curr, prev) { + fs.watchFile(filepathOne, function() { fs.unwatchFile(filepathOne); ++watchSeenOne; }); @@ -68,17 +68,17 @@ assert.throws( fs.watchFile(filepathTwo); }, function(e) { - return e.message === 'watchFile requires a listener function'; + return e.message === '"watchFile()" requires a listener function'; } ); assert.doesNotThrow( function() { - function a(curr, prev) { + function a() { fs.unwatchFile(filepathTwo, a); ++watchSeenTwo; } - function b(curr, prev) { + function b() { fs.unwatchFile(filepathTwo, b); ++watchSeenTwo; } @@ -93,10 +93,10 @@ setTimeout(function() { assert.doesNotThrow( function() { - function a(curr, prev) { + function a() { assert.ok(0); // should not run } - function b(curr, prev) { + function b() { fs.unwatchFile(filenameThree, b); ++watchSeenThree; } @@ -120,7 +120,7 @@ setTimeout(function() { assert.doesNotThrow( function() { - function a(curr, prev) { + function a() { ++watchSeenFour; assert.equal(1, watchSeenFour); fs.unwatchFile('.' + path.sep + filenameFour, a); diff --git a/test/pummel/test-keep-alive.js b/test/pummel/test-keep-alive.js index 1861b2df970e18..47d529b64082fa 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -12,8 +12,8 @@ if (common.isWindows) { return; } -var body = 'hello world\n'; -var server = http.createServer(function(req, res) { +const body = 'hello world\n'; +const server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' @@ -22,12 +22,12 @@ var server = http.createServer(function(req, res) { res.end(); }); -var keepAliveReqSec = 0; -var normalReqSec = 0; +let keepAliveReqSec = 0; +let normalReqSec = 0; function runAb(opts, callback) { - var args = [ + const args = [ '-c', opts.concurrent || 100, '-t', opts.threads || 2, '-d', opts.duration || '10s', @@ -41,13 +41,11 @@ function runAb(opts, callback) { args.push(url.format({ hostname: '127.0.0.1', port: common.PORT, protocol: 'http'})); - //console.log(comm, args.join(' ')); - - var child = spawn('wrk', args); + const child = spawn('wrk', args); child.stderr.pipe(process.stderr); child.stdout.setEncoding('utf8'); - var stdout; + let stdout; child.stdout.on('data', function(data) { stdout += data; @@ -60,11 +58,11 @@ function runAb(opts, callback) { return; } - var matches = /Requests\/sec:\s*(\d+)\./mi.exec(stdout); - var reqSec = parseInt(matches[1]); + let matches = /Requests\/sec:\s*(\d+)\./mi.exec(stdout); + const reqSec = parseInt(matches[1]); matches = /Keep-Alive requests:\s*(\d+)/mi.exec(stdout); - var keepAliveRequests; + let keepAliveRequests; if (matches) { keepAliveRequests = parseInt(matches[1]); } else { @@ -75,21 +73,19 @@ function runAb(opts, callback) { }); } -server.listen(common.PORT, function() { - runAb({ keepalive: true }, function(reqSec) { +server.listen(common.PORT, () => { + runAb({ keepalive: true }, (reqSec) => { keepAliveReqSec = reqSec; - console.log('keep-alive:', keepAliveReqSec, 'req/sec'); runAb({ keepalive: false }, function(reqSec) { normalReqSec = reqSec; - console.log('normal:' + normalReqSec + ' req/sec'); server.close(); }); }); }); process.on('exit', function() { - assert.equal(true, normalReqSec > 50); - assert.equal(true, keepAliveReqSec > 50); - assert.equal(true, normalReqSec < keepAliveReqSec); + assert.strictEqual(true, normalReqSec > 50); + assert.strictEqual(true, keepAliveReqSec > 50); + assert.strictEqual(true, normalReqSec < keepAliveReqSec); }); diff --git a/test/pummel/test-watch-file.js b/test/pummel/test-watch-file.js index 8fdf6b32b2d78c..8b79ef8ede4a63 100644 --- a/test/pummel/test-watch-file.js +++ b/test/pummel/test-watch-file.js @@ -5,14 +5,11 @@ var assert = require('assert'); var fs = require('fs'); var path = require('path'); -var f = path.join(common.fixturesDir, 'x.txt'); +const f = path.join(common.fixturesDir, 'x.txt'); -console.log('watching for changes of ' + f); - -var changes = 0; +let changes = 0; function watchFile() { - fs.watchFile(f, function(curr, prev) { - console.log(f + ' change'); + fs.watchFile(f, (curr, prev) => { changes++; assert.notDeepStrictEqual(curr.mtime, prev.mtime); fs.unwatchFile(f); @@ -24,7 +21,7 @@ function watchFile() { watchFile(); -var fd = fs.openSync(f, 'w+'); +const fd = fs.openSync(f, 'w+'); fs.writeSync(fd, 'xyz\n'); fs.closeSync(fd); diff --git a/test/sequential/test-crypto-timing-safe-equal.js b/test/sequential/test-crypto-timing-safe-equal.js index 9c4265a672cc0f..7a1f8d2993669b 100644 --- a/test/sequential/test-crypto-timing-safe-equal.js +++ b/test/sequential/test-crypto-timing-safe-equal.js @@ -24,14 +24,14 @@ assert.strictEqual( assert.throws(function() { crypto.timingSafeEqual(Buffer.from([1, 2, 3]), Buffer.from([1, 2])); }, /^TypeError: Input buffers must have the same length$/, - 'should throw when given buffers with different lengths'); + 'should throw when given buffers with different lengths'); assert.throws(function() { crypto.timingSafeEqual('not a buffer', Buffer.from([1, 2])); }, /^TypeError: First argument must be a buffer$/, - 'should throw if the first argument is not a buffer'); + 'should throw if the first argument is not a buffer'); assert.throws(function() { crypto.timingSafeEqual(Buffer.from([1, 2]), 'not a buffer'); }, /^TypeError: Second argument must be a buffer$/, - 'should throw if the second argument is not a buffer'); + 'should throw if the second argument is not a buffer'); diff --git a/test/parallel/test-fs-readfile-tostring-fail.js b/test/sequential/test-fs-readfile-tostring-fail.js similarity index 100% rename from test/parallel/test-fs-readfile-tostring-fail.js rename to test/sequential/test-fs-readfile-tostring-fail.js diff --git a/test/sequential/test-fs-watch.js b/test/sequential/test-fs-watch.js index 43b23bd5bd0a79..34e53f59aa0961 100644 --- a/test/sequential/test-fs-watch.js +++ b/test/sequential/test-fs-watch.js @@ -1,25 +1,25 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); -var expectFilePath = common.isWindows || - common.isLinux || - common.isOSX; +const expectFilePath = common.isWindows || + common.isLinux || + common.isOSX; -var watchSeenOne = 0; -var watchSeenTwo = 0; -var watchSeenThree = 0; +let watchSeenOne = 0; +let watchSeenTwo = 0; +let watchSeenThree = 0; -var testDir = common.tmpDir; +const testDir = common.tmpDir; -var filenameOne = 'watch.txt'; -var filepathOne = path.join(testDir, filenameOne); +const filenameOne = 'watch.txt'; +const filepathOne = path.join(testDir, filenameOne); -var filenameTwo = 'hasOwnProperty'; -var filepathTwo = filenameTwo; -var filepathTwoAbs = path.join(testDir, filenameTwo); +const filenameTwo = 'hasOwnProperty'; +const filepathTwo = filenameTwo; +const filepathTwoAbs = path.join(testDir, filenameTwo); process.on('exit', function() { assert.ok(watchSeenOne > 0); @@ -33,12 +33,12 @@ fs.writeFileSync(filepathOne, 'hello'); assert.doesNotThrow( function() { - var watcher = fs.watch(filepathOne); + const watcher = fs.watch(filepathOne); watcher.on('change', function(event, filename) { - assert.equal('change', event); + assert.strictEqual('change', event); if (expectFilePath) { - assert.equal('watch.txt', filename); + assert.strictEqual('watch.txt', filename); } watcher.close(); ++watchSeenOne; @@ -57,11 +57,11 @@ fs.writeFileSync(filepathTwoAbs, 'howdy'); assert.doesNotThrow( function() { - var watcher = fs.watch(filepathTwo, function(event, filename) { - assert.equal('change', event); + const watcher = fs.watch(filepathTwo, function(event, filename) { + assert.strictEqual('change', event); if (expectFilePath) { - assert.equal('hasOwnProperty', filename); + assert.strictEqual('hasOwnProperty', filename); } watcher.close(); ++watchSeenTwo; @@ -79,13 +79,13 @@ const filepathThree = path.join(testsubdir, filenameThree); assert.doesNotThrow( function() { - var watcher = fs.watch(testsubdir, function(event, filename) { - var renameEv = common.isSunOS ? 'change' : 'rename'; - assert.equal(renameEv, event); + const watcher = fs.watch(testsubdir, function(event, filename) { + const renameEv = common.isSunOS ? 'change' : 'rename'; + assert.strictEqual(renameEv, event); if (expectFilePath) { - assert.equal('newfile.txt', filename); + assert.strictEqual('newfile.txt', filename); } else { - assert.equal(null, filename); + assert.strictEqual(null, filename); } watcher.close(); ++watchSeenThree; @@ -94,7 +94,7 @@ assert.doesNotThrow( ); setImmediate(function() { - var fd = fs.openSync(filepathThree, 'w'); + const fd = fs.openSync(filepathThree, 'w'); fs.closeSync(fd); }); @@ -106,9 +106,9 @@ fs.watch(__filename, {persistent: false}, function() { // whitebox test to ensure that wrapped FSEvent is safe // https://github.com/joyent/node/issues/6690 -var oldhandle; +let oldhandle; assert.throws(function() { - var w = fs.watch(__filename, function(event, filename) { }); + const w = fs.watch(__filename, function(event, filename) { }); oldhandle = w._handle; w._handle = { close: w._handle.close }; w.close(); @@ -116,7 +116,7 @@ assert.throws(function() { oldhandle.close(); // clean up assert.throws(function() { - var w = fs.watchFile(__filename, {persistent: false}, function() {}); + const w = fs.watchFile(__filename, {persistent: false}, function() {}); oldhandle = w._handle; w._handle = { stop: w._handle.stop }; w.stop(); diff --git a/test/sequential/test-regress-GH-897.js b/test/sequential/test-regress-GH-897.js deleted file mode 100644 index 7b1297efd5a1b7..00000000000000 --- a/test/sequential/test-regress-GH-897.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -// Test for bug where a timer duration greater than 0 ms but less than 1 ms -// resulted in the duration being set for 1000 ms. The expected behavior is -// that the timeout would be set for 1 ms, and thus fire more-or-less -// immediately. -// -// Ref: https://github.com/nodejs/node-v0.x-archive/pull/897 - -const common = require('../common'); -const assert = require('assert'); - -const t = Date.now(); -setTimeout(common.mustCall(function() { - const diff = Date.now() - t; - assert.ok(diff < 100, `timer fired after ${diff} ms`); -}), 0.1); diff --git a/tools/doc/README.md b/tools/doc/README.md index 6985bc130d62c5..0535243e92f63b 100644 --- a/tools/doc/README.md +++ b/tools/doc/README.md @@ -99,10 +99,9 @@ This event is emitted on instances of SomeClass, not on the module itself. ``` -* Modules have (description, Properties, Functions, Classes, Examples) -* Properties have (type, description) -* Functions have (list of arguments, description) * Classes have (description, Properties, Methods, Events) * Events have (list of arguments, description) +* Functions have (list of arguments, description) * Methods have (list of arguments, description) +* Modules have (description, Properties, Functions, Classes, Examples) * Properties have (type, description) diff --git a/tools/doc/type-parser.js b/tools/doc/type-parser.js index 38451b0e16b358..0ac15a14b93341 100644 --- a/tools/doc/type-parser.js +++ b/tools/doc/type-parser.js @@ -1,9 +1,8 @@ 'use strict'; const nodeDocUrl = ''; -const jsDocUrl = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/' + - 'Reference/Global_Objects/'; -const jsPrimitiveUrl = 'https://developer.mozilla.org/en-US/docs/Web/' + - 'JavaScript/Data_structures'; +const jsDocPrefix = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/'; +const jsDocUrl = jsDocPrefix + 'Reference/Global_Objects/'; +const jsPrimitiveUrl = jsDocPrefix + 'Data_structures'; const jsPrimitives = { 'Integer': 'Number', // this is for extending 'Number': 'Number', @@ -37,6 +36,8 @@ const typeMap = { 'http.IncomingMessage': 'http.html#http_class_http_incomingmessage', 'http.Server': 'http.html#http_class_http_server', 'http.ServerResponse': 'http.html#http_class_http_serverresponse', + 'Iterator': jsDocPrefix + + 'Reference/Iteration_protocols#The_iterator_protocol' }; module.exports = { diff --git a/tools/eslint-rules/align-function-arguments.js b/tools/eslint-rules/align-function-arguments.js deleted file mode 100644 index 015552489a9d44..00000000000000 --- a/tools/eslint-rules/align-function-arguments.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @fileoverview Align arguments in multiline function calls - * @author Rich Trott - */ -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -function checkArgumentAlignment(context, node) { - - function isNodeFirstInLine(node, byEndLocation) { - const firstToken = byEndLocation === true ? context.getLastToken(node, 1) : - context.getTokenBefore(node); - const startLine = byEndLocation === true ? node.loc.end.line : - node.loc.start.line; - const endLine = firstToken ? firstToken.loc.end.line : -1; - - return startLine !== endLine; - } - - if (node.arguments.length === 0) - return; - - var msg = ''; - const first = node.arguments[0]; - var currentLine = first.loc.start.line; - const firstColumn = first.loc.start.column; - - const ignoreTypes = [ - 'ArrowFunctionExpression', - 'FunctionExpression', - 'ObjectExpression', - ]; - - const args = node.arguments; - - // For now, don't bother trying to validate potentially complicating things - // like closures. Different people will have very different ideas and it's - // probably best to implement configuration options. - if (args.some((node) => { return ignoreTypes.indexOf(node.type) !== -1; })) { - return; - } - - if (!isNodeFirstInLine(node)) { - return; - } - - var misaligned; - - args.slice(1).forEach((argument) => { - if (!misaligned) { - if (argument.loc.start.line === currentLine + 1) { - if (argument.loc.start.column !== firstColumn) { - if (isNodeFirstInLine(argument)) { - msg = 'Function argument in column ' + - `${argument.loc.start.column + 1}, ` + - `expected in ${firstColumn + 1}`; - misaligned = argument; - } - } - } - } - currentLine = argument.loc.start.line; - }); - - if (msg) - context.report(misaligned, msg); -} - -module.exports = function(context) { - return { - 'CallExpression': (node) => checkArgumentAlignment(context, node) - }; -}; diff --git a/tools/eslint-rules/no-useless-regex-char-class-escape.js b/tools/eslint-rules/no-useless-regex-char-class-escape.js deleted file mode 100644 index e18077098daee2..00000000000000 --- a/tools/eslint-rules/no-useless-regex-char-class-escape.js +++ /dev/null @@ -1,190 +0,0 @@ -/** - * @fileoverview Disallow useless escape in regex character class - * Based on 'no-useless-escape' rule - */ -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const REGEX_CHARCLASS_ESCAPES = new Set('\\bcdDfnrsStvwWxu0123456789]'); - -/** - * Parses a regular expression into a list of regex character class list. - * @param {string} regExpText raw text used to create the regular expression - * @returns {Object[]} A list of character classes tokens with index and - * escape info - * @example - * - * parseRegExpCharClass('a\\b[cd-]') - * - * returns: - * [ - * { - * empty: false, - * start: 4, - * end: 6, - * chars: [ - * {text: 'c', index: 4, escaped: false}, - * {text: 'd', index: 5, escaped: false}, - * {text: '-', index: 6, escaped: false} - * ] - * } - * ] - */ - -function parseRegExpCharClass(regExpText) { - const charList = []; - let charListIdx = -1; - const initState = { - escapeNextChar: false, - inCharClass: false, - startingCharClass: false - }; - - regExpText.split('').reduce((state, char, index) => { - if (!state.escapeNextChar) { - if (char === '\\') { - return Object.assign(state, { escapeNextChar: true }); - } - if (char === '[' && !state.inCharClass) { - charListIdx += 1; - charList.push({ start: index + 1, chars: [], end: -1 }); - return Object.assign(state, { - inCharClass: true, - startingCharClass: true - }); - } - if (char === ']' && state.inCharClass) { - const charClass = charList[charListIdx]; - charClass.empty = charClass.chars.length === 0; - if (charClass.empty) { - charClass.start = charClass.end = -1; - } else { - charList[charListIdx].end = index - 1; - } - return Object.assign(state, { - inCharClass: false, - startingCharClass: false - }); - } - } - if (state.inCharClass) { - charList[charListIdx].chars.push({ - text: char, - index, escaped: - state.escapeNextChar - }); - } - return Object.assign(state, { - escapeNextChar: false, - startingCharClass: false - }); - }, initState); - - return charList; -} - -module.exports = { - meta: { - docs: { - description: 'disallow unnecessary regex characer class escape sequences', - category: 'Best Practices', - recommended: false - }, - fixable: 'code', - schema: [{ - 'type': 'object', - 'properties': { - 'override': { - 'type': 'array', - 'items': { 'type': 'string' }, - 'uniqueItems': true - } - }, - 'additionalProperties': false - }] - }, - - create(context) { - const overrideSet = new Set(context.options.length ? - context.options[0].override || [] : - []); - - /** - * Reports a node - * @param {ASTNode} node The node to report - * @param {number} startOffset The backslash's offset - * from the start of the node - * @param {string} character The uselessly escaped character - * (not including the backslash) - * @returns {void} - */ - function report(node, startOffset, character) { - context.report({ - node, - loc: { - line: node.loc.start.line, - column: node.loc.start.column + startOffset - }, - message: 'Unnecessary regex escape in character' + - ' class: \\{{character}}', - data: { character }, - fix: (fixer) => { - const start = node.range[0] + startOffset; - return fixer.replaceTextRange([start, start + 1], ''); - } - }); - } - - /** - * Checks if a node has superflous escape character - * in regex character class. - * - * @param {ASTNode} node - node to check. - * @returns {void} - */ - function check(node) { - if (node.regex) { - parseRegExpCharClass(node.regex.pattern) - .forEach((charClass) => { - charClass - .chars - // The '-' character is a special case if is not at - // either edge of the character class. To account for this, - // filter out '-' characters that appear in the middle of a - // character class. - .filter((charInfo) => !(charInfo.text === '-' && - (charInfo.index !== charClass.start && - charInfo.index !== charClass.end))) - - // The '^' character is a special case if it's at the beginning - // of the character class. To account for this, filter out '^' - // characters that appear at the start of a character class. - // - .filter((charInfo) => !(charInfo.text === '^' && - charInfo.index === charClass.start)) - - // Filter out characters that aren't escaped. - .filter((charInfo) => charInfo.escaped) - - // Filter out characters that are valid to escape, based on - // their position in the regular expression. - .filter((charInfo) => !REGEX_CHARCLASS_ESCAPES.has(charInfo.text)) - - // Filter out overridden character list. - .filter((charInfo) => !overrideSet.has(charInfo.text)) - - // Report all the remaining characters. - .forEach((charInfo) => - report(node, charInfo.index, charInfo.text)); - }); - } - } - - return { - Literal: check - }; - } -}; diff --git a/tools/eslint-rules/timer-arguments.js b/tools/eslint-rules/timer-arguments.js new file mode 100644 index 00000000000000..4dd7816ff82ff2 --- /dev/null +++ b/tools/eslint-rules/timer-arguments.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Require at least two arguments when calling setTimeout() or + * setInterval(). + * @author Rich Trott + */ +'use strict'; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +function isTimer(name) { + return ['setTimeout', 'setInterval'].includes(name); +} + +module.exports = function(context) { + return { + 'CallExpression': function(node) { + const name = node.callee.name; + if (isTimer(name) && node.arguments.length < 2) { + context.report(node, `${name} must have at least 2 arguments`); + } + } + }; +}; diff --git a/tools/eslint/LICENSE b/tools/eslint/LICENSE index d41bdf7951f077..777939e8fc1a7f 100644 --- a/tools/eslint/LICENSE +++ b/tools/eslint/LICENSE @@ -1,5 +1,5 @@ ESLint -Copyright jQuery Foundation and other contributors, https://jquery.org/ +Copyright JS Foundation and other contributors, https://js.foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/tools/eslint/README.md b/tools/eslint/README.md index 4d84a7e3dfd5cd..dcd42cff46685a 100644 --- a/tools/eslint/README.md +++ b/tools/eslint/README.md @@ -13,7 +13,7 @@ [Rules](http://eslint.org/docs/rules/) | [Contributing](http://eslint.org/docs/developer-guide/contributing) | [Reporting Bugs](http://eslint.org/docs/developer-guide/contributing/reporting-bugs) | -[Code of Conduct](https://jquery.org/conduct/) | +[Code of Conduct](https://js.foundation/conduct/) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) | [Chat Room](https://gitter.im/eslint/eslint) @@ -210,10 +210,7 @@ ESLint has full support for ECMAScript 6. By default, this support is off. You c ESLint doesn't natively support experimental ECMAScript language features. You can use [babel-eslint](https://github.com/babel/babel-eslint) to use any option available in Babel. -Once a language feature has been adopted into the ECMAScript standard, we will accept -issues and pull requests related to the new feature, subject to our [contributing -guidelines](http://eslint.org/docs/developer-guide/contributing). Until then, please use -the appropriate parser and plugin(s) for your experimental feature. +Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](http://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. ### Where to ask for help? diff --git a/tools/eslint/bin/eslint.js b/tools/eslint/bin/eslint.js index d85d29d7a5bdae..bf534971f24d9b 100755 --- a/tools/eslint/bin/eslint.js +++ b/tools/eslint/bin/eslint.js @@ -5,7 +5,7 @@ * @author Nicholas C. Zakas */ -/* eslint no-console:off, no-process-exit:off */ +/* eslint no-console:off */ "use strict"; @@ -36,7 +36,7 @@ const concat = require("concat-stream"), // Execution //------------------------------------------------------------------------------ -process.on("uncaughtException", function(err) { +process.once("uncaughtException", err => { // lazy load const lodash = require("lodash"); @@ -51,17 +51,17 @@ process.on("uncaughtException", function(err) { console.log(err.stack); } - process.exit(1); + process.exitCode = 1; }); if (useStdIn) { - process.stdin.pipe(concat({ encoding: "string" }, function(text) { + process.stdin.pipe(concat({ encoding: "string" }, text => { process.exitCode = cli.execute(process.argv, text); })); } else if (init) { const configInit = require("../lib/config/config-initializer"); - configInit.initializeConfig(function(err) { + configInit.initializeConfig(err => { if (err) { process.exitCode = 1; console.error(err.message); diff --git a/tools/eslint/conf/eslint.json b/tools/eslint/conf/eslint.json index 4d54e3ab6dac6a..81f5bb8aa5ee82 100755 --- a/tools/eslint/conf/eslint.json +++ b/tools/eslint/conf/eslint.json @@ -4,6 +4,7 @@ "rules": { "no-alert": "off", "no-array-constructor": "off", + "no-await-in-loop": "off", "no-bitwise": "off", "no-caller": "off", "no-case-declarations": "error", @@ -41,7 +42,7 @@ "no-fallthrough": "error", "no-floating-decimal": "off", "no-func-assign": "error", - "no-global-assign": "off", + "no-global-assign": "error", "no-implicit-coercion": "off", "no-implicit-globals": "off", "no-implied-eval": "off", @@ -63,9 +64,9 @@ "no-multi-spaces": "off", "no-multi-str": "off", "no-multiple-empty-lines": "off", - "no-native-reassign": "error", + "no-native-reassign": "off", "no-negated-condition": "off", - "no-negated-in-lhs": "error", + "no-negated-in-lhs": "off", "no-nested-ternary": "off", "no-new": "off", "no-new-func": "off", @@ -91,6 +92,7 @@ "no-restricted-properties": "off", "no-restricted-syntax": "off", "no-return-assign": "off", + "no-return-await": "off", "no-script-url": "off", "no-self-assign": "error", "no-self-compare": "off", @@ -115,7 +117,7 @@ "no-unneeded-ternary": "off", "no-unreachable": "error", "no-unsafe-finally": "error", - "no-unsafe-negation": "off", + "no-unsafe-negation": "error", "no-unused-expressions": "off", "no-unused-labels": "error", "no-unused-vars": "error", @@ -126,6 +128,7 @@ "no-useless-constructor": "off", "no-useless-escape": "off", "no-useless-rename": "off", + "no-useless-return": "off", "no-void": "off", "no-var": "off", "no-warning-comments": "off", @@ -141,6 +144,7 @@ "brace-style": "off", "callback-return": "off", "camelcase": "off", + "capitalized-comments": "off", "class-methods-use-this": "off", "comma-dangle": "off", "comma-spacing": "off", @@ -200,6 +204,7 @@ "padded-blocks": "off", "prefer-arrow-callback": "off", "prefer-const": "off", + "prefer-destructuring": "off", "prefer-numeric-literals": "off", "prefer-reflect": "off", "prefer-rest-params": "off", @@ -208,6 +213,7 @@ "quote-props": "off", "quotes": "off", "radix": "off", + "require-await": "off", "require-jsdoc": "off", "require-yield": "error", "rest-spread-spacing": "off", diff --git a/tools/eslint/lib/ast-utils.js b/tools/eslint/lib/ast-utils.js index 9e171ea316fc31..46dfebe101caa2 100644 --- a/tools/eslint/lib/ast-utils.js +++ b/tools/eslint/lib/ast-utils.js @@ -10,6 +10,7 @@ //------------------------------------------------------------------------------ const esutils = require("esutils"); +const lodash = require("lodash"); //------------------------------------------------------------------------------ // Helpers @@ -21,7 +22,7 @@ const arrayOrTypedArrayPattern = /Array$/; const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/; const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/; const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/; -const thisTagPattern = /^[\s\*]*@this/m; +const thisTagPattern = /^[\s*]*@this/m; /** * Checks reference if is non initializer and writable. @@ -83,6 +84,56 @@ function getUpperFunction(node) { return null; } +/** + * Checks whether a given node is a function node or not. + * The following types are function nodes: + * + * - ArrowFunctionExpression + * - FunctionDeclaration + * - FunctionExpression + * + * @param {ASTNode|null} node - A node to check. + * @returns {boolean} `true` if the node is a function node. + */ +function isFunction(node) { + return Boolean(node && anyFunctionPattern.test(node.type)); +} + +/** + * Checks whether a given node is a loop node or not. + * The following types are loop nodes: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - WhileStatement + * + * @param {ASTNode|null} node - A node to check. + * @returns {boolean} `true` if the node is a loop node. + */ +function isLoop(node) { + return Boolean(node && anyLoopPattern.test(node.type)); +} + +/** + * Checks whether the given node is in a loop or not. + * + * @param {ASTNode} node - The node to check. + * @returns {boolean} `true` if the node is in a loop. + */ +function isInLoop(node) { + while (node && !isFunction(node)) { + if (isLoop(node)) { + return true; + } + + node = node.parent; + } + + return false; +} + /** * Checks whether or not a node is `null` or `undefined`. * @param {ASTNode} node - A node to check. @@ -176,9 +227,7 @@ function hasJSDocThisTag(node, sourceCode) { // because callbacks don't have its JSDoc comment. // e.g. // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); }); - return sourceCode.getComments(node).leading.some(function(comment) { - return thisTagPattern.test(comment.value); - }); + return sourceCode.getComments(node).leading.some(comment => thisTagPattern.test(comment.value)); } /** @@ -197,6 +246,59 @@ function isParenthesised(sourceCode, node) { nextToken.value === ")" && nextToken.range[0] >= node.range[1]; } +/** + * Gets the `=>` token of the given arrow function node. + * + * @param {ASTNode} node - The arrow function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {Token} `=>` token. + */ +function getArrowToken(node, sourceCode) { + let token = sourceCode.getTokenBefore(node.body); + + while (token.value !== "=>") { + token = sourceCode.getTokenBefore(token); + } + + return token; +} + +/** + * Gets the `(` token of the given function node. + * + * @param {ASTNode} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {Token} `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + let token = node.id ? sourceCode.getTokenAfter(node.id) : sourceCode.getFirstToken(node); + + while (token.value !== "(") { + token = sourceCode.getTokenAfter(token); + } + + return token; +} + +const lineIndexCache = new WeakMap(); + +/** + * Gets the range index for the first character in each of the lines of `sourceCode`. + * @param {SourceCode} sourceCode A sourceCode object + * @returns {number[]} The indices of the first characters in the each of the lines of the code + */ +function getLineIndices(sourceCode) { + + if (!lineIndexCache.has(sourceCode)) { + const lineIndices = (sourceCode.text.match(/[^\r\n\u2028\u2029]*(\r\n|\r|\n|\u2028|\u2029)/g) || []) + .reduce((indices, line) => indices.concat(indices[indices.length - 1] + line.length), [0]); + + // Store the sourceCode object in a WeakMap to avoid iterating over all of the lines every time a sourceCode object is passed in. + lineIndexCache.set(sourceCode, lineIndices); + } + return lineIndexCache.get(sourceCode); +} + //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ @@ -218,6 +320,9 @@ module.exports = { isCallee, isES5Constructor, getUpperFunction, + isFunction, + isLoop, + isInLoop, isArrayFromMethod, isParenthesised, @@ -583,35 +688,23 @@ module.exports = { }, /** - * Checks whether a given node is a loop node or not. - * The following types are loop nodes: + * Checks whether the given node is an empty block node or not. * - * - DoWhileStatement - * - ForInStatement - * - ForOfStatement - * - ForStatement - * - WhileStatement - * - * @param {ASTNode|null} node - A node to check. - * @returns {boolean} `true` if the node is a loop node. + * @param {ASTNode|null} node - The node to check. + * @returns {boolean} `true` if the node is an empty block. */ - isLoop(node) { - return Boolean(node && anyLoopPattern.test(node.type)); + isEmptyBlock(node) { + return Boolean(node && node.type === "BlockStatement" && node.body.length === 0); }, /** - * Checks whether a given node is a function node or not. - * The following types are function nodes: + * Checks whether the given node is an empty function node or not. * - * - ArrowFunctionExpression - * - FunctionDeclaration - * - FunctionExpression - * - * @param {ASTNode|null} node - A node to check. - * @returns {boolean} `true` if the node is a function node. + * @param {ASTNode|null} node - The node to check. + * @returns {boolean} `true` if the node is an empty function. */ - isFunction(node) { - return Boolean(node && anyFunctionPattern.test(node.type)); + isEmptyFunction(node) { + return isFunction(node) && module.exports.isEmptyBlock(node.body); }, /** @@ -738,5 +831,271 @@ module.exports = { */ isDecimalInteger(node) { return node.type === "Literal" && typeof node.value === "number" && /^(0|[1-9]\d*)$/.test(node.raw); + }, + + /** + * Gets the name and kind of the given function node. + * + * - `function foo() {}` .................... `function 'foo'` + * - `(function foo() {})` .................. `function 'foo'` + * - `(function() {})` ...................... `function` + * - `function* foo() {}` ................... `generator function 'foo'` + * - `(function* foo() {})` ................. `generator function 'foo'` + * - `(function*() {})` ..................... `generator function` + * - `() => {}` ............................. `arrow function` + * - `async () => {}` ....................... `async arrow function` + * - `({ foo: function foo() {} })` ......... `method 'foo'` + * - `({ foo: function() {} })` ............. `method 'foo'` + * - `({ ['foo']: function() {} })` ......... `method 'foo'` + * - `({ [foo]: function() {} })` ........... `method` + * - `({ foo() {} })` ....................... `method 'foo'` + * - `({ foo: function* foo() {} })` ........ `generator method 'foo'` + * - `({ foo: function*() {} })` ............ `generator method 'foo'` + * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'` + * - `({ [foo]: function*() {} })` .......... `generator method` + * - `({ *foo() {} })` ...................... `generator method 'foo'` + * - `({ foo: async function foo() {} })` ... `async method 'foo'` + * - `({ foo: async function() {} })` ....... `async method 'foo'` + * - `({ ['foo']: async function() {} })` ... `async method 'foo'` + * - `({ [foo]: async function() {} })` ..... `async method` + * - `({ async foo() {} })` ................. `async method 'foo'` + * - `({ get foo() {} })` ................... `getter 'foo'` + * - `({ set foo(a) {} })` .................. `setter 'foo'` + * - `class A { constructor() {} }` ......... `constructor` + * - `class A { foo() {} }` ................. `method 'foo'` + * - `class A { *foo() {} }` ................ `generator method 'foo'` + * - `class A { async foo() {} }` ........... `async method 'foo'` + * - `class A { ['foo']() {} }` ............. `method 'foo'` + * - `class A { *['foo']() {} }` ............ `generator method 'foo'` + * - `class A { async ['foo']() {} }` ....... `async method 'foo'` + * - `class A { [foo]() {} }` ............... `method` + * - `class A { *[foo]() {} }` .............. `generator method` + * - `class A { async [foo]() {} }` ......... `async method` + * - `class A { get foo() {} }` ............. `getter 'foo'` + * - `class A { set foo(a) {} }` ............ `setter 'foo'` + * - `class A { static foo() {} }` .......... `static method 'foo'` + * - `class A { static *foo() {} }` ......... `static generator method 'foo'` + * - `class A { static async foo() {} }` .... `static async method 'foo'` + * - `class A { static get foo() {} }` ...... `static getter 'foo'` + * - `class A { static set foo(a) {} }` ..... `static setter 'foo'` + * + * @param {ASTNode} node - The function node to get. + * @returns {string} The name and kind of the function node. + */ + getFunctionNameWithKind(node) { + const parent = node.parent; + const tokens = []; + + if (parent.type === "MethodDefinition" && parent.static) { + tokens.push("static"); + } + if (node.async) { + tokens.push("async"); + } + if (node.generator) { + tokens.push("generator"); + } + + if (node.type === "ArrowFunctionExpression") { + tokens.push("arrow", "function"); + } else if (parent.type === "Property" || parent.type === "MethodDefinition") { + if (parent.kind === "constructor") { + return "constructor"; + } else if (parent.kind === "get") { + tokens.push("getter"); + } else if (parent.kind === "set") { + tokens.push("setter"); + } else { + tokens.push("method"); + } + } else { + tokens.push("function"); + } + + if (node.id) { + tokens.push(`'${node.id.name}'`); + } else { + const name = module.exports.getStaticPropertyName(parent); + + if (name) { + tokens.push(`'${name}'`); + } + } + + return tokens.join(" "); + }, + + /** + * Gets the location of the given function node for reporting. + * + * - `function foo() {}` + * ^^^^^^^^^^^^ + * - `(function foo() {})` + * ^^^^^^^^^^^^ + * - `(function() {})` + * ^^^^^^^^ + * - `function* foo() {}` + * ^^^^^^^^^^^^^ + * - `(function* foo() {})` + * ^^^^^^^^^^^^^ + * - `(function*() {})` + * ^^^^^^^^^ + * - `() => {}` + * ^^ + * - `async () => {}` + * ^^ + * - `({ foo: function foo() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ foo: function() {} })` + * ^^^^^^^^^^^^^ + * - `({ ['foo']: function() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function() {} })` + * ^^^^^^^^^^^^^^^ + * - `({ foo() {} })` + * ^^^ + * - `({ foo: function* foo() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ foo: function*() {} })` + * ^^^^^^^^^^^^^^ + * - `({ ['foo']: function*() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function*() {} })` + * ^^^^^^^^^^^^^^^^ + * - `({ *foo() {} })` + * ^^^^ + * - `({ foo: async function foo() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ foo: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^ + * - `({ ['foo']: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `({ async foo() {} })` + * ^^^^^^^^^ + * - `({ get foo() {} })` + * ^^^^^^^ + * - `({ set foo(a) {} })` + * ^^^^^^^ + * - `class A { constructor() {} }` + * ^^^^^^^^^^^ + * - `class A { foo() {} }` + * ^^^ + * - `class A { *foo() {} }` + * ^^^^ + * - `class A { async foo() {} }` + * ^^^^^^^^^ + * - `class A { ['foo']() {} }` + * ^^^^^^^ + * - `class A { *['foo']() {} }` + * ^^^^^^^^ + * - `class A { async ['foo']() {} }` + * ^^^^^^^^^^^^^ + * - `class A { [foo]() {} }` + * ^^^^^ + * - `class A { *[foo]() {} }` + * ^^^^^^ + * - `class A { async [foo]() {} }` + * ^^^^^^^^^^^ + * - `class A { get foo() {} }` + * ^^^^^^^ + * - `class A { set foo(a) {} }` + * ^^^^^^^ + * - `class A { static foo() {} }` + * ^^^^^^^^^^ + * - `class A { static *foo() {} }` + * ^^^^^^^^^^^ + * - `class A { static async foo() {} }` + * ^^^^^^^^^^^^^^^^ + * - `class A { static get foo() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static set foo(a) {} }` + * ^^^^^^^^^^^^^^ + * + * @param {ASTNode} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {string} The location of the function node for reporting. + */ + getFunctionHeadLoc(node, sourceCode) { + const parent = node.parent; + let start = null; + let end = null; + + if (node.type === "ArrowFunctionExpression") { + const arrowToken = getArrowToken(node, sourceCode); + + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } else if (parent.type === "Property" || parent.type === "MethodDefinition") { + start = parent.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } else { + start = node.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + + return { + start: Object.assign({}, start), + end: Object.assign({}, end), + }; + }, + + /* + * Converts a range index into a (line, column) pair. + * @param {SourceCode} sourceCode A SourceCode object + * @param {number} rangeIndex The range index of a character in a file + * @returns {Object} A {line, column} location object with a 0-indexed column + */ + getLocationFromRangeIndex(sourceCode, rangeIndex) { + const lineIndices = getLineIndices(sourceCode); + + /* + * lineIndices is a sorted list of indices of the first character of each line. + * To figure out which line rangeIndex is on, determine the last index at which rangeIndex could + * be inserted into lineIndices to keep the list sorted. + */ + const lineNumber = lodash.sortedLastIndex(lineIndices, rangeIndex); + + return { line: lineNumber, column: rangeIndex - lineIndices[lineNumber - 1] }; + + }, + + /** + * Converts a (line, column) pair into a range index. + * @param {SourceCode} sourceCode A SourceCode object + * @param {Object} loc A line/column location + * @param {number} loc.line The line number of the location (1-indexed) + * @param {number} loc.column The column number of the location (0-indexed) + * @returns {number} The range index of the location in the file. + */ + getRangeIndexFromLocation(sourceCode, loc) { + return getLineIndices(sourceCode)[loc.line - 1] + loc.column; + }, + + /** + * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses + * surrounding the node. + * @param {SourceCode} sourceCode The source code object + * @param {ASTNode} node An expression node + * @returns {string} The text representing the node, with all surrounding parentheses included + */ + getParenthesisedText(sourceCode, node) { + let leftToken = sourceCode.getFirstToken(node); + let rightToken = sourceCode.getLastToken(node); + + while ( + sourceCode.getTokenBefore(leftToken) && + sourceCode.getTokenBefore(leftToken).type === "Punctuator" && + sourceCode.getTokenBefore(leftToken).value === "(" && + sourceCode.getTokenAfter(rightToken) && + sourceCode.getTokenAfter(rightToken).type === "Punctuator" && + sourceCode.getTokenAfter(rightToken).value === ")" + ) { + leftToken = sourceCode.getTokenBefore(leftToken); + rightToken = sourceCode.getTokenAfter(rightToken); + } + + return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]); } }; diff --git a/tools/eslint/lib/cli-engine.js b/tools/eslint/lib/cli-engine.js index b9019932fe9b54..de875a4d352926 100644 --- a/tools/eslint/lib/cli-engine.js +++ b/tools/eslint/lib/cli-engine.js @@ -90,7 +90,7 @@ const debug = require("debug")("eslint:cli-engine"); * @private */ function calculateStatsPerFile(messages) { - return messages.reduce(function(stat, message) { + return messages.reduce((stat, message) => { if (message.fatal || message.severity === 2) { stat.errorCount++; } else { @@ -110,7 +110,7 @@ function calculateStatsPerFile(messages) { * @private */ function calculateStatsPerRun(results) { - return results.reduce(function(stat, result) { + return results.reduce((stat, result) => { stat.errorCount += result.errorCount; stat.warningCount += result.warningCount; return stat; @@ -241,7 +241,7 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) { const parsedBlocks = processor.preprocess(text, filename); const unprocessedMessages = []; - parsedBlocks.forEach(function(block) { + parsedBlocks.forEach(block => { unprocessedMessages.push(eslint.verify(block, config, { filename, allowInlineConfig @@ -320,11 +320,11 @@ function createIgnoreResult(filePath, baseDir) { const isInBowerComponents = baseDir && /^bower_components/.test(path.relative(baseDir, filePath)); if (isHidden) { - message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern \'!\'\") to override."; + message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!'\") to override."; } else if (isInNodeModules) { - message = "File ignored by default. Use \"--ignore-pattern \'!node_modules/*\'\" to override."; + message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override."; } else if (isInBowerComponents) { - message = "File ignored by default. Use \"--ignore-pattern \'!bower_components/*\'\" to override."; + message = "File ignored by default. Use \"--ignore-pattern '!bower_components/*'\" to override."; } else { message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override."; } @@ -442,7 +442,7 @@ function CLIEngine(options) { options = Object.assign( Object.create(null), defaultOptions, - {cwd: process.cwd()}, + { cwd: process.cwd() }, options ); @@ -466,15 +466,15 @@ function CLIEngine(options) { if (this.options.rulePaths) { const cwd = this.options.cwd; - this.options.rulePaths.forEach(function(rulesdir) { + this.options.rulePaths.forEach(rulesdir => { debug(`Loading rules from ${rulesdir}`); rules.load(rulesdir, cwd); }); } - Object.keys(this.options.rules || {}).forEach(function(name) { + Object.keys(this.options.rules || {}).forEach(name => { validator.validateRuleOptions(name, this.options.rules[name], "CLI"); - }.bind(this)); + }); } /** @@ -526,7 +526,7 @@ CLIEngine.getFormatter = function(format) { CLIEngine.getErrorResults = function(results) { const filtered = []; - results.forEach(function(result) { + results.forEach(result => { const filteredMessages = result.messages.filter(isErrorMessage); if (filteredMessages.length > 0) { @@ -549,9 +549,7 @@ CLIEngine.getErrorResults = function(results) { * @returns {void} */ CLIEngine.outputFixes = function(report) { - report.results.filter(function(result) { - return result.hasOwnProperty("output"); - }).forEach(function(result) { + report.results.filter(result => result.hasOwnProperty("output")).forEach(result => { fs.writeFileSync(result.filePath, result.output); }); }; @@ -708,7 +706,7 @@ CLIEngine.prototype = { patterns = this.resolveFileGlobPatterns(patterns); const fileList = globUtil.listFilesToProcess(patterns, options); - fileList.forEach(function(fileInfo) { + fileList.forEach(fileInfo => { executeOnFile(fileInfo.filename, fileInfo.ignored); }); @@ -794,4 +792,6 @@ CLIEngine.prototype = { }; +CLIEngine.version = pkg.version; + module.exports = CLIEngine; diff --git a/tools/eslint/lib/code-path-analysis/code-path-analyzer.js b/tools/eslint/lib/code-path-analysis/code-path-analyzer.js index 655211430b4e2e..cb8b1e1bf8ce8c 100644 --- a/tools/eslint/lib/code-path-analysis/code-path-analyzer.js +++ b/tools/eslint/lib/code-path-analysis/code-path-analyzer.js @@ -569,21 +569,20 @@ function postprocess(analyzer, node) { /** * The class to analyze code paths. * This class implements the EventGenerator interface. - * - * @constructor - * @param {EventGenerator} eventGenerator - An event generator to wrap. */ -function CodePathAnalyzer(eventGenerator) { - this.original = eventGenerator; - this.emitter = eventGenerator.emitter; - this.codePath = null; - this.idGenerator = new IdGenerator("s"); - this.currentNode = null; - this.onLooped = this.onLooped.bind(this); -} +class CodePathAnalyzer { -CodePathAnalyzer.prototype = { - constructor: CodePathAnalyzer, + /** + * @param {EventGenerator} eventGenerator - An event generator to wrap. + */ + constructor(eventGenerator) { + this.original = eventGenerator; + this.emitter = eventGenerator.emitter; + this.codePath = null; + this.idGenerator = new IdGenerator("s"); + this.currentNode = null; + this.onLooped = this.onLooped.bind(this); + } /** * Does the process to enter a given AST node. @@ -608,7 +607,7 @@ CodePathAnalyzer.prototype = { this.original.enterNode(node); this.currentNode = null; - }, + } /** * Does the process to leave a given AST node. @@ -631,7 +630,7 @@ CodePathAnalyzer.prototype = { postprocess(this, node); this.currentNode = null; - }, + } /** * This is called on a code path looped. @@ -652,6 +651,6 @@ CodePathAnalyzer.prototype = { ); } } -}; +} module.exports = CodePathAnalyzer; diff --git a/tools/eslint/lib/code-path-analysis/code-path-segment.js b/tools/eslint/lib/code-path-analysis/code-path-segment.js index b3966c415b0aac..db1eba4560c251 100644 --- a/tools/eslint/lib/code-path-analysis/code-path-segment.js +++ b/tools/eslint/lib/code-path-analysis/code-path-segment.js @@ -68,174 +68,175 @@ function isReachable(segment) { /** * A code path segment. - * - * @constructor - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * This array includes unreachable segments. - * @param {boolean} reachable - A flag which shows this is reachable. */ -function CodePathSegment(id, allPrevSegments, reachable) { +class CodePathSegment { /** - * The identifier of this code path. - * Rules use it to store additional information of each rule. - * @type {string} + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * This array includes unreachable segments. + * @param {boolean} reachable - A flag which shows this is reachable. */ - this.id = id; + constructor(id, allPrevSegments, reachable) { + + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * An array of the next segments. + * @type {CodePathSegment[]} + */ + this.nextSegments = []; + + /** + * An array of the previous segments. + * @type {CodePathSegment[]} + */ + this.prevSegments = allPrevSegments.filter(isReachable); + + /** + * An array of the next segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allNextSegments = []; + + /** + * An array of the previous segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allPrevSegments = allPrevSegments; + + /** + * A flag which shows this is reachable. + * @type {boolean} + */ + this.reachable = reachable; + + // Internal data. + Object.defineProperty(this, "internal", { + value: { + used: false, + loopedPrevSegments: [] + } + }); - /** - * An array of the next segments. - * @type {CodePathSegment[]} - */ - this.nextSegments = []; + /* istanbul ignore if */ + if (debug.enabled) { + this.internal.nodes = []; + this.internal.exitNodes = []; + } + } /** - * An array of the previous segments. - * @type {CodePathSegment[]} + * Checks a given previous segment is coming from the end of a loop. + * + * @param {CodePathSegment} segment - A previous segment to check. + * @returns {boolean} `true` if the segment is coming from the end of a loop. */ - this.prevSegments = allPrevSegments.filter(isReachable); + isLoopedPrevSegment(segment) { + return this.internal.loopedPrevSegments.indexOf(segment) !== -1; + } /** - * An array of the next segments. - * This array includes unreachable segments. - * @type {CodePathSegment[]} + * Creates the root segment. + * + * @param {string} id - An identifier. + * @returns {CodePathSegment} The created segment. */ - this.allNextSegments = []; + static newRoot(id) { + return new CodePathSegment(id, [], true); + } /** - * An array of the previous segments. - * This array includes unreachable segments. - * @type {CodePathSegment[]} + * Creates a segment that follows given segments. + * + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * @returns {CodePathSegment} The created segment. */ - this.allPrevSegments = allPrevSegments; + static newNext(id, allPrevSegments) { + return new CodePathSegment( + id, + flattenUnusedSegments(allPrevSegments), + allPrevSegments.some(isReachable)); + } /** - * A flag which shows this is reachable. - * @type {boolean} + * Creates an unreachable segment that follows given segments. + * + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * @returns {CodePathSegment} The created segment. */ - this.reachable = reachable; - - // Internal data. - Object.defineProperty(this, "internal", {value: { - used: false, - loopedPrevSegments: [] - }}); - - /* istanbul ignore if */ - if (debug.enabled) { - this.internal.nodes = []; - this.internal.exitNodes = []; - } -} + static newUnreachable(id, allPrevSegments) { + const segment = new CodePathSegment(id, flattenUnusedSegments(allPrevSegments), false); -CodePathSegment.prototype = { - constructor: CodePathSegment, + // In `if (a) return a; foo();` case, the unreachable segment preceded by + // the return statement is not used but must not be remove. + CodePathSegment.markUsed(segment); + + return segment; + } /** - * Checks a given previous segment is coming from the end of a loop. + * Creates a segment that follows given segments. + * This factory method does not connect with `allPrevSegments`. + * But this inherits `reachable` flag. * - * @param {CodePathSegment} segment - A previous segment to check. - * @returns {boolean} `true` if the segment is coming from the end of a loop. + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * @returns {CodePathSegment} The created segment. */ - isLoopedPrevSegment(segment) { - return this.internal.loopedPrevSegments.indexOf(segment) !== -1; + static newDisconnected(id, allPrevSegments) { + return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); } -}; - -/** - * Creates the root segment. - * - * @param {string} id - An identifier. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newRoot = function(id) { - return new CodePathSegment(id, [], true); -}; -/** - * Creates a segment that follows given segments. - * - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newNext = function(id, allPrevSegments) { - return new CodePathSegment( - id, - flattenUnusedSegments(allPrevSegments), - allPrevSegments.some(isReachable)); -}; - -/** - * Creates an unreachable segment that follows given segments. - * - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newUnreachable = function(id, allPrevSegments) { - const segment = new CodePathSegment(id, flattenUnusedSegments(allPrevSegments), false); - - // In `if (a) return a; foo();` case, the unreachable segment preceded by - // the return statement is not used but must not be remove. - CodePathSegment.markUsed(segment); - - return segment; -}; - -/** - * Creates a segment that follows given segments. - * This factory method does not connect with `allPrevSegments`. - * But this inherits `reachable` flag. - * - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newDisconnected = function(id, allPrevSegments) { - return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); -}; - -/** - * Makes a given segment being used. - * - * And this function registers the segment into the previous segments as a next. - * - * @param {CodePathSegment} segment - A segment to mark. - * @returns {void} - */ -CodePathSegment.markUsed = function(segment) { - if (segment.internal.used) { - return; - } - segment.internal.used = true; + /** + * Makes a given segment being used. + * + * And this function registers the segment into the previous segments as a next. + * + * @param {CodePathSegment} segment - A segment to mark. + * @returns {void} + */ + static markUsed(segment) { + if (segment.internal.used) { + return; + } + segment.internal.used = true; - let i; + let i; - if (segment.reachable) { - for (i = 0; i < segment.allPrevSegments.length; ++i) { - const prevSegment = segment.allPrevSegments[i]; + if (segment.reachable) { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + const prevSegment = segment.allPrevSegments[i]; - prevSegment.allNextSegments.push(segment); - prevSegment.nextSegments.push(segment); - } - } else { - for (i = 0; i < segment.allPrevSegments.length; ++i) { - segment.allPrevSegments[i].allNextSegments.push(segment); + prevSegment.allNextSegments.push(segment); + prevSegment.nextSegments.push(segment); + } + } else { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + segment.allPrevSegments[i].allNextSegments.push(segment); + } } } -}; -/** - * Marks a previous segment as looped. - * - * @param {CodePathSegment} segment - A segment. - * @param {CodePathSegment} prevSegment - A previous segment to mark. - * @returns {void} - */ -CodePathSegment.markPrevSegmentAsLooped = function(segment, prevSegment) { - segment.internal.loopedPrevSegments.push(prevSegment); -}; + /** + * Marks a previous segment as looped. + * + * @param {CodePathSegment} segment - A segment. + * @param {CodePathSegment} prevSegment - A previous segment to mark. + * @returns {void} + */ + static markPrevSegmentAsLooped(segment, prevSegment) { + segment.internal.loopedPrevSegments.push(prevSegment); + } +} module.exports = CodePathSegment; diff --git a/tools/eslint/lib/code-path-analysis/code-path-state.js b/tools/eslint/lib/code-path-analysis/code-path-state.js index 3b0b1606e2c993..64779c0d3c8b12 100644 --- a/tools/eslint/lib/code-path-analysis/code-path-state.js +++ b/tools/eslint/lib/code-path-analysis/code-path-state.js @@ -221,36 +221,35 @@ function finalizeTestSegmentsOfFor(context, choiceContext, head) { /** * A class which manages state to analyze code paths. - * - * @constructor - * @param {IdGenerator} idGenerator - An id generator to generate id for code - * path segments. - * @param {Function} onLooped - A callback function to notify looping. */ -function CodePathState(idGenerator, onLooped) { - this.idGenerator = idGenerator; - this.notifyLooped = onLooped; - this.forkContext = ForkContext.newRoot(idGenerator); - this.choiceContext = null; - this.switchContext = null; - this.tryContext = null; - this.loopContext = null; - this.breakContext = null; - - this.currentSegments = []; - this.initialSegment = this.forkContext.head[0]; - - // returnedSegments and thrownSegments push elements into finalSegments also. - const final = this.finalSegments = []; - const returned = this.returnedForkContext = []; - const thrown = this.thrownForkContext = []; - - returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); - thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); -} +class CodePathState { -CodePathState.prototype = { - constructor: CodePathState, + /** + * @param {IdGenerator} idGenerator - An id generator to generate id for code + * path segments. + * @param {Function} onLooped - A callback function to notify looping. + */ + constructor(idGenerator, onLooped) { + this.idGenerator = idGenerator; + this.notifyLooped = onLooped; + this.forkContext = ForkContext.newRoot(idGenerator); + this.choiceContext = null; + this.switchContext = null; + this.tryContext = null; + this.loopContext = null; + this.breakContext = null; + + this.currentSegments = []; + this.initialSegment = this.forkContext.head[ 0 ]; + + // returnedSegments and thrownSegments push elements into finalSegments also. + const final = this.finalSegments = []; + const returned = this.returnedForkContext = []; + const thrown = this.thrownForkContext = []; + + returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); + thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); + } /** * The head segments. @@ -258,7 +257,7 @@ CodePathState.prototype = { */ get headSegments() { return this.forkContext.head; - }, + } /** * The parent forking context. @@ -269,7 +268,7 @@ CodePathState.prototype = { const current = this.forkContext; return current && current.upper; - }, + } /** * Creates and stacks new forking context. @@ -285,7 +284,7 @@ CodePathState.prototype = { ); return this.forkContext; - }, + } /** * Pops and merges the last forking context. @@ -298,7 +297,7 @@ CodePathState.prototype = { this.forkContext.replaceHead(lastContext.makeNext(0, -1)); return lastContext; - }, + } /** * Creates a new path. @@ -306,7 +305,7 @@ CodePathState.prototype = { */ forkPath() { this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); - }, + } /** * Creates a bypass path. @@ -316,7 +315,7 @@ CodePathState.prototype = { */ forkBypassPath() { this.forkContext.add(this.parentForkContext.head); - }, + } //-------------------------------------------------------------------------- // ConditionalExpression, LogicalExpression, IfStatement @@ -362,7 +361,7 @@ CodePathState.prototype = { falseForkContext: ForkContext.newEmpty(this.forkContext), processed: false }; - }, + } /** * Pops the last choice context and finalizes it. @@ -449,7 +448,7 @@ CodePathState.prototype = { forkContext.replaceHead(prevForkContext.makeNext(0, -1)); return context; - }, + } /** * Makes a code path segment of the right-hand operand of a logical @@ -494,7 +493,7 @@ CodePathState.prototype = { forkContext.replaceHead(forkContext.makeNext(-1, -1)); } - }, + } /** * Makes a code path segment of the `if` block. @@ -521,7 +520,7 @@ CodePathState.prototype = { forkContext.replaceHead( context.trueForkContext.makeNext(0, -1) ); - }, + } /** * Makes a code path segment of the `else` block. @@ -544,7 +543,7 @@ CodePathState.prototype = { forkContext.replaceHead( context.falseForkContext.makeNext(0, -1) ); - }, + } //-------------------------------------------------------------------------- // SwitchStatement @@ -570,7 +569,7 @@ CodePathState.prototype = { }; this.pushBreakContext(true, label); - }, + } /** * Pops the last context of SwitchStatement and finalizes it. @@ -649,7 +648,7 @@ CodePathState.prototype = { * This is a path after switch statement. */ this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - }, + } /** * Makes a code path segment for a `SwitchCase` node. @@ -696,7 +695,7 @@ CodePathState.prototype = { context.lastIsDefault = isDefault; context.countForks += 1; - }, + } //-------------------------------------------------------------------------- // TryStatement @@ -723,7 +722,7 @@ CodePathState.prototype = { lastOfTryIsReachable: false, lastOfCatchIsReachable: false }; - }, + } /** * Pops the last context of TryStatement and finalizes it. @@ -777,7 +776,7 @@ CodePathState.prototype = { if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { this.forkContext.makeUnreachable(); } - }, + } /** * Makes a code path segment for a `catch` block. @@ -802,7 +801,7 @@ CodePathState.prototype = { this.pushForkContext(); this.forkBypassPath(); this.forkContext.add(thrownSegments); - }, + } /** * Makes a code path segment for a `finally` block. @@ -863,7 +862,7 @@ CodePathState.prototype = { this.pushForkContext(true); this.forkContext.add(segments); - }, + } /** * Makes a code path segment from the first throwable node to the `catch` @@ -889,7 +888,7 @@ CodePathState.prototype = { context.thrownForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeNext(-1, -1)); - }, + } //-------------------------------------------------------------------------- // Loop Statements @@ -969,7 +968,7 @@ CodePathState.prototype = { default: throw new Error(`unknown type: "${type}"`); } - }, + } /** * Pops the last context of a loop statement and finalizes it. @@ -1039,7 +1038,7 @@ CodePathState.prototype = { } else { forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); } - }, + } /** * Makes a code path segment for the test part of a WhileStatement. @@ -1056,7 +1055,7 @@ CodePathState.prototype = { context.test = test; context.continueDestSegments = testSegments; forkContext.replaceHead(testSegments); - }, + } /** * Makes a code path segment for the body part of a WhileStatement. @@ -1078,7 +1077,7 @@ CodePathState.prototype = { context.brokenForkContext.addAll(choiceContext.falseForkContext); } forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); - }, + } /** * Makes a code path segment for the body part of a DoWhileStatement. @@ -1093,7 +1092,7 @@ CodePathState.prototype = { // Update state. context.entrySegments = bodySegments; forkContext.replaceHead(bodySegments); - }, + } /** * Makes a code path segment for the test part of a DoWhileStatement. @@ -1114,7 +1113,7 @@ CodePathState.prototype = { forkContext.replaceHead(testSegments); } - }, + } /** * Makes a code path segment for the test part of a ForStatement. @@ -1133,7 +1132,7 @@ CodePathState.prototype = { context.endOfInitSegments = endOfInitSegments; context.continueDestSegments = context.testSegments = testSegments; forkContext.replaceHead(testSegments); - }, + } /** * Makes a code path segment for the update part of a ForStatement. @@ -1160,7 +1159,7 @@ CodePathState.prototype = { context.continueDestSegments = context.updateSegments = updateSegments; forkContext.replaceHead(updateSegments); - }, + } /** * Makes a code path segment for the body part of a ForStatement. @@ -1211,7 +1210,7 @@ CodePathState.prototype = { } context.continueDestSegments = context.continueDestSegments || bodySegments; forkContext.replaceHead(bodySegments); - }, + } /** * Makes a code path segment for the left part of a ForInStatement and a @@ -1228,7 +1227,7 @@ CodePathState.prototype = { context.prevSegments = forkContext.head; context.leftSegments = context.continueDestSegments = leftSegments; forkContext.replaceHead(leftSegments); - }, + } /** * Makes a code path segment for the right part of a ForInStatement and a @@ -1247,7 +1246,7 @@ CodePathState.prototype = { // Update state. context.endOfLeftSegments = forkContext.head; forkContext.replaceHead(rightSegments); - }, + } /** * Makes a code path segment for the body part of a ForInStatement and a @@ -1269,7 +1268,7 @@ CodePathState.prototype = { // Update state. context.brokenForkContext.add(forkContext.head); forkContext.replaceHead(bodySegments); - }, + } //-------------------------------------------------------------------------- // Control Statements @@ -1291,7 +1290,7 @@ CodePathState.prototype = { brokenForkContext: ForkContext.newEmpty(this.forkContext) }; return this.breakContext; - }, + } /** * Removes the top item of the break context stack. @@ -1315,7 +1314,7 @@ CodePathState.prototype = { } return context; - }, + } /** * Makes a path for a `break` statement. @@ -1341,7 +1340,7 @@ CodePathState.prototype = { } forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - }, + } /** * Makes a path for a `continue` statement. @@ -1377,7 +1376,7 @@ CodePathState.prototype = { } } forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - }, + } /** * Makes a path for a `return` statement. @@ -1394,7 +1393,7 @@ CodePathState.prototype = { getReturnContext(this).returnedForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); } - }, + } /** * Makes a path for a `throw` statement. @@ -1411,7 +1410,7 @@ CodePathState.prototype = { getThrowContext(this).thrownForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); } - }, + } /** * Makes the final path. @@ -1424,6 +1423,6 @@ CodePathState.prototype = { this.returnedForkContext.add(segments); } } -}; +} module.exports = CodePathState; diff --git a/tools/eslint/lib/code-path-analysis/code-path.js b/tools/eslint/lib/code-path-analysis/code-path.js index 96363423c23ed5..6ef07b4a2d93b2 100644 --- a/tools/eslint/lib/code-path-analysis/code-path.js +++ b/tools/eslint/lib/code-path-analysis/code-path.js @@ -18,47 +18,56 @@ const IdGenerator = require("./id-generator"); /** * A code path. - * - * @constructor - * @param {string} id - An identifier. - * @param {CodePath|null} upper - The code path of the upper function scope. - * @param {Function} onLooped - A callback function to notify looping. */ -function CodePath(id, upper, onLooped) { +class CodePath { /** - * The identifier of this code path. - * Rules use it to store additional information of each rule. - * @type {string} + * @param {string} id - An identifier. + * @param {CodePath|null} upper - The code path of the upper function scope. + * @param {Function} onLooped - A callback function to notify looping. */ - this.id = id; + constructor(id, upper, onLooped) { - /** - * The code path of the upper function scope. - * @type {CodePath|null} - */ - this.upper = upper; + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; - /** - * The code paths of nested function scopes. - * @type {CodePath[]} - */ - this.childCodePaths = []; + /** + * The code path of the upper function scope. + * @type {CodePath|null} + */ + this.upper = upper; + + /** + * The code paths of nested function scopes. + * @type {CodePath[]} + */ + this.childCodePaths = []; - // Initializes internal state. - Object.defineProperty( - this, - "internal", - {value: new CodePathState(new IdGenerator(`${id}_`), onLooped)}); + // Initializes internal state. + Object.defineProperty( + this, + "internal", + { value: new CodePathState(new IdGenerator(`${id}_`), onLooped) }); - // Adds this into `childCodePaths` of `upper`. - if (upper) { - upper.childCodePaths.push(this); + // Adds this into `childCodePaths` of `upper`. + if (upper) { + upper.childCodePaths.push(this); + } } -} -CodePath.prototype = { - constructor: CodePath, + /** + * Gets the state of a given code path. + * + * @param {CodePath} codePath - A code path to get. + * @returns {CodePathState} The state of the code path. + */ + static getState(codePath) { + return codePath.internal; + } /** * The initial code path segment. @@ -66,7 +75,7 @@ CodePath.prototype = { */ get initialSegment() { return this.internal.initialSegment; - }, + } /** * Final code path segments. @@ -75,7 +84,7 @@ CodePath.prototype = { */ get finalSegments() { return this.internal.finalSegments; - }, + } /** * Final code path segments which is with `return` statements. @@ -85,7 +94,7 @@ CodePath.prototype = { */ get returnedSegments() { return this.internal.returnedForkContext; - }, + } /** * Final code path segments which is with `throw` statements. @@ -93,7 +102,7 @@ CodePath.prototype = { */ get thrownSegments() { return this.internal.thrownForkContext; - }, + } /** * Current code path segments. @@ -101,7 +110,7 @@ CodePath.prototype = { */ get currentSegments() { return this.internal.currentSegments; - }, + } /** * Traverses all segments in this code path. @@ -219,16 +228,6 @@ CodePath.prototype = { } } } -}; - -/** - * Gets the state of a given code path. - * - * @param {CodePath} codePath - A code path to get. - * @returns {CodePathState} The state of the code path. - */ -CodePath.getState = function getState(codePath) { - return codePath.internal; -}; +} module.exports = CodePath; diff --git a/tools/eslint/lib/code-path-analysis/debug-helpers.js b/tools/eslint/lib/code-path-analysis/debug-helpers.js index 5e311eb352b986..622bd6081fa546 100644 --- a/tools/eslint/lib/code-path-analysis/debug-helpers.js +++ b/tools/eslint/lib/code-path-analysis/debug-helpers.js @@ -108,7 +108,7 @@ module.exports = { } if (segment.internal.nodes.length > 0) { - text += segment.internal.nodes.map(function(node) { + text += segment.internal.nodes.map(node => { switch (node.type) { case "Identifier": return `${node.type} (${node.name})`; case "Literal": return `${node.type} (${node.value})`; @@ -116,7 +116,7 @@ module.exports = { } }).join("\\n"); } else if (segment.internal.exitNodes.length > 0) { - text += segment.internal.exitNodes.map(function(node) { + text += segment.internal.exitNodes.map(node => { switch (node.type) { case "Identifier": return `${node.type}:exit (${node.name})`; case "Literal": return `${node.type}:exit (${node.value})`; @@ -176,7 +176,7 @@ module.exports = { stack.push([nextSegment, 0]); } - codePath.returnedSegments.forEach(function(finalSegment) { + codePath.returnedSegments.forEach(finalSegment => { if (lastId === finalSegment.id) { text += "->final"; } else { @@ -185,7 +185,7 @@ module.exports = { lastId = null; }); - codePath.thrownSegments.forEach(function(finalSegment) { + codePath.thrownSegments.forEach(finalSegment => { if (lastId === finalSegment.id) { text += "->thrown"; } else { diff --git a/tools/eslint/lib/code-path-analysis/fork-context.js b/tools/eslint/lib/code-path-analysis/fork-context.js index 6996af1dcc1f71..7423c13199b3ff 100644 --- a/tools/eslint/lib/code-path-analysis/fork-context.js +++ b/tools/eslint/lib/code-path-analysis/fork-context.js @@ -99,21 +99,20 @@ function mergeExtraSegments(context, segments) { /** * A class to manage forking. - * - * @constructor - * @param {IdGenerator} idGenerator - An identifier generator for segments. - * @param {ForkContext|null} upper - An upper fork context. - * @param {number} count - A number of parallel segments. */ -function ForkContext(idGenerator, upper, count) { - this.idGenerator = idGenerator; - this.upper = upper; - this.count = count; - this.segmentsList = []; -} +class ForkContext { -ForkContext.prototype = { - constructor: ForkContext, + /** + * @param {IdGenerator} idGenerator - An identifier generator for segments. + * @param {ForkContext|null} upper - An upper fork context. + * @param {number} count - A number of parallel segments. + */ + constructor(idGenerator, upper, count) { + this.idGenerator = idGenerator; + this.upper = upper; + this.count = count; + this.segmentsList = []; + } /** * The head segments. @@ -123,7 +122,7 @@ ForkContext.prototype = { const list = this.segmentsList; return list.length === 0 ? [] : list[list.length - 1]; - }, + } /** * A flag which shows empty. @@ -131,7 +130,7 @@ ForkContext.prototype = { */ get empty() { return this.segmentsList.length === 0; - }, + } /** * A flag which shows reachable. @@ -141,7 +140,7 @@ ForkContext.prototype = { const segments = this.head; return segments.length > 0 && segments.some(isReachable); - }, + } /** * Creates new segments from this context. @@ -152,7 +151,7 @@ ForkContext.prototype = { */ makeNext(begin, end) { return makeSegments(this, begin, end, CodePathSegment.newNext); - }, + } /** * Creates new segments from this context. @@ -164,7 +163,7 @@ ForkContext.prototype = { */ makeUnreachable(begin, end) { return makeSegments(this, begin, end, CodePathSegment.newUnreachable); - }, + } /** * Creates new segments from this context. @@ -177,7 +176,7 @@ ForkContext.prototype = { */ makeDisconnected(begin, end) { return makeSegments(this, begin, end, CodePathSegment.newDisconnected); - }, + } /** * Adds segments into this context. @@ -190,7 +189,7 @@ ForkContext.prototype = { assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); this.segmentsList.push(mergeExtraSegments(this, segments)); - }, + } /** * Replaces the head segments with given segments. @@ -203,7 +202,7 @@ ForkContext.prototype = { assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); this.segmentsList.splice(-1, 1, mergeExtraSegments(this, segments)); - }, + } /** * Adds all segments of a given fork context into this context. @@ -219,7 +218,7 @@ ForkContext.prototype = { for (let i = 0; i < source.length; ++i) { this.segmentsList.push(source[i]); } - }, + } /** * Clears all secments in this context. @@ -229,34 +228,34 @@ ForkContext.prototype = { clear() { this.segmentsList = []; } -}; -/** - * Creates the root fork context. - * - * @param {IdGenerator} idGenerator - An identifier generator for segments. - * @returns {ForkContext} New fork context. - */ -ForkContext.newRoot = function(idGenerator) { - const context = new ForkContext(idGenerator, null, 1); + /** + * Creates the root fork context. + * + * @param {IdGenerator} idGenerator - An identifier generator for segments. + * @returns {ForkContext} New fork context. + */ + static newRoot(idGenerator) { + const context = new ForkContext(idGenerator, null, 1); - context.add([CodePathSegment.newRoot(idGenerator.next())]); + context.add([CodePathSegment.newRoot(idGenerator.next())]); - return context; -}; + return context; + } -/** - * Creates an empty fork context preceded by a given context. - * - * @param {ForkContext} parentContext - The parent fork context. - * @param {boolean} forkLeavingPath - A flag which shows inside of `finally` block. - * @returns {ForkContext} New fork context. - */ -ForkContext.newEmpty = function(parentContext, forkLeavingPath) { - return new ForkContext( - parentContext.idGenerator, - parentContext, - (forkLeavingPath ? 2 : 1) * parentContext.count); -}; + /** + * Creates an empty fork context preceded by a given context. + * + * @param {ForkContext} parentContext - The parent fork context. + * @param {boolean} forkLeavingPath - A flag which shows inside of `finally` block. + * @returns {ForkContext} New fork context. + */ + static newEmpty(parentContext, forkLeavingPath) { + return new ForkContext( + parentContext.idGenerator, + parentContext, + (forkLeavingPath ? 2 : 1) * parentContext.count); + } +} module.exports = ForkContext; diff --git a/tools/eslint/lib/code-path-analysis/id-generator.js b/tools/eslint/lib/code-path-analysis/id-generator.js index f33858cacd4071..062058ddc12639 100644 --- a/tools/eslint/lib/code-path-analysis/id-generator.js +++ b/tools/eslint/lib/code-path-analysis/id-generator.js @@ -15,29 +15,32 @@ /** * A generator for unique ids. - * - * @constructor - * @param {string} prefix - Optional. A prefix of generated ids. - */ -function IdGenerator(prefix) { - this.prefix = String(prefix); - this.n = 0; -} - -/** - * Generates id. - * - * @returns {string} A generated id. */ -IdGenerator.prototype.next = function() { - this.n = 1 + this.n | 0; +class IdGenerator { - /* istanbul ignore if */ - if (this.n < 0) { - this.n = 1; + /** + * @param {string} prefix - Optional. A prefix of generated ids. + */ + constructor(prefix) { + this.prefix = String(prefix); + this.n = 0; } - return this.prefix + this.n; -}; + /** + * Generates id. + * + * @returns {string} A generated id. + */ + next() { + this.n = 1 + this.n | 0; + + /* istanbul ignore if */ + if (this.n < 0) { + this.n = 1; + } + + return this.prefix + this.n; + } +} module.exports = IdGenerator; diff --git a/tools/eslint/lib/config.js b/tools/eslint/lib/config.js index 9ff203c16d9e45..9c56e7ad988e28 100644 --- a/tools/eslint/lib/config.js +++ b/tools/eslint/lib/config.js @@ -179,155 +179,159 @@ function getLocalConfig(thisConfig, directory) { //------------------------------------------------------------------------------ /** - * Config - * @constructor - * @class Config - * @param {Object} options Options to be passed in + * Configuration class */ -function Config(options) { - options = options || {}; +class Config { - this.ignore = options.ignore; - this.ignorePath = options.ignorePath; - this.cache = {}; - this.parser = options.parser; - this.parserOptions = options.parserOptions || {}; + /** + * Config options + * @param {Object} options Options to be passed in + */ + constructor(options) { + options = options || {}; - this.baseConfig = options.baseConfig ? loadConfig(options.baseConfig) : { rules: {} }; + this.ignore = options.ignore; + this.ignorePath = options.ignorePath; + this.cache = {}; + this.parser = options.parser; + this.parserOptions = options.parserOptions || {}; - this.useEslintrc = (options.useEslintrc !== false); + this.baseConfig = options.baseConfig ? loadConfig(options.baseConfig) : { rules: {} }; - this.env = (options.envs || []).reduce(function(envs, name) { - envs[name] = true; - return envs; - }, {}); + this.useEslintrc = (options.useEslintrc !== false); - /* - * Handle declared globals. - * For global variable foo, handle "foo:false" and "foo:true" to set - * whether global is writable. - * If user declares "foo", convert to "foo:false". - */ - this.globals = (options.globals || []).reduce(function(globals, def) { - const parts = def.split(":"); + this.env = (options.envs || []).reduce((envs, name) => { + envs[ name ] = true; + return envs; + }, {}); - globals[parts[0]] = (parts.length > 1 && parts[1] === "true"); + /* + * Handle declared globals. + * For global variable foo, handle "foo:false" and "foo:true" to set + * whether global is writable. + * If user declares "foo", convert to "foo:false". + */ + this.globals = (options.globals || []).reduce((globals, def) => { + const parts = def.split(":"); - return globals; - }, {}); + globals[parts[0]] = (parts.length > 1 && parts[1] === "true"); - const useConfig = options.configFile; + return globals; + }, {}); - this.options = options; + const useConfig = options.configFile; - if (useConfig) { - debug(`Using command line config ${useConfig}`); - if (isResolvable(useConfig) || isResolvable(`eslint-config-${useConfig}`) || useConfig.charAt(0) === "@") { - this.useSpecificConfig = loadConfig(useConfig); - } else { - this.useSpecificConfig = loadConfig(path.resolve(this.options.cwd, useConfig)); + this.options = options; + + if (useConfig) { + debug(`Using command line config ${useConfig}`); + if (isResolvable(useConfig) || isResolvable(`eslint-config-${useConfig}`) || useConfig.charAt(0) === "@") { + this.useSpecificConfig = loadConfig(useConfig); + } else { + this.useSpecificConfig = loadConfig(path.resolve(this.options.cwd, useConfig)); + } } } -} -/** - * Build a config object merging the base config (conf/eslint.json), the - * environments config (conf/environments.js) and eventually the user config. - * @param {string} filePath a file in whose directory we start looking for a local config - * @returns {Object} config object - */ -Config.prototype.getConfig = function(filePath) { - const directory = filePath ? path.dirname(filePath) : this.options.cwd; - let config, - userConfig; + /** + * Build a config object merging the base config (conf/eslint.json), the + * environments config (conf/environments.js) and eventually the user config. + * @param {string} filePath a file in whose directory we start looking for a local config + * @returns {Object} config object + */ + getConfig(filePath) { + const directory = filePath ? path.dirname(filePath) : this.options.cwd; + let config, + userConfig; - debug(`Constructing config for ${filePath ? filePath : "text"}`); + debug(`Constructing config for ${filePath ? filePath : "text"}`); - config = this.cache[directory]; + config = this.cache[directory]; - if (config) { - debug("Using config from cache"); - return config; - } + if (config) { + debug("Using config from cache"); + return config; + } - // Step 1: Determine user-specified config from .eslintrc.* and package.json files - if (this.useEslintrc) { - debug("Using .eslintrc and package.json files"); - userConfig = getLocalConfig(this, directory); - } else { - debug("Not using .eslintrc or package.json files"); - userConfig = {}; - } + // Step 1: Determine user-specified config from .eslintrc.* and package.json files + if (this.useEslintrc) { + debug("Using .eslintrc and package.json files"); + userConfig = getLocalConfig(this, directory); + } else { + debug("Not using .eslintrc or package.json files"); + userConfig = {}; + } - // Step 2: Create a copy of the baseConfig - config = ConfigOps.merge({}, this.baseConfig); + // Step 2: Create a copy of the baseConfig + config = ConfigOps.merge({}, this.baseConfig); - // Step 3: Merge in the user-specified configuration from .eslintrc and package.json - config = ConfigOps.merge(config, userConfig); + // Step 3: Merge in the user-specified configuration from .eslintrc and package.json + config = ConfigOps.merge(config, userConfig); - // Step 4: Merge in command line config file - if (this.useSpecificConfig) { - debug("Merging command line config file"); + // Step 4: Merge in command line config file + if (this.useSpecificConfig) { + debug("Merging command line config file"); - config = ConfigOps.merge(config, this.useSpecificConfig); - } + config = ConfigOps.merge(config, this.useSpecificConfig); + } - // Step 5: Merge in command line environments - debug("Merging command line environment settings"); - config = ConfigOps.merge(config, { env: this.env }); + // Step 5: Merge in command line environments + debug("Merging command line environment settings"); + config = ConfigOps.merge(config, { env: this.env }); - // Step 6: Merge in command line rules - if (this.options.rules) { - debug("Merging command line rules"); - config = ConfigOps.merge(config, { rules: this.options.rules }); - } + // Step 6: Merge in command line rules + if (this.options.rules) { + debug("Merging command line rules"); + config = ConfigOps.merge(config, { rules: this.options.rules }); + } - // Step 7: Merge in command line globals - config = ConfigOps.merge(config, { globals: this.globals }); + // Step 7: Merge in command line globals + config = ConfigOps.merge(config, { globals: this.globals }); - // Only override parser if it is passed explicitly through the command line or if it's not - // defined yet (because the final object will at least have the parser key) - if (this.parser || !config.parser) { - config = ConfigOps.merge(config, { - parser: this.parser - }); - } + // Only override parser if it is passed explicitly through the command line or if it's not + // defined yet (because the final object will at least have the parser key) + if (this.parser || !config.parser) { + config = ConfigOps.merge(config, { + parser: this.parser + }); + } - if (this.parserOptions) { - config = ConfigOps.merge(config, { - parserOptions: this.parserOptions - }); - } + if (this.parserOptions) { + config = ConfigOps.merge(config, { + parserOptions: this.parserOptions + }); + } - // Step 8: Merge in command line plugins - if (this.options.plugins) { - debug("Merging command line plugins"); - Plugins.loadAll(this.options.plugins); - config = ConfigOps.merge(config, { plugins: this.options.plugins }); - } + // Step 8: Merge in command line plugins + if (this.options.plugins) { + debug("Merging command line plugins"); + Plugins.loadAll(this.options.plugins); + config = ConfigOps.merge(config, { plugins: this.options.plugins }); + } - // Step 9: Apply environments to the config if present - if (config.env) { - config = ConfigOps.applyEnvironments(config); - } + // Step 9: Apply environments to the config if present + if (config.env) { + config = ConfigOps.applyEnvironments(config); + } - this.cache[directory] = config; + this.cache[directory] = config; - return config; -}; + return config; + } -/** - * Find local config files from directory and parent directories. - * @param {string} directory The directory to start searching from. - * @returns {string[]} The paths of local config files found. - */ -Config.prototype.findLocalConfigFiles = function(directory) { + /** + * Find local config files from directory and parent directories. + * @param {string} directory The directory to start searching from. + * @returns {string[]} The paths of local config files found. + */ + findLocalConfigFiles(directory) { - if (!this.localConfigFinder) { - this.localConfigFinder = new FileFinder(ConfigFile.CONFIG_FILES, this.options.cwd); - } + if (!this.localConfigFinder) { + this.localConfigFinder = new FileFinder(ConfigFile.CONFIG_FILES, this.options.cwd); + } - return this.localConfigFinder.findAllInDirectoryAndParents(directory); -}; + return this.localConfigFinder.findAllInDirectoryAndParents(directory); + } +} module.exports = Config; diff --git a/tools/eslint/lib/config/autoconfig.js b/tools/eslint/lib/config/autoconfig.js index dd25bcd49191bc..23fdbe69803afc 100644 --- a/tools/eslint/lib/config/autoconfig.js +++ b/tools/eslint/lib/config/autoconfig.js @@ -49,14 +49,12 @@ const MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only * @returns {Object} registryItems for each rule in provided rulesConfig */ function makeRegistryItems(rulesConfig) { - return Object.keys(rulesConfig).reduce(function(accumulator, ruleId) { - accumulator[ruleId] = rulesConfig[ruleId].map(function(config) { - return { - config, - specificity: config.length || 1, - errorCount: void 0 - }; - }); + return Object.keys(rulesConfig).reduce((accumulator, ruleId) => { + accumulator[ruleId] = rulesConfig[ruleId].map(config => ({ + config, + specificity: config.length || 1, + errorCount: void 0 + })); return accumulator; }, {}); } @@ -173,10 +171,8 @@ Registry.prototype = { newRegistry = new Registry(); newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(function(ruleId) { - const errorFreeItems = newRegistry.rules[ruleId].filter(function(registryItem) { - return (registryItem.errorCount === 0); - }); + ruleIds.forEach(ruleId => { + const errorFreeItems = newRegistry.rules[ruleId].filter(registryItem => (registryItem.errorCount === 0)); if (errorFreeItems.length > 0) { newRegistry.rules[ruleId] = errorFreeItems; @@ -198,10 +194,8 @@ Registry.prototype = { newRegistry = new Registry(); newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(function(ruleId) { - newRegistry.rules[ruleId] = newRegistry.rules[ruleId].filter(function(registryItem) { - return (typeof registryItem.errorCount !== "undefined"); - }); + ruleIds.forEach(ruleId => { + newRegistry.rules[ruleId] = newRegistry.rules[ruleId].filter(registryItem => (typeof registryItem.errorCount !== "undefined")); }); return newRegistry; @@ -218,15 +212,13 @@ Registry.prototype = { const ruleIds = Object.keys(this.rules), failingRegistry = new Registry(); - ruleIds.forEach(function(ruleId) { - const failingConfigs = this.rules[ruleId].filter(function(registryItem) { - return (registryItem.errorCount > 0); - }); + ruleIds.forEach(ruleId => { + const failingConfigs = this.rules[ruleId].filter(registryItem => (registryItem.errorCount > 0)); if (failingConfigs && failingConfigs.length === this.rules[ruleId].length) { failingRegistry.rules[ruleId] = failingConfigs; } - }.bind(this)); + }); return failingRegistry; }, @@ -239,13 +231,13 @@ Registry.prototype = { */ createConfig() { const ruleIds = Object.keys(this.rules), - config = {rules: {}}; + config = { rules: {} }; - ruleIds.forEach(function(ruleId) { + ruleIds.forEach(ruleId => { if (this.rules[ruleId].length === 1) { config.rules[ruleId] = this.rules[ruleId][0].config; } - }.bind(this)); + }); return config; }, @@ -261,11 +253,9 @@ Registry.prototype = { newRegistry = new Registry(); newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(function(ruleId) { - newRegistry.rules[ruleId] = this.rules[ruleId].filter(function(registryItem) { - return (registryItem.specificity === specificity); - }); - }.bind(this)); + ruleIds.forEach(ruleId => { + newRegistry.rules[ruleId] = this.rules[ruleId].filter(registryItem => (registryItem.specificity === specificity)); + }); return newRegistry; }, @@ -294,16 +284,16 @@ Registry.prototype = { const filenames = Object.keys(sourceCodes); const totalFilesLinting = filenames.length * ruleSets.length; - filenames.forEach(function(filename) { + filenames.forEach(filename => { debug(`Linting file: ${filename}`); ruleSetIdx = 0; - ruleSets.forEach(function(ruleSet) { - const lintConfig = Object.assign({}, config, {rules: ruleSet}); + ruleSets.forEach(ruleSet => { + const lintConfig = Object.assign({}, config, { rules: ruleSet }); const lintResults = eslint.verify(sourceCodes[filename], lintConfig); - lintResults.forEach(function(result) { + lintResults.forEach(result => { // It is possible that the error is from a configuration comment // in a linted file, in which case there may not be a config @@ -342,11 +332,9 @@ function extendFromRecommended(config) { ConfigOps.normalizeToStrings(newConfig); - const recRules = Object.keys(recConfig.rules).filter(function(ruleId) { - return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]); - }); + const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId])); - recRules.forEach(function(ruleId) { + recRules.forEach(ruleId => { if (lodash.isEqual(recConfig.rules[ruleId], newConfig.rules[ruleId])) { delete newConfig.rules[ruleId]; } diff --git a/tools/eslint/lib/config/config-file.js b/tools/eslint/lib/config/config-file.js index c11a55fad8413d..90015097a3db97 100644 --- a/tools/eslint/lib/config/config-file.js +++ b/tools/eslint/lib/config/config-file.js @@ -235,7 +235,7 @@ function loadConfigFile(file) { function writeJSONConfigFile(config, filePath) { debug(`Writing JSON config file: ${filePath}`); - const content = stringify(config, {cmp: sortByKey, space: 4}); + const content = stringify(config, { cmp: sortByKey, space: 4 }); fs.writeFileSync(filePath, content, "utf8"); } @@ -253,7 +253,7 @@ function writeYAMLConfigFile(config, filePath) { // lazy load YAML to improve performance when not used const yaml = require("js-yaml"); - const content = yaml.safeDump(config, {sortKeys: true}); + const content = yaml.safeDump(config, { sortKeys: true }); fs.writeFileSync(filePath, content, "utf8"); } @@ -268,7 +268,7 @@ function writeYAMLConfigFile(config, filePath) { function writeJSConfigFile(config, filePath) { debug(`Writing JS config file: ${filePath}`); - const content = `module.exports = ${stringify(config, {cmp: sortByKey, space: 4})};`; + const content = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`; fs.writeFileSync(filePath, content, "utf8"); } @@ -359,7 +359,7 @@ function applyExtends(config, filePath, relativeTo) { } // Make the last element in an array take the highest precedence - config = configExtends.reduceRight(function(previousValue, parentPath) { + config = configExtends.reduceRight((previousValue, parentPath) => { if (parentPath === "eslint:recommended") { @@ -430,7 +430,7 @@ function normalizePackageName(name, prefix) { * it's a scoped package * package name is "eslint-config", or just a username */ - const scopedPackageShortcutRegex = new RegExp(`^(@[^\/]+)(?:\/(?:${prefix})?)?$`), + const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`), scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`); if (scopedPackageShortcutRegex.test(name)) { @@ -441,7 +441,7 @@ function normalizePackageName(name, prefix) { * for scoped packages, insert the eslint-config after the first / unless * the path is already @scope/eslint or @scope/eslint-config-xxx */ - name = name.replace(/^@([^\/]+)\/(.*)$/, `@$1/${prefix}-$2`); + name = name.replace(/^@([^/]+)\/(.*)$/, `@$1/${prefix}-$2`); } } else if (name.indexOf(`${prefix}-`) !== 0) { name = `${prefix}-${name}`; diff --git a/tools/eslint/lib/config/config-initializer.js b/tools/eslint/lib/config/config-initializer.js index e3aef07baef388..502a73bd6c3ed1 100644 --- a/tools/eslint/lib/config/config-initializer.js +++ b/tools/eslint/lib/config/config-initializer.js @@ -44,10 +44,14 @@ function writeFile(config, format) { extname = ".json"; } + const installedESLint = config.installedESLint; + + delete config.installedESLint; + ConfigFile.write(config, `./.eslintrc${extname}`); log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`); - if (config.installedESLint) { + if (installedESLint) { log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy."); } } @@ -62,9 +66,7 @@ function installModules(config) { // Create a list of modules which should be installed based on config if (config.plugins) { - modules = modules.concat(config.plugins.map(function(name) { - return `eslint-plugin-${name}`; - })); + modules = modules.concat(config.plugins.map(name => `eslint-plugin-${name}`)); } if (config.extends && config.extends.indexOf("eslint:") === -1) { modules.push(`eslint-config-${config.extends}`); @@ -81,7 +83,7 @@ function installModules(config) { const installStatus = npmUtil.checkDevDeps(modules); // Install packages which aren't already installed - const modulesToInstall = Object.keys(installStatus).filter(function(module) { + const modulesToInstall = Object.keys(installStatus).filter(module => { const notInstalled = installStatus[module] === false; if (module === "eslint" && notInstalled) { @@ -128,7 +130,7 @@ function configureRules(answers, config) { const patterns = answers.patterns.split(/[\s]+/); try { - sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, function(total) { + sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => { bar.tick((BAR_SOURCE_CODE_TOTAL / total)); }); } catch (e) { @@ -147,20 +149,18 @@ function configureRules(answers, config) { registry.populateFromCoreRules(); // Lint all files with each rule config in the registry - registry = registry.lintSourceCode(sourceCodes, newConfig, function(total) { + registry = registry.lintSourceCode(sourceCodes, newConfig, total => { bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning }); - debug(`\nRegistry: ${util.inspect(registry.rules, {depth: null})}`); + debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`); // Create a list of recommended rules, because we don't want to disable them - const recRules = Object.keys(recConfig.rules).filter(function(ruleId) { - return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]); - }); + const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId])); // Find and disable rules which had no error-free configuration const failingRegistry = registry.getFailingRulesRegistry(); - Object.keys(failingRegistry.rules).forEach(function(ruleId) { + Object.keys(failingRegistry.rules).forEach(ruleId => { // If the rule is recommended, set it to error, otherwise disable it disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0; @@ -194,9 +194,7 @@ function configureRules(answers, config) { // Log out some stats to let the user know what happened const finalRuleIds = Object.keys(newConfig.rules); const totalRules = finalRuleIds.length; - const enabledRules = finalRuleIds.filter(function(ruleId) { - return (newConfig.rules[ruleId] !== 0); - }).length; + const enabledRules = finalRuleIds.filter(ruleId => (newConfig.rules[ruleId] !== 0)).length; const resultMessage = [ `\nEnabled ${enabledRules} out of ${totalRules}`, `rules based on ${fileQty}`, @@ -215,7 +213,7 @@ function configureRules(answers, config) { * @returns {Object} config object */ function processAnswers(answers) { - let config = {rules: {}, env: {}}; + let config = { rules: {}, env: {} }; if (answers.es6) { config.env.es6 = true; @@ -227,7 +225,7 @@ function processAnswers(answers) { if (answers.commonjs) { config.env.commonjs = true; } - answers.env.forEach(function(env) { + answers.env.forEach(env => { config.env[env] = true; }); if (answers.jsx) { @@ -266,9 +264,10 @@ function processAnswers(answers) { */ function getConfigForStyleGuide(guide) { const guides = { - google: {extends: "google"}, - airbnb: {extends: "airbnb", plugins: ["react", "jsx-a11y", "import"]}, - standard: {extends: "standard", plugins: ["standard", "promise"]} + google: { extends: "google" }, + airbnb: { extends: "airbnb", plugins: ["react", "jsx-a11y", "import"] }, + "airbnb-base": { extends: "airbnb-base", plugins: ["import"] }, + standard: { extends: "standard", plugins: ["standard", "promise"] } }; if (!guides[guide]) { @@ -296,21 +295,30 @@ function promptUser(callback) { message: "How would you like to configure ESLint?", default: "prompt", choices: [ - {name: "Answer questions about your style", value: "prompt"}, - {name: "Use a popular style guide", value: "guide"}, - {name: "Inspect your JavaScript file(s)", value: "auto"} + { name: "Answer questions about your style", value: "prompt" }, + { name: "Use a popular style guide", value: "guide" }, + { name: "Inspect your JavaScript file(s)", value: "auto" } ] }, { type: "list", name: "styleguide", message: "Which style guide do you want to follow?", - choices: [{name: "Google", value: "google"}, {name: "Airbnb", value: "airbnb"}, {name: "Standard", value: "standard"}], + choices: [{ name: "Google", value: "google" }, { name: "Airbnb", value: "airbnb" }, { name: "Standard", value: "standard" }], when(answers) { answers.packageJsonExists = npmUtil.checkPackageJson(); return answers.source === "guide" && answers.packageJsonExists; } }, + { + type: "confirm", + name: "airbnbReact", + message: "Do you use React?", + default: false, + when(answers) { + return answers.styleguide === "airbnb"; + }, + }, { type: "input", name: "patterns", @@ -335,7 +343,7 @@ function promptUser(callback) { return ((answers.source === "guide" && answers.packageJsonExists) || answers.source === "auto"); } } - ], function(earlyAnswers) { + ], earlyAnswers => { // early exit if you are using a style guide if (earlyAnswers.source === "guide") { @@ -343,7 +351,9 @@ function promptUser(callback) { log.info("A package.json is necessary to install plugins such as style guides. Run `npm init` to create a package.json file and try again."); return; } - + if (earlyAnswers.styleguide === "airbnb" && !earlyAnswers.airbnbReact) { + earlyAnswers.styleguide = "airbnb-base"; + } try { config = getConfigForStyleGuide(earlyAnswers.styleguide); writeFile(config, earlyAnswers.format); @@ -376,7 +386,7 @@ function promptUser(callback) { name: "env", message: "Where will your code run?", default: ["browser"], - choices: [{name: "Browser", value: "browser"}, {name: "Node", value: "node"}] + choices: [{ name: "Browser", value: "browser" }, { name: "Node", value: "node" }] }, { type: "confirm", @@ -384,9 +394,7 @@ function promptUser(callback) { message: "Do you use CommonJS?", default: false, when(answers) { - return answers.env.some(function(env) { - return env === "browser"; - }); + return answers.env.some(env => env === "browser"); } }, { @@ -398,13 +406,13 @@ function promptUser(callback) { { type: "confirm", name: "react", - message: "Do you use React", + message: "Do you use React?", default: false, when(answers) { return answers.jsx; } } - ], function(secondAnswers) { + ], secondAnswers => { // early exit if you are using automatic style generation if (earlyAnswers.source === "auto") { @@ -428,21 +436,21 @@ function promptUser(callback) { name: "indent", message: "What style of indentation do you use?", default: "tab", - choices: [{name: "Tabs", value: "tab"}, {name: "Spaces", value: 4}] + choices: [{ name: "Tabs", value: "tab" }, { name: "Spaces", value: 4 }] }, { type: "list", name: "quotes", message: "What quotes do you use for strings?", default: "double", - choices: [{name: "Double", value: "double"}, {name: "Single", value: "single"}] + choices: [{ name: "Double", value: "double" }, { name: "Single", value: "single" }] }, { type: "list", name: "linebreak", message: "What line endings do you use?", default: "unix", - choices: [{name: "Unix", value: "unix"}, {name: "Windows", value: "windows"}] + choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }] }, { type: "confirm", @@ -457,7 +465,7 @@ function promptUser(callback) { default: "JavaScript", choices: ["JavaScript", "YAML", "JSON"] } - ], function(answers) { + ], answers => { try { const totalAnswers = Object.assign({}, earlyAnswers, secondAnswers, answers); @@ -465,10 +473,8 @@ function promptUser(callback) { installModules(config); writeFile(config, answers.format); } catch (err) { - callback(err); - return; + callback(err); // eslint-disable-line callback-return } - return; }); }); }); diff --git a/tools/eslint/lib/config/config-ops.js b/tools/eslint/lib/config/config-ops.js index 42b0fe81b90615..52dea1a106df79 100644 --- a/tools/eslint/lib/config/config-ops.js +++ b/tools/eslint/lib/config/config-ops.js @@ -18,7 +18,7 @@ const debug = require("debug")("eslint:config-ops"); //------------------------------------------------------------------------------ const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], - RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce(function(map, value, index) { + RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { map[value] = index; return map; }, {}), @@ -57,9 +57,7 @@ module.exports = { envConfig.env = env; - Object.keys(env).filter(function(name) { - return env[name]; - }).forEach(function(name) { + Object.keys(env).filter(name => env[name]).forEach(name => { const environment = Environments.get(name); if (environment) { @@ -149,7 +147,7 @@ module.exports = { if (typeof src !== "object" && !Array.isArray(src)) { src = [src]; } - Object.keys(src).forEach(function(e, i) { + Object.keys(src).forEach((e, i) => { e = src[i]; if (typeof dst[i] === "undefined") { dst[i] = e; @@ -171,11 +169,11 @@ module.exports = { }); } else { if (target && typeof target === "object") { - Object.keys(target).forEach(function(key) { + Object.keys(target).forEach(key => { dst[key] = target[key]; }); } - Object.keys(src).forEach(function(key) { + Object.keys(src).forEach(key => { if (Array.isArray(src[key]) || Array.isArray(target[key])) { dst[key] = deepmerge(target[key], src[key], key === "plugins", isRule); } else if (typeof src[key] !== "object" || !src[key] || key === "exported" || key === "astGlobals") { @@ -199,7 +197,7 @@ module.exports = { normalize(config) { if (config.rules) { - Object.keys(config.rules).forEach(function(ruleId) { + Object.keys(config.rules).forEach(ruleId => { const ruleConfig = config.rules[ruleId]; if (typeof ruleConfig === "string") { @@ -221,7 +219,7 @@ module.exports = { normalizeToStrings(config) { if (config.rules) { - Object.keys(config.rules).forEach(function(ruleId) { + Object.keys(config.rules).forEach(ruleId => { const ruleConfig = config.rules[ruleId]; if (typeof ruleConfig === "number") { @@ -269,8 +267,6 @@ module.exports = { * @returns {boolean} `true` if the configuration has valid severity. */ isEverySeverityValid(config) { - return Object.keys(config).every(function(ruleId) { - return this.isValidSeverity(config[ruleId]); - }, this); + return Object.keys(config).every(ruleId => this.isValidSeverity(config[ruleId])); } }; diff --git a/tools/eslint/lib/config/config-rule.js b/tools/eslint/lib/config/config-rule.js index eb5c23fe8c840a..d495198aed454b 100644 --- a/tools/eslint/lib/config/config-rule.js +++ b/tools/eslint/lib/config/config-rule.js @@ -23,7 +23,7 @@ const rules = require("../rules"), * @returns {Array[]} An array of arrays. */ function explodeArray(xs) { - return xs.reduce(function(accumulator, x) { + return xs.reduce((accumulator, x) => { accumulator.push([x]); return accumulator; }, []); @@ -49,8 +49,8 @@ function combineArrays(arr1, arr2) { if (arr2.length === 0) { return explodeArray(arr1); } - arr1.forEach(function(x1) { - arr2.forEach(function(x2) { + arr1.forEach(x1 => { + arr2.forEach(x2 => { res.push([].concat(x1, x2)); }); }); @@ -78,16 +78,14 @@ function combineArrays(arr1, arr2) { * @returns {Array[]} Array of arrays of objects grouped by property */ function groupByProperty(objects) { - const groupedObj = objects.reduce(function(accumulator, obj) { + const groupedObj = objects.reduce((accumulator, obj) => { const prop = Object.keys(obj)[0]; accumulator[prop] = accumulator[prop] ? accumulator[prop].concat(obj) : [obj]; return accumulator; }, {}); - return Object.keys(groupedObj).map(function(prop) { - return groupedObj[prop]; - }); + return Object.keys(groupedObj).map(prop => groupedObj[prop]); } @@ -152,16 +150,16 @@ function combinePropertyObjects(objArr1, objArr2) { if (objArr2.length === 0) { return objArr1; } - objArr1.forEach(function(obj1) { - objArr2.forEach(function(obj2) { + objArr1.forEach(obj1 => { + objArr2.forEach(obj2 => { const combinedObj = {}; const obj1Props = Object.keys(obj1); const obj2Props = Object.keys(obj2); - obj1Props.forEach(function(prop1) { + obj1Props.forEach(prop1 => { combinedObj[prop1] = obj1[prop1]; }); - obj2Props.forEach(function(prop2) { + obj2Props.forEach(prop2 => { combinedObj[prop2] = obj2[prop2]; }); res.push(combinedObj); @@ -205,7 +203,7 @@ RuleConfigSet.prototype = { addErrorSeverity(severity) { severity = severity || 2; - this.ruleConfigs = this.ruleConfigs.map(function(config) { + this.ruleConfigs = this.ruleConfigs.map(config => { config.unshift(severity); return config; }); @@ -241,9 +239,7 @@ RuleConfigSet.prototype = { }, combine() { - this.objectConfigs = groupByProperty(this.objectConfigs).reduce(function(accumulator, objArr) { - return combinePropertyObjects(accumulator, objArr); - }, []); + this.objectConfigs = groupByProperty(this.objectConfigs).reduce((accumulator, objArr) => combinePropertyObjects(accumulator, objArr), []); } }; @@ -251,7 +247,7 @@ RuleConfigSet.prototype = { * The object schema could have multiple independent properties. * If any contain enums or booleans, they can be added and then combined */ - Object.keys(obj.properties).forEach(function(prop) { + Object.keys(obj.properties).forEach(prop => { if (obj.properties[prop].enum) { objectConfigSet.add(prop, obj.properties[prop].enum); } @@ -276,7 +272,7 @@ function generateConfigsFromSchema(schema) { const configSet = new RuleConfigSet(); if (Array.isArray(schema)) { - schema.forEach(function(opt) { + schema.forEach(opt => { if (opt.enum) { configSet.addEnums(opt.enum); } @@ -302,7 +298,7 @@ function generateConfigsFromSchema(schema) { function createCoreRuleConfigs() { const ruleList = loadRules(); - return Object.keys(ruleList).reduce(function(accumulator, id) { + return Object.keys(ruleList).reduce((accumulator, id) => { const rule = rules.get(id); const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema; diff --git a/tools/eslint/lib/config/config-validator.js b/tools/eslint/lib/config/config-validator.js index ef285eae4e6032..c5268169b92356 100644 --- a/tools/eslint/lib/config/config-validator.js +++ b/tools/eslint/lib/config/config-validator.js @@ -54,65 +54,59 @@ function getRuleOptionsSchema(id) { } /** - * Validates a rule's options against its schema. - * @param {string} id The rule's unique name. - * @param {array|number} options The given options for the rule. - * @param {string} source The name of the configuration source. - * @returns {void} - */ -function validateRuleOptions(id, options, source) { - const schema = getRuleOptionsSchema(id); - let validateRule = validators.rules[id], - severity, - localOptions, - validSeverity = true; - - if (!validateRule && schema) { - validateRule = schemaValidator(schema, { verbose: true }); - validators.rules[id] = validateRule; +* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. +* @param {options} options The given options for the rule. +* @returns {number|string} The rule's severity value +*/ +function validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + + if (severity !== 0 && severity !== 1 && severity !== 2 && !(typeof severity === "string" && /^(?:off|warn|error)$/i.test(severity))) { + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, "")}').\n`); } - // if it's not an array, it should be just a severity - if (Array.isArray(options)) { - localOptions = options.concat(); // clone - severity = localOptions.shift(); - } else { - severity = options; - localOptions = []; + return severity; +} + +/** +* Validates the non-severity options passed to a rule, based on its schema. +* @param {string} id The rule's unique name +* @param {array} localOptions The options for the rule, excluding severity +* @returns {void} +*/ +function validateRuleSchema(id, localOptions) { + const schema = getRuleOptionsSchema(id); + + if (!validators.rules[id] && schema) { + validators.rules[id] = schemaValidator(schema, { verbose: true }); } - validSeverity = ( - severity === 0 || severity === 1 || severity === 2 || - (typeof severity === "string" && /^(?:off|warn|error)$/i.test(severity)) - ); + const validateRule = validators.rules[id]; if (validateRule) { validateRule(localOptions); + if (validateRule.errors) { + throw new Error(validateRule.errors.map(error => `\tValue "${error.value}" ${error.message}.\n`).join("")); + } } +} - if ((validateRule && validateRule.errors) || !validSeverity) { - const message = [ - source, ":\n", - "\tConfiguration for rule \"", id, "\" is invalid:\n" - ]; - - if (!validSeverity) { - message.push( - "\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '", - util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, ""), - "').\n" - ); - } +/** + * Validates a rule's options against its schema. + * @param {string} id The rule's unique name. + * @param {array|number} options The given options for the rule. + * @param {string} source The name of the configuration source. + * @returns {void} + */ +function validateRuleOptions(id, options, source) { + try { + const severity = validateRuleSeverity(options); - if (validateRule && validateRule.errors) { - validateRule.errors.forEach(function(error) { - message.push( - "\tValue \"", error.value, "\" ", error.message, ".\n" - ); - }); + if (severity !== 0 && !(typeof severity === "string" && severity.toLowerCase() === "off")) { + validateRuleSchema(id, Array.isArray(options) ? options.slice(1) : []); } - - throw new Error(message.join("")); + } catch (err) { + throw new Error(`${source}:\n\tConfiguration for rule "${id}" is invalid:\n${err.message}`); } } @@ -134,7 +128,7 @@ function validateEnvironment(environment, source) { } if (typeof environment === "object") { - Object.keys(environment).forEach(function(env) { + Object.keys(environment).forEach(env => { if (!Environments.get(env)) { const message = [ source, ":\n", @@ -158,7 +152,7 @@ function validateEnvironment(environment, source) { function validate(config, source) { if (typeof config.rules === "object") { - Object.keys(config.rules).forEach(function(id) { + Object.keys(config.rules).forEach(id => { validateRuleOptions(id, config.rules[id], source); }); } diff --git a/tools/eslint/lib/config/environments.js b/tools/eslint/lib/config/environments.js index 36b989068ff6da..5c34da9328a4da 100644 --- a/tools/eslint/lib/config/environments.js +++ b/tools/eslint/lib/config/environments.js @@ -22,7 +22,7 @@ let environments = new Map(); * @private */ function load() { - Object.keys(envs).forEach(function(envName) { + Object.keys(envs).forEach(envName => { environments.set(envName, envs[envName]); }); } @@ -65,9 +65,9 @@ module.exports = { */ importPlugin(plugin, pluginName) { if (plugin.environments) { - Object.keys(plugin.environments).forEach(function(envName) { + Object.keys(plugin.environments).forEach(envName => { this.define(`${pluginName}/${envName}`, plugin.environments[envName]); - }, this); + }); } }, diff --git a/tools/eslint/lib/eslint.js b/tools/eslint/lib/eslint.js index fd7685f49257c6..3ae7cfe9c68103 100755 --- a/tools/eslint/lib/eslint.js +++ b/tools/eslint/lib/eslint.js @@ -26,7 +26,22 @@ const assert = require("assert"), Traverser = require("./util/traverser"), RuleContext = require("./rule-context"), rules = require("./rules"), - timing = require("./timing"); + timing = require("./timing"), + + pkg = require("../package.json"); + + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * The result of a parsing operation from parseForESLint() + * @typedef {Object} CustomParseResult + * @property {ASTNode} ast The ESTree AST Program node. + * @property {Object} services An object containing additional services related + * to the parser. + */ //------------------------------------------------------------------------------ // Helpers @@ -45,7 +60,7 @@ function parseBooleanConfig(string, comment) { // Collapse whitespace around `:` and `,` to make parsing easier string = string.replace(/\s*([:,])\s*/g, "$1"); - string.split(/\s|,+/).forEach(function(name) { + string.split(/\s|,+/).forEach(name => { if (!name) { return; } @@ -95,7 +110,7 @@ function parseJsonConfig(string, location, messages) { // Optionator cannot parse commaless notations. // But we are supporting that. So this is a fallback for that. items = {}; - string = string.replace(/([a-zA-Z0-9\-\/]+):/g, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/, "$1,"); + string = string.replace(/([a-zA-Z0-9\-/]+):/g, "\"$1\":").replace(/(]|[0-9])\s+(?=")/, "$1,"); try { items = JSON.parse(`{${string}}`); } catch (ex) { @@ -126,7 +141,7 @@ function parseListConfig(string) { // Collapse whitespace around , string = string.replace(/\s*,\s*/g, ","); - string.split(/,+/).forEach(function(name) { + string.split(/,+/).forEach(name => { name = name.trim(); if (!name) { return; @@ -153,7 +168,7 @@ function addDeclaredGlobals(program, globalScope, config) { Object.assign(declaredGlobals, builtin); - Object.keys(config.env).forEach(function(name) { + Object.keys(config.env).forEach(name => { if (config.env[name]) { const env = Environments.get(name), environmentGlobals = env && env.globals; @@ -168,7 +183,7 @@ function addDeclaredGlobals(program, globalScope, config) { Object.assign(declaredGlobals, config.globals); Object.assign(explicitGlobals, config.astGlobals); - Object.keys(declaredGlobals).forEach(function(name) { + Object.keys(declaredGlobals).forEach(name => { let variable = globalScope.set.get(name); if (!variable) { @@ -180,7 +195,7 @@ function addDeclaredGlobals(program, globalScope, config) { variable.writeable = declaredGlobals[name]; }); - Object.keys(explicitGlobals).forEach(function(name) { + Object.keys(explicitGlobals).forEach(name => { let variable = globalScope.set.get(name); if (!variable) { @@ -194,7 +209,7 @@ function addDeclaredGlobals(program, globalScope, config) { }); // mark all exported variables as such - Object.keys(exportedGlobals).forEach(function(name) { + Object.keys(exportedGlobals).forEach(name => { const variable = globalScope.set.get(name); if (variable) { @@ -207,7 +222,7 @@ function addDeclaredGlobals(program, globalScope, config) { * Since we augment the global scope using configuration, we need to update * references and remove the ones that were added by configuration. */ - globalScope.through = globalScope.through.filter(function(reference) { + globalScope.through = globalScope.through.filter(reference => { const name = reference.identifier.name; const variable = globalScope.set.get(name); @@ -238,7 +253,7 @@ function addDeclaredGlobals(program, globalScope, config) { function disableReporting(reportingConfig, start, rulesToDisable) { if (rulesToDisable.length) { - rulesToDisable.forEach(function(rule) { + rulesToDisable.forEach(rule => { reportingConfig.push({ start, end: null, @@ -266,7 +281,7 @@ function enableReporting(reportingConfig, start, rulesToEnable) { let i; if (rulesToEnable.length) { - rulesToEnable.forEach(function(rule) { + rulesToEnable.forEach(rule => { for (i = reportingConfig.length - 1; i >= 0; i--) { if (!reportingConfig[i].end && reportingConfig[i].rule === rule) { reportingConfig[i].end = start; @@ -313,7 +328,7 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa }; const commentRules = {}; - ast.comments.forEach(function(comment) { + ast.comments.forEach(comment => { let value = comment.value.trim(); const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/.exec(value); @@ -347,7 +362,7 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa case "eslint": { const items = parseJsonConfig(value, comment.loc, messages); - Object.keys(items).forEach(function(name) { + Object.keys(items).forEach(name => { const ruleValue = items[name]; validator.validateRuleOptions(name, ruleValue, `${filename} line ${comment.loc.start.line}`); @@ -371,7 +386,7 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa }); // apply environment configs - Object.keys(commentConfig.env).forEach(function(name) { + Object.keys(commentConfig.env).forEach(name => { const env = Environments.get(name); if (env) { @@ -442,11 +457,11 @@ function prepareConfig(config) { let parserOptions = {}; if (typeof config.rules === "object") { - Object.keys(config.rules).forEach(function(k) { + Object.keys(config.rules).forEach(k => { const rule = config.rules[k]; if (rule === null) { - throw new Error(`Invalid config for rule '${k}'\.`); + throw new Error(`Invalid config for rule '${k}'.`); } if (Array.isArray(rule)) { copiedRules[k] = rule.slice(); @@ -458,7 +473,7 @@ function prepareConfig(config) { // merge in environment parserOptions if (typeof config.env === "object") { - Object.keys(config.env).forEach(function(envName) { + Object.keys(config.env).forEach(envName => { const env = Environments.get(envName); if (config.env[envName] && env && env.parserOptions) { @@ -598,7 +613,8 @@ module.exports = (function() { * @param {string} text The text to parse. * @param {Object} config The ESLint configuration object. * @param {string} filePath The path to the file being parsed. - * @returns {ASTNode} The AST if successful or null if not. + * @returns {ASTNode|CustomParseResult} The AST or parse result if successful, + * or null if not. * @private */ function parse(text, config, filePath) { @@ -642,7 +658,11 @@ module.exports = (function() { * problem that ESLint identified just like any other. */ try { - return parser.parse(text, parserOptions); + if (typeof parser.parseForESLint === "function") { + return parser.parseForESLint(text, parserOptions); + } else { + return parser.parse(text, parserOptions); + } } catch (ex) { // If the message includes a leading line number, strip it: @@ -738,6 +758,7 @@ module.exports = (function() { api.verify = function(textOrSourceCode, config, filenameOrOptions, saveState) { const text = (typeof textOrSourceCode === "string") ? textOrSourceCode : null; let ast, + parseResult, shebang, allowInlineConfig; @@ -759,7 +780,7 @@ module.exports = (function() { if (envInFile) { if (!config || !config.env) { - config = Object.assign({}, config || {}, {env: envInFile}); + config = Object.assign({}, config || {}, { env: envInFile }); } else { config = Object.assign({}, config); config.env = Object.assign({}, config.env, envInFile); @@ -778,8 +799,8 @@ module.exports = (function() { return messages; } - ast = parse( - stripUnicodeBOM(text).replace(/^#!([^\r\n]+)/, function(match, captured) { + parseResult = parse( + stripUnicodeBOM(text).replace(/^#!([^\r\n]+)/, (match, captured) => { shebang = captured; return `//${captured}`; }), @@ -787,6 +808,14 @@ module.exports = (function() { currentFilename ); + // if this result is from a parseForESLint() method, normalize + if (parseResult && parseResult.ast) { + ast = parseResult.ast; + } else { + ast = parseResult; + parseResult = null; + } + if (ast) { sourceCode = new SourceCode(text, ast); } @@ -808,9 +837,7 @@ module.exports = (function() { ConfigOps.normalize(config); // enable appropriate rules - Object.keys(config.rules).filter(function(key) { - return getRuleSeverity(config.rules[key]) > 0; - }).forEach(function(key) { + Object.keys(config.rules).filter(key => getRuleSeverity(config.rules[key]) > 0).forEach(key => { let ruleCreator; ruleCreator = rules.get(key); @@ -832,13 +859,16 @@ module.exports = (function() { try { const ruleContext = new RuleContext( key, api, severity, options, - config.settings, config.parserOptions, config.parser, ruleCreator.meta); + config.settings, config.parserOptions, config.parser, + ruleCreator.meta, + (parseResult && parseResult.services ? parseResult.services : {}) + ); const rule = ruleCreator.create ? ruleCreator.create(ruleContext) : ruleCreator(ruleContext); // add all the node types as listeners - Object.keys(rule).forEach(function(nodeType) { + Object.keys(rule).forEach(nodeType => { api.on(nodeType, timing.enabled ? timing.time(key, rule[nodeType]) : rule[nodeType] @@ -904,7 +934,7 @@ module.exports = (function() { } // sort by line and column - messages.sort(function(a, b) { + messages.sort((a, b) => { const lineDiff = a.line - b.line; if (lineDiff === 0) { @@ -957,7 +987,7 @@ module.exports = (function() { } if (opts) { - message = message.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, function(fullMatch, term) { + message = message.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (fullMatch, term) => { if (term in opts) { return opts[term]; } @@ -1027,7 +1057,7 @@ module.exports = (function() { }; // copy over methods - Object.keys(externalMethods).forEach(function(methodName) { + Object.keys(externalMethods).forEach(methodName => { const exMethodName = externalMethods[methodName]; // All functions expected to have less arguments than 5. @@ -1152,7 +1182,7 @@ module.exports = (function() { * @returns {void} */ api.defineRules = function(rulesToDefine) { - Object.getOwnPropertyNames(rulesToDefine).forEach(function(ruleId) { + Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => { defineRule(ruleId, rulesToDefine[ruleId]); }); }; @@ -1165,6 +1195,16 @@ module.exports = (function() { return require("../conf/eslint.json"); }; + /** + * Gets an object with all loaded rules. + * @returns {Map} All loaded rules + */ + api.getRules = function() { + return rules.getAllLoadedRules(); + }; + + api.version = pkg.version; + /** * Gets variables that are declared by a specified node. * diff --git a/tools/eslint/lib/file-finder.js b/tools/eslint/lib/file-finder.js index 18f3b65133d7a3..acb886c9d1e2c2 100644 --- a/tools/eslint/lib/file-finder.js +++ b/tools/eslint/lib/file-finder.js @@ -31,22 +31,6 @@ function getDirectoryEntries(directory) { } } -//------------------------------------------------------------------------------ -// API -//------------------------------------------------------------------------------ - -/** - * FileFinder - * @constructor - * @param {string[]} files The basename(s) of the file(s) to find. - * @param {stirng} cwd Current working directory - */ -function FileFinder(files, cwd) { - this.fileNames = Array.isArray(files) ? files : [files]; - this.cwd = cwd || process.cwd(); - this.cache = {}; -} - /** * Create a hash of filenames from a directory listing * @param {string[]} entries Array of directory entries. @@ -57,7 +41,7 @@ function FileFinder(files, cwd) { function normalizeDirectoryEntries(entries, directory, supportedConfigs) { const fileHash = {}; - entries.forEach(function(entry) { + entries.forEach(entry => { if (supportedConfigs.indexOf(entry) >= 0) { const resolvedEntry = path.resolve(directory, entry); @@ -69,69 +53,89 @@ function normalizeDirectoryEntries(entries, directory, supportedConfigs) { return fileHash; } +//------------------------------------------------------------------------------ +// API +//------------------------------------------------------------------------------ + /** - * Find all instances of files with the specified file names, in directory and - * parent directories. Cache the results. - * Does not check if a matching directory entry is a file. - * Searches for all the file names in this.fileNames. - * Is currently used by lib/config.js to find .eslintrc and package.json files. - * @param {string} directory The directory to start the search from. - * @returns {string[]} The file paths found. + * FileFinder class */ -FileFinder.prototype.findAllInDirectoryAndParents = function(directory) { - const cache = this.cache; - - if (directory) { - directory = path.resolve(this.cwd, directory); - } else { - directory = this.cwd; +class FileFinder { + + /** + * @param {string[]} files The basename(s) of the file(s) to find. + * @param {stirng} cwd Current working directory + */ + constructor(files, cwd) { + this.fileNames = Array.isArray(files) ? files : [files]; + this.cwd = cwd || process.cwd(); + this.cache = {}; } - if (cache.hasOwnProperty(directory)) { - return cache[directory]; - } + /** + * Find all instances of files with the specified file names, in directory and + * parent directories. Cache the results. + * Does not check if a matching directory entry is a file. + * Searches for all the file names in this.fileNames. + * Is currently used by lib/config.js to find .eslintrc and package.json files. + * @param {string} directory The directory to start the search from. + * @returns {string[]} The file paths found. + */ + findAllInDirectoryAndParents(directory) { + const cache = this.cache; + + if (directory) { + directory = path.resolve(this.cwd, directory); + } else { + directory = this.cwd; + } - const dirs = []; - const fileNames = this.fileNames; - let searched = 0; + if (cache.hasOwnProperty(directory)) { + return cache[directory]; + } - do { - dirs[searched++] = directory; - cache[directory] = []; + const dirs = []; + const fileNames = this.fileNames; + let searched = 0; - const filesMap = normalizeDirectoryEntries(getDirectoryEntries(directory), directory, fileNames); + do { + dirs[searched++] = directory; + cache[directory] = []; - if (Object.keys(filesMap).length) { - for (let k = 0; k < fileNames.length; k++) { + const filesMap = normalizeDirectoryEntries(getDirectoryEntries(directory), directory, fileNames); - if (filesMap[fileNames[k]]) { - const filePath = filesMap[fileNames[k]]; + if (Object.keys(filesMap).length) { + for (let k = 0; k < fileNames.length; k++) { - // Add the file path to the cache of each directory searched. - for (let j = 0; j < searched; j++) { - cache[dirs[j]].push(filePath); - } + if (filesMap[fileNames[k]]) { + const filePath = filesMap[fileNames[k]]; + + // Add the file path to the cache of each directory searched. + for (let j = 0; j < searched; j++) { + cache[dirs[j]].push(filePath); + } - break; + break; + } } } - } - const child = directory; + const child = directory; + + // Assign parent directory to directory. + directory = path.dirname(directory); - // Assign parent directory to directory. - directory = path.dirname(directory); + if (directory === child) { + return cache[dirs[0]]; + } + } while (!cache.hasOwnProperty(directory)); - if (directory === child) { - return cache[dirs[0]]; + // Add what has been cached previously to the cache of each directory searched. + for (let i = 0; i < searched; i++) { + dirs.push.apply(cache[dirs[i]], cache[directory]); } - } while (!cache.hasOwnProperty(directory)); - // Add what has been cached previously to the cache of each directory searched. - for (let i = 0; i < searched; i++) { - dirs.push.apply(cache[dirs[i]], cache[directory]); + return cache[dirs[0]]; } - - return cache[dirs[0]]; -}; +} module.exports = FileFinder; diff --git a/tools/eslint/lib/formatters/checkstyle.js b/tools/eslint/lib/formatters/checkstyle.js index 0beedcf6895217..5985ad0eff5752 100644 --- a/tools/eslint/lib/formatters/checkstyle.js +++ b/tools/eslint/lib/formatters/checkstyle.js @@ -35,12 +35,12 @@ module.exports = function(results) { output += ""; output += ""; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; output += ``; - messages.forEach(function(message) { + messages.forEach(message => { output += [ ` 0 ? "red" : "yellow"; + const summary = []; + + if (errors > 0) { + summary.push(`${errors} ${pluralize("error", errors)}`); + } + + if (warnings > 0) { + summary.push(`${warnings} ${pluralize("warning", warnings)}`); + } + + return chalk[summaryColor].bold(`${summary.join(" and ")} found.`); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + let errors = 0; + let warnings = 0; + const resultsWithMessages = results.filter(result => result.messages.length > 0); + + let output = resultsWithMessages.reduce((resultsOutput, result) => { + const messages = result.messages.map(message => { + if (message.fatal || message.severity === 2) { + errors++; + } else { + warnings++; + } + + return `${formatMessage(message, result)}\n\n`; + }); + + return resultsOutput.concat(messages); + }, []).join("\n"); + + output += "\n"; + output += formatSummary(errors, warnings); + + return (errors + warnings) > 0 ? output : ""; +}; diff --git a/tools/eslint/lib/formatters/compact.js b/tools/eslint/lib/formatters/compact.js index 9c7aeb87d7c064..c641039ff284c6 100644 --- a/tools/eslint/lib/formatters/compact.js +++ b/tools/eslint/lib/formatters/compact.js @@ -32,13 +32,13 @@ module.exports = function(results) { let output = "", total = 0; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; total += messages.length; - messages.forEach(function(message) { + messages.forEach(message => { output += `${result.filePath}: `; output += `line ${message.line || 0}`; diff --git a/tools/eslint/lib/formatters/html.js b/tools/eslint/lib/formatters/html.js index 66e89d372cb8db..e61fdea6a93eec 100644 --- a/tools/eslint/lib/formatters/html.js +++ b/tools/eslint/lib/formatters/html.js @@ -70,7 +70,7 @@ function renderMessages(messages, parentIndex) { * @param {Object} message Message. * @returns {string} HTML (table row) describing a message. */ - return lodash.map(messages, function(message) { + return lodash.map(messages, message => { const lineNumber = message.line || 0; const columnNumber = message.column || 0; @@ -91,15 +91,13 @@ function renderMessages(messages, parentIndex) { * @returns {string} HTML string describing the results. */ function renderResults(results) { - return lodash.map(results, function(result, index) { - return resultTemplate({ - index, - color: renderColor(result.errorCount, result.warningCount), - filePath: result.filePath, - summary: renderSummary(result.errorCount, result.warningCount) - - }) + renderMessages(result.messages, index); - }).join("\n"); + return lodash.map(results, (result, index) => resultTemplate({ + index, + color: renderColor(result.errorCount, result.warningCount), + filePath: result.filePath, + summary: renderSummary(result.errorCount, result.warningCount) + + }) + renderMessages(result.messages, index)).join("\n"); } //------------------------------------------------------------------------------ @@ -114,7 +112,7 @@ module.exports = function(results) { totalWarnings = 0; // Iterate over results to get totals - results.forEach(function(result) { + results.forEach(result => { totalErrors += result.errorCount; totalWarnings += result.warningCount; }); diff --git a/tools/eslint/lib/formatters/jslint-xml.js b/tools/eslint/lib/formatters/jslint-xml.js index 7cfa893d32fad2..14743430d8ff94 100644 --- a/tools/eslint/lib/formatters/jslint-xml.js +++ b/tools/eslint/lib/formatters/jslint-xml.js @@ -17,12 +17,12 @@ module.exports = function(results) { output += ""; output += ""; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; output += ``; - messages.forEach(function(message) { + messages.forEach(message => { output += [ `\n"; output += "\n"; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; @@ -43,7 +43,7 @@ module.exports = function(results) { output += `\n`; } - messages.forEach(function(message) { + messages.forEach(message => { const type = message.fatal ? "error" : "failure"; output += ``; diff --git a/tools/eslint/lib/formatters/stylish.js b/tools/eslint/lib/formatters/stylish.js index 578a146c010f57..a176d03ab83e0b 100644 --- a/tools/eslint/lib/formatters/stylish.js +++ b/tools/eslint/lib/formatters/stylish.js @@ -33,7 +33,7 @@ module.exports = function(results) { warnings = 0, summaryColor = "yellow"; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; if (messages.length === 0) { @@ -44,7 +44,7 @@ module.exports = function(results) { output += `${chalk.underline(result.filePath)}\n`; output += `${table( - messages.map(function(message) { + messages.map(message => { let messageType; if (message.fatal || message.severity === 2) { @@ -71,11 +71,7 @@ module.exports = function(results) { return chalk.stripColor(str).length; } } - ).split("\n").map(function(el) { - return el.replace(/(\d+)\s+(\d+)/, function(m, p1, p2) { - return chalk.dim(`${p1}:${p2}`); - }); - }).join("\n")}\n\n`; + ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`; }); if (total > 0) { diff --git a/tools/eslint/lib/formatters/table.js b/tools/eslint/lib/formatters/table.js index cd09626cc79381..b4859154ba610d 100644 --- a/tools/eslint/lib/formatters/table.js +++ b/tools/eslint/lib/formatters/table.js @@ -36,7 +36,7 @@ function drawTable(messages) { chalk.bold("Rule ID") ]); - messages.forEach(function(message) { + messages.forEach(message => { let messageType; if (message.fatal || message.severity === 2) { @@ -92,7 +92,7 @@ function drawTable(messages) { function drawReport(results) { let files; - files = results.map(function(result) { + files = results.map(result => { if (!result.messages.length) { return ""; } @@ -100,9 +100,7 @@ function drawReport(results) { return `\n${result.filePath}\n\n${drawTable(result.messages)}`; }); - files = files.filter(function(content) { - return content.trim(); - }); + files = files.filter(content => content.trim()); return files.join(""); } @@ -120,7 +118,7 @@ module.exports = function(report) { errorCount = 0; warningCount = 0; - report.forEach(function(fileReport) { + report.forEach(fileReport => { errorCount += fileReport.errorCount; warningCount += fileReport.warningCount; }); diff --git a/tools/eslint/lib/formatters/tap.js b/tools/eslint/lib/formatters/tap.js index 568ac1e8b64548..27825d0ba996e7 100644 --- a/tools/eslint/lib/formatters/tap.js +++ b/tools/eslint/lib/formatters/tap.js @@ -44,7 +44,7 @@ function outputDiagnostics(diagnostic) { module.exports = function(results) { let output = `TAP version 13\n1..${results.length}\n`; - results.forEach(function(result, id) { + results.forEach((result, id) => { const messages = result.messages; let testResult = "ok"; let diagnostics = {}; @@ -52,7 +52,7 @@ module.exports = function(results) { if (messages.length > 0) { testResult = "not ok"; - messages.forEach(function(message) { + messages.forEach(message => { const diagnostic = { message: message.message, severity: getMessageType(message), diff --git a/tools/eslint/lib/formatters/unix.js b/tools/eslint/lib/formatters/unix.js index 867bbd5b49fcd3..a5635278bc3fa9 100644 --- a/tools/eslint/lib/formatters/unix.js +++ b/tools/eslint/lib/formatters/unix.js @@ -31,13 +31,13 @@ module.exports = function(results) { let output = "", total = 0; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; total += messages.length; - messages.forEach(function(message) { + messages.forEach(message => { output += `${result.filePath}:`; output += `${message.line || 0}:`; diff --git a/tools/eslint/lib/formatters/visualstudio.js b/tools/eslint/lib/formatters/visualstudio.js index 134a04a5134ca0..feb7fb4bef382b 100644 --- a/tools/eslint/lib/formatters/visualstudio.js +++ b/tools/eslint/lib/formatters/visualstudio.js @@ -33,13 +33,13 @@ module.exports = function(results) { let output = "", total = 0; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; total += messages.length; - messages.forEach(function(message) { + messages.forEach(message => { output += result.filePath; output += `(${message.line || 0}`; diff --git a/tools/eslint/lib/ignored-paths.js b/tools/eslint/lib/ignored-paths.js index bc2db8aaac8dc0..bace73db6a394b 100644 --- a/tools/eslint/lib/ignored-paths.js +++ b/tools/eslint/lib/ignored-paths.js @@ -72,160 +72,161 @@ function mergeDefaultOptions(options) { //------------------------------------------------------------------------------ /** - * IgnoredPaths - * @constructor - * @class IgnoredPaths - * @param {Object} options object containing 'ignore', 'ignorePath' and 'patterns' properties + * IgnoredPaths class */ -function IgnoredPaths(options) { - - options = mergeDefaultOptions(options); - - /** - * add pattern to node-ignore instance - * @param {Object} ig, instance of node-ignore - * @param {string} pattern, pattern do add to ig - * @returns {array} raw ignore rules - */ - function addPattern(ig, pattern) { - return ig.addPattern(pattern); - } +class IgnoredPaths { /** - * add ignore file to node-ignore instance - * @param {Object} ig, instance of node-ignore - * @param {string} filepath, file to add to ig - * @returns {array} raw ignore rules + * @param {Object} options object containing 'ignore', 'ignorePath' and 'patterns' properties */ - function addIgnoreFile(ig, filepath) { - ig.ignoreFiles.push(filepath); - return ig.add(fs.readFileSync(filepath, "utf8")); - } - - this.defaultPatterns = [].concat(DEFAULT_IGNORE_DIRS, options.patterns || []); - this.baseDir = options.cwd; - - this.ig = { - custom: ignore(), - default: ignore() - }; + constructor(options) { + options = mergeDefaultOptions(options); + + /** + * add pattern to node-ignore instance + * @param {Object} ig, instance of node-ignore + * @param {string} pattern, pattern do add to ig + * @returns {array} raw ignore rules + */ + function addPattern(ig, pattern) { + return ig.addPattern(pattern); + } - // Add a way to keep track of ignored files. This was present in node-ignore - // 2.x, but dropped for now as of 3.0.10. - this.ig.custom.ignoreFiles = []; - this.ig.default.ignoreFiles = []; + /** + * add ignore file to node-ignore instance + * @param {Object} ig, instance of node-ignore + * @param {string} filepath, file to add to ig + * @returns {array} raw ignore rules + */ + function addIgnoreFile(ig, filepath) { + ig.ignoreFiles.push(filepath); + return ig.add(fs.readFileSync(filepath, "utf8")); + } - if (options.dotfiles !== true) { + this.defaultPatterns = [].concat(DEFAULT_IGNORE_DIRS, options.patterns || []); + this.baseDir = options.cwd; - /* - * ignore files beginning with a dot, but not files in a parent or - * ancestor directory (which in relative format will begin with `../`). - */ - addPattern(this.ig.default, [".*", "!../"]); - } + this.ig = { + custom: ignore(), + default: ignore() + }; - addPattern(this.ig.default, this.defaultPatterns); + // Add a way to keep track of ignored files. This was present in node-ignore + // 2.x, but dropped for now as of 3.0.10. + this.ig.custom.ignoreFiles = []; + this.ig.default.ignoreFiles = []; - if (options.ignore !== false) { - let ignorePath; + if (options.dotfiles !== true) { - if (options.ignorePath) { - debug("Using specific ignore file"); + /* + * ignore files beginning with a dot, but not files in a parent or + * ancestor directory (which in relative format will begin with `../`). + */ + addPattern(this.ig.default, [".*", "!../"]); + } - try { - fs.statSync(options.ignorePath); - ignorePath = options.ignorePath; - } catch (e) { - e.message = `Cannot read ignore file: ${options.ignorePath}\nError: ${e.message}`; - throw e; + addPattern(this.ig.default, this.defaultPatterns); + + if (options.ignore !== false) { + let ignorePath; + + if (options.ignorePath) { + debug("Using specific ignore file"); + + try { + fs.statSync(options.ignorePath); + ignorePath = options.ignorePath; + } catch (e) { + e.message = `Cannot read ignore file: ${options.ignorePath}\nError: ${e.message}`; + throw e; + } + } else { + debug(`Looking for ignore file in ${options.cwd}`); + ignorePath = findIgnoreFile(options.cwd); + + try { + fs.statSync(ignorePath); + debug(`Loaded ignore file ${ignorePath}`); + } catch (e) { + debug("Could not find ignore file in cwd"); + this.options = options; + } } - } else { - debug(`Looking for ignore file in ${options.cwd}`); - ignorePath = findIgnoreFile(options.cwd); - - try { - fs.statSync(ignorePath); - debug(`Loaded ignore file ${ignorePath}`); - } catch (e) { - debug("Could not find ignore file in cwd"); - this.options = options; + + if (ignorePath) { + debug(`Adding ${ignorePath}`); + this.baseDir = path.dirname(path.resolve(options.cwd, ignorePath)); + addIgnoreFile(this.ig.custom, ignorePath); + addIgnoreFile(this.ig.default, ignorePath); } - } - if (ignorePath) { - debug(`Adding ${ignorePath}`); - this.baseDir = path.dirname(path.resolve(options.cwd, ignorePath)); - addIgnoreFile(this.ig.custom, ignorePath); - addIgnoreFile(this.ig.default, ignorePath); + if (options.ignorePattern) { + addPattern(this.ig.custom, options.ignorePattern); + addPattern(this.ig.default, options.ignorePattern); + } } - if (options.ignorePattern) { - addPattern(this.ig.custom, options.ignorePattern); - addPattern(this.ig.default, options.ignorePattern); - } + this.options = options; } - this.options = options; + /** + * Determine whether a file path is included in the default or custom ignore patterns + * @param {string} filepath Path to check + * @param {string} [category=null] check 'default', 'custom' or both (null) + * @returns {boolean} true if the file path matches one or more patterns, false otherwise + */ + contains(filepath, category) { -} + let result = false; + const absolutePath = path.resolve(this.options.cwd, filepath); + const relativePath = pathUtil.getRelativePath(absolutePath, this.options.cwd); -/** - * Determine whether a file path is included in the default or custom ignore patterns - * @param {string} filepath Path to check - * @param {string} [category=null] check 'default', 'custom' or both (null) - * @returns {boolean} true if the file path matches one or more patterns, false otherwise - */ -IgnoredPaths.prototype.contains = function(filepath, category) { + if ((typeof category === "undefined") || (category === "default")) { + result = result || (this.ig.default.filter([relativePath]).length === 0); + } - let result = false; - const absolutePath = path.resolve(this.options.cwd, filepath); - const relativePath = pathUtil.getRelativePath(absolutePath, this.options.cwd); + if ((typeof category === "undefined") || (category === "custom")) { + result = result || (this.ig.custom.filter([relativePath]).length === 0); + } - if ((typeof category === "undefined") || (category === "default")) { - result = result || (this.ig.default.filter([relativePath]).length === 0); - } + return result; - if ((typeof category === "undefined") || (category === "custom")) { - result = result || (this.ig.custom.filter([relativePath]).length === 0); } - return result; - -}; - -/** - * Returns a list of dir patterns for glob to ignore - * @returns {function()} method to check whether a folder should be ignored by glob. - */ -IgnoredPaths.prototype.getIgnoredFoldersGlobChecker = function() { + /** + * Returns a list of dir patterns for glob to ignore + * @returns {function()} method to check whether a folder should be ignored by glob. + */ + getIgnoredFoldersGlobChecker() { - const ig = ignore().add(DEFAULT_IGNORE_DIRS); + const ig = ignore().add(DEFAULT_IGNORE_DIRS); - if (this.options.ignore) { - ig.add(this.ig.custom); - } + if (this.options.ignore) { + ig.add(this.ig.custom); + } - const filter = ig.createFilter(); + const filter = ig.createFilter(); - /** - * TODO - * 1. - * Actually, it should be `this.options.baseDir`, which is the base dir of `ignore-path`, - * as well as Line 177. - * But doing this leads to a breaking change and fails tests. - * Related to #6759 - */ - const base = this.options.cwd; + /** + * TODO + * 1. + * Actually, it should be `this.options.baseDir`, which is the base dir of `ignore-path`, + * as well as Line 177. + * But doing this leads to a breaking change and fails tests. + * Related to #6759 + */ + const base = this.options.cwd; - return function(absolutePath) { - const relative = pathUtil.getRelativePath(absolutePath, base); + return function(absolutePath) { + const relative = pathUtil.getRelativePath(absolutePath, base); - if (!relative) { - return false; - } + if (!relative) { + return false; + } - return !filter(relative); - }; -}; + return !filter(relative); + }; + } +} module.exports = IgnoredPaths; diff --git a/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js b/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js index 3e4671aa7b151d..a4a5dca03fbbf2 100644 --- a/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js +++ b/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js @@ -95,7 +95,6 @@ function checkMetaDocsDescription(context, exportsNode) { firstWord } }); - return; } } diff --git a/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js b/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js index 783a1109e76571..d1c78efa61e557 100644 --- a/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js +++ b/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js @@ -147,7 +147,6 @@ function checkMetaValidity(context, exportsNode, ruleIsFixable) { if (ruleIsFixable && !hasMetaFixable(metaProperty)) { context.report(metaProperty, "Rule is fixable, but is missing a meta.fixable property."); - return; } } @@ -216,7 +215,7 @@ module.exports = { "Program:exit"() { if (!isCorrectExportsFormat(exportsNode)) { - context.report(exportsNode, "Rule does not export an Object. Make sure the rule follows the new rule format."); + context.report({ node: exportsNode, message: "Rule does not export an Object. Make sure the rule follows the new rule format." }); return; } diff --git a/tools/eslint/lib/load-rules.js b/tools/eslint/lib/load-rules.js index c698faa5e132d0..92fb7bf20ada0c 100644 --- a/tools/eslint/lib/load-rules.js +++ b/tools/eslint/lib/load-rules.js @@ -31,7 +31,7 @@ module.exports = function(rulesDir, cwd) { const rules = Object.create(null); - fs.readdirSync(rulesDir).forEach(function(file) { + fs.readdirSync(rulesDir).forEach(file => { if (path.extname(file) !== ".js") { return; } diff --git a/tools/eslint/lib/rule-context.js b/tools/eslint/lib/rule-context.js index ded5dab962d70c..9c80d2e1a31cc6 100644 --- a/tools/eslint/lib/rule-context.js +++ b/tools/eslint/lib/rule-context.js @@ -61,36 +61,41 @@ const PASSTHROUGHS = [ //------------------------------------------------------------------------------ /** + * Rule context class * Acts as an abstraction layer between rules and the main eslint object. - * @constructor - * @param {string} ruleId The ID of the rule using this object. - * @param {eslint} eslint The eslint object. - * @param {number} severity The configured severity level of the rule. - * @param {Array} options The configuration information to be added to the rule. - * @param {Object} settings The configuration settings passed from the config file. - * @param {Object} parserOptions The parserOptions settings passed from the config file. - * @param {Object} parserPath The parser setting passed from the config file. - * @param {Object} meta The metadata of the rule */ -function RuleContext(ruleId, eslint, severity, options, settings, parserOptions, parserPath, meta) { +class RuleContext { - // public. - this.id = ruleId; - this.options = options; - this.settings = settings; - this.parserOptions = parserOptions; - this.parserPath = parserPath; - this.meta = meta; + /** + * @param {string} ruleId The ID of the rule using this object. + * @param {eslint} eslint The eslint object. + * @param {number} severity The configured severity level of the rule. + * @param {Array} options The configuration information to be added to the rule. + * @param {Object} settings The configuration settings passed from the config file. + * @param {Object} parserOptions The parserOptions settings passed from the config file. + * @param {Object} parserPath The parser setting passed from the config file. + * @param {Object} meta The metadata of the rule + * @param {Object} parserServices The parser services for the rule. + */ + constructor(ruleId, eslint, severity, options, settings, parserOptions, parserPath, meta, parserServices) { - // private. - this.eslint = eslint; - this.severity = severity; + // public. + this.id = ruleId; + this.options = options; + this.settings = settings; + this.parserOptions = parserOptions; + this.parserPath = parserPath; + this.meta = meta; - Object.freeze(this); -} + // create a separate copy and freeze it (it's not nice to freeze other people's objects) + this.parserServices = Object.freeze(Object.assign({}, parserServices)); -RuleContext.prototype = { - constructor: RuleContext, + // private. + this.eslint = eslint; + this.severity = severity; + + Object.freeze(this); + } /** * Passthrough to eslint.getSourceCode(). @@ -98,7 +103,7 @@ RuleContext.prototype = { */ getSourceCode() { return this.eslint.getSourceCode(); - }, + } /** * Passthrough to eslint.report() that automatically assigns the rule ID and severity. @@ -147,7 +152,7 @@ RuleContext.prototype = { this.meta ); } -}; +} // Copy over passthrough methods. All functions will have 5 or fewer parameters. PASSTHROUGHS.forEach(function(name) { diff --git a/tools/eslint/lib/rules.js b/tools/eslint/lib/rules.js index 128a6bcd15b652..80f83882d331cb 100644 --- a/tools/eslint/lib/rules.js +++ b/tools/eslint/lib/rules.js @@ -40,7 +40,7 @@ function define(ruleId, ruleModule) { function load(rulesDir, cwd) { const newRules = loadRules(rulesDir, cwd); - Object.keys(newRules).forEach(function(ruleId) { + Object.keys(newRules).forEach(ruleId => { define(ruleId, newRules[ruleId]); }); } @@ -53,7 +53,7 @@ function load(rulesDir, cwd) { */ function importPlugin(plugin, pluginName) { if (plugin.rules) { - Object.keys(plugin.rules).forEach(function(ruleId) { + Object.keys(plugin.rules).forEach(ruleId => { const qualifiedRuleId = `${pluginName}/${ruleId}`, rule = plugin.rules[ruleId]; @@ -75,6 +75,21 @@ function getHandler(ruleId) { } } +/** + * Get an object with all currently loaded rules + * @returns {Map} All loaded rules + */ +function getAllLoadedRules() { + const allRules = new Map(); + + Object.keys(rules).forEach(name => { + const rule = getHandler(name); + + allRules.set(name, rule); + }); + return allRules; +} + /** * Reset rules storage. * Should be used only in tests. @@ -89,6 +104,7 @@ module.exports = { load, importPlugin, get: getHandler, + getAllLoadedRules, testClear, /** diff --git a/tools/eslint/lib/rules/accessor-pairs.js b/tools/eslint/lib/rules/accessor-pairs.js index 7e8870edc8c8e1..4afdc7136ca2a6 100644 --- a/tools/eslint/lib/rules/accessor-pairs.js +++ b/tools/eslint/lib/rules/accessor-pairs.js @@ -139,9 +139,9 @@ module.exports = { } if (checkSetWithoutGet && isSetPresent && !isGetPresent) { - context.report(node, "Getter is not present."); + context.report({ node, message: "Getter is not present." }); } else if (checkGetWithoutSet && isGetPresent && !isSetPresent) { - context.report(node, "Setter is not present."); + context.report({ node, message: "Setter is not present." }); } } diff --git a/tools/eslint/lib/rules/array-bracket-spacing.js b/tools/eslint/lib/rules/array-bracket-spacing.js index 9bd7e944951a77..73cfbdc3c1fa8e 100644 --- a/tools/eslint/lib/rules/array-bracket-spacing.js +++ b/tools/eslint/lib/rules/array-bracket-spacing.js @@ -179,8 +179,10 @@ module.exports = { const first = sourceCode.getFirstToken(node), second = sourceCode.getFirstToken(node, 1), - penultimate = sourceCode.getLastToken(node, 1), - last = sourceCode.getLastToken(node), + last = node.typeAnnotation + ? sourceCode.getTokenBefore(node.typeAnnotation) + : sourceCode.getLastToken(node), + penultimate = sourceCode.getTokenBefore(last), firstElement = node.elements[0], lastElement = node.elements[node.elements.length - 1]; diff --git a/tools/eslint/lib/rules/arrow-body-style.js b/tools/eslint/lib/rules/arrow-body-style.js index 038aeeb5af2550..9778a6776f5e1f 100644 --- a/tools/eslint/lib/rules/arrow-body-style.js +++ b/tools/eslint/lib/rules/arrow-body-style.js @@ -37,7 +37,7 @@ module.exports = { { type: "object", properties: { - requireReturnForObjectLiteral: {type: "boolean"} + requireReturnForObjectLiteral: { type: "boolean" } }, additionalProperties: false } @@ -46,7 +46,9 @@ module.exports = { maxItems: 2 } ] - } + }, + + fixable: "code" }, create(context) { @@ -55,6 +57,7 @@ module.exports = { const asNeeded = !options[0] || options[0] === "as-needed"; const never = options[0] === "never"; const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral; + const sourceCode = context.getSourceCode(); /** * Determines whether a arrow function body needs braces @@ -65,38 +68,85 @@ module.exports = { const arrowBody = node.body; if (arrowBody.type === "BlockStatement") { - if (never) { + const blockBody = arrowBody.body; + + if (blockBody.length !== 1 && !never) { + return; + } + + if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" && + blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") { + return; + } + + if (never || asNeeded && blockBody[0].type === "ReturnStatement") { context.report({ node, loc: arrowBody.loc.start, - message: "Unexpected block statement surrounding arrow body." + message: "Unexpected block statement surrounding arrow body.", + fix(fixer) { + if (blockBody.length !== 1 || blockBody[0].type !== "ReturnStatement" || !blockBody[0].argument) { + return null; + } + + const sourceText = sourceCode.getText(); + const returnKeyword = sourceCode.getFirstToken(blockBody[0]); + const firstValueToken = sourceCode.getTokenAfter(returnKeyword); + let lastValueToken = sourceCode.getLastToken(blockBody[0]); + + if (lastValueToken.type === "Punctuator" && lastValueToken.value === ";") { + + /* The last token of the returned value is the last token of the ReturnExpression (if + * the ReturnExpression has no semicolon), or the second-to-last token (if the ReturnExpression + * has a semicolon). + */ + lastValueToken = sourceCode.getTokenBefore(lastValueToken); + } + + const tokenAfterArrowBody = sourceCode.getTokenAfter(arrowBody); + + if (tokenAfterArrowBody && tokenAfterArrowBody.type === "Punctuator" && /^[([/`+-]/.test(tokenAfterArrowBody.value)) { + + // Don't do a fix if the next token would cause ASI issues when preceded by the returned value. + return null; + } + + const textBeforeReturn = sourceText.slice(arrowBody.range[0] + 1, returnKeyword.range[0]); + const textBetweenReturnAndValue = sourceText.slice(returnKeyword.range[1], firstValueToken.range[0]); + const rawReturnValueText = sourceText.slice(firstValueToken.range[0], lastValueToken.range[1]); + const returnValueText = firstValueToken.value === "{" ? `(${rawReturnValueText})` : rawReturnValueText; + const textAfterValue = sourceText.slice(lastValueToken.range[1], blockBody[0].range[1] - 1); + const textAfterReturnStatement = sourceText.slice(blockBody[0].range[1], arrowBody.range[1] - 1); + + /* + * For fixes that only contain spaces around the return value, remove the extra spaces. + * This avoids ugly fixes that end up with extra spaces after the arrow, e.g. `() => 0 ;` + */ + return fixer.replaceText( + arrowBody, + (textBeforeReturn + textBetweenReturnAndValue).replace(/^\s*$/, "") + returnValueText + (textAfterValue + textAfterReturnStatement).replace(/^\s*$/, "") + ); + } }); - } else { - const blockBody = arrowBody.body; - - if (blockBody.length !== 1) { - return; - } - - if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" && - blockBody[0].argument.type === "ObjectExpression") { - return; - } - - if (asNeeded && blockBody[0].type === "ReturnStatement") { - context.report({ - node, - loc: arrowBody.loc.start, - message: "Unexpected block statement surrounding arrow body." - }); - } } } else { if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) { context.report({ node, loc: arrowBody.loc.start, - message: "Expected block statement surrounding arrow body." + message: "Expected block statement surrounding arrow body.", + fix(fixer) { + const lastTokenBeforeBody = sourceCode.getTokensBetween(sourceCode.getFirstToken(node), arrowBody) + .reverse() + .find(token => token.value !== "("); + + const firstBodyToken = sourceCode.getTokenAfter(lastTokenBeforeBody); + + return fixer.replaceTextRange( + [firstBodyToken.range[0], node.range[1]], + `{return ${sourceCode.getText().slice(firstBodyToken.range[0], node.range[1])}}` + ); + } }); } } diff --git a/tools/eslint/lib/rules/arrow-parens.js b/tools/eslint/lib/rules/arrow-parens.js index 67bfdf541c2955..e069e307eb2040 100644 --- a/tools/eslint/lib/rules/arrow-parens.js +++ b/tools/eslint/lib/rules/arrow-parens.js @@ -58,7 +58,9 @@ module.exports = { requireForBlockBody && node.params.length === 1 && node.params[0].type === "Identifier" && - node.body.type !== "BlockStatement" + !node.params[0].typeAnnotation && + node.body.type !== "BlockStatement" && + !node.returnType ) { if (token.type === "Punctuator" && token.value === "(") { context.report({ @@ -95,7 +97,12 @@ module.exports = { } // "as-needed": x => x - if (asNeeded && node.params.length === 1 && node.params[0].type === "Identifier") { + if (asNeeded && + node.params.length === 1 && + node.params[0].type === "Identifier" && + !node.params[0].typeAnnotation && + !node.returnType + ) { if (token.type === "Punctuator" && token.value === "(") { context.report({ node, diff --git a/tools/eslint/lib/rules/block-scoped-var.js b/tools/eslint/lib/rules/block-scoped-var.js index 0f4705a1f140d9..bb0931a3ceb63f 100644 --- a/tools/eslint/lib/rules/block-scoped-var.js +++ b/tools/eslint/lib/rules/block-scoped-var.js @@ -47,10 +47,7 @@ module.exports = { function report(reference) { const identifier = reference.identifier; - context.report( - identifier, - "'{{name}}' used outside of binding context.", - {name: identifier.name}); + context.report({ node: identifier, message: "'{{name}}' used outside of binding context.", data: { name: identifier.name } }); } /** diff --git a/tools/eslint/lib/rules/block-spacing.js b/tools/eslint/lib/rules/block-spacing.js index f18b3cceba3132..9c0a7f388ba3bb 100644 --- a/tools/eslint/lib/rules/block-spacing.js +++ b/tools/eslint/lib/rules/block-spacing.js @@ -22,7 +22,7 @@ module.exports = { fixable: "whitespace", schema: [ - {enum: ["always", "never"]} + { enum: ["always", "never"] } ] }, diff --git a/tools/eslint/lib/rules/brace-style.js b/tools/eslint/lib/rules/brace-style.js index 6bd8a8f4c87edb..197767b07c19a5 100644 --- a/tools/eslint/lib/rules/brace-style.js +++ b/tools/eslint/lib/rules/brace-style.js @@ -30,7 +30,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "whitespace" }, create(context) { @@ -69,6 +71,28 @@ module.exports = { return token.value === "{" || token.value === "}"; } + /** + * Reports a place where a newline unexpectedly appears + * @param {ASTNode} node The node to report + * @param {string} message The message to report + * @param {Token} firstToken The token before the unexpected newline + * @returns {void} + */ + function reportExtraNewline(node, message, firstToken) { + context.report({ + node, + message, + fix(fixer) { + const secondToken = sourceCode.getTokenAfter(firstToken); + const textBetween = sourceCode.getText().slice(firstToken.range[1], secondToken.range[0]); + const NEWLINE_REGEX = /\r\n|\r|\n|\u2028|\u2029/g; + + // Don't do a fix if there is a comment between the tokens. + return textBetween.trim() ? null : fixer.replaceTextRange([firstToken.range[1], secondToken.range[0]], textBetween.replace(NEWLINE_REGEX, "")); + } + }); + } + /** * Binds a list of properties to a function that verifies that the opening * curly brace is on the same line as its controlling statement of a given @@ -81,7 +105,7 @@ module.exports = { const blockProperties = arguments; return function(node) { - Array.prototype.forEach.call(blockProperties, function(blockProp) { + Array.prototype.forEach.call(blockProperties, blockProp => { const block = node[blockProp]; if (!isBlock(block)) { @@ -98,9 +122,13 @@ module.exports = { } if (style !== "allman" && previousToken.loc.start.line !== curlyToken.loc.start.line) { - context.report(node, OPEN_MESSAGE); + reportExtraNewline(node, OPEN_MESSAGE, previousToken); } else if (style === "allman" && previousToken.loc.start.line === curlyToken.loc.start.line) { - context.report(node, OPEN_MESSAGE_ALLMAN); + context.report({ + node, + message: OPEN_MESSAGE_ALLMAN, + fix: fixer => fixer.insertTextBefore(curlyToken, "\n") + }); } if (!block.body.length) { @@ -108,11 +136,19 @@ module.exports = { } if (curlyToken.loc.start.line === block.body[0].loc.start.line) { - context.report(block.body[0], BODY_MESSAGE); + context.report({ + node: block.body[0], + message: BODY_MESSAGE, + fix: fixer => fixer.insertTextAfter(curlyToken, "\n") + }); } - if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.start.line) { - context.report(block.body[block.body.length - 1], CLOSE_MESSAGE_SINGLE); + if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.end.line) { + context.report({ + node: block.body[block.body.length - 1], + message: CLOSE_MESSAGE_SINGLE, + fix: fixer => fixer.insertTextBefore(curlyTokenEnd, "\n") + }); } }); }; @@ -135,10 +171,14 @@ module.exports = { if (tokens[0].loc.start.line !== tokens[1].loc.start.line && node.consequent.type === "BlockStatement" && isCurlyPunctuator(tokens[0])) { - context.report(node.alternate, CLOSE_MESSAGE); + reportExtraNewline(node.alternate, CLOSE_MESSAGE, tokens[0]); } } else if (tokens[0].loc.start.line === tokens[1].loc.start.line) { - context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); + context.report({ + node: node.alternate, + message: CLOSE_MESSAGE_STROUSTRUP_ALLMAN, + fix: fixer => fixer.insertTextAfter(tokens[0], "\n") + }); } } @@ -158,10 +198,14 @@ module.exports = { if (style === "1tbs") { if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { - context.report(node.finalizer, CLOSE_MESSAGE); + reportExtraNewline(node.finalizer, CLOSE_MESSAGE, tokens[0]); } } else if (tokens[0].loc.start.line === tokens[1].loc.start.line) { - context.report(node.finalizer, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); + context.report({ + node: node.finalizer, + message: CLOSE_MESSAGE_STROUSTRUP_ALLMAN, + fix: fixer => fixer.insertTextAfter(tokens[0], "\n") + }); } } } @@ -181,11 +225,15 @@ module.exports = { if (isBlock(node.body)) { if (style === "1tbs") { if (previousToken.loc.start.line !== firstToken.loc.start.line) { - context.report(node, CLOSE_MESSAGE); + reportExtraNewline(node, CLOSE_MESSAGE, previousToken); } } else { if (previousToken.loc.start.line === firstToken.loc.start.line) { - context.report(node, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); + context.report({ + node, + message: CLOSE_MESSAGE_STROUSTRUP_ALLMAN, + fix: fixer => fixer.insertTextAfter(previousToken, "\n") + }); } } } @@ -207,9 +255,13 @@ module.exports = { } if (style !== "allman" && tokens[0].loc.start.line !== tokens[1].loc.start.line) { - context.report(node, OPEN_MESSAGE); + reportExtraNewline(node, OPEN_MESSAGE, tokens[0]); } else if (style === "allman" && tokens[0].loc.start.line === tokens[1].loc.start.line) { - context.report(node, OPEN_MESSAGE_ALLMAN); + context.report({ + node, + message: OPEN_MESSAGE_ALLMAN, + fix: fixer => fixer.insertTextBefore(tokens[1], "\n") + }); } } diff --git a/tools/eslint/lib/rules/callback-return.js b/tools/eslint/lib/rules/callback-return.js index 242ef666d2ac6e..08600c01e58cd1 100644 --- a/tools/eslint/lib/rules/callback-return.js +++ b/tools/eslint/lib/rules/callback-return.js @@ -164,7 +164,7 @@ module.exports = { // as long as you're the child of a function at this point you should be asked to return if (findClosestParentOfType(node, ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"])) { - context.report(node, "Expected return with your callback function."); + context.report({ node, message: "Expected return with your callback function." }); } } diff --git a/tools/eslint/lib/rules/camelcase.js b/tools/eslint/lib/rules/camelcase.js index 1b22c25e675ca3..6fb1475b21dbcd 100644 --- a/tools/eslint/lib/rules/camelcase.js +++ b/tools/eslint/lib/rules/camelcase.js @@ -38,6 +38,7 @@ module.exports = { // contains reported nodes to avoid reporting twice on destructuring with shorthand notation const reported = []; + const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]); /** * Checks if a string contains an underscore and isn't all upper-case @@ -60,7 +61,7 @@ module.exports = { function report(node) { if (reported.indexOf(node) < 0) { reported.push(node); - context.report(node, "Identifier '{{name}}' is not in camel case.", { name: node.name }); + context.report({ node, message: "Identifier '{{name}}' is not in camel case.", data: { name: node.name } }); } } @@ -118,7 +119,7 @@ module.exports = { return; } - if (isUnderscored(name) && effectiveParent.type !== "CallExpression") { + if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) { report(node); } @@ -131,7 +132,7 @@ module.exports = { } // Report anything that is underscored that isn't a CallExpression - } else if (isUnderscored(name) && effectiveParent.type !== "CallExpression") { + } else if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) { report(node); } } diff --git a/tools/eslint/lib/rules/capitalized-comments.js b/tools/eslint/lib/rules/capitalized-comments.js new file mode 100644 index 00000000000000..29cff4450b535a --- /dev/null +++ b/tools/eslint/lib/rules/capitalized-comments.js @@ -0,0 +1,301 @@ +/** + * @fileoverview enforce or disallow capitalization of the first letter of a comment + * @author Kevin Partington + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const LETTER_PATTERN = require("../util/patterns/letters"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ALWAYS_MESSAGE = "Comments should not begin with a lowercase character", + NEVER_MESSAGE = "Comments should not begin with an uppercase character", + DEFAULT_IGNORE_PATTERN = /^\s*(?:eslint|istanbul|jscs|jshint|globals?|exported)\b/, + WHITESPACE = /\s/g, + MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/, // TODO: Combine w/ max-len pattern? + DEFAULTS = { + ignorePattern: null, + ignoreInlineComments: false, + ignoreConsecutiveComments: false + }; + +/* + * Base schema body for defining the basic capitalization rule, ignorePattern, + * and ignoreInlineComments values. + * This can be used in a few different ways in the actual schema. + */ +const SCHEMA_BODY = { + type: "object", + properties: { + ignorePattern: { + type: "string" + }, + ignoreInlineComments: { + type: "boolean" + }, + ignoreConsecutiveComments: { + type: "boolean" + } + }, + additionalProperties: false +}; + +/** + * Get normalized options for either block or line comments from the given + * user-provided options. + * - If the user-provided options is just a string, returns a normalized + * set of options using default values for all other options. + * - If the user-provided options is an object, then a normalized option + * set is returned. Options specified in overrides will take priority + * over options specified in the main options object, which will in + * turn take priority over the rule's defaults. + * + * @param {Object|string} rawOptions The user-provided options. + * @param {string} which Either "line" or "block". + * @returns {Object} The normalized options. + */ +function getNormalizedOptions(rawOptions, which) { + if (!rawOptions) { + return Object.assign({}, DEFAULTS); + } + + return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); +} + +/** + * Get normalized options for block and line comments. + * + * @param {Object|string} rawOptions The user-provided options. + * @returns {Object} An object with "Line" and "Block" keys and corresponding + * normalized options objects. + */ +function getAllNormalizedOptions(rawOptions) { + return { + Line: getNormalizedOptions(rawOptions, "line"), + Block: getNormalizedOptions(rawOptions, "block") + }; +} + +/** + * Creates a regular expression for each ignorePattern defined in the rule + * options. + * + * This is done in order to avoid invoking the RegExp constructor repeatedly. + * + * @param {Object} normalizedOptions The normalized rule options. + * @returns {void} + */ +function createRegExpForIgnorePatterns(normalizedOptions) { + Object.keys(normalizedOptions).forEach(key => { + const ignorePatternStr = normalizedOptions[key].ignorePattern; + + if (ignorePatternStr) { + const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); + + normalizedOptions[key].ignorePatternRegExp = regExp; + } + }); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "enforce or disallow capitalization of the first letter of a comment", + category: "Stylistic Issues", + recommended: false + }, + fixable: "code", + schema: [ + { enum: ["always", "never"] }, + { + oneOf: [ + SCHEMA_BODY, + { + type: "object", + properties: { + line: SCHEMA_BODY, + block: SCHEMA_BODY + }, + additionalProperties: false + } + ] + } + ] + }, + + create(context) { + + const capitalize = context.options[0] || "always", + normalizedOptions = getAllNormalizedOptions(context.options[1]), + sourceCode = context.getSourceCode(); + + createRegExpForIgnorePatterns(normalizedOptions); + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks whether a comment is an inline comment. + * + * For the purpose of this rule, a comment is inline if: + * 1. The comment is preceded by a token on the same line; and + * 2. The command is followed by a token on the same line. + * + * Note that the comment itself need not be single-line! + * + * Also, it follows from this definition that only block comments can + * be considered as possibly inline. This is because line comments + * would consume any following tokens on the same line as the comment. + * + * @param {ASTNode} comment The comment node to check. + * @returns {boolean} True if the comment is an inline comment, false + * otherwise. + */ + function isInlineComment(comment) { + const previousToken = sourceCode.getTokenOrCommentBefore(comment), + nextToken = sourceCode.getTokenOrCommentAfter(comment); + + return Boolean( + previousToken && + nextToken && + comment.loc.start.line === previousToken.loc.end.line && + comment.loc.end.line === nextToken.loc.start.line + ); + } + + /** + * Determine if a comment follows another comment. + * + * @param {ASTNode} comment The comment to check. + * @returns {boolean} True if the comment follows a valid comment. + */ + function isConsecutiveComment(comment) { + const previousTokenOrComment = sourceCode.getTokenOrCommentBefore(comment); + + return Boolean( + previousTokenOrComment && + ["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1 + ); + } + + /** + * Check a comment to determine if it is valid for this rule. + * + * @param {ASTNode} comment The comment node to process. + * @param {Object} options The options for checking this comment. + * @returns {boolean} True if the comment is valid, false otherwise. + */ + function isCommentValid(comment, options) { + + // 1. Check for default ignore pattern. + if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { + return true; + } + + // 2. Check for custom ignore pattern. + const commentWithoutAsterisks = comment.value + .replace(/\*/g, ""); + + if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { + return true; + } + + // 3. Check for inline comments. + if (options.ignoreInlineComments && isInlineComment(comment)) { + return true; + } + + // 4. Is this a consecutive comment (and are we tolerating those)? + if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) { + return true; + } + + // 5. Does the comment start with a possible URL? + if (MAYBE_URL.test(commentWithoutAsterisks)) { + return true; + } + + // 6. Is the initial word character a letter? + const commentWordCharsOnly = commentWithoutAsterisks + .replace(WHITESPACE, ""); + + if (commentWordCharsOnly.length === 0) { + return true; + } + + const firstWordChar = commentWordCharsOnly[0]; + + if (!LETTER_PATTERN.test(firstWordChar)) { + return true; + } + + // 7. Check the case of the initial word character. + const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(), + isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase(); + + if (capitalize === "always" && isLowercase) { + return false; + } else if (capitalize === "never" && isUppercase) { + return false; + } + + return true; + } + + /** + * Process a comment to determine if it needs to be reported. + * + * @param {ASTNode} comment The comment node to process. + * @returns {void} + */ + function processComment(comment) { + const options = normalizedOptions[comment.type], + commentValid = isCommentValid(comment, options); + + if (!commentValid) { + const message = capitalize === "always" ? + ALWAYS_MESSAGE : + NEVER_MESSAGE; + + context.report({ + node: null, // Intentionally using loc instead + loc: comment.loc, + message, + fix(fixer) { + const match = comment.value.match(LETTER_PATTERN); + + return fixer.replaceTextRange( + + // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) + [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], + capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase() + ); + } + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments.forEach(processComment); + } + }; + } +}; diff --git a/tools/eslint/lib/rules/comma-dangle.js b/tools/eslint/lib/rules/comma-dangle.js index 763ee89fd5d55e..af7ab2767f5566 100644 --- a/tools/eslint/lib/rules/comma-dangle.js +++ b/tools/eslint/lib/rules/comma-dangle.js @@ -112,11 +112,11 @@ module.exports = { { type: "object", properties: { - arrays: {$refs: "#/defs/valueWithIgnore"}, - objects: {$refs: "#/defs/valueWithIgnore"}, - imports: {$refs: "#/defs/valueWithIgnore"}, - exports: {$refs: "#/defs/valueWithIgnore"}, - functions: {$refs: "#/defs/valueWithIgnore"} + arrays: { $refs: "#/defs/valueWithIgnore" }, + objects: { $refs: "#/defs/valueWithIgnore" }, + imports: { $refs: "#/defs/valueWithIgnore" }, + exports: { $refs: "#/defs/valueWithIgnore" }, + functions: { $refs: "#/defs/valueWithIgnore" } }, additionalProperties: false } @@ -171,15 +171,10 @@ module.exports = { function getTrailingToken(node, lastItem) { switch (node.type) { case "ObjectExpression": - case "ObjectPattern": case "ArrayExpression": - case "ArrayPattern": case "CallExpression": case "NewExpression": return sourceCode.getLastToken(node, 1); - case "FunctionDeclaration": - case "FunctionExpression": - return sourceCode.getTokenBefore(node.body, 1); default: { const nextToken = sourceCode.getTokenAfter(lastItem); diff --git a/tools/eslint/lib/rules/comma-spacing.js b/tools/eslint/lib/rules/comma-spacing.js index 72b5bad6badabe..f571cfa199675a 100644 --- a/tools/eslint/lib/rules/comma-spacing.js +++ b/tools/eslint/lib/rules/comma-spacing.js @@ -141,7 +141,7 @@ module.exports = { function addNullElementsToIgnoreList(node) { let previousToken = sourceCode.getFirstToken(node); - node.elements.forEach(function(element) { + node.elements.forEach(element => { let token; if (element === null) { @@ -164,7 +164,7 @@ module.exports = { return { "Program:exit"() { - tokensAndComments.forEach(function(token, i) { + tokensAndComments.forEach((token, i) => { if (!isComma(token)) { return; diff --git a/tools/eslint/lib/rules/comma-style.js b/tools/eslint/lib/rules/comma-style.js index f707ce80557e09..bb290f90b980d1 100644 --- a/tools/eslint/lib/rules/comma-style.js +++ b/tools/eslint/lib/rules/comma-style.js @@ -41,10 +41,22 @@ module.exports = { create(context) { const style = context.options[0] || "last", sourceCode = context.getSourceCode(); - let exceptions = {}; + const exceptions = { + ArrayPattern: true, + ArrowFunctionExpression: true, + CallExpression: true, + FunctionDeclaration: true, + FunctionExpression: true, + ImportDeclaration: true, + ObjectPattern: true, + }; if (context.options.length === 2 && context.options[1].hasOwnProperty("exceptions")) { - exceptions = context.options[1].exceptions; + const keys = Object.keys(context.options[1].exceptions); + + for (let i = 0; i < keys.length; i++) { + exceptions[keys[i]] = context.options[1].exceptions[keys[i]]; + } } //-------------------------------------------------------------------------- @@ -119,7 +131,7 @@ module.exports = { if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) && astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { - return; + // do nothing. } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) && !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { @@ -166,14 +178,14 @@ module.exports = { */ function validateComma(node, property) { const items = node[property], - arrayLiteral = (node.type === "ArrayExpression"); + arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern"); if (items.length > 1 || arrayLiteral) { // seed as opening [ let previousItemToken = sourceCode.getFirstToken(node); - items.forEach(function(item) { + items.forEach(item => { const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken, currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken), reportItem = item || currentItemToken, @@ -245,11 +257,46 @@ module.exports = { validateComma(node, "properties"); }; } + if (!exceptions.ObjectPattern) { + nodes.ObjectPattern = function(node) { + validateComma(node, "properties"); + }; + } if (!exceptions.ArrayExpression) { nodes.ArrayExpression = function(node) { validateComma(node, "elements"); }; } + if (!exceptions.ArrayPattern) { + nodes.ArrayPattern = function(node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.FunctionDeclaration) { + nodes.FunctionDeclaration = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.FunctionExpression) { + nodes.FunctionExpression = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.ArrowFunctionExpression) { + nodes.ArrowFunctionExpression = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.CallExpression) { + nodes.CallExpression = function(node) { + validateComma(node, "arguments"); + }; + } + if (!exceptions.ImportDeclaration) { + nodes.ImportDeclaration = function(node) { + validateComma(node, "specifiers"); + }; + } return nodes; } diff --git a/tools/eslint/lib/rules/complexity.js b/tools/eslint/lib/rules/complexity.js index 0d837e74d3b650..2f3e4040799872 100644 --- a/tools/eslint/lib/rules/complexity.js +++ b/tools/eslint/lib/rules/complexity.js @@ -91,7 +91,7 @@ module.exports = { } if (complexity > THRESHOLD) { - context.report(node, "Function '{{name}}' has a complexity of {{complexity}}.", { name, complexity }); + context.report({ node, message: "Function '{{name}}' has a complexity of {{complexity}}.", data: { name, complexity } }); } } diff --git a/tools/eslint/lib/rules/consistent-return.js b/tools/eslint/lib/rules/consistent-return.js index eed69c2cb78ac3..0c1a6a7493f663 100644 --- a/tools/eslint/lib/rules/consistent-return.js +++ b/tools/eslint/lib/rules/consistent-return.js @@ -33,6 +33,18 @@ function isUnreachable(segment) { return !segment.reachable; } +/** +* Checks whether a given node is a `constructor` method in an ES6 class +* @param {ASTNode} node A node to check +* @returns {boolean} `true` if the node is a `constructor` method +*/ +function isClassConstructor(node) { + return node.type === "FunctionExpression" && + node.parent && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor"; +} + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -77,7 +89,8 @@ module.exports = { */ if (!funcInfo.hasReturnValue || funcInfo.codePath.currentSegments.every(isUnreachable) || - astUtils.isES5Constructor(node) + astUtils.isES5Constructor(node) || + isClassConstructor(node) ) { return; } @@ -86,7 +99,7 @@ module.exports = { if (node.type === "Program") { // The head of program. - loc = {line: 1, column: 0}; + loc = { line: 1, column: 0 }; type = "program"; } else if (node.type === "ArrowFunctionExpression") { @@ -113,7 +126,7 @@ module.exports = { node, loc, message: "Expected to return a value at the end of this {{type}}.", - data: {type} + data: { type } }); } diff --git a/tools/eslint/lib/rules/consistent-this.js b/tools/eslint/lib/rules/consistent-this.js index 2a068ed1fc2add..35c2d56272a638 100644 --- a/tools/eslint/lib/rules/consistent-this.js +++ b/tools/eslint/lib/rules/consistent-this.js @@ -43,9 +43,7 @@ module.exports = { * @returns {void} */ function reportBadAssignment(node, alias) { - context.report(node, - "Designated alias '{{alias}}' is not assigned to 'this'.", - { alias }); + context.report({ node, message: "Designated alias '{{alias}}' is not assigned to 'this'.", data: { alias } }); } /** @@ -64,8 +62,7 @@ module.exports = { reportBadAssignment(node, name); } } else if (isThis) { - context.report(node, - "Unexpected alias '{{name}}' for 'this'.", { name }); + context.report({ node, message: "Unexpected alias '{{name}}' for 'this'.", data: { name } }); } } @@ -84,16 +81,14 @@ module.exports = { return; } - if (variable.defs.some(function(def) { - return def.node.type === "VariableDeclarator" && - def.node.init !== null; - })) { + if (variable.defs.some(def => def.node.type === "VariableDeclarator" && + def.node.init !== null)) { return; } // The alias has been declared and not assigned: check it was // assigned later in the same scope. - if (!variable.references.some(function(reference) { + if (!variable.references.some(reference => { const write = reference.writeExpr; return ( @@ -102,9 +97,7 @@ module.exports = { write.parent.operator === "=" ); })) { - variable.defs.map(function(def) { - return def.node; - }).forEach(function(node) { + variable.defs.map(def => def.node).forEach(node => { reportBadAssignment(node, alias); }); } @@ -117,7 +110,7 @@ module.exports = { function ensureWasAssigned() { const scope = context.getScope(); - aliases.forEach(function(alias) { + aliases.forEach(alias => { checkWasAssigned(alias, scope); }); } diff --git a/tools/eslint/lib/rules/constructor-super.js b/tools/eslint/lib/rules/constructor-super.js index 49271cee5899be..e84df7e81da025 100644 --- a/tools/eslint/lib/rules/constructor-super.js +++ b/tools/eslint/lib/rules/constructor-super.js @@ -261,8 +261,8 @@ module.exports = { const isRealLoop = toSegment.prevSegments.length >= 2; funcInfo.codePath.traverseSegments( - {first: toSegment, last: fromSegment}, - function(segment) { + { first: toSegment, last: fromSegment }, + segment => { const info = segInfoMap[segment.id]; const prevSegments = segment.prevSegments; diff --git a/tools/eslint/lib/rules/curly.js b/tools/eslint/lib/rules/curly.js index 02d74a1e037560..801552d69e151b 100644 --- a/tools/eslint/lib/rules/curly.js +++ b/tools/eslint/lib/rules/curly.js @@ -74,10 +74,11 @@ module.exports = { * @private */ function isCollapsedOneLiner(node) { - const before = sourceCode.getTokenBefore(node), - last = sourceCode.getLastToken(node); + const before = sourceCode.getTokenBefore(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = last.type === "Punctuator" && last.value === ";" ? sourceCode.getTokenBefore(last) : last; - return before.loc.start.line === last.loc.end.line; + return before.loc.start.line === lastExcludingSemicolon.loc.end.line; } /** @@ -195,7 +196,7 @@ module.exports = { return true; } - if (/^[(\[\/`+-]/.test(tokenAfter.value)) { + if (/^[([/`+-]/.test(tokenAfter.value)) { // If the next token starts with a character that would disrupt ASI, insert a semicolon. return true; @@ -289,7 +290,9 @@ module.exports = { } } else if (multiOrNest) { if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) { - expected = false; + const leadingComments = sourceCode.getComments(body.body[0]).leading; + + expected = leadingComments.length > 0; } else if (!isOneLiner(body)) { expected = true; } @@ -337,14 +340,14 @@ module.exports = { * all have braces. * If all nodes shouldn't have braces, make sure they don't. */ - const expected = preparedChecks.some(function(preparedCheck) { + const expected = preparedChecks.some(preparedCheck => { if (preparedCheck.expected !== null) { return preparedCheck.expected; } return preparedCheck.actual; }); - preparedChecks.forEach(function(preparedCheck) { + preparedChecks.forEach(preparedCheck => { preparedCheck.expected = expected; }); } @@ -359,7 +362,7 @@ module.exports = { return { IfStatement(node) { if (node.parent.type !== "IfStatement") { - prepareIfChecks(node).forEach(function(preparedCheck) { + prepareIfChecks(node).forEach(preparedCheck => { preparedCheck.check(); }); } diff --git a/tools/eslint/lib/rules/default-case.js b/tools/eslint/lib/rules/default-case.js index e062798db235ab..070ff3c7a9666b 100644 --- a/tools/eslint/lib/rules/default-case.js +++ b/tools/eslint/lib/rules/default-case.js @@ -4,7 +4,7 @@ */ "use strict"; -const DEFAULT_COMMENT_PATTERN = /^no default$/; +const DEFAULT_COMMENT_PATTERN = /^no default$/i; //------------------------------------------------------------------------------ // Rule Definition @@ -67,9 +67,7 @@ module.exports = { return; } - const hasDefault = node.cases.some(function(v) { - return v.test === null; - }); + const hasDefault = node.cases.some(v => v.test === null); if (!hasDefault) { @@ -83,7 +81,7 @@ module.exports = { } if (!comment || !commentPattern.test(comment.value.trim())) { - context.report(node, "Expected a default case."); + context.report({ node, message: "Expected a default case." }); } } } diff --git a/tools/eslint/lib/rules/eqeqeq.js b/tools/eslint/lib/rules/eqeqeq.js index 4d61399f207ba7..d77607afb5f2aa 100644 --- a/tools/eslint/lib/rules/eqeqeq.js +++ b/tools/eslint/lib/rules/eqeqeq.js @@ -47,7 +47,9 @@ module.exports = { additionalItems: false } ] - } + }, + + fixable: "code" }, create(context) { @@ -112,22 +114,32 @@ module.exports = { function getOperatorLocation(node) { const opToken = sourceCode.getTokenAfter(node.left); - return {line: opToken.loc.start.line, column: opToken.loc.start.column}; + return { line: opToken.loc.start.line, column: opToken.loc.start.column }; } /** * Reports a message for this rule. * @param {ASTNode} node The binary expression node that was checked - * @param {string} message The message to report + * @param {string} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==') * @returns {void} * @private */ - function report(node, message) { + function report(node, expectedOperator) { context.report({ node, loc: getOperatorLocation(node), - message, - data: { op: node.operator.charAt(0) } + message: "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'.", + data: { expectedOperator, actualOperator: node.operator }, + fix(fixer) { + + // If the comparison is a `typeof` comparison or both sides are literals with the same type, then it's safe to fix. + if (isTypeOfBinary(node) || areLiteralsAndSameType(node)) { + const operatorToken = sourceCode.getTokensBetween(node.left, node.right).find(token => token.value === node.operator); + + return fixer.replaceText(operatorToken, expectedOperator); + } + return null; + } }); } @@ -137,7 +149,7 @@ module.exports = { if (node.operator !== "==" && node.operator !== "!=") { if (enforceInverseRuleForNull && isNull) { - report(node, "Expected '{{op}}=' and instead saw '{{op}}=='."); + report(node, node.operator.slice(0, -1)); } return; } @@ -151,7 +163,7 @@ module.exports = { return; } - report(node, "Expected '{{op}}==' and instead saw '{{op}}='."); + report(node, `${node.operator}=`); } }; diff --git a/tools/eslint/lib/rules/func-call-spacing.js b/tools/eslint/lib/rules/func-call-spacing.js index 417f2bdf313e17..5c416f0373fcac 100644 --- a/tools/eslint/lib/rules/func-call-spacing.js +++ b/tools/eslint/lib/rules/func-call-spacing.js @@ -120,7 +120,14 @@ module.exports = { loc: lastCalleeToken.loc.start, message: "Unexpected space between function name and paren.", fix(fixer) { - return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); + + // Only autofix if there is no newline + // https://github.com/eslint/eslint/issues/7787 + if (!hasNewline) { + return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); + } + + return null; } }); } else if (!never && !hasWhitespace) { diff --git a/tools/eslint/lib/rules/func-name-matching.js b/tools/eslint/lib/rules/func-name-matching.js index d4d760cbe45f1b..4eed7a68ea2b51 100644 --- a/tools/eslint/lib/rules/func-name-matching.js +++ b/tools/eslint/lib/rules/func-name-matching.js @@ -54,6 +54,17 @@ function isIdentifier(name, ecmaVersion) { // Rule Definition //------------------------------------------------------------------------------ +const alwaysOrNever = { enum: ["always", "never"] }; +const optionsObject = { + type: "object", + properties: { + includeCommonJSModuleExports: { + type: "boolean" + } + }, + additionalProperties: false +}; + module.exports = { meta: { docs: { @@ -62,24 +73,35 @@ module.exports = { recommended: false }, - schema: [ - { - type: "object", - properties: { - includeCommonJSModuleExports: { - type: "boolean" - } - }, - additionalProperties: false - } - ] + schema: { + anyOf: [{ + type: "array", + additionalItems: false, + items: [alwaysOrNever, optionsObject] + }, { + type: "array", + additionalItems: false, + items: [optionsObject] + }] + } }, create(context) { - - const includeModuleExports = context.options[0] && context.options[0].includeCommonJSModuleExports; + const options = (typeof context.options[0] === "object" ? context.options[0] : context.options[1]) || {}; + const nameMatches = typeof context.options[0] === "string" ? context.options[0] : "always"; + const includeModuleExports = options.includeCommonJSModuleExports; const ecmaVersion = context.parserOptions && context.parserOptions.ecmaVersion ? context.parserOptions.ecmaVersion : 5; + /** + * Compares identifiers based on the nameMatches option + * @param {string} x the first identifier + * @param {string} y the second identifier + * @returns {boolean} whether the two identifiers should warn. + */ + function shouldWarn(x, y) { + return (nameMatches === "always" && x !== y) || (nameMatches === "never" && x === y); + } + /** * Reports * @param {ASTNode} node The node to report @@ -89,10 +111,20 @@ module.exports = { * @returns {void} */ function report(node, name, funcName, isProp) { + let message; + + if (nameMatches === "always" && isProp) { + message = "Function name `{{funcName}}` should match property name `{{name}}`"; + } else if (nameMatches === "always") { + message = "Function name `{{funcName}}` should match variable name `{{name}}`"; + } else if (isProp) { + message = "Function name `{{funcName}}` should not match property name `{{name}}`"; + } else { + message = "Function name `{{funcName}}` should not match variable name `{{name}}`"; + } context.report({ node, - message: isProp ? "Function name `{{funcName}}` should match property name `{{name}}`" - : "Function name `{{funcName}}` should match variable name `{{name}}`", + message, data: { name, funcName @@ -110,7 +142,7 @@ module.exports = { if (!node.init || node.init.type !== "FunctionExpression") { return; } - if (node.init.id && node.id.name !== node.init.id.name) { + if (node.init.id && shouldWarn(node.id.name, node.init.id.name)) { report(node, node.id.name, node.init.id.name, false); } }, @@ -126,7 +158,7 @@ module.exports = { const isProp = node.left.type === "MemberExpression" ? true : false; const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name; - if (node.right.id && isIdentifier(name) && name !== node.right.id.name) { + if (node.right.id && isIdentifier(name) && shouldWarn(name, node.right.id.name)) { report(node, name, node.right.id.name, isProp); } }, @@ -135,12 +167,13 @@ module.exports = { if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && node.key.type !== "Literal") { return; } - if (node.key.type === "Identifier" && node.key.name !== node.value.id.name) { + if (node.key.type === "Identifier" && shouldWarn(node.key.name, node.value.id.name)) { report(node, node.key.name, node.value.id.name, true); - } else if (node.key.type === "Literal" && - isIdentifier(node.key.value, ecmaVersion) && - node.key.value !== node.value.id.name - ) { + } else if ( + node.key.type === "Literal" && + isIdentifier(node.key.value, ecmaVersion) && + shouldWarn(node.key.value, node.value.id.name) + ) { report(node, node.key.value, node.value.id.name, true); } } diff --git a/tools/eslint/lib/rules/func-names.js b/tools/eslint/lib/rules/func-names.js index 397ef37e91614d..0d8567149493dc 100644 --- a/tools/eslint/lib/rules/func-names.js +++ b/tools/eslint/lib/rules/func-names.js @@ -28,21 +28,23 @@ module.exports = { schema: [ { - enum: ["always", "never"] + enum: ["always", "as-needed", "never"] } ] }, create(context) { const never = context.options[0] === "never"; + const asNeeded = context.options[0] === "as-needed"; /** * Determines whether the current FunctionExpression node is a get, set, or * shorthand method in an object literal or a class. + * @param {ASTNode} node - A node to check. * @returns {boolean} True if the node is a get, set, or shorthand method. */ - function isObjectOrClassMethod() { - const parent = context.getAncestors().pop(); + function isObjectOrClassMethod(node) { + const parent = node.parent; return (parent.type === "MethodDefinition" || ( parent.type === "Property" && ( @@ -53,6 +55,23 @@ module.exports = { )); } + /** + * Determines whether the current FunctionExpression node has a name that would be + * inferred from context in a conforming ES6 environment. + * @param {ASTNode} node - A node to check. + * @returns {boolean} True if the node would have a name assigned automatically. + */ + function hasInferredName(node) { + const parent = node.parent; + + return isObjectOrClassMethod(node) || + (parent.type === "VariableDeclarator" && parent.id.type === "Identifier" && parent.init === node) || + (parent.type === "Property" && parent.value === node) || + (parent.type === "AssignmentExpression" && parent.left.type === "Identifier" && parent.right === node) || + (parent.type === "ExportDefaultDeclaration" && parent.declaration === node) || + (parent.type === "AssignmentPattern" && parent.right === node); + } + return { "FunctionExpression:exit"(node) { @@ -67,11 +86,11 @@ module.exports = { if (never) { if (name) { - context.report(node, "Unexpected function expression name."); + context.report({ node, message: "Unexpected function expression name." }); } } else { - if (!name && !isObjectOrClassMethod()) { - context.report(node, "Missing function expression name."); + if (!name && (asNeeded ? !hasInferredName(node) : !isObjectOrClassMethod(node))) { + context.report({ node, message: "Missing function expression name." }); } } } diff --git a/tools/eslint/lib/rules/func-style.js b/tools/eslint/lib/rules/func-style.js index e0974209c4bb78..123eae3d8a406f 100644 --- a/tools/eslint/lib/rules/func-style.js +++ b/tools/eslint/lib/rules/func-style.js @@ -44,7 +44,7 @@ module.exports = { stack.push(false); if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") { - context.report(node, "Expected a function expression."); + context.report({ node, message: "Expected a function expression." }); } }, "FunctionDeclaration:exit"() { @@ -55,7 +55,7 @@ module.exports = { stack.push(false); if (enforceDeclarations && node.parent.type === "VariableDeclarator") { - context.report(node.parent, "Expected a function declaration."); + context.report({ node: node.parent, message: "Expected a function declaration." }); } }, "FunctionExpression:exit"() { @@ -78,7 +78,7 @@ module.exports = { const hasThisExpr = stack.pop(); if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") { - context.report(node.parent, "Expected a function declaration."); + context.report({ node: node.parent, message: "Expected a function declaration." }); } }; } diff --git a/tools/eslint/lib/rules/generator-star-spacing.js b/tools/eslint/lib/rules/generator-star-spacing.js index f9ec3a4af52c25..fc676d0cbbb85f 100644 --- a/tools/eslint/lib/rules/generator-star-spacing.js +++ b/tools/eslint/lib/rules/generator-star-spacing.js @@ -28,8 +28,8 @@ module.exports = { { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"} + before: { type: "boolean" }, + after: { type: "boolean" } }, additionalProperties: false } diff --git a/tools/eslint/lib/rules/global-require.js b/tools/eslint/lib/rules/global-require.js index 3d6492cfde4671..bfd01433957e3e 100644 --- a/tools/eslint/lib/rules/global-require.js +++ b/tools/eslint/lib/rules/global-require.js @@ -23,10 +23,8 @@ const ACCEPTABLE_PARENTS = [ * @returns {Reference|null} Returns the found reference or null if none were found. */ function findReference(scope, node) { - const references = scope.references.filter(function(reference) { - return reference.identifier.range[0] === node.range[0] && - reference.identifier.range[1] === node.range[1]; - }); + const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1]); /* istanbul ignore else: correctly returns null */ if (references.length === 1) { @@ -65,12 +63,10 @@ module.exports = { const currentScope = context.getScope(); if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) { - const isGoodRequire = context.getAncestors().every(function(parent) { - return ACCEPTABLE_PARENTS.indexOf(parent.type) > -1; - }); + const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1); if (!isGoodRequire) { - context.report(node, "Unexpected require()."); + context.report({ node, message: "Unexpected require()." }); } } } diff --git a/tools/eslint/lib/rules/guard-for-in.js b/tools/eslint/lib/rules/guard-for-in.js index 7ccfec90c1c572..754830f6a64be3 100644 --- a/tools/eslint/lib/rules/guard-for-in.js +++ b/tools/eslint/lib/rules/guard-for-in.js @@ -33,7 +33,7 @@ module.exports = { const body = node.body.type === "BlockStatement" ? node.body.body[0] : node.body; if (body && body.type !== "IfStatement") { - context.report(node, "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."); + context.report({ node, message: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." }); } } }; diff --git a/tools/eslint/lib/rules/handle-callback-err.js b/tools/eslint/lib/rules/handle-callback-err.js index e8c6d1b3b8f647..de36a0c1b002c6 100644 --- a/tools/eslint/lib/rules/handle-callback-err.js +++ b/tools/eslint/lib/rules/handle-callback-err.js @@ -59,9 +59,7 @@ module.exports = { * @returns {array} All parameters of the given scope. */ function getParameters(scope) { - return scope.variables.filter(function(variable) { - return variable.defs[0] && variable.defs[0].type === "Parameter"; - }); + return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter"); } /** @@ -76,7 +74,7 @@ module.exports = { if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) { if (firstParameter.references.length === 0) { - context.report(node, "Expected error to be handled."); + context.report({ node, message: "Expected error to be handled." }); } } } diff --git a/tools/eslint/lib/rules/id-blacklist.js b/tools/eslint/lib/rules/id-blacklist.js index 8795cfc6be6964..f94f6d0a4684d4 100644 --- a/tools/eslint/lib/rules/id-blacklist.js +++ b/tools/eslint/lib/rules/id-blacklist.js @@ -67,9 +67,9 @@ module.exports = { * @private */ function report(node) { - context.report(node, "Identifier '{{name}}' is blacklisted.", { + context.report({ node, message: "Identifier '{{name}}' is blacklisted.", data: { name: node.name - }); + } }); } return { diff --git a/tools/eslint/lib/rules/id-length.js b/tools/eslint/lib/rules/id-length.js index 1747552707901c..6a6c69d1017e8c 100644 --- a/tools/eslint/lib/rules/id-length.js +++ b/tools/eslint/lib/rules/id-length.js @@ -50,7 +50,7 @@ module.exports = { const maxLength = typeof options.max !== "undefined" ? options.max : Infinity; const properties = options.properties !== "never"; const exceptions = (options.exceptions ? options.exceptions : []) - .reduce(function(obj, item) { + .reduce((obj, item) => { obj[item] = true; return obj; @@ -102,13 +102,13 @@ module.exports = { const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type]; if (isValidExpression && (isValidExpression === true || isValidExpression(parent, node))) { - context.report( + context.report({ node, - isShort ? + message: isShort ? "Identifier name '{{name}}' is too short (< {{min}})." : "Identifier name '{{name}}' is too long (> {{max}}).", - { name, min: minLength, max: maxLength } - ); + data: { name, min: minLength, max: maxLength } + }); } } }; diff --git a/tools/eslint/lib/rules/id-match.js b/tools/eslint/lib/rules/id-match.js index 961a1859049d24..29d06c36024c57 100644 --- a/tools/eslint/lib/rules/id-match.js +++ b/tools/eslint/lib/rules/id-match.js @@ -75,10 +75,10 @@ module.exports = { * @private */ function report(node) { - context.report(node, "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", { + context.report({ node, message: "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", data: { name: node.name, pattern - }); + } }); } return { diff --git a/tools/eslint/lib/rules/indent.js b/tools/eslint/lib/rules/indent.js index 2b069011f99d02..6c3c27c8e1941a 100644 --- a/tools/eslint/lib/rules/indent.js +++ b/tools/eslint/lib/rules/indent.js @@ -113,6 +113,44 @@ module.exports = { minimum: 0 } } + }, + CallExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + } + } + }, + ArrayExpression: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + }, + ObjectExpression: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] } }, additionalProperties: false @@ -142,7 +180,12 @@ module.exports = { FunctionExpression: { parameters: DEFAULT_PARAMETER_INDENT, body: DEFAULT_FUNCTION_BODY_INDENT - } + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT + }, + ArrayExpression: 1, + ObjectExpression: 1 }; const sourceCode = context.getSourceCode(); @@ -187,6 +230,18 @@ module.exports = { if (typeof opts.FunctionExpression === "object") { Object.assign(options.FunctionExpression, opts.FunctionExpression); } + + if (typeof opts.CallExpression === "object") { + Object.assign(options.CallExpression, opts.CallExpression); + } + + if (typeof opts.ArrayExpression === "number" || typeof opts.ArrayExpression === "string") { + options.ArrayExpression = opts.ArrayExpression; + } + + if (typeof opts.ObjectExpression === "number" || typeof opts.ObjectExpression === "string") { + options.ObjectExpression = opts.ObjectExpression; + } } } @@ -229,10 +284,10 @@ module.exports = { * @param {int} gottenTabs Indentation tab count in the actual node/code * @param {Object=} loc Error line and column location * @param {boolean} isLastNodeCheck Is the error for last node check + * @param {int} lastNodeCheckEndOffset Number of charecters to skip from the end * @returns {void} */ function report(node, needed, gottenSpaces, gottenTabs, loc, isLastNodeCheck) { - if (gottenSpaces && gottenTabs) { // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs. @@ -242,8 +297,8 @@ module.exports = { const desiredIndent = (indentType === "space" ? " " : "\t").repeat(needed); const textRange = isLastNodeCheck - ? [node.range[1] - gottenSpaces - gottenTabs - 1, node.range[1] - 1] - : [node.range[0] - gottenSpaces - gottenTabs, node.range[0]]; + ? [node.range[1] - node.loc.end.column, node.range[1] - node.loc.end.column + gottenSpaces + gottenTabs] + : [node.range[0] - node.loc.start.column, node.range[0] - node.loc.start.column + gottenSpaces + gottenTabs]; context.report({ node, @@ -319,6 +374,24 @@ module.exports = { checkNodeIndent(node.alternate, neededIndent); } } + + if (node.type === "TryStatement" && node.handler) { + const catchToken = sourceCode.getFirstToken(node.handler); + + checkNodeIndent(catchToken, neededIndent); + } + + if (node.type === "TryStatement" && node.finalizer) { + const finallyToken = sourceCode.getTokenBefore(node.finalizer); + + checkNodeIndent(finallyToken, neededIndent); + } + + if (node.type === "DoWhileStatement") { + const whileToken = sourceCode.getTokenAfter(node.body); + + checkNodeIndent(whileToken, neededIndent); + } } /** @@ -354,6 +427,45 @@ module.exports = { } } + /** + * Check last node line indent this detects, that block closed correctly + * This function for more complicated return statement case, where closing parenthesis may be followed by ';' + * @param {ASTNode} node Node to examine + * @param {int} firstLineIndent first line needed indent + * @returns {void} + */ + function checkLastReturnStatementLineIndent(node, firstLineIndent) { + const nodeLastToken = sourceCode.getLastToken(node); + let lastToken = nodeLastToken; + + // in case if return statement ends with ');' we have traverse back to ')' + // otherwise we'll measure indent for ';' and replace ')' + while (lastToken.value !== ")") { + lastToken = sourceCode.getTokenBefore(lastToken); + } + + const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1); + + if (textBeforeClosingParenthesis.trim()) { + + // There are tokens before the closing paren, don't report this case + return; + } + + const endIndent = getNodeIndent(lastToken, true); + + if (endIndent.goodChar !== firstLineIndent) { + report( + node, + firstLineIndent, + endIndent.space, + endIndent.tab, + { line: lastToken.loc.start.line, column: lastToken.loc.start.column }, + true + ); + } + } + /** * Check first node line indent is correct * @param {ASTNode} node Node to examine @@ -379,12 +491,17 @@ module.exports = { * if not present then return null * @param {ASTNode} node node to examine * @param {string} type type that is being looked for + * @param {string} stopAtList end points for the evaluating code * @returns {ASTNode|void} if found then node otherwise null */ - function getParentNodeByType(node, type) { + function getParentNodeByType(node, type, stopAtList) { let parent = node.parent; - while (parent.type !== type && parent.type !== "Program") { + if (!stopAtList) { + stopAtList = ["Program"]; + } + + while (parent.type !== type && stopAtList.indexOf(parent.type) === -1 && parent.type !== "Program") { parent = parent.parent; } @@ -401,16 +518,6 @@ module.exports = { return getParentNodeByType(node, "VariableDeclarator"); } - /** - * Returns the ExpressionStatement based on the current node - * if not present then return null - * @param {ASTNode} node node to examine - * @returns {ASTNode|void} if found then node otherwise null - */ - function getAssignmentExpressionNode(node) { - return getParentNodeByType(node, "AssignmentExpression"); - } - /** * Check to see if the node is part of the multi-line variable declaration. * Also if its on the same line as the varNode @@ -604,14 +711,7 @@ module.exports = { let elements = (node.type === "ArrayExpression") ? node.elements : node.properties; // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null - elements = elements.filter(function(elem) { - return elem !== null; - }); - - // Skip if first element is in same line with this node - if (elements.length > 0 && elements[0].loc.start.line === node.loc.start.line) { - return; - } + elements = elements.filter(elem => elem !== null); let nodeIndent; let elementsIndent; @@ -620,41 +720,59 @@ module.exports = { // TODO - come up with a better strategy in future if (isNodeFirstInLine(node)) { const parent = node.parent; - let effectiveParent = parent; - if (parent.type === "MemberExpression") { - if (isNodeFirstInLine(parent)) { - effectiveParent = parent.parent.parent; - } else { - effectiveParent = parent.parent; - } - } - nodeIndent = getNodeIndent(effectiveParent).goodChar; - if (parentVarNode && parentVarNode.loc.start.line !== node.loc.start.line) { + nodeIndent = getNodeIndent(parent).goodChar; + if (!parentVarNode || parentVarNode.loc.start.line !== node.loc.start.line) { if (parent.type !== "VariableDeclarator" || parentVarNode === parentVarNode.parent.declarations[0]) { - if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === effectiveParent.loc.start.line) { + if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === parent.loc.start.line) { nodeIndent = nodeIndent + (indentSize * options.VariableDeclarator[parentVarNode.parent.kind]); - } else if ( - parent.type === "ObjectExpression" || - parent.type === "ArrayExpression" || - parent.type === "CallExpression" || - parent.type === "ArrowFunctionExpression" || - parent.type === "NewExpression" || - parent.type === "LogicalExpression" - ) { - nodeIndent = nodeIndent + indentSize; + } else if (parent.type === "ObjectExpression" || parent.type === "ArrayExpression") { + const parentElements = node.parent.type === "ObjectExpression" ? node.parent.properties : node.parent.elements; + + if (parentElements[0].loc.start.line === parent.loc.start.line && parentElements[0].loc.end.line !== parent.loc.start.line) { + + /* + * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest. + * e.g. [{ + * foo: 1 + * }, + * { + * bar: 1 + * }] + * the second object is not indented. + */ + } else if (typeof options[parent.type] === "number") { + nodeIndent += options[parent.type] * indentSize; + } else { + nodeIndent = parentElements[0].loc.start.column; + } + } else if (parent.type === "CallExpression" || parent.type === "NewExpression") { + if (typeof options.CallExpression.arguments === "number") { + nodeIndent += options.CallExpression.arguments * indentSize; + } else if (options.CallExpression.arguments === "first") { + if (parent.arguments.indexOf(node) !== -1) { + nodeIndent = parent.arguments[0].loc.start.column; + } + } else { + nodeIndent += indentSize; + } + } else if (parent.type === "LogicalExpression" || parent.type === "ArrowFunctionExpression") { + nodeIndent += indentSize; } } - } else if (!parentVarNode && !isFirstArrayElementOnSameLine(parent) && effectiveParent.type !== "MemberExpression" && effectiveParent.type !== "ExpressionStatement" && effectiveParent.type !== "AssignmentExpression" && effectiveParent.type !== "Property") { + } else if (!parentVarNode && !isFirstArrayElementOnSameLine(parent) && parent.type !== "MemberExpression" && parent.type !== "ExpressionStatement" && parent.type !== "AssignmentExpression" && parent.type !== "Property") { nodeIndent = nodeIndent + indentSize; } - elementsIndent = nodeIndent + indentSize; - checkFirstNodeLineIndent(node, nodeIndent); } else { nodeIndent = getNodeIndent(node).goodChar; - elementsIndent = nodeIndent + indentSize; + } + + if (options[node.type] === "first") { + elementsIndent = elements.length ? elements[0].loc.start.column : 0; // If there are no elements, elementsIndent doesn't matter. + } else { + elementsIndent = nodeIndent + indentSize * options[node.type]; } /* @@ -675,7 +793,7 @@ module.exports = { } } - checkLastNodeLineIndent(node, elementsIndent - indentSize); + checkLastNodeLineIndent(node, nodeIndent + (isNodeInVarOnTop(node, parentVarNode) ? options.VariableDeclarator[parentVarNode.parent.kind] * indentSize : 0)); } /** @@ -717,11 +835,13 @@ module.exports = { * not from the beginning of the block. */ const statementsWithProperties = [ - "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration" + "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement" ]; if (node.parent && statementsWithProperties.indexOf(node.parent.type) !== -1 && isNodeBodyBlock(node)) { indent = getNodeIndent(node.parent).goodChar; + } else if (node.parent && node.parent.type === "CatchClause") { + indent = getNodeIndent(node.parent.parent).goodChar; } else { indent = getNodeIndent(node).goodChar; } @@ -750,7 +870,7 @@ module.exports = { * @returns {ASTNode[]} Filtered elements */ function filterOutSameLineVars(node) { - return node.declarations.reduce(function(finalCollection, elem) { + return node.declarations.reduce((finalCollection, elem) => { const lastElem = finalCollection[finalCollection.length - 1]; if ((elem.loc.start.line !== node.loc.start.line && !lastElem) || @@ -832,6 +952,20 @@ module.exports = { } } + /** + * Checks wether a return statement is wrapped in () + * @param {ASTNode} node node to examine + * @returns {boolean} the result + */ + function isWrappedInParenthesis(node) { + const regex = /^return\s*?\(\s*?\);*?/; + + const statementWithoutArgument = sourceCode.getText(node).replace( + sourceCode.getText(node.argument), ""); + + return regex.test(statementWithoutArgument); + } + return { Program(node) { if (node.body.length > 0) { @@ -876,6 +1010,7 @@ module.exports = { }, MemberExpression(node) { + if (typeof options.MemberExpression === "undefined") { return; } @@ -888,11 +1023,11 @@ module.exports = { // alter the expectation of correct indentation. Skip them. // TODO: Add appropriate configuration options for variable // declarations and assignments. - if (getVariableDeclaratorNode(node)) { + if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) { return; } - if (getAssignmentExpressionNode(node)) { + if (getParentNodeByType(node, "AssignmentExpression", ["FunctionExpression"])) { return; } @@ -952,7 +1087,34 @@ module.exports = { } else if (options.FunctionExpression.parameters !== null) { checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionExpression.parameters); } + }, + + ReturnStatement(node) { + if (isSingleLineNode(node)) { + return; + } + + const firstLineIndent = getNodeIndent(node).goodChar; + + // in case if return statement is wrapped in parenthesis + if (isWrappedInParenthesis(node)) { + checkLastReturnStatementLineIndent(node, firstLineIndent); + } else { + checkNodeIndent(node, firstLineIndent); + } + }, + + CallExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if (options.CallExpression.arguments === "first" && node.arguments.length) { + checkNodesIndent(node.arguments.slice(1), node.arguments[0].loc.start.column); + } else if (options.CallExpression.arguments !== null) { + checkNodesIndent(node.arguments, getNodeIndent(node).goodChar + indentSize * options.CallExpression.arguments); + } } + }; } diff --git a/tools/eslint/lib/rules/jsx-quotes.js b/tools/eslint/lib/rules/jsx-quotes.js index 2b6a57b961d88f..5653922d9495d5 100644 --- a/tools/eslint/lib/rules/jsx-quotes.js +++ b/tools/eslint/lib/rules/jsx-quotes.js @@ -48,7 +48,7 @@ module.exports = { schema: [ { - enum: [ "prefer-single", "prefer-double" ] + enum: ["prefer-single", "prefer-double"] } ] }, diff --git a/tools/eslint/lib/rules/key-spacing.js b/tools/eslint/lib/rules/key-spacing.js index b195d31d32a4ee..8d7564a5bbf246 100644 --- a/tools/eslint/lib/rules/key-spacing.js +++ b/tools/eslint/lib/rules/key-spacing.js @@ -417,8 +417,8 @@ module.exports = { function report(property, side, whitespace, expected, mode) { const diff = whitespace.length - expected, nextColon = getNextColon(property.key), - tokenBeforeColon = sourceCode.getTokenBefore(nextColon), - tokenAfterColon = sourceCode.getTokenAfter(nextColon), + tokenBeforeColon = sourceCode.getTokenOrCommentBefore(nextColon), + tokenAfterColon = sourceCode.getTokenOrCommentAfter(nextColon), isKeySide = side === "key", locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start, isExtra = diff > 0, @@ -514,7 +514,7 @@ module.exports = { return [node.properties]; } - return node.properties.reduce(function(groups, property) { + return node.properties.reduce((groups, property) => { const currentGroup = last(groups), prev = last(currentGroup); @@ -579,7 +579,7 @@ module.exports = { * @returns {void} */ function verifyAlignment(node) { - createGroups(node).forEach(function(group) { + createGroups(node).forEach(group => { verifyGroupAlignment(group.filter(isKeyValueProperty)); }); } diff --git a/tools/eslint/lib/rules/keyword-spacing.js b/tools/eslint/lib/rules/keyword-spacing.js index 4a6a024552111c..1dfc291f6e827b 100644 --- a/tools/eslint/lib/rules/keyword-spacing.js +++ b/tools/eslint/lib/rules/keyword-spacing.js @@ -16,10 +16,10 @@ const astUtils = require("../ast-utils"), // Constants //------------------------------------------------------------------------------ -const PREV_TOKEN = /^[\)\]\}>]$/; -const NEXT_TOKEN = /^(?:[\(\[\{<~!]|\+\+?|--?)$/; -const PREV_TOKEN_M = /^[\)\]\}>*]$/; -const NEXT_TOKEN_M = /^[\{*]$/; +const PREV_TOKEN = /^[)\]}>]$/; +const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/; +const PREV_TOKEN_M = /^[)\]}>*]$/; +const NEXT_TOKEN_M = /^[{*]$/; const TEMPLATE_OPEN_PAREN = /\$\{$/; const TEMPLATE_CLOSE_PAREN = /^\}/; const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/; @@ -77,16 +77,16 @@ module.exports = { { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"}, + before: { type: "boolean" }, + after: { type: "boolean" }, overrides: { type: "object", - properties: KEYS.reduce(function(retv, key) { + properties: KEYS.reduce((retv, key) => { retv[key] = { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"} + before: { type: "boolean" }, + after: { type: "boolean" } }, additionalProperties: false }; diff --git a/tools/eslint/lib/rules/lines-around-comment.js b/tools/eslint/lib/rules/lines-around-comment.js index 094fefa74f4646..83751cd6a50ad6 100644 --- a/tools/eslint/lib/rules/lines-around-comment.js +++ b/tools/eslint/lib/rules/lines-around-comment.js @@ -21,16 +21,10 @@ const lodash = require("lodash"), * @returns {Array} An array of line numbers. */ function getEmptyLineNums(lines) { - const emptyLines = lines.map(function(line, i) { - return { - code: line.trim(), - num: i + 1 - }; - }).filter(function(line) { - return !line.code; - }).map(function(line) { - return line.num; - }); + const emptyLines = lines.map((line, i) => ({ + code: line.trim(), + num: i + 1 + })).filter(line => !line.code).map(line => line.num); return emptyLines; } @@ -43,7 +37,7 @@ function getEmptyLineNums(lines) { function getCommentLineNums(comments) { const lines = []; - comments.forEach(function(token) { + comments.forEach(token => { const start = token.loc.start.line; const end = token.loc.end.line; diff --git a/tools/eslint/lib/rules/lines-around-directive.js b/tools/eslint/lib/rules/lines-around-directive.js index f0f0ebd0b9037b..b1e54e940b8f64 100644 --- a/tools/eslint/lib/rules/lines-around-directive.js +++ b/tools/eslint/lib/rules/lines-around-directive.js @@ -63,15 +63,32 @@ module.exports = { return node.loc.start.line - tokenLineBefore >= 2; } + /** + * Gets the last token of a node that is on the same line as the rest of the node. + * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing + * semicolon on a different line. + * @param {ASTNode} node A directive node + * @returns {Token} The last token of the node on the line + */ + function getLastTokenOnLine(node) { + const lastToken = sourceCode.getLastToken(node); + const secondToLastToken = sourceCode.getTokenBefore(lastToken); + + return lastToken.type === "Punctuator" && lastToken.value === ";" && lastToken.loc.start.line > secondToLastToken.loc.end.line + ? secondToLastToken + : lastToken; + } + /** * Check if node is followed by a blank newline. * @param {ASTNode} node Node to check. * @returns {boolean} Whether or not the passed in node is followed by a blank newline. */ function hasNewlineAfter(node) { - const tokenAfter = sourceCode.getTokenOrCommentAfter(node); + const lastToken = getLastTokenOnLine(node); + const tokenAfter = sourceCode.getTokenOrCommentAfter(lastToken); - return tokenAfter.loc.start.line - node.loc.end.line >= 2; + return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; } /** @@ -91,10 +108,12 @@ module.exports = { location }, fix(fixer) { + const lastToken = getLastTokenOnLine(node); + if (expected) { - return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(node, "\n"); + return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n"); } - return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [node.range[1], node.range[1] + 1]); + return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]); } }); } diff --git a/tools/eslint/lib/rules/max-depth.js b/tools/eslint/lib/rules/max-depth.js index 35b7e9ce8946de..74c13ffa9fad2e 100644 --- a/tools/eslint/lib/rules/max-depth.js +++ b/tools/eslint/lib/rules/max-depth.js @@ -91,8 +91,7 @@ module.exports = { const len = ++functionStack[functionStack.length - 1]; if (len > maxDepth) { - context.report(node, "Blocks are nested too deeply ({{depth}}).", - { depth: len }); + context.report({ node, message: "Blocks are nested too deeply ({{depth}}).", data: { depth: len } }); } } diff --git a/tools/eslint/lib/rules/max-len.js b/tools/eslint/lib/rules/max-len.js index d1f6df2996f9aa..dd5a4e1ef62553 100644 --- a/tools/eslint/lib/rules/max-len.js +++ b/tools/eslint/lib/rules/max-len.js @@ -39,6 +39,9 @@ const OPTIONS_SCHEMA = { ignoreTemplateLiterals: { type: "boolean" }, + ignoreRegExpLiterals: { + type: "boolean" + }, ignoreTrailingComments: { type: "boolean" } @@ -100,7 +103,7 @@ module.exports = { function computeLineLength(line, tabWidth) { let extraCharacterCount = 0; - line.replace(/\t/g, function(match, offset) { + line.replace(/\t/g, (match, offset) => { const totalOffset = offset + extraCharacterCount, previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, spaceCount = tabWidth - previousTabStopOffset; @@ -129,6 +132,7 @@ module.exports = { ignoreComments = options.ignoreComments || false, ignoreStrings = options.ignoreStrings || false, ignoreTemplateLiterals = options.ignoreTemplateLiterals || false, + ignoreRegExpLiterals = options.ignoreRegExpLiterals || false, ignoreTrailingComments = options.ignoreTrailingComments || options.ignoreComments || false, ignoreUrls = options.ignoreUrls || false, maxCommentLength = options.comments; @@ -209,9 +213,7 @@ module.exports = { * @returns {ASTNode[]} An array of string nodes. */ function getAllStrings() { - return sourceCode.ast.tokens.filter(function(token) { - return token.type === "String"; - }); + return sourceCode.ast.tokens.filter(token => token.type === "String"); } /** @@ -220,9 +222,17 @@ module.exports = { * @returns {ASTNode[]} An array of template literal nodes. */ function getAllTemplateLiterals() { - return sourceCode.ast.tokens.filter(function(token) { - return token.type === "Template"; - }); + return sourceCode.ast.tokens.filter(token => token.type === "Template"); + } + + + /** + * Retrieves an array containing all RegExp literals in the source code. + * + * @returns {ASTNode[]} An array of RegExp literal nodes. + */ + function getAllRegExpLiterals() { + return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression"); } @@ -264,7 +274,10 @@ module.exports = { const templateLiterals = getAllTemplateLiterals(sourceCode); const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); - lines.forEach(function(line, i) { + const regExpLiterals = getAllRegExpLiterals(sourceCode); + const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); + + lines.forEach((line, i) => { // i is zero-indexed, line numbers are one-indexed const lineNumber = i + 1; @@ -299,7 +312,8 @@ module.exports = { if (ignorePattern && ignorePattern.test(line) || ignoreUrls && URL_REGEXP.test(line) || ignoreStrings && stringsByLine[lineNumber] || - ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] + ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || + ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] ) { // ignore this line diff --git a/tools/eslint/lib/rules/max-lines.js b/tools/eslint/lib/rules/max-lines.js index a54ad9e3538dbc..08cf9f6084b2a1 100644 --- a/tools/eslint/lib/rules/max-lines.js +++ b/tools/eslint/lib/rules/max-lines.js @@ -114,26 +114,18 @@ module.exports = { return { "Program:exit"() { - let lines = sourceCode.lines.map(function(text, i) { - return { lineNumber: i + 1, text }; - }); + let lines = sourceCode.lines.map((text, i) => ({ lineNumber: i + 1, text })); if (skipBlankLines) { - lines = lines.filter(function(l) { - return l.text.trim() !== ""; - }); + lines = lines.filter(l => l.text.trim() !== ""); } if (skipComments) { const comments = sourceCode.getAllComments(); - const commentLines = lodash.flatten(comments.map(function(comment) { - return getLinesWithoutCode(comment); - })); + const commentLines = lodash.flatten(comments.map(comment => getLinesWithoutCode(comment))); - lines = lines.filter(function(l) { - return !lodash.includes(commentLines, l.lineNumber); - }); + lines = lines.filter(l => !lodash.includes(commentLines, l.lineNumber)); } if (lines.length > max) { diff --git a/tools/eslint/lib/rules/max-nested-callbacks.js b/tools/eslint/lib/rules/max-nested-callbacks.js index 7e0c3d24738862..a89f49ae02094e 100644 --- a/tools/eslint/lib/rules/max-nested-callbacks.js +++ b/tools/eslint/lib/rules/max-nested-callbacks.js @@ -81,9 +81,9 @@ module.exports = { } if (callbackStack.length > THRESHOLD) { - const opts = {num: callbackStack.length, max: THRESHOLD}; + const opts = { num: callbackStack.length, max: THRESHOLD }; - context.report(node, "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", opts); + context.report({ node, message: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", data: opts }); } } diff --git a/tools/eslint/lib/rules/max-params.js b/tools/eslint/lib/rules/max-params.js index fc84efcd40b285..bbf087092e5057 100644 --- a/tools/eslint/lib/rules/max-params.js +++ b/tools/eslint/lib/rules/max-params.js @@ -66,10 +66,10 @@ module.exports = { */ function checkFunction(node) { if (node.params.length > numParams) { - context.report(node, "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", { + context.report({ node, message: "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", data: { count: node.params.length, max: numParams - }); + } }); } } diff --git a/tools/eslint/lib/rules/max-statements.js b/tools/eslint/lib/rules/max-statements.js index 1232930c6e68f1..63d51fa571b7b0 100644 --- a/tools/eslint/lib/rules/max-statements.js +++ b/tools/eslint/lib/rules/max-statements.js @@ -84,10 +84,20 @@ module.exports = { */ function reportIfTooManyStatements(node, count, max) { if (count > max) { - context.report( + const messageEnd = " has too many statements ({{count}}). Maximum allowed is {{max}}."; + let name = "This function"; + + if (node.id) { + name = `Function '${node.id.name}'`; + } else if (node.parent.type === "MethodDefinition" || node.parent.type === "Property") { + name = `Function '${context.getSource(node.parent.key)}'`; + } + + context.report({ node, - "This function has too many statements ({{count}}). Maximum allowed is {{max}}.", - { count, max }); + message: name + messageEnd, + data: { count, max } + }); } } @@ -110,7 +120,7 @@ module.exports = { const count = functionStack.pop(); if (ignoreTopLevelFunctions && functionStack.length === 0) { - topLevelFunctions.push({ node, count}); + topLevelFunctions.push({ node, count }); } else { reportIfTooManyStatements(node, count, maxStatements); } @@ -146,7 +156,7 @@ module.exports = { return; } - topLevelFunctions.forEach(function(element) { + topLevelFunctions.forEach(element => { const count = element.count; const node = element.node; diff --git a/tools/eslint/lib/rules/new-cap.js b/tools/eslint/lib/rules/new-cap.js index 6fcd582a694d1a..e7f7f1ab893396 100644 --- a/tools/eslint/lib/rules/new-cap.js +++ b/tools/eslint/lib/rules/new-cap.js @@ -227,7 +227,7 @@ module.exports = { callee = callee.property; } - context.report(node, callee.loc.start, message); + context.report({ node, loc: callee.loc.start, message }); } //-------------------------------------------------------------------------- diff --git a/tools/eslint/lib/rules/new-parens.js b/tools/eslint/lib/rules/new-parens.js index 29f4b5c2082152..b0fc5ba97950b7 100644 --- a/tools/eslint/lib/rules/new-parens.js +++ b/tools/eslint/lib/rules/new-parens.js @@ -29,20 +29,6 @@ function isClosingParen(token) { return token.type === "Punctuator" && token.value === ")"; } -/** - * Checks whether the given node is inside of another given node. - * - * @param {ASTNode|Token} inner - The inner node to check. - * @param {ASTNode|Token} outer - The outer node to check. - * @returns {boolean} `true` if the `inner` is in `outer`. - */ -function isInRange(inner, outer) { - const ir = inner.range; - const or = outer.range; - - return or[0] <= ir[0] && ir[1] <= or[1]; -} - //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -65,14 +51,15 @@ module.exports = { return { NewExpression(node) { - let token = sourceCode.getTokenAfter(node.callee); - - // Skip ')' - while (token && isClosingParen(token)) { - token = sourceCode.getTokenAfter(token); + if (node.arguments.length !== 0) { + return; // shortcut: if there are arguments, there have to be parens } - if (!(token && isOpeningParen(token) && isInRange(token, node))) { + const lastToken = sourceCode.getLastToken(node); + const hasLastParen = lastToken && isClosingParen(lastToken); + const hasParens = hasLastParen && isOpeningParen(sourceCode.getTokenBefore(lastToken)); + + if (!hasParens) { context.report({ node, message: "Missing '()' invoking a constructor.", diff --git a/tools/eslint/lib/rules/newline-after-var.js b/tools/eslint/lib/rules/newline-after-var.js index 440652b1c10696..51130e23db9ffe 100644 --- a/tools/eslint/lib/rules/newline-after-var.js +++ b/tools/eslint/lib/rules/newline-after-var.js @@ -21,7 +21,9 @@ module.exports = { { enum: ["never", "always"] } - ] + ], + + fixable: "whitespace" }, create(context) { @@ -35,7 +37,7 @@ module.exports = { const mode = context.options[0] === "never" ? "never" : "always"; // Cache starting and ending line numbers of comments for faster lookup - const commentEndLine = sourceCode.getAllComments().reduce(function(result, token) { + const commentEndLine = sourceCode.getAllComments().reduce((result, token) => { result[token.loc.start.line] = token.loc.end.line; return result; }, {}); @@ -119,6 +121,17 @@ module.exports = { return !token || (token.type === "Punctuator" && token.value === "}"); } + /** + * Gets the last line of a group of consecutive comments + * @param {number} commentStartLine The starting line of the group + * @returns {number} The number of the last comment line of the group + */ + function getLastCommentLineOfBlock(commentStartLine) { + const currentCommentEnd = commentEndLine[commentStartLine]; + + return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd; + } + /** * Determine if a token starts more than one line after a comment ends * @param {token} token The token being checked @@ -126,14 +139,7 @@ module.exports = { * @returns {boolean} True if `token` does not start immediately after a comment */ function hasBlankLineAfterComment(token, commentStartLine) { - const commentEnd = commentEndLine[commentStartLine]; - - // If there's another comment, repeat check for blank line - if (commentEndLine[commentEnd + 1]) { - return hasBlankLineAfterComment(token, commentEnd + 1); - } - - return (token.loc.start.line > commentEndLine[commentStartLine] + 1); + return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1; } /** @@ -145,8 +151,18 @@ module.exports = { * @returns {void} */ function checkForBlankLine(node) { + + /* + * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will + * sometimes be second-last if there is a semicolon on a different line. + */ const lastToken = getLastToken(node), - nextToken = sourceCode.getTokenAfter(node), + + /* + * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken + * is the last token of the node. + */ + nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node), nextLineNum = lastToken.loc.end.line + 1; // Ignore if there is no following statement @@ -180,7 +196,17 @@ module.exports = { const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined"); if (mode === "never" && noNextLineToken && !hasNextLineComment) { - context.report(node, NEVER_MESSAGE, { identifier: node.name }); + context.report({ + node, + message: NEVER_MESSAGE, + data: { identifier: node.name }, + fix(fixer) { + const NEWLINE_REGEX = /\r\n|\r|\n|\u2028|\u2029/; + const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(NEWLINE_REGEX); + + return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`); + } + }); } // Token on the next line, or comment without blank line @@ -190,7 +216,18 @@ module.exports = { hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum) ) ) { - context.report(node, ALWAYS_MESSAGE, { identifier: node.name }); + context.report({ + node, + message: ALWAYS_MESSAGE, + data: { identifier: node.name }, + fix(fixer) { + if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) { + return fixer.insertTextBefore(nextToken, "\n\n"); + } + + return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n"); + } + }); } } diff --git a/tools/eslint/lib/rules/newline-before-return.js b/tools/eslint/lib/rules/newline-before-return.js index 7d297fd0035313..e8cd74b2c7b728 100644 --- a/tools/eslint/lib/rules/newline-before-return.js +++ b/tools/eslint/lib/rules/newline-before-return.js @@ -36,9 +36,7 @@ module.exports = { function isPrecededByTokens(node, testTokens) { const tokenBefore = sourceCode.getTokenBefore(node); - return testTokens.some(function(token) { - return tokenBefore.value === token; - }); + return testTokens.some(token => tokenBefore.value === token); } /** @@ -82,7 +80,7 @@ module.exports = { return numLinesComments; } - comments.forEach(function(comment) { + comments.forEach(comment => { numLinesComments++; if (comment.type === "Block") { diff --git a/tools/eslint/lib/rules/no-alert.js b/tools/eslint/lib/rules/no-alert.js index 96b5d64c6c4e6b..f2cfc3a87762d2 100644 --- a/tools/eslint/lib/rules/no-alert.js +++ b/tools/eslint/lib/rules/no-alert.js @@ -41,10 +41,8 @@ function report(context, node, identifierName) { * @returns {Reference|null} Returns the found reference or null if none were found. */ function findReference(scope, node) { - const references = scope.references.filter(function(reference) { - return reference.identifier.range[0] === node.range[0] && - reference.identifier.range[1] === node.range[1]; - }); + const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1]); if (references.length === 1) { return references[0]; diff --git a/tools/eslint/lib/rules/no-array-constructor.js b/tools/eslint/lib/rules/no-array-constructor.js index 2c29217d720fcc..70dc8b4cd5ded8 100644 --- a/tools/eslint/lib/rules/no-array-constructor.js +++ b/tools/eslint/lib/rules/no-array-constructor.js @@ -34,7 +34,7 @@ module.exports = { node.callee.type === "Identifier" && node.callee.name === "Array" ) { - context.report(node, "The array literal notation [] is preferrable."); + context.report({ node, message: "The array literal notation [] is preferrable." }); } } diff --git a/tools/eslint/lib/rules/no-await-in-loop.js b/tools/eslint/lib/rules/no-await-in-loop.js new file mode 100644 index 00000000000000..a75f7f2934bc23 --- /dev/null +++ b/tools/eslint/lib/rules/no-await-in-loop.js @@ -0,0 +1,75 @@ +/** + * @fileoverview Rule to disallow uses of await inside of loops. + * @author Nat Mote (nmote) + */ +"use strict"; + +// Node types which are considered loops. +const loopTypes = new Set([ + "ForStatement", + "ForOfStatement", + "ForInStatement", + "WhileStatement", + "DoWhileStatement", +]); + +// Node types at which we should stop looking for loops. For example, it is fine to declare an async +// function within a loop, and use await inside of that. +const boundaryTypes = new Set([ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", +]); + +module.exports = { + meta: { + docs: { + description: "disallow `await` inside of loops", + category: "Possible Errors", + recommended: false, + }, + schema: [], + }, + create(context) { + return { + AwaitExpression(node) { + const ancestors = context.getAncestors(); + + // Reverse so that we can traverse from the deepest node upwards. + ancestors.reverse(); + + // Create a set of all the ancestors plus this node so that we can check + // if this use of await appears in the body of the loop as opposed to + // the right-hand side of a for...of, for example. + const ancestorSet = new Set(ancestors).add(node); + + for (let i = 0; i < ancestors.length; i++) { + const ancestor = ancestors[i]; + + if (boundaryTypes.has(ancestor.type)) { + + // Short-circuit out if we encounter a boundary type. Loops above + // this do not matter. + return; + } + if (loopTypes.has(ancestor.type)) { + + // Only report if we are actually in the body or another part that gets executed on + // every iteration. + if ( + ancestorSet.has(ancestor.body) || + ancestorSet.has(ancestor.test) || + ancestorSet.has(ancestor.update) + ) { + context.report({ + node, + message: "Unexpected `await` inside a loop." + }); + return; + } + } + } + }, + }; + } +}; diff --git a/tools/eslint/lib/rules/no-bitwise.js b/tools/eslint/lib/rules/no-bitwise.js index 2c6456912f70f8..28028028cae090 100644 --- a/tools/eslint/lib/rules/no-bitwise.js +++ b/tools/eslint/lib/rules/no-bitwise.js @@ -57,7 +57,7 @@ module.exports = { * @returns {void} */ function report(node) { - context.report(node, "Unexpected use of '{{operator}}'.", { operator: node.operator }); + context.report({ node, message: "Unexpected use of '{{operator}}'.", data: { operator: node.operator } }); } /** diff --git a/tools/eslint/lib/rules/no-caller.js b/tools/eslint/lib/rules/no-caller.js index 16c5fa414b0cb8..55a37b7d86406a 100644 --- a/tools/eslint/lib/rules/no-caller.js +++ b/tools/eslint/lib/rules/no-caller.js @@ -29,7 +29,7 @@ module.exports = { propertyName = node.property.name; if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/)) { - context.report(node, "Avoid arguments.{{property}}.", { property: propertyName }); + context.report({ node, message: "Avoid arguments.{{property}}.", data: { property: propertyName } }); } } diff --git a/tools/eslint/lib/rules/no-catch-shadow.js b/tools/eslint/lib/rules/no-catch-shadow.js index 7f2523333239a7..7cffae3b99d758 100644 --- a/tools/eslint/lib/rules/no-catch-shadow.js +++ b/tools/eslint/lib/rules/no-catch-shadow.js @@ -58,8 +58,7 @@ module.exports = { } if (paramIsShadowing(scope, node.param.name)) { - context.report(node, "Value of '{{name}}' may be overwritten in IE 8 and earlier.", - { name: node.param.name }); + context.report({ node, message: "Value of '{{name}}' may be overwritten in IE 8 and earlier.", data: { name: node.param.name } }); } } }; diff --git a/tools/eslint/lib/rules/no-class-assign.js b/tools/eslint/lib/rules/no-class-assign.js index cbd4b1da81fe42..4b0443abc72858 100644 --- a/tools/eslint/lib/rules/no-class-assign.js +++ b/tools/eslint/lib/rules/no-class-assign.js @@ -30,11 +30,8 @@ module.exports = { * @returns {void} */ function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(function(reference) { - context.report( - reference.identifier, - "'{{name}}' is a class.", - {name: reference.identifier.name}); + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, message: "'{{name}}' is a class.", data: { name: reference.identifier.name } }); }); } diff --git a/tools/eslint/lib/rules/no-cond-assign.js b/tools/eslint/lib/rules/no-cond-assign.js index 2d66f55a5ba77b..3e94d12a539942 100644 --- a/tools/eslint/lib/rules/no-cond-assign.js +++ b/tools/eslint/lib/rules/no-cond-assign.js @@ -125,9 +125,9 @@ module.exports = { const ancestor = findConditionalAncestor(node); if (ancestor) { - context.report(ancestor, "Unexpected assignment within {{type}}.", { + context.report({ node: ancestor, message: "Unexpected assignment within {{type}}.", data: { type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type - }); + } }); } } diff --git a/tools/eslint/lib/rules/no-confusing-arrow.js b/tools/eslint/lib/rules/no-confusing-arrow.js index 5e1b051423d674..d6edbcc810e4fb 100644 --- a/tools/eslint/lib/rules/no-confusing-arrow.js +++ b/tools/eslint/lib/rules/no-confusing-arrow.js @@ -36,7 +36,7 @@ module.exports = { schema: [{ type: "object", properties: { - allowParens: {type: "boolean"} + allowParens: { type: "boolean" } }, additionalProperties: false }] @@ -55,7 +55,7 @@ module.exports = { const body = node.body; if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) { - context.report(node, "Arrow function used ambiguously with a conditional expression."); + context.report({ node, message: "Arrow function used ambiguously with a conditional expression." }); } } diff --git a/tools/eslint/lib/rules/no-const-assign.js b/tools/eslint/lib/rules/no-const-assign.js index 232e9446fd7955..db1848a9819f00 100644 --- a/tools/eslint/lib/rules/no-const-assign.js +++ b/tools/eslint/lib/rules/no-const-assign.js @@ -30,11 +30,8 @@ module.exports = { * @returns {void} */ function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(function(reference) { - context.report( - reference.identifier, - "'{{name}}' is constant.", - {name: reference.identifier.name}); + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, message: "'{{name}}' is constant.", data: { name: reference.identifier.name } }); }); } diff --git a/tools/eslint/lib/rules/no-constant-condition.js b/tools/eslint/lib/rules/no-constant-condition.js index f78ddbc2e972b0..7178d5dbecc10e 100644 --- a/tools/eslint/lib/rules/no-constant-condition.js +++ b/tools/eslint/lib/rules/no-constant-condition.js @@ -122,7 +122,7 @@ module.exports = { */ function checkConstantCondition(node) { if (node.test && isConstant(node.test, true)) { - context.report(node, "Unexpected constant condition."); + context.report({ node, message: "Unexpected constant condition." }); } } diff --git a/tools/eslint/lib/rules/no-continue.js b/tools/eslint/lib/rules/no-continue.js index b8956da4b75025..2615fba13e2401 100644 --- a/tools/eslint/lib/rules/no-continue.js +++ b/tools/eslint/lib/rules/no-continue.js @@ -24,7 +24,7 @@ module.exports = { return { ContinueStatement(node) { - context.report(node, "Unexpected use of continue statement."); + context.report({ node, message: "Unexpected use of continue statement." }); } }; diff --git a/tools/eslint/lib/rules/no-control-regex.js b/tools/eslint/lib/rules/no-control-regex.js index 466f5666ac181f..1ebf9800009371 100644 --- a/tools/eslint/lib/rules/no-control-regex.js +++ b/tools/eslint/lib/rules/no-control-regex.js @@ -85,7 +85,7 @@ module.exports = { stringControlChars = regexStr.slice(subStrIndex, -1) .split(consecutiveSlashes) .filter(Boolean) - .map(function(x) { + .map(x => { const match = x.match(stringControlCharWithoutSlash) || [x]; return `\\${match[0]}`; @@ -93,7 +93,7 @@ module.exports = { } } - return controlChars.map(function(x) { + return controlChars.map(x => { const hexCode = `0${x.charCodeAt(0).toString(16)}`.slice(-2); return `\\x${hexCode}`; diff --git a/tools/eslint/lib/rules/no-debugger.js b/tools/eslint/lib/rules/no-debugger.js index 6356d5269b61f1..897b3dbb6094f9 100644 --- a/tools/eslint/lib/rules/no-debugger.js +++ b/tools/eslint/lib/rules/no-debugger.js @@ -24,7 +24,7 @@ module.exports = { return { DebuggerStatement(node) { - context.report(node, "Unexpected 'debugger' statement."); + context.report({ node, message: "Unexpected 'debugger' statement." }); } }; diff --git a/tools/eslint/lib/rules/no-delete-var.js b/tools/eslint/lib/rules/no-delete-var.js index dce202dc834c7e..adc1b5bb9c2c01 100644 --- a/tools/eslint/lib/rules/no-delete-var.js +++ b/tools/eslint/lib/rules/no-delete-var.js @@ -26,7 +26,7 @@ module.exports = { UnaryExpression(node) { if (node.operator === "delete" && node.argument.type === "Identifier") { - context.report(node, "Variables should not be deleted."); + context.report({ node, message: "Variables should not be deleted." }); } } }; diff --git a/tools/eslint/lib/rules/no-div-regex.js b/tools/eslint/lib/rules/no-div-regex.js index c5ffa7ce7e2e7a..84a9b9a3aaa9a6 100644 --- a/tools/eslint/lib/rules/no-div-regex.js +++ b/tools/eslint/lib/rules/no-div-regex.js @@ -29,7 +29,7 @@ module.exports = { const token = sourceCode.getFirstToken(node); if (token.type === "RegularExpression" && token.value[1] === "=") { - context.report(node, "A regular expression literal can be confused with '/='."); + context.report({ node, message: "A regular expression literal can be confused with '/='." }); } } }; diff --git a/tools/eslint/lib/rules/no-dupe-args.js b/tools/eslint/lib/rules/no-dupe-args.js index 0d420eb92aaaf9..cdb38035c0a01f 100644 --- a/tools/eslint/lib/rules/no-dupe-args.js +++ b/tools/eslint/lib/rules/no-dupe-args.js @@ -54,7 +54,7 @@ module.exports = { context.report({ node, message: "Duplicate param '{{name}}'.", - data: {name: variable.name} + data: { name: variable.name } }); } } diff --git a/tools/eslint/lib/rules/no-dupe-class-members.js b/tools/eslint/lib/rules/no-dupe-class-members.js index 3b857a67fb9e65..07b999fab19bb9 100644 --- a/tools/eslint/lib/rules/no-dupe-class-members.js +++ b/tools/eslint/lib/rules/no-dupe-class-members.js @@ -38,8 +38,8 @@ module.exports = { if (!stateMap[key]) { stateMap[key] = { - nonStatic: {init: false, get: false, set: false}, - static: {init: false, get: false, set: false} + nonStatic: { init: false, get: false, set: false }, + static: { init: false, get: false, set: false } }; } @@ -101,7 +101,7 @@ module.exports = { } if (isDuplicate) { - context.report(node, "Duplicate name '{{name}}'.", {name}); + context.report({ node, message: "Duplicate name '{{name}}'.", data: { name } }); } } }; diff --git a/tools/eslint/lib/rules/no-dupe-keys.js b/tools/eslint/lib/rules/no-dupe-keys.js index f34c323f1ed491..f056b1fcbeb43e 100644 --- a/tools/eslint/lib/rules/no-dupe-keys.js +++ b/tools/eslint/lib/rules/no-dupe-keys.js @@ -42,7 +42,7 @@ class ObjectInfo { const name = astUtils.getStaticPropertyName(node); if (!this.properties.has(name)) { - this.properties.set(name, {get: false, set: false}); + this.properties.set(name, { get: false, set: false }); } return this.properties.get(name); } @@ -123,7 +123,7 @@ module.exports = { node: info.node, loc: node.key.loc, message: "Duplicate key '{{name}}'.", - data: {name}, + data: { name }, }); } diff --git a/tools/eslint/lib/rules/no-duplicate-case.js b/tools/eslint/lib/rules/no-duplicate-case.js index 5b20fc3d582980..07823f284c1c3d 100644 --- a/tools/eslint/lib/rules/no-duplicate-case.js +++ b/tools/eslint/lib/rules/no-duplicate-case.js @@ -28,11 +28,11 @@ module.exports = { SwitchStatement(node) { const mapping = {}; - node.cases.forEach(function(switchCase) { + node.cases.forEach(switchCase => { const key = sourceCode.getText(switchCase.test); if (mapping[key]) { - context.report(switchCase, "Duplicate case label."); + context.report({ node: switchCase, message: "Duplicate case label." }); } else { mapping[key] = switchCase; } diff --git a/tools/eslint/lib/rules/no-else-return.js b/tools/eslint/lib/rules/no-else-return.js index 07b596238caf2b..43564346b043e2 100644 --- a/tools/eslint/lib/rules/no-else-return.js +++ b/tools/eslint/lib/rules/no-else-return.js @@ -33,7 +33,7 @@ module.exports = { * @returns {void} */ function displayReport(node) { - context.report(node, "Unnecessary 'else' after 'return'."); + context.report({ node, message: "Unnecessary 'else' after 'return'." }); } /** diff --git a/tools/eslint/lib/rules/no-empty-character-class.js b/tools/eslint/lib/rules/no-empty-character-class.js index 723cebc9450f00..f36c6c9f0d8b19 100644 --- a/tools/eslint/lib/rules/no-empty-character-class.js +++ b/tools/eslint/lib/rules/no-empty-character-class.js @@ -21,7 +21,7 @@ plain-English description of the following regexp: 4. `[gimuy]*`: optional regexp flags 5. `$`: fix the match at the end of the string */ -const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimuy]*$/; +const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+])*\/[gimuy]*$/; //------------------------------------------------------------------------------ // Rule Definition @@ -47,7 +47,7 @@ module.exports = { const token = sourceCode.getFirstToken(node); if (token.type === "RegularExpression" && !regex.test(token.value)) { - context.report(node, "Empty class."); + context.report({ node, message: "Empty class." }); } } diff --git a/tools/eslint/lib/rules/no-empty-function.js b/tools/eslint/lib/rules/no-empty-function.js index 8299f40685ca52..65f9c9e1515342 100644 --- a/tools/eslint/lib/rules/no-empty-function.js +++ b/tools/eslint/lib/rules/no-empty-function.js @@ -108,7 +108,7 @@ module.exports = { properties: { allow: { type: "array", - items: {enum: ALLOW_OPTIONS}, + items: { enum: ALLOW_OPTIONS }, uniqueItems: true } }, diff --git a/tools/eslint/lib/rules/no-empty-pattern.js b/tools/eslint/lib/rules/no-empty-pattern.js index 77302fc8d73f9d..11f50b54142e04 100644 --- a/tools/eslint/lib/rules/no-empty-pattern.js +++ b/tools/eslint/lib/rules/no-empty-pattern.js @@ -23,12 +23,12 @@ module.exports = { return { ObjectPattern(node) { if (node.properties.length === 0) { - context.report(node, "Unexpected empty object pattern."); + context.report({ node, message: "Unexpected empty object pattern." }); } }, ArrayPattern(node) { if (node.elements.length === 0) { - context.report(node, "Unexpected empty array pattern."); + context.report({ node, message: "Unexpected empty array pattern." }); } } }; diff --git a/tools/eslint/lib/rules/no-empty.js b/tools/eslint/lib/rules/no-empty.js index 8514b9cf89d0c8..a9b0776c933b07 100644 --- a/tools/eslint/lib/rules/no-empty.js +++ b/tools/eslint/lib/rules/no-empty.js @@ -63,13 +63,13 @@ module.exports = { return; } - context.report(node, "Empty block statement."); + context.report({ node, message: "Empty block statement." }); }, SwitchStatement(node) { if (typeof node.cases === "undefined" || node.cases.length === 0) { - context.report(node, "Empty switch statement."); + context.report({ node, message: "Empty switch statement." }); } } }; diff --git a/tools/eslint/lib/rules/no-eq-null.js b/tools/eslint/lib/rules/no-eq-null.js index 62215d05f1b0eb..7e915a8c726f9f 100644 --- a/tools/eslint/lib/rules/no-eq-null.js +++ b/tools/eslint/lib/rules/no-eq-null.js @@ -30,7 +30,7 @@ module.exports = { if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || node.left.type === "Literal" && node.left.raw === "null" && badOperator) { - context.report(node, "Use ‘===’ to compare with ‘null’."); + context.report({ node, message: "Use ‘===’ to compare with ‘null’." }); } } }; diff --git a/tools/eslint/lib/rules/no-eval.js b/tools/eslint/lib/rules/no-eval.js index af87e4289fcc31..fe1456cba0a431 100644 --- a/tools/eslint/lib/rules/no-eval.js +++ b/tools/eslint/lib/rules/no-eval.js @@ -86,7 +86,7 @@ module.exports = { { type: "object", properties: { - allowIndirect: {type: "boolean"} + allowIndirect: { type: "boolean" } }, additionalProperties: false } diff --git a/tools/eslint/lib/rules/no-ex-assign.js b/tools/eslint/lib/rules/no-ex-assign.js index 6ffa8408677292..20869d5cd107c9 100644 --- a/tools/eslint/lib/rules/no-ex-assign.js +++ b/tools/eslint/lib/rules/no-ex-assign.js @@ -30,10 +30,8 @@ module.exports = { * @returns {void} */ function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(function(reference) { - context.report( - reference.identifier, - "Do not assign to the exception parameter."); + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, message: "Do not assign to the exception parameter." }); }); } diff --git a/tools/eslint/lib/rules/no-extend-native.js b/tools/eslint/lib/rules/no-extend-native.js index 27de9b5bd36deb..c44a2e894699e9 100644 --- a/tools/eslint/lib/rules/no-extend-native.js +++ b/tools/eslint/lib/rules/no-extend-native.js @@ -44,14 +44,10 @@ module.exports = { const config = context.options[0] || {}; const exceptions = config.exceptions || []; - let modifiedBuiltins = Object.keys(globals.builtin).filter(function(builtin) { - return builtin[0].toUpperCase() === builtin[0]; - }); + let modifiedBuiltins = Object.keys(globals.builtin).filter(builtin => builtin[0].toUpperCase() === builtin[0]); if (exceptions.length) { - modifiedBuiltins = modifiedBuiltins.filter(function(builtIn) { - return exceptions.indexOf(builtIn) === -1; - }); + modifiedBuiltins = modifiedBuiltins.filter(builtIn => exceptions.indexOf(builtIn) === -1); } return { @@ -72,7 +68,7 @@ module.exports = { return; } - modifiedBuiltins.forEach(function(builtin) { + modifiedBuiltins.forEach(builtin => { if (lhs.object.object.name === builtin) { context.report({ node, diff --git a/tools/eslint/lib/rules/no-extra-boolean-cast.js b/tools/eslint/lib/rules/no-extra-boolean-cast.js index 89a193b2d12435..123a7cacc5256a 100644 --- a/tools/eslint/lib/rules/no-extra-boolean-cast.js +++ b/tools/eslint/lib/rules/no-extra-boolean-cast.js @@ -17,10 +17,13 @@ module.exports = { recommended: true }, - schema: [] + schema: [], + + fixable: "code" }, create(context) { + const sourceCode = context.getSourceCode(); // Node types which have a test which will coerce values to booleans. const BOOLEAN_NODE_TYPES = [ @@ -70,7 +73,11 @@ module.exports = { grandparent.callee.type === "Identifier" && grandparent.callee.name === "Boolean") ) { - context.report(node, "Redundant double negation."); + context.report({ + node, + message: "Redundant double negation.", + fix: fixer => fixer.replaceText(parent, sourceCode.getText(node.argument)) + }); } }, CallExpression(node) { @@ -81,7 +88,11 @@ module.exports = { } if (isInBooleanContext(node, parent)) { - context.report(node, "Redundant Boolean call."); + context.report({ + node, + message: "Redundant Boolean call.", + fix: fixer => fixer.replaceText(node, sourceCode.getText(node.arguments[0])) + }); } } }; diff --git a/tools/eslint/lib/rules/no-extra-label.js b/tools/eslint/lib/rules/no-extra-label.js index b34e075163472d..22afbf405b7ea9 100644 --- a/tools/eslint/lib/rules/no-extra-label.js +++ b/tools/eslint/lib/rules/no-extra-label.js @@ -23,10 +23,13 @@ module.exports = { recommended: false }, - schema: [] + schema: [], + + fixable: "code" }, create(context) { + const sourceCode = context.getSourceCode(); let scopeInfo = null; /** @@ -37,7 +40,7 @@ module.exports = { */ function enterBreakableStatement(node) { scopeInfo = { - label: astUtils.getLabel(node), + label: node.parent.type === "LabeledStatement" ? node.parent.label : null, breakable: true, upper: scopeInfo }; @@ -64,7 +67,7 @@ module.exports = { function enterLabeledStatement(node) { if (!astUtils.isBreakableStatement(node.body)) { scopeInfo = { - label: node.label.name, + label: node.label, breakable: false, upper: scopeInfo }; @@ -99,22 +102,24 @@ module.exports = { } const labelNode = node.label; - const label = labelNode.name; - let info = scopeInfo; - while (info) { - if (info.breakable || info.label === label) { - if (info.breakable && info.label === label) { + for (let info = scopeInfo; info !== null; info = info.upper) { + if (info.breakable || info.label && info.label.name === labelNode.name) { + if (info.breakable && info.label && info.label.name === labelNode.name) { context.report({ node: labelNode, message: "This label '{{name}}' is unnecessary.", - data: labelNode + data: labelNode, + fix(fixer) { + return fixer.replaceTextRange( + [info.label.range[0], labelNode.range[1]], + sourceCode.text.slice(info.label.parent.body.range[0], sourceCode.getFirstToken(node).range[1]) + ); + } }); } return; } - - info = info.upper; } } diff --git a/tools/eslint/lib/rules/no-extra-parens.js b/tools/eslint/lib/rules/no-extra-parens.js index efa3d53bbd3328..004d431701a574 100644 --- a/tools/eslint/lib/rules/no-extra-parens.js +++ b/tools/eslint/lib/rules/no-extra-parens.js @@ -42,9 +42,9 @@ module.exports = { { type: "object", properties: { - conditionalAssign: {type: "boolean"}, - nestedBinaryExpressions: {type: "boolean"}, - returnAssign: {type: "boolean"} + conditionalAssign: { type: "boolean" }, + nestedBinaryExpressions: { type: "boolean" }, + returnAssign: { type: "boolean" } }, additionalProperties: false } @@ -348,12 +348,12 @@ module.exports = { report(node.callee); } if (node.arguments.length === 1) { - if (hasDoubleExcessParens(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({type: "AssignmentExpression"})) { + if (hasDoubleExcessParens(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({ type: "AssignmentExpression" })) { report(node.arguments[0]); } } else { - [].forEach.call(node.arguments, function(arg) { - if (hasExcessParens(arg) && precedence(arg) >= precedence({type: "AssignmentExpression"})) { + [].forEach.call(node.arguments, arg => { + if (hasExcessParens(arg) && precedence(arg) >= precedence({ type: "AssignmentExpression" })) { report(arg); } }); @@ -381,8 +381,8 @@ module.exports = { return { ArrayExpression(node) { - [].forEach.call(node.elements, function(e) { - if (e && hasExcessParens(e) && precedence(e) >= precedence({type: "AssignmentExpression"})) { + [].forEach.call(node.elements, e => { + if (e && hasExcessParens(e) && precedence(e) >= precedence({ type: "AssignmentExpression" })) { report(e); } }); @@ -394,7 +394,7 @@ module.exports = { } if (node.body.type !== "BlockStatement") { - if (sourceCode.getFirstToken(node.body).value !== "{" && hasExcessParens(node.body) && precedence(node.body) >= precedence({type: "AssignmentExpression"})) { + if (sourceCode.getFirstToken(node.body).value !== "{" && hasExcessParens(node.body) && precedence(node.body) >= precedence({ type: "AssignmentExpression" })) { report(node.body); return; } @@ -402,7 +402,6 @@ module.exports = { // Object literals *must* be parenthesised if (node.body.type === "ObjectExpression" && hasDoubleExcessParens(node.body)) { report(node.body); - return; } } }, @@ -425,15 +424,15 @@ module.exports = { return; } - if (hasExcessParens(node.test) && precedence(node.test) >= precedence({type: "LogicalExpression", operator: "||"})) { + if (hasExcessParens(node.test) && precedence(node.test) >= precedence({ type: "LogicalExpression", operator: "||" })) { report(node.test); } - if (hasExcessParens(node.consequent) && precedence(node.consequent) >= precedence({type: "AssignmentExpression"})) { + if (hasExcessParens(node.consequent) && precedence(node.consequent) >= precedence({ type: "AssignmentExpression" })) { report(node.consequent); } - if (hasExcessParens(node.alternate) && precedence(node.alternate) >= precedence({type: "AssignmentExpression"})) { + if (hasExcessParens(node.alternate) && precedence(node.alternate) >= precedence({ type: "AssignmentExpression" })) { report(node.alternate); } }, @@ -509,7 +508,7 @@ module.exports = { !( (node.object.type === "Literal" && typeof node.object.value === "number" && - /^[0-9]+$/.test(sourceCode.getFirstToken(node.object).value)) + astUtils.isDecimalInteger(node.object)) || // RegExp literal is allowed to have parens (#1589) @@ -532,10 +531,10 @@ module.exports = { NewExpression: dryCallNew, ObjectExpression(node) { - [].forEach.call(node.properties, function(e) { + [].forEach.call(node.properties, e => { const v = e.value; - if (v && hasExcessParens(v) && precedence(v) >= precedence({type: "AssignmentExpression"})) { + if (v && hasExcessParens(v) && precedence(v) >= precedence({ type: "AssignmentExpression" })) { report(v); } }); @@ -558,7 +557,7 @@ module.exports = { }, SequenceExpression(node) { - [].forEach.call(node.expressions, function(e) { + [].forEach.call(node.expressions, e => { if (hasExcessParens(e) && precedence(e) >= precedence(node)) { report(e); } @@ -591,7 +590,7 @@ module.exports = { VariableDeclarator(node) { if (node.init && hasExcessParens(node.init) && - precedence(node.init) >= precedence({type: "AssignmentExpression"}) && + precedence(node.init) >= precedence({ type: "AssignmentExpression" }) && // RegExp literal is allowed to have parens (#1589) !(node.init.type === "Literal" && node.init.regex)) { diff --git a/tools/eslint/lib/rules/no-fallthrough.js b/tools/eslint/lib/rules/no-fallthrough.js index 380a53634be1cb..30d13da06ddc8f 100644 --- a/tools/eslint/lib/rules/no-fallthrough.js +++ b/tools/eslint/lib/rules/no-fallthrough.js @@ -109,7 +109,7 @@ module.exports = { if (fallthroughCase && !hasFallthroughComment(node, context, fallthroughCommentPattern)) { context.report({ message: "Expected a 'break' statement before '{{type}}'.", - data: {type: node.test ? "case" : "default"}, + data: { type: node.test ? "case" : "default" }, node }); } diff --git a/tools/eslint/lib/rules/no-func-assign.js b/tools/eslint/lib/rules/no-func-assign.js index daa6fa52ba7301..ea86365b2914eb 100644 --- a/tools/eslint/lib/rules/no-func-assign.js +++ b/tools/eslint/lib/rules/no-func-assign.js @@ -30,11 +30,8 @@ module.exports = { * @returns {void} */ function checkReference(references) { - astUtils.getModifyingReferences(references).forEach(function(reference) { - context.report( - reference.identifier, - "'{{name}}' is a function.", - {name: reference.identifier.name}); + astUtils.getModifyingReferences(references).forEach(reference => { + context.report({ node: reference.identifier, message: "'{{name}}' is a function.", data: { name: reference.identifier.name } }); }); } diff --git a/tools/eslint/lib/rules/no-global-assign.js b/tools/eslint/lib/rules/no-global-assign.js index 2bc38cb5d70bb6..caf2500231e14a 100644 --- a/tools/eslint/lib/rules/no-global-assign.js +++ b/tools/eslint/lib/rules/no-global-assign.js @@ -23,7 +23,7 @@ module.exports = { properties: { exceptions: { type: "array", - items: {type: "string"}, + items: { type: "string" }, uniqueItems: true } }, diff --git a/tools/eslint/lib/rules/no-implicit-globals.js b/tools/eslint/lib/rules/no-implicit-globals.js index fd49f0c5ac3011..f0962cdc7a864a 100644 --- a/tools/eslint/lib/rules/no-implicit-globals.js +++ b/tools/eslint/lib/rules/no-implicit-globals.js @@ -25,27 +25,27 @@ module.exports = { Program() { const scope = context.getScope(); - scope.variables.forEach(function(variable) { + scope.variables.forEach(variable => { if (variable.writeable) { return; } - variable.defs.forEach(function(def) { + variable.defs.forEach(def => { if (def.type === "FunctionName" || (def.type === "Variable" && def.parent.kind === "var")) { - context.report(def.node, "Implicit global variable, assign as global property instead."); + context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." }); } }); }); - scope.implicit.variables.forEach(function(variable) { + scope.implicit.variables.forEach(variable => { const scopeVariable = scope.set.get(variable.name); if (scopeVariable && scopeVariable.writeable) { return; } - variable.defs.forEach(function(def) { - context.report(def.node, "Implicit global variable, assign as global property instead."); + variable.defs.forEach(def => { + context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." }); }); }); } diff --git a/tools/eslint/lib/rules/no-implied-eval.js b/tools/eslint/lib/rules/no-implied-eval.js index 9b48e896821363..4daadd8fb8733d 100644 --- a/tools/eslint/lib/rules/no-implied-eval.js +++ b/tools/eslint/lib/rules/no-implied-eval.js @@ -21,7 +21,7 @@ module.exports = { }, create(context) { - const CALLEE_RE = /set(?:Timeout|Interval)|execScript/; + const CALLEE_RE = /^(setTimeout|setInterval|execScript)$/; /* * Figures out if we should inspect a given binary expression. Is a stack @@ -105,7 +105,7 @@ module.exports = { // remove the entire substack, to avoid duplicate reports const substack = impliedEvalAncestorsStack.pop(); - context.report(substack[0], "Implied eval. Consider passing a function instead of a string."); + context.report({ node: substack[0], message: "Implied eval. Consider passing a function instead of a string." }); } } diff --git a/tools/eslint/lib/rules/no-inline-comments.js b/tools/eslint/lib/rules/no-inline-comments.js index d51a59a183c199..46815d15418f6a 100644 --- a/tools/eslint/lib/rules/no-inline-comments.js +++ b/tools/eslint/lib/rules/no-inline-comments.js @@ -46,7 +46,7 @@ module.exports = { // Should be empty if there was only whitespace around the comment if (!isDirective && (preamble || postamble)) { - context.report(node, "Unexpected comment inline with code."); + context.report({ node, message: "Unexpected comment inline with code." }); } } diff --git a/tools/eslint/lib/rules/no-inner-declarations.js b/tools/eslint/lib/rules/no-inner-declarations.js index e5a186133cc34e..01cc67863ffff5 100644 --- a/tools/eslint/lib/rules/no-inner-declarations.js +++ b/tools/eslint/lib/rules/no-inner-declarations.js @@ -36,8 +36,8 @@ module.exports = { generation = 1; while (ancestor && ["Program", "FunctionDeclaration", - "FunctionExpression", "ArrowFunctionExpression" - ].indexOf(ancestor.type) < 0) { + "FunctionExpression", "ArrowFunctionExpression" + ].indexOf(ancestor.type) < 0) { generation += 1; ancestor = ancestors.pop(); } @@ -63,14 +63,12 @@ module.exports = { body.distance === 2); if (!valid) { - context.report(node, "Move {{type}} declaration to {{body}} root.", - { - type: (node.type === "FunctionDeclaration" ? + context.report({ node, message: "Move {{type}} declaration to {{body}} root.", data: { + type: (node.type === "FunctionDeclaration" ? "function" : "variable"), - body: (body.type === "Program" ? + body: (body.type === "Program" ? "program" : "function body") - } - ); + } }); } } diff --git a/tools/eslint/lib/rules/no-invalid-this.js b/tools/eslint/lib/rules/no-invalid-this.js index fe2bc3a1baa647..64ef4882e252ec 100644 --- a/tools/eslint/lib/rules/no-invalid-this.js +++ b/tools/eslint/lib/rules/no-invalid-this.js @@ -114,7 +114,7 @@ module.exports = { const current = stack.getCurrent(); if (current && !current.valid) { - context.report(node, "Unexpected 'this'."); + context.report({ node, message: "Unexpected 'this'." }); } } }; diff --git a/tools/eslint/lib/rules/no-irregular-whitespace.js b/tools/eslint/lib/rules/no-irregular-whitespace.js index 74a3c10fed1c9d..b1949fbc735479 100644 --- a/tools/eslint/lib/rules/no-irregular-whitespace.js +++ b/tools/eslint/lib/rules/no-irregular-whitespace.js @@ -76,7 +76,7 @@ module.exports = { const locStart = node.loc.start; const locEnd = node.loc.end; - errors = errors.filter(function(error) { + errors = errors.filter(error => { const errorLoc = error[1]; if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) { @@ -142,7 +142,7 @@ module.exports = { function checkForIrregularWhitespace(node) { const sourceLines = sourceCode.lines; - sourceLines.forEach(function(sourceLine, lineIndex) { + sourceLines.forEach((sourceLine, lineIndex) => { const lineNumber = lineIndex + 1; let match; @@ -233,7 +233,7 @@ module.exports = { } // If we have any errors remaining report on them - errors.forEach(function(error) { + errors.forEach(error => { context.report.apply(context, error); }); }; diff --git a/tools/eslint/lib/rules/no-iterator.js b/tools/eslint/lib/rules/no-iterator.js index faa5153335bd76..3677dd94d9f938 100644 --- a/tools/eslint/lib/rules/no-iterator.js +++ b/tools/eslint/lib/rules/no-iterator.js @@ -29,7 +29,7 @@ module.exports = { if (node.property && (node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) || (node.property.type === "Literal" && node.property.value === "__iterator__")) { - context.report(node, "Reserved name '__iterator__'."); + context.report({ node, message: "Reserved name '__iterator__'." }); } } }; diff --git a/tools/eslint/lib/rules/no-label-var.js b/tools/eslint/lib/rules/no-label-var.js index 450c9a91fca893..00133685613609 100644 --- a/tools/eslint/lib/rules/no-label-var.js +++ b/tools/eslint/lib/rules/no-label-var.js @@ -57,7 +57,7 @@ module.exports = { // Recursively find the identifier walking up the scope, starting // with the innermost scope. if (findIdentifier(scope, node.label.name)) { - context.report(node, "Found identifier with same name as label."); + context.report({ node, message: "Found identifier with same name as label." }); } } diff --git a/tools/eslint/lib/rules/no-lone-blocks.js b/tools/eslint/lib/rules/no-lone-blocks.js index 9945147129cd81..9528421ca5bd39 100644 --- a/tools/eslint/lib/rules/no-lone-blocks.js +++ b/tools/eslint/lib/rules/no-lone-blocks.js @@ -34,10 +34,10 @@ module.exports = { function report(node) { const parent = context.getAncestors().pop(); - context.report(node, parent.type === "Program" ? + context.report({ node, message: parent.type === "Program" ? "Block is redundant." : "Nested block is redundant." - ); + }); } /** diff --git a/tools/eslint/lib/rules/no-lonely-if.js b/tools/eslint/lib/rules/no-lonely-if.js index 19517bc3dc491a..31f47b90e06595 100644 --- a/tools/eslint/lib/rules/no-lonely-if.js +++ b/tools/eslint/lib/rules/no-lonely-if.js @@ -55,7 +55,7 @@ module.exports = { node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock && ( node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line || - /^[(\[\/+`-]/.test(tokenAfterElseBlock.value) || + /^[([/+`-]/.test(tokenAfterElseBlock.value) || lastIfToken.value === "++" || lastIfToken.value === "--" ) diff --git a/tools/eslint/lib/rules/no-loop-func.js b/tools/eslint/lib/rules/no-loop-func.js index 6db7a95f7c7254..b8bed958652e46 100644 --- a/tools/eslint/lib/rules/no-loop-func.js +++ b/tools/eslint/lib/rules/no-loop-func.js @@ -185,7 +185,7 @@ module.exports = { if (references.length > 0 && !references.every(isSafe.bind(null, node, loopNode)) ) { - context.report(node, "Don't make functions within a loop."); + context.report({ node, message: "Don't make functions within a loop." }); } } diff --git a/tools/eslint/lib/rules/no-mixed-operators.js b/tools/eslint/lib/rules/no-mixed-operators.js index 12779f8e738c68..b066d74a0c40e0 100644 --- a/tools/eslint/lib/rules/no-mixed-operators.js +++ b/tools/eslint/lib/rules/no-mixed-operators.js @@ -62,9 +62,7 @@ function normalizeOptions(options) { * @returns {boolean} `true` if such group existed. */ function includesBothInAGroup(groups, left, right) { - return groups.some(function(group) { - return group.indexOf(left) !== -1 && group.indexOf(right) !== -1; - }); + return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1); } //------------------------------------------------------------------------------ @@ -86,7 +84,7 @@ module.exports = { type: "array", items: { type: "array", - items: {enum: ALL_OPERATORS}, + items: { enum: ALL_OPERATORS }, minItems: 2, uniqueItems: true }, diff --git a/tools/eslint/lib/rules/no-mixed-requires.js b/tools/eslint/lib/rules/no-mixed-requires.js index 89ba345c248f61..4d51d3ab3a07a4 100644 --- a/tools/eslint/lib/rules/no-mixed-requires.js +++ b/tools/eslint/lib/rules/no-mixed-requires.js @@ -169,7 +169,7 @@ module.exports = { function isMixed(declarations) { const contains = {}; - declarations.forEach(function(declaration) { + declarations.forEach(declaration => { const type = getDeclarationType(declaration.init); contains[type] = true; @@ -190,7 +190,7 @@ module.exports = { function isGrouped(declarations) { const found = {}; - declarations.forEach(function(declaration) { + declarations.forEach(declaration => { if (getDeclarationType(declaration.init) === DECL_REQUIRE) { found[inferModuleType(declaration.init)] = true; } @@ -205,15 +205,9 @@ module.exports = { VariableDeclaration(node) { if (isMixed(node.declarations)) { - context.report( - node, - "Do not mix 'require' and other declarations." - ); + context.report({ node, message: "Do not mix 'require' and other declarations." }); } else if (grouping && !isGrouped(node.declarations)) { - context.report( - node, - "Do not mix core, module, file and computed requires." - ); + context.report({ node, message: "Do not mix core, module, file and computed requires." }); } } }; diff --git a/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js index 0e2dcb1b8a8672..2b8e89d3c87123 100644 --- a/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js +++ b/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js @@ -89,11 +89,11 @@ module.exports = { const lines = sourceCode.lines, comments = sourceCode.getAllComments(); - comments.forEach(function(comment) { + comments.forEach(comment => { ignoredLocs.push(comment.loc); }); - ignoredLocs.sort(function(first, second) { + ignoredLocs.sort((first, second) => { if (beforeLoc(first, second.start.line, second.start.column)) { return 1; } @@ -114,7 +114,7 @@ module.exports = { regex = /^(?=[\t ]* \t)/; } - lines.forEach(function(line, i) { + lines.forEach((line, i) => { const match = regex.exec(line); if (match) { @@ -132,7 +132,7 @@ module.exports = { return; } - context.report(node, { line: lineNumber, column }, "Mixed spaces and tabs."); + context.report({ node, loc: { line: lineNumber, column }, message: "Mixed spaces and tabs." }); } }); } diff --git a/tools/eslint/lib/rules/no-multi-spaces.js b/tools/eslint/lib/rules/no-multi-spaces.js index 43e26a4415353e..64eeebec55a383 100644 --- a/tools/eslint/lib/rules/no-multi-spaces.js +++ b/tools/eslint/lib/rules/no-multi-spaces.js @@ -47,7 +47,7 @@ module.exports = { lastCommentIndex = 0; if (options && options.exceptions) { - Object.keys(options.exceptions).forEach(function(key) { + Object.keys(options.exceptions).forEach(key => { if (options.exceptions[key]) { exceptions[key] = true; } else { diff --git a/tools/eslint/lib/rules/no-multi-str.js b/tools/eslint/lib/rules/no-multi-str.js index 092226f7cad355..6cf5840e30264b 100644 --- a/tools/eslint/lib/rules/no-multi-str.js +++ b/tools/eslint/lib/rules/no-multi-str.js @@ -42,7 +42,7 @@ module.exports = { const lineBreak = /\n/; if (lineBreak.test(node.raw) && !isJSXElement(node.parent)) { - context.report(node, "Multiline support is limited to browsers supporting ES5 only."); + context.report({ node, message: "Multiline support is limited to browsers supporting ES5 only." }); } } }; diff --git a/tools/eslint/lib/rules/no-multiple-empty-lines.js b/tools/eslint/lib/rules/no-multiple-empty-lines.js index 9d44064d23f1d3..c45c7aa1678927 100644 --- a/tools/eslint/lib/rules/no-multiple-empty-lines.js +++ b/tools/eslint/lib/rules/no-multiple-empty-lines.js @@ -5,6 +5,8 @@ */ "use strict"; +const astUtils = require("../ast-utils"); + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -56,8 +58,6 @@ module.exports = { } const sourceCode = context.getSourceCode(); - const fullLines = sourceCode.text.match(/.*(\r\n|\r|\n|\u2028|\u2029)/g) || []; - const lineStartLocations = fullLines.reduce((startIndices, nextLine) => startIndices.concat(startIndices[startIndices.length - 1] + nextLine.length), [0]); // Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue const allLines = sourceCode.lines[sourceCode.lines.length - 1] === "" ? sourceCode.lines.slice(0, -1) : sourceCode.lines; @@ -81,7 +81,12 @@ module.exports = { return allLines // Given a list of lines, first get a list of line numbers that are non-empty. - .reduce((nonEmptyLineNumbers, line, index) => nonEmptyLineNumbers.concat(line.trim() || templateLiteralLines.has(index + 1) ? [index + 1] : []), []) + .reduce((nonEmptyLineNumbers, line, index) => { + if (line.trim() || templateLiteralLines.has(index + 1)) { + nonEmptyLineNumbers.push(index + 1); + } + return nonEmptyLineNumbers; + }, []) // Add a value at the end to allow trailing empty lines to be checked. .concat(allLines.length + 1) @@ -104,10 +109,15 @@ module.exports = { if (lineNumber - lastLineNumber - 1 > maxAllowed) { context.report({ node, - loc: {start: {line: lastLineNumber + 1, column: 0}, end: {line: lineNumber, column: 0}}, + loc: { start: { line: lastLineNumber + 1, column: 0 }, end: { line: lineNumber, column: 0 } }, message, - data: {max: maxAllowed, pluralizedLines: maxAllowed === 1 ? "line" : "lines"}, - fix: fixer => fixer.removeRange([lineStartLocations[lastLineNumber], lineStartLocations[lineNumber - maxAllowed - 1]]) + data: { max: maxAllowed, pluralizedLines: maxAllowed === 1 ? "line" : "lines" }, + fix(fixer) { + return fixer.removeRange([ + astUtils.getRangeIndexFromLocation(sourceCode, { line: lastLineNumber + 1, column: 0 }), + astUtils.getRangeIndexFromLocation(sourceCode, { line: lineNumber - maxAllowed, column: 0 }) + ]); + } }); } diff --git a/tools/eslint/lib/rules/no-native-reassign.js b/tools/eslint/lib/rules/no-native-reassign.js index 2b1c41b2d100b0..f721fc278fe3ec 100644 --- a/tools/eslint/lib/rules/no-native-reassign.js +++ b/tools/eslint/lib/rules/no-native-reassign.js @@ -27,7 +27,7 @@ module.exports = { properties: { exceptions: { type: "array", - items: {type: "string"}, + items: { type: "string" }, uniqueItems: true } }, diff --git a/tools/eslint/lib/rules/no-negated-condition.js b/tools/eslint/lib/rules/no-negated-condition.js index ea8b1210774f16..8ea8559ea1c96f 100644 --- a/tools/eslint/lib/rules/no-negated-condition.js +++ b/tools/eslint/lib/rules/no-negated-condition.js @@ -69,12 +69,12 @@ module.exports = { } if (isNegatedIf(node)) { - context.report(node, "Unexpected negated condition."); + context.report({ node, message: "Unexpected negated condition." }); } }, ConditionalExpression(node) { if (isNegatedIf(node)) { - context.report(node, "Unexpected negated condition."); + context.report({ node, message: "Unexpected negated condition." }); } } }; diff --git a/tools/eslint/lib/rules/no-negated-in-lhs.js b/tools/eslint/lib/rules/no-negated-in-lhs.js index 6631336ea74d9f..143518060b33bd 100644 --- a/tools/eslint/lib/rules/no-negated-in-lhs.js +++ b/tools/eslint/lib/rules/no-negated-in-lhs.js @@ -29,7 +29,7 @@ module.exports = { BinaryExpression(node) { if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") { - context.report(node, "The 'in' expression's left operand is negated."); + context.report({ node, message: "The 'in' expression's left operand is negated." }); } } }; diff --git a/tools/eslint/lib/rules/no-nested-ternary.js b/tools/eslint/lib/rules/no-nested-ternary.js index 50265913b02ecf..4fe49fc9c01e58 100644 --- a/tools/eslint/lib/rules/no-nested-ternary.js +++ b/tools/eslint/lib/rules/no-nested-ternary.js @@ -26,7 +26,7 @@ module.exports = { ConditionalExpression(node) { if (node.alternate.type === "ConditionalExpression" || node.consequent.type === "ConditionalExpression") { - context.report(node, "Do not nest ternary expressions."); + context.report({ node, message: "Do not nest ternary expressions." }); } } }; diff --git a/tools/eslint/lib/rules/no-new-func.js b/tools/eslint/lib/rules/no-new-func.js index e78bcc0772a024..17ca7c9f03d6b3 100644 --- a/tools/eslint/lib/rules/no-new-func.js +++ b/tools/eslint/lib/rules/no-new-func.js @@ -34,7 +34,7 @@ module.exports = { */ function validateCallee(node) { if (node.callee.name === "Function") { - context.report(node, "The Function constructor is eval."); + context.report({ node, message: "The Function constructor is eval." }); } } diff --git a/tools/eslint/lib/rules/no-new-object.js b/tools/eslint/lib/rules/no-new-object.js index d11a2ebc615350..d4d77b55147a62 100644 --- a/tools/eslint/lib/rules/no-new-object.js +++ b/tools/eslint/lib/rules/no-new-object.js @@ -26,7 +26,7 @@ module.exports = { NewExpression(node) { if (node.callee.name === "Object") { - context.report(node, "The object literal notation {} is preferrable."); + context.report({ node, message: "The object literal notation {} is preferrable." }); } } }; diff --git a/tools/eslint/lib/rules/no-new-require.js b/tools/eslint/lib/rules/no-new-require.js index eed2028de351fa..f9ea1f84bf3bb3 100644 --- a/tools/eslint/lib/rules/no-new-require.js +++ b/tools/eslint/lib/rules/no-new-require.js @@ -26,7 +26,7 @@ module.exports = { NewExpression(node) { if (node.callee.type === "Identifier" && node.callee.name === "require") { - context.report(node, "Unexpected use of new with require."); + context.report({ node, message: "Unexpected use of new with require." }); } } }; diff --git a/tools/eslint/lib/rules/no-new-symbol.js b/tools/eslint/lib/rules/no-new-symbol.js index c65e7c9df90afb..5743a4748a9275 100644 --- a/tools/eslint/lib/rules/no-new-symbol.js +++ b/tools/eslint/lib/rules/no-new-symbol.js @@ -28,11 +28,11 @@ module.exports = { const variable = globalScope.set.get("Symbol"); if (variable && variable.defs.length === 0) { - variable.references.forEach(function(ref) { + variable.references.forEach(ref => { const node = ref.identifier; if (node.parent && node.parent.type === "NewExpression") { - context.report(node, "`Symbol` cannot be called as a constructor."); + context.report({ node, message: "`Symbol` cannot be called as a constructor." }); } }); } diff --git a/tools/eslint/lib/rules/no-new-wrappers.js b/tools/eslint/lib/rules/no-new-wrappers.js index 67e69ee0fefe0a..65bf79b87c50b3 100644 --- a/tools/eslint/lib/rules/no-new-wrappers.js +++ b/tools/eslint/lib/rules/no-new-wrappers.js @@ -28,7 +28,7 @@ module.exports = { const wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"]; if (wrapperObjects.indexOf(node.callee.name) > -1) { - context.report(node, "Do not use {{fn}} as a constructor.", { fn: node.callee.name }); + context.report({ node, message: "Do not use {{fn}} as a constructor.", data: { fn: node.callee.name } }); } } }; diff --git a/tools/eslint/lib/rules/no-new.js b/tools/eslint/lib/rules/no-new.js index 639ae22685a96b..e0f45de1bd298b 100644 --- a/tools/eslint/lib/rules/no-new.js +++ b/tools/eslint/lib/rules/no-new.js @@ -28,7 +28,7 @@ module.exports = { ExpressionStatement(node) { if (node.expression.type === "NewExpression") { - context.report(node, "Do not use 'new' for side effects."); + context.report({ node, message: "Do not use 'new' for side effects." }); } } }; diff --git a/tools/eslint/lib/rules/no-obj-calls.js b/tools/eslint/lib/rules/no-obj-calls.js index bd9b6ee4f04f76..0ca8a5effb6e86 100644 --- a/tools/eslint/lib/rules/no-obj-calls.js +++ b/tools/eslint/lib/rules/no-obj-calls.js @@ -28,8 +28,8 @@ module.exports = { if (node.callee.type === "Identifier") { const name = node.callee.name; - if (name === "Math" || name === "JSON") { - context.report(node, "'{{name}}' is not a function.", { name }); + if (name === "Math" || name === "JSON" || name === "Reflect") { + context.report({ node, message: "'{{name}}' is not a function.", data: { name } }); } } } diff --git a/tools/eslint/lib/rules/no-octal-escape.js b/tools/eslint/lib/rules/no-octal-escape.js index 25a5b022e92402..04bfb6aae3357c 100644 --- a/tools/eslint/lib/rules/no-octal-escape.js +++ b/tools/eslint/lib/rules/no-octal-escape.js @@ -36,8 +36,7 @@ module.exports = { // \0 is actually not considered an octal if (match[2] !== "0" || typeof match[3] !== "undefined") { - context.report(node, "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.", - { octalDigit }); + context.report({ node, message: "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.", data: { octalDigit } }); } } } diff --git a/tools/eslint/lib/rules/no-octal.js b/tools/eslint/lib/rules/no-octal.js index ebc5e3252d9771..58082d0d1cfb04 100644 --- a/tools/eslint/lib/rules/no-octal.js +++ b/tools/eslint/lib/rules/no-octal.js @@ -26,7 +26,7 @@ module.exports = { Literal(node) { if (typeof node.value === "number" && /^0[0-7]/.test(node.raw)) { - context.report(node, "Octal literals should not be used."); + context.report({ node, message: "Octal literals should not be used." }); } } }; diff --git a/tools/eslint/lib/rules/no-param-reassign.js b/tools/eslint/lib/rules/no-param-reassign.js index c20f340d7ab43a..31f5be3cb25972 100644 --- a/tools/eslint/lib/rules/no-param-reassign.js +++ b/tools/eslint/lib/rules/no-param-reassign.js @@ -22,7 +22,7 @@ module.exports = { { type: "object", properties: { - props: {type: "boolean"} + props: { type: "boolean" } }, additionalProperties: false } @@ -102,15 +102,9 @@ module.exports = { (index === 0 || references[index - 1].identifier !== identifier) ) { if (reference.isWrite()) { - context.report( - identifier, - "Assignment to function parameter '{{name}}'.", - {name: identifier.name}); + context.report({ node: identifier, message: "Assignment to function parameter '{{name}}'.", data: { name: identifier.name } }); } else if (props && isModifyingProp(reference)) { - context.report( - identifier, - "Assignment to property of function parameter '{{name}}'.", - {name: identifier.name}); + context.report({ node: identifier, message: "Assignment to property of function parameter '{{name}}'.", data: { name: identifier.name } }); } } } diff --git a/tools/eslint/lib/rules/no-path-concat.js b/tools/eslint/lib/rules/no-path-concat.js index 6b27678aedc8f8..1e153a43b6c683 100644 --- a/tools/eslint/lib/rules/no-path-concat.js +++ b/tools/eslint/lib/rules/no-path-concat.js @@ -39,7 +39,7 @@ module.exports = { (right.type === "Identifier" && MATCHER.test(right.name))) ) { - context.report(node, "Use path.join() or path.resolve() instead of + to create paths."); + context.report({ node, message: "Use path.join() or path.resolve() instead of + to create paths." }); } } diff --git a/tools/eslint/lib/rules/no-process-env.js b/tools/eslint/lib/rules/no-process-env.js index a2ae1fd408ac44..ef58b38e3cccd4 100644 --- a/tools/eslint/lib/rules/no-process-env.js +++ b/tools/eslint/lib/rules/no-process-env.js @@ -28,7 +28,7 @@ module.exports = { propertyName = node.property.name; if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { - context.report(node, "Unexpected use of process.env."); + context.report({ node, message: "Unexpected use of process.env." }); } } diff --git a/tools/eslint/lib/rules/no-process-exit.js b/tools/eslint/lib/rules/no-process-exit.js index 69023e58e1b109..c0c2455545afab 100644 --- a/tools/eslint/lib/rules/no-process-exit.js +++ b/tools/eslint/lib/rules/no-process-exit.js @@ -33,7 +33,7 @@ module.exports = { if (callee.type === "MemberExpression" && callee.object.name === "process" && callee.property.name === "exit" ) { - context.report(node, "Don't use process.exit(); throw an error instead."); + context.report({ node, message: "Don't use process.exit(); throw an error instead." }); } } diff --git a/tools/eslint/lib/rules/no-proto.js b/tools/eslint/lib/rules/no-proto.js index 03eb88273c4bc2..933746f559cd4b 100644 --- a/tools/eslint/lib/rules/no-proto.js +++ b/tools/eslint/lib/rules/no-proto.js @@ -29,7 +29,7 @@ module.exports = { if (node.property && (node.property.type === "Identifier" && node.property.name === "__proto__" && !node.computed) || (node.property.type === "Literal" && node.property.value === "__proto__")) { - context.report(node, "The '__proto__' property is deprecated."); + context.report({ node, message: "The '__proto__' property is deprecated." }); } } }; diff --git a/tools/eslint/lib/rules/no-prototype-builtins.js b/tools/eslint/lib/rules/no-prototype-builtins.js index e9f46881597333..b9f040eaf67497 100644 --- a/tools/eslint/lib/rules/no-prototype-builtins.js +++ b/tools/eslint/lib/rules/no-prototype-builtins.js @@ -41,7 +41,7 @@ module.exports = { context.report({ message: "Do not access Object.prototype method '{{prop}}' from target object.", loc: node.callee.property.loc.start, - data: {prop: propName}, + data: { prop: propName }, node }); } diff --git a/tools/eslint/lib/rules/no-redeclare.js b/tools/eslint/lib/rules/no-redeclare.js index fcd4943460b421..deb896289b76f0 100644 --- a/tools/eslint/lib/rules/no-redeclare.js +++ b/tools/eslint/lib/rules/no-redeclare.js @@ -21,7 +21,7 @@ module.exports = { { type: "object", properties: { - builtinGlobals: {type: "boolean"} + builtinGlobals: { type: "boolean" } }, additionalProperties: false } @@ -40,20 +40,15 @@ module.exports = { * @private */ function findVariablesInScope(scope) { - scope.variables.forEach(function(variable) { + scope.variables.forEach(variable => { const hasBuiltin = options.builtinGlobals && "writeable" in variable; const count = (hasBuiltin ? 1 : 0) + variable.identifiers.length; if (count >= 2) { - variable.identifiers.sort(function(a, b) { - return a.range[1] - b.range[1]; - }); + variable.identifiers.sort((a, b) => a.range[1] - b.range[1]); for (let i = (hasBuiltin ? 0 : 1), l = variable.identifiers.length; i < l; i++) { - context.report( - variable.identifiers[i], - "'{{a}}' is already defined.", - {a: variable.name}); + context.report({ node: variable.identifiers[i], message: "'{{a}}' is already defined.", data: { a: variable.name } }); } } }); diff --git a/tools/eslint/lib/rules/no-regex-spaces.js b/tools/eslint/lib/rules/no-regex-spaces.js index c6e26ac3980020..05ac86e87a9db3 100644 --- a/tools/eslint/lib/rules/no-regex-spaces.js +++ b/tools/eslint/lib/rules/no-regex-spaces.js @@ -46,7 +46,7 @@ module.exports = { context.report({ node, message: "Spaces are hard to count. Use {{{count}}}.", - data: {count}, + data: { count }, fix(fixer) { return fixer.replaceTextRange( [valueStart + regexResults.index, valueStart + regexResults.index + count], diff --git a/tools/eslint/lib/rules/no-restricted-globals.js b/tools/eslint/lib/rules/no-restricted-globals.js index 07ff8b532d2307..603a6b2d3762ae 100644 --- a/tools/eslint/lib/rules/no-restricted-globals.js +++ b/tools/eslint/lib/rules/no-restricted-globals.js @@ -40,9 +40,9 @@ module.exports = { * @private */ function reportReference(reference) { - context.report(reference.identifier, "Unexpected use of '{{name}}'.", { + context.report({ node: reference.identifier, message: "Unexpected use of '{{name}}'.", data: { name: reference.identifier.name - }); + } }); } /** @@ -60,14 +60,14 @@ module.exports = { const scope = context.getScope(); // Report variables declared elsewhere (ex: variables defined as "global" by eslint) - scope.variables.forEach(function(variable) { + scope.variables.forEach(variable => { if (!variable.defs.length && isRestricted(variable.name)) { variable.references.forEach(reportReference); } }); // Report variables not declared at all - scope.through.forEach(function(reference) { + scope.through.forEach(reference => { if (isRestricted(reference.identifier.name)) { reportReference(reference); } diff --git a/tools/eslint/lib/rules/no-restricted-imports.js b/tools/eslint/lib/rules/no-restricted-imports.js index 87f9af2a6477e0..c245f22a0a4494 100644 --- a/tools/eslint/lib/rules/no-restricted-imports.js +++ b/tools/eslint/lib/rules/no-restricted-imports.js @@ -8,6 +8,16 @@ // Rule Definition //------------------------------------------------------------------------------ +const ignore = require("ignore"); + +const arrayOfStrings = { + type: "array", + items: { + type: "string" + }, + uniqueItems: true +}; + module.exports = { meta: { docs: { @@ -17,31 +27,55 @@ module.exports = { }, schema: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true + anyOf: [ + arrayOfStrings, + { + type: "array", + items: [{ + type: "object", + properties: { + paths: arrayOfStrings, + patterns: arrayOfStrings + }, + additionalProperties: false + }], + additionalItems: false + } + ] } }, create(context) { - const restrictedImports = context.options; + const options = Array.isArray(context.options) ? context.options : []; + const isStringArray = typeof options[0] !== "object"; + const restrictedPaths = new Set(isStringArray ? context.options : options[0].paths || []); + const restrictedPatterns = isStringArray ? [] : options[0].patterns || []; // if no imports are restricted we don"t need to check - if (restrictedImports.length === 0) { + if (restrictedPaths.size === 0 && restrictedPatterns.length === 0) { return {}; } + const ig = ignore().add(restrictedPatterns); + return { ImportDeclaration(node) { if (node && node.source && node.source.value) { - const value = node.source.value.trim(); + const importName = node.source.value.trim(); - if (restrictedImports.indexOf(value) !== -1) { - context.report(node, "'{{importName}}' import is restricted from being used.", { - importName: value + if (restrictedPaths.has(importName)) { + context.report({ + node, + message: "'{{importName}}' import is restricted from being used.", + data: { importName } + }); + } + if (restrictedPatterns.length > 0 && ig.ignores(importName)) { + context.report({ + node, + message: "'{{importName}}' import is restricted from being used by a pattern.", + data: { importName } }); } } diff --git a/tools/eslint/lib/rules/no-restricted-modules.js b/tools/eslint/lib/rules/no-restricted-modules.js index 1a46c40a81dbe2..3a9634de9e18d1 100644 --- a/tools/eslint/lib/rules/no-restricted-modules.js +++ b/tools/eslint/lib/rules/no-restricted-modules.js @@ -8,6 +8,16 @@ // Rule Definition //------------------------------------------------------------------------------ +const ignore = require("ignore"); + +const arrayOfStrings = { + type: "array", + items: { + type: "string" + }, + uniqueItems: true +}; + module.exports = { meta: { docs: { @@ -17,24 +27,37 @@ module.exports = { }, schema: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true + anyOf: [ + arrayOfStrings, + { + type: "array", + items: [{ + type: "object", + properties: { + paths: arrayOfStrings, + patterns: arrayOfStrings + }, + additionalProperties: false + }], + additionalItems: false + } + ] } }, create(context) { + const options = Array.isArray(context.options) ? context.options : []; + const isStringArray = typeof options[0] !== "object"; + const restrictedPaths = new Set(isStringArray ? context.options : options[0].paths || []); + const restrictedPatterns = isStringArray ? [] : options[0].patterns || []; - // trim restricted module names - const restrictedModules = context.options; - - // if no modules are restricted we don't need to check the CallExpressions - if (restrictedModules.length === 0) { + // if no imports are restricted we don"t need to check + if (restrictedPaths.size === 0 && restrictedPatterns.length === 0) { return {}; } + const ig = ignore().add(restrictedPatterns); + /** * Function to check if a node is a string literal. * @param {ASTNode} node The node to check. @@ -53,36 +76,30 @@ module.exports = { return node.callee.type === "Identifier" && node.callee.name === "require"; } - /** - * Function to check if a node has an argument that is an restricted module and return its name. - * @param {ASTNode} node The node to check - * @returns {undefined|string} restricted module name or undefined if node argument isn't restricted. - */ - function getRestrictedModuleName(node) { - let moduleName; - - // node has arguments and first argument is string - if (node.arguments.length && isString(node.arguments[0])) { - const argumentValue = node.arguments[0].value.trim(); - - // check if argument value is in restricted modules array - if (restrictedModules.indexOf(argumentValue) !== -1) { - moduleName = argumentValue; - } - } - - return moduleName; - } - return { CallExpression(node) { if (isRequireCall(node)) { - const restrictedModuleName = getRestrictedModuleName(node); - if (restrictedModuleName) { - context.report(node, "'{{moduleName}}' module is restricted from being used.", { - moduleName: restrictedModuleName - }); + // node has arguments and first argument is string + if (node.arguments.length && isString(node.arguments[0])) { + const moduleName = node.arguments[0].value.trim(); + + // check if argument value is in restricted modules array + if (restrictedPaths.has(moduleName)) { + context.report({ + node, + message: "'{{moduleName}}' module is restricted from being used.", + data: { moduleName } + }); + } + + if (restrictedPatterns.length > 0 && ig.ignores(moduleName)) { + context.report({ + node, + message: "'{{moduleName}}' module is restricted from being used by a pattern.", + data: { moduleName } + }); + } } } } diff --git a/tools/eslint/lib/rules/no-restricted-properties.js b/tools/eslint/lib/rules/no-restricted-properties.js index f8bd47ba4b2c18..b6c584c57e32e3 100644 --- a/tools/eslint/lib/rules/no-restricted-properties.js +++ b/tools/eslint/lib/rules/no-restricted-properties.js @@ -77,9 +77,9 @@ module.exports = { const propertyName = option.property; if (typeof objectName === "undefined") { - globallyRestrictedProperties.set(propertyName, {message: option.message}); + globallyRestrictedProperties.set(propertyName, { message: option.message }); } else if (typeof propertyName === "undefined") { - globallyRestrictedObjects.set(objectName, {message: option.message}); + globallyRestrictedObjects.set(objectName, { message: option.message }); } else { if (!restrictedProperties.has(objectName)) { restrictedProperties.set(objectName, new Map()); @@ -109,18 +109,18 @@ module.exports = { if (matchedObjectProperty) { const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : ""; - context.report(node, "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}", { + context.report({ node, message: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}", data: { objectName, propertyName, message - }); + } }); } else if (globalMatchedProperty) { const message = globalMatchedProperty.message ? ` ${globalMatchedProperty.message}` : ""; - context.report(node, "'{{propertyName}}' is restricted from being used.{{message}}", { + context.report({ node, message: "'{{propertyName}}' is restricted from being used.{{message}}", data: { propertyName, message - }); + } }); } } diff --git a/tools/eslint/lib/rules/no-restricted-syntax.js b/tools/eslint/lib/rules/no-restricted-syntax.js index ab6c36923a69b0..830452d995dab4 100644 --- a/tools/eslint/lib/rules/no-restricted-syntax.js +++ b/tools/eslint/lib/rules/no-restricted-syntax.js @@ -22,9 +22,7 @@ module.exports = { type: "array", items: [ { - enum: Object.keys(nodeTypes).map(function(k) { - return nodeTypes[k]; - }) + enum: Object.keys(nodeTypes).map(k => nodeTypes[k]) } ], uniqueItems: true, @@ -40,10 +38,10 @@ module.exports = { * @returns {void} */ function warn(node) { - context.report(node, "Using '{{type}}' is not allowed.", node); + context.report({ node, message: "Using '{{type}}' is not allowed.", data: node }); } - return context.options.reduce(function(result, nodeType) { + return context.options.reduce((result, nodeType) => { result[nodeType] = warn; return result; diff --git a/tools/eslint/lib/rules/no-return-await.js b/tools/eslint/lib/rules/no-return-await.js new file mode 100644 index 00000000000000..bc0498cb044d70 --- /dev/null +++ b/tools/eslint/lib/rules/no-return-await.js @@ -0,0 +1,94 @@ +/** + * @fileoverview Disallows unnecessary `return await` + * @author Jordan Harband + */ +"use strict"; + +const astUtils = require("../ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const message = "Redundant use of `await` on a return value."; + +module.exports = { + meta: { + docs: { + description: "disallow unnecessary `return await`", + category: "Best Practices", + recommended: false // TODO: set to true + }, + fixable: false, + schema: [ + ] + }, + + create(context) { + + /** + * Reports a found unnecessary `await` expression. + * @param {ASTNode} node The node representing the `await` expression to report + * @returns {void} + */ + function reportUnnecessaryAwait(node) { + context.report({ + node: context.getSourceCode().getFirstToken(node), + loc: node.loc, + message, + }); + } + + /** + * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting + * this function. For example, a statement in a `try` block will always have an error handler. A statement in + * a `catch` block will only have an error handler if there is also a `finally` block. + * @param {ASTNode} node A node representing a location where an could be thrown + * @returns {boolean} `true` if a thrown error will be caught/handled in this function + */ + function hasErrorHandler(node) { + let ancestor = node; + + while (!astUtils.isFunction(ancestor) && ancestor.type !== "Program") { + if (ancestor.parent.type === "TryStatement" && (ancestor === ancestor.parent.block || ancestor === ancestor.parent.handler && ancestor.parent.finalizer)) { + return true; + } + ancestor = ancestor.parent; + } + return false; + } + + /** + * Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression, + * an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position. + * @param {ASTNode} node A node representing the `await` expression to check + * @returns {boolean} The checking result + */ + function isInTailCallPosition(node) { + if (node.parent.type === "ArrowFunctionExpression") { + return true; + } + if (node.parent.type === "ReturnStatement") { + return !hasErrorHandler(node.parent); + } + if (node.parent.type === "ConditionalExpression" && (node === node.parent.consequent || node === node.parent.alternate)) { + return isInTailCallPosition(node.parent); + } + if (node.parent.type === "LogicalExpression" && node === node.parent.right) { + return isInTailCallPosition(node.parent); + } + if (node.parent.type === "SequenceExpression" && node === node.parent.expressions[node.parent.expressions.length - 1]) { + return isInTailCallPosition(node.parent); + } + return false; + } + + return { + AwaitExpression(node) { + if (isInTailCallPosition(node) && !hasErrorHandler(node)) { + reportUnnecessaryAwait(node); + } + }, + }; + } +}; diff --git a/tools/eslint/lib/rules/no-script-url.js b/tools/eslint/lib/rules/no-script-url.js index fd2f1e8c3e8954..98f988ff1a3b96 100644 --- a/tools/eslint/lib/rules/no-script-url.js +++ b/tools/eslint/lib/rules/no-script-url.js @@ -31,7 +31,7 @@ module.exports = { const value = node.value.toLowerCase(); if (value.indexOf("javascript:") === 0) { - context.report(node, "Script URL is a form of eval."); + context.report({ node, message: "Script URL is a form of eval." }); } } } diff --git a/tools/eslint/lib/rules/no-self-compare.js b/tools/eslint/lib/rules/no-self-compare.js index 17ce77a939d53e..54f907f594be06 100644 --- a/tools/eslint/lib/rules/no-self-compare.js +++ b/tools/eslint/lib/rules/no-self-compare.js @@ -31,7 +31,7 @@ module.exports = { if (operators.indexOf(node.operator) > -1 && (node.left.type === "Identifier" && node.right.type === "Identifier" && node.left.name === node.right.name || node.left.type === "Literal" && node.right.type === "Literal" && node.left.value === node.right.value)) { - context.report(node, "Comparing to itself is potentially pointless."); + context.report({ node, message: "Comparing to itself is potentially pointless." }); } } }; diff --git a/tools/eslint/lib/rules/no-sequences.js b/tools/eslint/lib/rules/no-sequences.js index 49f20ea43ff61a..67f9d8212fd4e5 100644 --- a/tools/eslint/lib/rules/no-sequences.js +++ b/tools/eslint/lib/rules/no-sequences.js @@ -101,7 +101,7 @@ module.exports = { const child = sourceCode.getTokenAfter(node.expressions[0]); - context.report(node, child.loc.start, "Unexpected use of comma operator."); + context.report({ node, loc: child.loc.start, message: "Unexpected use of comma operator." }); } }; diff --git a/tools/eslint/lib/rules/no-shadow.js b/tools/eslint/lib/rules/no-shadow.js index 27ea10ef9217aa..e093d48c810aeb 100644 --- a/tools/eslint/lib/rules/no-shadow.js +++ b/tools/eslint/lib/rules/no-shadow.js @@ -27,8 +27,8 @@ module.exports = { { type: "object", properties: { - builtinGlobals: {type: "boolean"}, - hoist: {enum: ["all", "functions", "never"]}, + builtinGlobals: { type: "boolean" }, + hoist: { enum: ["all", "functions", "never"] }, allow: { type: "array", items: { diff --git a/tools/eslint/lib/rules/no-sparse-arrays.js b/tools/eslint/lib/rules/no-sparse-arrays.js index 31bd6f2bbffb00..3044896c612d17 100644 --- a/tools/eslint/lib/rules/no-sparse-arrays.js +++ b/tools/eslint/lib/rules/no-sparse-arrays.js @@ -33,7 +33,7 @@ module.exports = { const emptySpot = node.elements.indexOf(null) > -1; if (emptySpot) { - context.report(node, "Unexpected comma in middle of array."); + context.report({ node, message: "Unexpected comma in middle of array." }); } } diff --git a/tools/eslint/lib/rules/no-tabs.js b/tools/eslint/lib/rules/no-tabs.js index d57ac324c1d58b..19983c57ba9ed4 100644 --- a/tools/eslint/lib/rules/no-tabs.js +++ b/tools/eslint/lib/rules/no-tabs.js @@ -17,7 +17,7 @@ const regex = /\t/; module.exports = { meta: { docs: { - description: "disallow tabs in file", + description: "disallow all tabs", category: "Stylistic Issues", recommended: false }, @@ -31,14 +31,10 @@ module.exports = { const match = regex.exec(line); if (match) { - context.report( - node, - { - line: index + 1, - column: match.index + 1 - }, - "Unexpected tab character." - ); + context.report({ node, loc: { + line: index + 1, + column: match.index + 1 + }, message: "Unexpected tab character." }); } }); } diff --git a/tools/eslint/lib/rules/no-ternary.js b/tools/eslint/lib/rules/no-ternary.js index 2408cd9c39a0ea..3e254f68126f5a 100644 --- a/tools/eslint/lib/rules/no-ternary.js +++ b/tools/eslint/lib/rules/no-ternary.js @@ -25,7 +25,7 @@ module.exports = { return { ConditionalExpression(node) { - context.report(node, "Ternary operator used."); + context.report({ node, message: "Ternary operator used." }); } }; diff --git a/tools/eslint/lib/rules/no-this-before-super.js b/tools/eslint/lib/rules/no-this-before-super.js index 80a769a481a44a..c8d5dc4698d7b0 100644 --- a/tools/eslint/lib/rules/no-this-before-super.js +++ b/tools/eslint/lib/rules/no-this-before-super.js @@ -179,7 +179,7 @@ module.exports = { return; } - codePath.traverseSegments(function(segment, controller) { + codePath.traverseSegments((segment, controller) => { const info = segInfoMap[segment.id]; for (let i = 0; i < info.invalidNodes.length; ++i) { @@ -236,8 +236,8 @@ module.exports = { // Update information inside of the loop. funcInfo.codePath.traverseSegments( - {first: toSegment, last: fromSegment}, - function(segment, controller) { + { first: toSegment, last: fromSegment }, + (segment, controller) => { const info = segInfoMap[segment.id]; if (info.superCalled) { diff --git a/tools/eslint/lib/rules/no-throw-literal.js b/tools/eslint/lib/rules/no-throw-literal.js index 034361c7a620c9..0d1f42985f89ec 100644 --- a/tools/eslint/lib/rules/no-throw-literal.js +++ b/tools/eslint/lib/rules/no-throw-literal.js @@ -65,10 +65,10 @@ module.exports = { ThrowStatement(node) { if (!couldBeError(node.argument)) { - context.report(node, "Expected an object to be thrown."); + context.report({ node, message: "Expected an object to be thrown." }); } else if (node.argument.type === "Identifier") { if (node.argument.name === "undefined") { - context.report(node, "Do not throw undefined."); + context.report({ node, message: "Do not throw undefined." }); } } diff --git a/tools/eslint/lib/rules/no-undef-init.js b/tools/eslint/lib/rules/no-undef-init.js index ca9f0272ba5bf5..9df40e9cebb186 100644 --- a/tools/eslint/lib/rules/no-undef-init.js +++ b/tools/eslint/lib/rules/no-undef-init.js @@ -41,7 +41,7 @@ module.exports = { context.report({ node, message: "It's not necessary to initialize '{{name}}' to undefined.", - data: {name}, + data: { name }, fix(fixer) { if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") { diff --git a/tools/eslint/lib/rules/no-undef.js b/tools/eslint/lib/rules/no-undef.js index 2cd2980f840581..74a33dd9973234 100644 --- a/tools/eslint/lib/rules/no-undef.js +++ b/tools/eslint/lib/rules/no-undef.js @@ -52,7 +52,7 @@ module.exports = { "Program:exit"(/* node */) { const globalScope = context.getScope(); - globalScope.through.forEach(function(ref) { + globalScope.through.forEach(ref => { const identifier = ref.identifier; if (!considerTypeOf && hasTypeOfOperator(identifier)) { diff --git a/tools/eslint/lib/rules/no-undefined.js b/tools/eslint/lib/rules/no-undefined.js index 2aad3d0d1f4b55..18e1d98641dc86 100644 --- a/tools/eslint/lib/rules/no-undefined.js +++ b/tools/eslint/lib/rules/no-undefined.js @@ -28,7 +28,7 @@ module.exports = { const parent = context.getAncestors().pop(); if (!parent || parent.type !== "MemberExpression" || node !== parent.property || parent.computed) { - context.report(node, "Unexpected use of undefined."); + context.report({ node, message: "Unexpected use of undefined." }); } } } diff --git a/tools/eslint/lib/rules/no-underscore-dangle.js b/tools/eslint/lib/rules/no-underscore-dangle.js index abc5967b5348be..6803cc68fc7e81 100644 --- a/tools/eslint/lib/rules/no-underscore-dangle.js +++ b/tools/eslint/lib/rules/no-underscore-dangle.js @@ -57,9 +57,7 @@ module.exports = { * @private */ function isAllowed(identifier) { - return ALLOWED_VARIABLES.some(function(ident) { - return ident === identifier; - }); + return ALLOWED_VARIABLES.some(ident => ident === identifier); } /** diff --git a/tools/eslint/lib/rules/no-unexpected-multiline.js b/tools/eslint/lib/rules/no-unexpected-multiline.js index 5208813dadada0..bae4833983b14e 100644 --- a/tools/eslint/lib/rules/no-unexpected-multiline.js +++ b/tools/eslint/lib/rules/no-unexpected-multiline.js @@ -45,7 +45,7 @@ module.exports = { } if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { - context.report(node, openParen.loc.start, msg, { char: openParen.value }); + context.report({ node, loc: openParen.loc.start, message: msg, data: { char: openParen.value } }); } } @@ -66,7 +66,7 @@ module.exports = { if (node.tag.loc.end.line === node.quasi.loc.start.line) { return; } - context.report(node, node.loc.start, TAGGED_TEMPLATE_MESSAGE); + context.report({ node, loc: node.loc.start, message: TAGGED_TEMPLATE_MESSAGE }); }, CallExpression(node) { diff --git a/tools/eslint/lib/rules/no-unneeded-ternary.js b/tools/eslint/lib/rules/no-unneeded-ternary.js index c755f5f4b4fd11..cba83ea48140ec 100644 --- a/tools/eslint/lib/rules/no-unneeded-ternary.js +++ b/tools/eslint/lib/rules/no-unneeded-ternary.js @@ -5,6 +5,19 @@ "use strict"; +const astUtils = require("../ast-utils"); + +// Operators that always result in a boolean value +const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]); +const OPERATOR_INVERSES = { + "==": "!=", + "!=": "==", + "===": "!==", + "!==": "===" + + // Operators like < and >= are not true inverses, since both will return false with NaN. +}; + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -27,12 +40,15 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "code" }, create(context) { const options = context.options[0] || {}; const defaultAssignment = options.defaultAssignment !== false; + const sourceCode = context.getSourceCode(); /** * Test if the node is a boolean literal @@ -44,6 +60,34 @@ module.exports = { return node.type === "Literal" && typeof node.value === "boolean"; } + /** + * Creates an expression that represents the boolean inverse of the expression represented by the original node + * @param {ASTNode} node A node representing an expression + * @returns {string} A string representing an inverted expression + */ + function invertExpression(node) { + if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) { + const operatorToken = sourceCode.getTokensBetween(node.left, node.right).find(token => token.value === node.operator); + + return sourceCode.getText().slice(node.range[0], operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + sourceCode.getText().slice(operatorToken.range[1], node.range[1]); + } + + if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) { + return `!(${astUtils.getParenthesisedText(sourceCode, node)})`; + } + return `!${astUtils.getParenthesisedText(sourceCode, node)}`; + } + + /** + * Tests if a given node always evaluates to a boolean value + * @param {ASTNode} node - An expression node + * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value + */ + function isBooleanExpression(node) { + return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) || + node.type === "UnaryExpression" && node.operator === "!"; + } + /** * Test if the node matches the pattern id ? id : expression * @param {ASTNode} node - The ConditionalExpression to check. @@ -60,9 +104,34 @@ module.exports = { ConditionalExpression(node) { if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) { - context.report(node, node.consequent.loc.start, "Unnecessary use of boolean literals in conditional expression."); + context.report({ + node, + loc: node.consequent.loc.start, + message: "Unnecessary use of boolean literals in conditional expression.", + fix(fixer) { + if (node.consequent.value === node.alternate.value) { + + // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true` + return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null; + } + if (node.alternate.value) { + + // Replace `foo() ? false : true` with `!(foo())` + return fixer.replaceText(node, invertExpression(node.test)); + } + + // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise. + + return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`); + } + }); } else if (!defaultAssignment && matchesDefaultAssignment(node)) { - context.report(node, node.consequent.loc.start, "Unnecessary use of conditional expression for default assignment."); + context.report({ + node, + loc: node.consequent.loc.start, + message: "Unnecessary use of conditional expression for default assignment.", + fix: fixer => fixer.replaceText(node, `${astUtils.getParenthesisedText(sourceCode, node.test)} || ${astUtils.getParenthesisedText(sourceCode, node.alternate)}`) + }); } } }; diff --git a/tools/eslint/lib/rules/no-unused-expressions.js b/tools/eslint/lib/rules/no-unused-expressions.js index cdabca204a64df..548e02f463e71a 100644 --- a/tools/eslint/lib/rules/no-unused-expressions.js +++ b/tools/eslint/lib/rules/no-unused-expressions.js @@ -108,7 +108,7 @@ module.exports = { return { ExpressionStatement(node) { if (!isValidExpression(node.expression) && !isDirective(node, context.getAncestors())) { - context.report(node, "Expected an assignment or function call and instead saw an expression."); + context.report({ node, message: "Expected an assignment or function call and instead saw an expression." }); } } }; diff --git a/tools/eslint/lib/rules/no-unused-vars.js b/tools/eslint/lib/rules/no-unused-vars.js index 683176e944f357..ac8f2ed1c0a20a 100644 --- a/tools/eslint/lib/rules/no-unused-vars.js +++ b/tools/eslint/lib/rules/no-unused-vars.js @@ -156,28 +156,6 @@ module.exports = { return false; } - /** - * Checks whether a given node is inside of a loop or not. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is inside of a loop. - * @private - */ - function isInsideOfLoop(node) { - while (node) { - if (astUtils.isLoop(node)) { - return true; - } - if (astUtils.isFunction(node)) { - return false; - } - - node = node.parent; - } - - return false; - } - /** * Checks the position of given nodes. * @@ -215,7 +193,7 @@ module.exports = { const granpa = parent.parent; const refScope = ref.from.variableScope; const varScope = ref.resolved.scope.variableScope; - const canBeUsedLater = refScope !== varScope || isInsideOfLoop(id); + const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id); /* * Inherits the previous node if this reference is in the node. @@ -390,15 +368,11 @@ module.exports = { * @private */ function isUsedVariable(variable) { - const functionNodes = variable.defs.filter(function(def) { - return def.type === "FunctionName"; - }).map(function(def) { - return def.node; - }), + const functionNodes = variable.defs.filter(def => def.type === "FunctionName").map(def => def.node), isFunctionDefinition = functionNodes.length > 0; let rhsNode = null; - return variable.references.some(function(ref) { + return variable.references.some(ref => { if (isForInRef(ref)) { return true; } diff --git a/tools/eslint/lib/rules/no-use-before-define.js b/tools/eslint/lib/rules/no-use-before-define.js index 01c899ca3920c4..ea1cf301f29af4 100644 --- a/tools/eslint/lib/rules/no-use-before-define.js +++ b/tools/eslint/lib/rules/no-use-before-define.js @@ -29,7 +29,7 @@ function parseOptions(options) { classes = options.classes !== false; } - return {functions, classes}; + return { functions, classes }; } /** @@ -154,8 +154,8 @@ module.exports = { { type: "object", properties: { - functions: {type: "boolean"}, - classes: {type: "boolean"} + functions: { type: "boolean" }, + classes: { type: "boolean" } }, additionalProperties: false } @@ -187,7 +187,7 @@ module.exports = { * @private */ function findVariablesInScope(scope) { - scope.references.forEach(function(reference) { + scope.references.forEach(reference => { const variable = reference.resolved; // Skips when the reference is: diff --git a/tools/eslint/lib/rules/no-useless-call.js b/tools/eslint/lib/rules/no-useless-call.js index 2be665992a08e5..eb67bcb3b25271 100644 --- a/tools/eslint/lib/rules/no-useless-call.js +++ b/tools/eslint/lib/rules/no-useless-call.js @@ -96,10 +96,7 @@ module.exports = { const thisArg = node.arguments[0]; if (isValidThisArg(expectedThis, thisArg, sourceCode)) { - context.report( - node, - "unnecessary '.{{name}}()'.", - {name: node.callee.property.name}); + context.report({ node, message: "unnecessary '.{{name}}()'.", data: { name: node.callee.property.name } }); } } }; diff --git a/tools/eslint/lib/rules/no-useless-concat.js b/tools/eslint/lib/rules/no-useless-concat.js index d9cf6a2c354b8b..ed0ef66a2441e1 100644 --- a/tools/eslint/lib/rules/no-useless-concat.js +++ b/tools/eslint/lib/rules/no-useless-concat.js @@ -93,10 +93,11 @@ module.exports = { operatorToken = sourceCode.getTokenAfter(operatorToken); } - context.report( + context.report({ node, - operatorToken.loc.start, - "Unexpected string concatenation of literals."); + loc: operatorToken.loc.start, + message: "Unexpected string concatenation of literals." + }); } } }; diff --git a/tools/eslint/lib/rules/no-useless-escape.js b/tools/eslint/lib/rules/no-useless-escape.js index 629a52a7ec9b9f..b9266bbbafa69a 100644 --- a/tools/eslint/lib/rules/no-useless-escape.js +++ b/tools/eslint/lib/rules/no-useless-escape.js @@ -5,57 +5,70 @@ "use strict"; +const astUtils = require("../ast-utils"); + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ -const VALID_STRING_ESCAPES = [ - "\\", - "n", - "r", - "v", - "t", - "b", - "f", - "u", - "x", - "\n", - "\r" -]; - -const VALID_REGEX_ESCAPES = [ - "\\", - ".", - "-", - "^", - "$", - "*", - "+", - "?", - "{", - "}", - "[", - "]", - "|", - "(", - ")", - "b", - "B", - "c", - "d", - "D", - "f", - "n", - "r", - "s", - "S", - "t", - "v", - "w", - "W", - "x", - "u" -]; +/** +* Returns the union of two sets. +* @param {Set} setA The first set +* @param {Set} setB The second set +* @returns {Set} The union of the two sets +*/ +function union(setA, setB) { + return new Set(function *() { + yield* setA; + yield* setB; + }()); +} + +const VALID_STRING_ESCAPES = new Set("\\nrvtbfux\n\r\u2028\u2029"); +const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnrsStvwWxu0123456789]"); +const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()B")); + +/** +* Parses a regular expression into a list of characters with character class info. +* @param {string} regExpText The raw text used to create the regular expression +* @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class. +* @example +* +* parseRegExp('a\\b[cd-]') +* +* returns: +* [ +* {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false}, +* {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false}, +* {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false}, +* {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}, +* {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false} +* ] +*/ +function parseRegExp(regExpText) { + const charList = []; + + regExpText.split("").reduce((state, char, index) => { + if (!state.escapeNextChar) { + if (char === "\\") { + return Object.assign(state, { escapeNextChar: true }); + } + if (char === "[" && !state.inCharClass) { + return Object.assign(state, { inCharClass: true, startingCharClass: true }); + } + if (char === "]" && state.inCharClass) { + if (charList.length && charList[charList.length - 1].inCharClass) { + charList[charList.length - 1].endsCharClass = true; + } + return Object.assign(state, { inCharClass: false, startingCharClass: false }); + } + } + charList.push({ text: char, index, escaped: state.escapeNextChar, inCharClass: state.inCharClass, startsCharClass: state.startingCharClass, endsCharClass: false }); + return Object.assign(state, { escapeNextChar: false, startingCharClass: false }); + }, { escapeNextChar: false, inCharClass: false, startingCharClass: false }); + + return charList; +} module.exports = { meta: { @@ -69,20 +82,36 @@ module.exports = { }, create(context) { + const sourceCode = context.getSourceCode(); + + /** + * Reports a node + * @param {ASTNode} node The node to report + * @param {number} startOffset The backslash's offset from the start of the node + * @param {string} character The uselessly escaped character (not including the backslash) + * @returns {void} + */ + function report(node, startOffset, character) { + context.report({ + node, + loc: astUtils.getLocationFromRangeIndex(sourceCode, astUtils.getRangeIndexFromLocation(sourceCode, node.loc.start) + startOffset), + message: "Unnecessary escape character: \\{{character}}.", + data: { character } + }); + } /** - * Checks if the escape character in given slice is unnecessary. + * Checks if the escape character in given string slice is unnecessary. * * @private - * @param {string[]} escapes - list of valid escapes * @param {ASTNode} node - node to validate. * @param {string} match - string slice to validate. * @returns {void} */ - function validate(escapes, node, match) { + function validateString(node, match) { const isTemplateElement = node.type === "TemplateElement"; const escapedChar = match[0][1]; - let isUnnecessaryEscape = escapes.indexOf(escapedChar) === -1; + let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar); let isQuoteEscape; if (isTemplateElement) { @@ -105,17 +134,7 @@ module.exports = { } if (isUnnecessaryEscape && !isQuoteEscape) { - context.report({ - node, - loc: { - line: node.loc.start.line, - column: node.loc.start.column + match.index - }, - message: "Unnecessary escape character: {{character}}.", - data: { - character: match[0] - } - }); + report(node, match.index + 1, match[0].slice(1)); } } @@ -127,10 +146,12 @@ module.exports = { */ function check(node) { const isTemplateElement = node.type === "TemplateElement"; - const value = isTemplateElement ? node.value.raw : node.raw; - const pattern = /\\[^\d]/g; - let nodeEscapes, - match; + + if (isTemplateElement && node.parent && node.parent.parent && node.parent.parent.type === "TaggedTemplateExpression") { + + // Don't report tagged template literals, because the backslash character is accessible to the tag function. + return; + } if (typeof node.value === "string" || isTemplateElement) { @@ -138,20 +159,46 @@ module.exports = { * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/. * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25. */ - if (node.parent.type === "JSXAttribute") { + if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement") { return; } - nodeEscapes = VALID_STRING_ESCAPES; + const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1); + const pattern = /\\[^\d]/g; + let match; + + while ((match = pattern.exec(value))) { + validateString(node, match); + } } else if (node.regex) { - nodeEscapes = VALID_REGEX_ESCAPES; - } else { - return; - } + parseRegExp(node.regex.pattern) - while ((match = pattern.exec(value))) { - validate(nodeEscapes, node, match); + /* + * The '-' character is a special case, because it's only valid to escape it if it's in a character + * class, and is not at either edge of the character class. To account for this, don't consider '-' + * characters to be valid in general, and filter out '-' characters that appear in the middle of a + * character class. + */ + .filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass)) + + /* + * The '^' character is also a special case; it must always be escaped outside of character classes, but + * it only needs to be escaped in character classes if it's at the beginning of the character class. To + * account for this, consider it to be a valid escape character outside of character classes, and filter + * out '^' characters that appear at the start of a character class. + */ + .filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass)) + + // Filter out characters that aren't escaped. + .filter(charInfo => charInfo.escaped) + + // Filter out characters that are valid to escape, based on their position in the regular expression. + .filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text)) + + // Report all the remaining characters. + .forEach(charInfo => report(node, charInfo.index, charInfo.text)); } + } return { diff --git a/tools/eslint/lib/rules/no-useless-return.js b/tools/eslint/lib/rules/no-useless-return.js new file mode 100644 index 00000000000000..e2a6da03183501 --- /dev/null +++ b/tools/eslint/lib/rules/no-useless-return.js @@ -0,0 +1,293 @@ +/** + * @fileoverview Disallow redundant return statements + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("../ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Adds all elements of 2nd argument into 1st argument. + * + * @param {Array} array - The destination array to add. + * @param {Array} elements - The source array to add. + * @returns {void} + */ +const pushAll = Function.apply.bind(Array.prototype.push); + +/** + * Removes the given element from the array. + * + * @param {Array} array - The source array to remove. + * @param {any} element - The target item to remove. + * @returns {void} + */ +function remove(array, element) { + const index = array.indexOf(element); + + if (index !== -1) { + array.splice(index, 1); + } +} + +/** + * Checks whether it can remove the given return statement or not. + * + * @param {ASTNode} node - The return statement node to check. + * @returns {boolean} `true` if the node is removeable. + */ +function isRemovable(node) { + const parent = node.parent; + + return ( + parent.type === "Program" || + parent.type === "BlockStatement" || + parent.type === "SwitchCase" + ); +} + +/** + * Checks whether the given return statement is in a `finally` block or not. + * + * @param {ASTNode} node - The return statement node to check. + * @returns {boolean} `true` if the node is in a `finally` block. + */ +function isInFinally(node) { + while (node && node.parent && !astUtils.isFunction(node)) { + if (node.parent.type === "TryStatement" && node.parent.finalizer === node) { + return true; + } + + node = node.parent; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "disallow redundant return statements", + category: "Best Practices", + recommended: false + }, + fixable: "code", + schema: [] + }, + + create(context) { + const segmentInfoMap = new WeakMap(); + const usedUnreachableSegments = new WeakSet(); + let scopeInfo = null; + + /** + * Checks whether the given segment is terminated by a return statement or not. + * + * @param {CodePathSegment} segment - The segment to check. + * @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. + */ + function isReturned(segment) { + const info = segmentInfoMap.get(segment); + + return !info || info.returned; + } + + /** + * Collects useless return statements from the given previous segments. + * + * A previous segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * + * @param {ASTNode[]} uselessReturns - The collected return statements. + * @param {CodePathSegment[]} prevSegments - The previous segments to traverse. + * @param {WeakSet} [traversedSegments] A set of segments that have already been traversed in this call + * @returns {ASTNode[]} `uselessReturns`. + */ + function getUselessReturns(uselessReturns, prevSegments, traversedSegments) { + if (!traversedSegments) { + traversedSegments = new WeakSet(); + } + for (const segment of prevSegments) { + if (!segment.reachable) { + if (!traversedSegments.has(segment)) { + traversedSegments.add(segment); + getUselessReturns( + uselessReturns, + segment.allPrevSegments.filter(isReturned), + traversedSegments + ); + } + continue; + } + + pushAll(uselessReturns, segmentInfoMap.get(segment).uselessReturns); + } + + return uselessReturns; + } + + /** + * Removes the return statements on the given segment from the useless return + * statement list. + * + * This segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * + * @param {CodePathSegment} segment - The segment to get return statements. + * @returns {void} + */ + function markReturnStatementsOnSegmentAsUsed(segment) { + if (!segment.reachable) { + usedUnreachableSegments.add(segment); + segment.allPrevSegments + .filter(isReturned) + .filter(prevSegment => !usedUnreachableSegments.has(prevSegment)) + .forEach(markReturnStatementsOnSegmentAsUsed); + return; + } + + const info = segmentInfoMap.get(segment); + + for (const node of info.uselessReturns) { + remove(scopeInfo.uselessReturns, node); + } + info.uselessReturns = []; + } + + /** + * Removes the return statements on the current segments from the useless + * return statement list. + * + * This function will be called at every statement except FunctionDeclaration, + * BlockStatement, and BreakStatement. + * + * - FunctionDeclarations are always executed whether it's returned or not. + * - BlockStatements do nothing. + * - BreakStatements go the next merely. + * + * @returns {void} + */ + function markReturnStatementsOnCurrentSegmentsAsUsed() { + scopeInfo + .codePath + .currentSegments + .forEach(markReturnStatementsOnSegmentAsUsed); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + + // Makes and pushs a new scope information. + onCodePathStart(codePath) { + scopeInfo = { + upper: scopeInfo, + uselessReturns: [], + codePath, + }; + }, + + // Reports useless return statements if exist. + onCodePathEnd() { + for (const node of scopeInfo.uselessReturns) { + context.report({ + node, + loc: node.loc, + message: "Unnecessary return statement.", + fix(fixer) { + return isRemovable(node) ? fixer.remove(node) : null; + }, + }); + } + + scopeInfo = scopeInfo.upper; + }, + + // Initializes segments. + // NOTE: This event is notified for only reachable segments. + onCodePathSegmentStart(segment) { + const info = { + uselessReturns: getUselessReturns([], segment.allPrevSegments), + returned: false, + }; + + // Stores the info. + segmentInfoMap.set(segment, info); + }, + + // Adds ReturnStatement node to check whether it's useless or not. + ReturnStatement(node) { + if (node.argument) { + markReturnStatementsOnCurrentSegmentsAsUsed(); + } + if (node.argument || astUtils.isInLoop(node) || isInFinally(node)) { + return; + } + + for (const segment of scopeInfo.codePath.currentSegments) { + const info = segmentInfoMap.get(segment); + + if (info) { + info.uselessReturns.push(node); + info.returned = true; + } + } + scopeInfo.uselessReturns.push(node); + }, + + // Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. + // Removes return statements of the current segments from the useless return statement list. + ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + }; + } +}; diff --git a/tools/eslint/lib/rules/no-var.js b/tools/eslint/lib/rules/no-var.js index 0e98170e65e7c1..3c22f009c63bb6 100644 --- a/tools/eslint/lib/rules/no-var.js +++ b/tools/eslint/lib/rules/no-var.js @@ -5,10 +5,67 @@ "use strict"; +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("../ast-utils"); + //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ +/** + * Finds the nearest function scope or global scope walking up the scope + * hierarchy. + * + * @param {escope.Scope} scope - The scope to traverse. + * @returns {escope.Scope} a function scope or global scope containing the given + * scope. + */ +function getEnclosingFunctionScope(scope) { + while (scope.type !== "function" && scope.type !== "global") { + scope = scope.upper; + } + return scope; +} + +/** + * Checks whether the given variable has any references from a more specific + * function expression (i.e. a closure). + * + * @param {escope.Variable} variable - A variable to check. + * @returns {boolean} `true` if the variable is used from a closure. + */ +function isReferencedInClosure(variable) { + const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope); + + return variable.references.some(reference => + getEnclosingFunctionScope(reference.from) !== enclosingFunctionScope); +} + +/** + * Checks whether the given node is the assignee of a loop. + * + * @param {ASTNode} node - A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration is assigned as part of loop + * iteration. + */ +function isLoopAssignee(node) { + return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") && + node === node.parent.left; +} + +/** + * Checks whether the given variable declaration is immediately initialized. + * + * @param {ASTNode} node - A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration has an initializer. + */ +function isDeclarationInitialized(node) { + return node.declarations.every(declarator => declarator.init !== null); +} + const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/; /** @@ -97,6 +154,8 @@ module.exports = { * - A variable is declared on a SwitchCase node. * - A variable is redeclared. * - A variable is used from outside the scope. + * - A variable is used from a closure within a loop. + * - A variable might be used before it is assigned within a loop. * * ## A variable is declared on a SwitchCase node. * @@ -115,6 +174,25 @@ module.exports = { * The language spec disallows accesses from outside of the scope for * `let` declarations. Those variables would cause reference errors. * + * ## A variable is used from a closure within a loop. + * + * A `var` declaration within a loop shares the same variable instance + * across all loop iterations, while a `let` declaration creates a new + * instance for each iteration. This means if a variable in a loop is + * referenced by any closure, changing it from `var` to `let` would + * change the behavior in a way that is generally unsafe. + * + * ## A variable might be used before it is assigned within a loop. + * + * Within a loop, a `let` declaration without an initializer will be + * initialized to null, while a `var` declaration will retain its value + * from the previous iteration, so it is only safe to change `var` to + * `let` if we can statically determine that the variable is always + * assigned a value before its first access in the loop body. To keep + * the implementation simple, we only convert `var` to `let` within + * loops when the variable is a loop assignee or the declaration has an + * initializer. + * * @param {ASTNode} node - A variable declaration node to check. * @returns {boolean} `true` if it can fix the node. */ @@ -122,11 +200,22 @@ module.exports = { const variables = context.getDeclaredVariables(node); const scopeNode = getScopeNode(node); - return !( - node.parent.type === "SwitchCase" || - variables.some(isRedeclared) || - variables.some(isUsedFromOutsideOf(scopeNode)) - ); + if (node.parent.type === "SwitchCase" || + variables.some(isRedeclared) || + variables.some(isUsedFromOutsideOf(scopeNode))) { + return false; + } + + if (astUtils.isInLoop(node)) { + if (variables.some(isReferencedInClosure)) { + return false; + } + if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) { + return false; + } + } + + return true; } /** diff --git a/tools/eslint/lib/rules/no-void.js b/tools/eslint/lib/rules/no-void.js index 16a36fb3a56df1..5202fa49a8543a 100644 --- a/tools/eslint/lib/rules/no-void.js +++ b/tools/eslint/lib/rules/no-void.js @@ -28,7 +28,7 @@ module.exports = { return { UnaryExpression(node) { if (node.operator === "void") { - context.report(node, "Expected 'undefined' and instead saw 'void'."); + context.report({ node, message: "Expected 'undefined' and instead saw 'void'." }); } } }; diff --git a/tools/eslint/lib/rules/no-warning-comments.js b/tools/eslint/lib/rules/no-warning-comments.js index 511bd9bb48d6ed..bda43086865a1c 100644 --- a/tools/eslint/lib/rules/no-warning-comments.js +++ b/tools/eslint/lib/rules/no-warning-comments.js @@ -54,7 +54,7 @@ module.exports = { * @returns {RegExp} The term converted to a RegExp */ function convertToRegExp(term) { - const escaped = term.replace(/[-\/\\$\^*+?.()|\[\]{}]/g, "\\$&"); + const escaped = term.replace(/[-/\\$^*+?.()|[\]{}]/g, "\\$&"); let prefix; /* @@ -95,7 +95,7 @@ module.exports = { function commentContainsWarningTerm(comment) { const matches = []; - warningRegExps.forEach(function(regex, index) { + warningRegExps.forEach((regex, index) => { if (regex.test(comment)) { matches.push(warningTerms[index]); } @@ -116,7 +116,7 @@ module.exports = { const matches = commentContainsWarningTerm(node.value); - matches.forEach(function(matchedTerm) { + matches.forEach(matchedTerm => { context.report({ node, message: "Unexpected '{{matchedTerm}}' comment.", diff --git a/tools/eslint/lib/rules/no-with.js b/tools/eslint/lib/rules/no-with.js index 6d5bfd8e61605e..be9e3463606404 100644 --- a/tools/eslint/lib/rules/no-with.js +++ b/tools/eslint/lib/rules/no-with.js @@ -24,7 +24,7 @@ module.exports = { return { WithStatement(node) { - context.report(node, "Unexpected use of 'with' statement."); + context.report({ node, message: "Unexpected use of 'with' statement." }); } }; diff --git a/tools/eslint/lib/rules/object-curly-newline.js b/tools/eslint/lib/rules/object-curly-newline.js index 3ba786a6f1e2c2..88fc79463cb6ae 100644 --- a/tools/eslint/lib/rules/object-curly-newline.js +++ b/tools/eslint/lib/rules/object-curly-newline.js @@ -61,7 +61,7 @@ function normalizeOptionValue(value) { multiline = true; } - return {multiline, minProperties}; + return { multiline, minProperties }; } /** @@ -80,7 +80,7 @@ function normalizeOptions(options) { const value = normalizeOptionValue(options); - return {ObjectExpression: value, ObjectPattern: value}; + return { ObjectExpression: value, ObjectPattern: value }; } //------------------------------------------------------------------------------ diff --git a/tools/eslint/lib/rules/object-property-newline.js b/tools/eslint/lib/rules/object-property-newline.js index f06cb41843e534..a64420be93a910 100644 --- a/tools/eslint/lib/rules/object-property-newline.js +++ b/tools/eslint/lib/rules/object-property-newline.js @@ -27,7 +27,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "whitespace" }, create(context) { @@ -61,7 +63,18 @@ module.exports = { context.report({ node, loc: firstTokenOfCurrentProperty.loc.start, - message: errorMessage + message: errorMessage, + fix(fixer) { + const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty); + const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]]; + + // Don't perform a fix if there are any comments between the comma and the next property. + if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) { + return null; + } + + return fixer.replaceTextRange(rangeAfterComma, "\n"); + } }); } } diff --git a/tools/eslint/lib/rules/object-shorthand.js b/tools/eslint/lib/rules/object-shorthand.js index 3ef782461a4018..43997f90692de5 100644 --- a/tools/eslint/lib/rules/object-shorthand.js +++ b/tools/eslint/lib/rules/object-shorthand.js @@ -77,6 +77,9 @@ module.exports = { }, avoidQuotes: { type: "boolean" + }, + avoidExplicitReturnArrows: { + type: "boolean" } }, additionalProperties: false @@ -100,6 +103,8 @@ module.exports = { const PARAMS = context.options[1] || {}; const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors; const AVOID_QUOTES = PARAMS.avoidQuotes; + const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows; + const sourceCode = context.getSourceCode(); //-------------------------------------------------------------------------- // Helpers @@ -188,7 +193,7 @@ module.exports = { // We have at least 1 shorthand property if (shorthandProperties.length > 0) { - context.report(node, "Unexpected mix of shorthand and non-shorthand properties."); + context.report({ node, message: "Unexpected mix of shorthand and non-shorthand properties." }); } else if (checkRedundancy) { // If all properties of the object contain a method or value with a name matching it's key, @@ -196,18 +201,143 @@ module.exports = { const canAlwaysUseShorthand = properties.every(isRedundant); if (canAlwaysUseShorthand) { - context.report(node, "Expected shorthand for all properties."); + context.report({ node, message: "Expected shorthand for all properties." }); } } } } } + /** + * Fixes a FunctionExpression node by making it into a shorthand property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionShorthand(fixer, node) { + const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); + let keyPrefix = ""; + + if (node.value.generator) { + keyPrefix = "*"; + } else if (node.value.async) { + keyPrefix = "async "; + } + + if (node.value.type === "FunctionExpression") { + const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function"); + const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken; + + return fixer.replaceTextRange([firstKeyToken.range[0], tokenBeforeParams.range[1]], keyPrefix + keyText); + } else { + const arrowToken = sourceCode.getTokens(node.value).find(token => token.value === "=>"); + const tokenBeforeArrow = sourceCode.getTokenBefore(arrowToken); + const hasParensAroundParameters = tokenBeforeArrow.type === "Punctuator" && tokenBeforeArrow.value === ")"; + const oldParamText = sourceCode.text.slice(sourceCode.getFirstToken(node.value, node.value.async ? 1 : 0).range[0], tokenBeforeArrow.range[1]); + const newParamText = hasParensAroundParameters ? oldParamText : `(${oldParamText})`; + + return fixer.replaceTextRange([firstKeyToken.range[0], arrowToken.range[1]], keyPrefix + keyText + newParamText); + } + } + + /** + * Fixes a FunctionExpression node by making it into a longform property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionLongform(fixer, node) { + const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); + let functionHeader = "function"; + + if (node.value.generator) { + functionHeader = "function*"; + } else if (node.value.async) { + functionHeader = "async function"; + } + + return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`); + } + + /* + * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`), + * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is + * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical + * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered, + * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited. + * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them + * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule, + * because converting it into a method would change the value of one of the lexical identifiers. + */ + const lexicalScopeStack = []; + const arrowsWithLexicalIdentifiers = new WeakSet(); + const argumentsIdentifiers = new WeakSet(); + + /** + * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. + * Also, this marks all `arguments` identifiers so that they can be detected later. + * @returns {void} + */ + function enterFunction() { + lexicalScopeStack.unshift(new Set()); + context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => { + variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier)); + }); + } + + /** + * Exits a function. This pops the current set of arrow functions off the lexical scope stack. + * @returns {void} + */ + function exitFunction() { + lexicalScopeStack.shift(); + } + + /** + * Marks the current function as having a lexical keyword. This implies that all arrow functions + * in the current lexical scope contain a reference to this lexical keyword. + * @returns {void} + */ + function reportLexicalIdentifier() { + lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction)); + } + //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { + Program: enterFunction, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + "Program:exit": exitFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + + ArrowFunctionExpression(node) { + lexicalScopeStack[0].add(node); + }, + "ArrowFunctionExpression:exit"(node) { + lexicalScopeStack[0].delete(node); + }, + + ThisExpression: reportLexicalIdentifier, + Super: reportLexicalIdentifier, + MetaProperty(node) { + if (node.meta.name === "new" && node.property.name === "target") { + reportLexicalIdentifier(); + } + }, + Identifier(node) { + if (argumentsIdentifiers.has(node)) { + reportLexicalIdentifier(); + } + }, + ObjectExpression(node) { if (APPLY_CONSISTENT) { checkConsistency(node, false); @@ -216,7 +346,7 @@ module.exports = { } }, - Property(node) { + "Property:exit"(node) { const isConciseProperty = node.method || node.shorthand; // Ignore destructuring assignment @@ -230,59 +360,31 @@ module.exports = { } // only computed methods can fail the following checks - if (node.computed && node.value.type !== "FunctionExpression") { + if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") { return; } //-------------------------------------------------------------- // Checks for property/method shorthand. if (isConciseProperty) { + if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) { - // if we're "never" and concise we should warn now - if (APPLY_NEVER) { - const type = node.method ? "method" : "property"; - + // { x() {} } should be written as { x: function() {} } context.report({ node, - message: "Expected longform {{type}} syntax.", - data: { - type - }, - fix(fixer) { - if (node.method) { - if (node.value.generator) { - return fixer.replaceTextRange([node.range[0], node.key.range[1]], `${node.key.name}: function*`); - } - - return fixer.insertTextAfter(node.key, ": function"); - } - - return fixer.insertTextAfter(node.key, `: ${node.key.name}`); - } + message: `Expected longform method syntax${APPLY_NEVER ? "" : " for string literal keys"}.`, + fix: fixer => makeFunctionLongform(fixer, node) }); - } + } else if (APPLY_NEVER) { - // {'xyz'() {}} should be written as {'xyz': function() {}} - if (AVOID_QUOTES && isStringLiteral(node.key)) { + // { x } should be written as { x: x } context.report({ node, - message: "Expected longform method syntax for string literal keys.", - fix(fixer) { - if (node.computed) { - return fixer.insertTextAfterRange([node.key.range[0], node.key.range[1] + 1], ": function"); - } - - return fixer.insertTextAfter(node.key, ": function"); - } + message: "Expected longform property syntax.", + fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`) }); } - - return; - } - - //-------------------------------------------------------------- - // Checks for longform properties. - if (node.value.type === "FunctionExpression" && !node.value.id && APPLY_TO_METHODS) { + } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) { if (IGNORE_CONSTRUCTORS && isConstructor(node.key.name)) { return; } @@ -291,39 +393,18 @@ module.exports = { } // {[x]: function(){}} should be written as {[x]() {}} - if (node.computed) { + if (node.value.type === "FunctionExpression" || + node.value.type === "ArrowFunctionExpression" && + node.value.body.type === "BlockStatement" && + AVOID_EXPLICIT_RETURN_ARROWS && + !arrowsWithLexicalIdentifiers.has(node.value) + ) { context.report({ node, message: "Expected method shorthand.", - fix(fixer) { - if (node.value.generator) { - return fixer.replaceTextRange( - [node.key.range[0], node.value.range[0] + "function*".length], - `*[${node.key.name}]` - ); - } - - return fixer.removeRange([node.key.range[1] + 1, node.value.range[0] + "function".length]); - } + fix: fixer => makeFunctionShorthand(fixer, node) }); - return; } - - // {x: function(){}} should be written as {x() {}} - context.report({ - node, - message: "Expected method shorthand.", - fix(fixer) { - if (node.value.generator) { - return fixer.replaceTextRange( - [node.key.range[0], node.value.range[0] + "function*".length], - `*${node.key.name}` - ); - } - - return fixer.removeRange([node.key.range[1], node.value.range[0] + "function".length]); - } - }); } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) { // {x: x} should be written as {x} diff --git a/tools/eslint/lib/rules/one-var-declaration-per-line.js b/tools/eslint/lib/rules/one-var-declaration-per-line.js index eb0d5c3bf1ad74..61b505c82d5d71 100644 --- a/tools/eslint/lib/rules/one-var-declaration-per-line.js +++ b/tools/eslint/lib/rules/one-var-declaration-per-line.js @@ -59,7 +59,7 @@ module.exports = { const declarations = node.declarations; let prev; - declarations.forEach(function(current) { + declarations.forEach(current => { if (prev && prev.loc.end.line === current.loc.start.line) { if (always || prev.init || current.init) { context.report({ diff --git a/tools/eslint/lib/rules/one-var.js b/tools/eslint/lib/rules/one-var.js index 27166559714065..9e40d4ea6f26c1 100644 --- a/tools/eslint/lib/rules/one-var.js +++ b/tools/eslint/lib/rules/one-var.js @@ -66,18 +66,18 @@ module.exports = { }; if (typeof mode === "string") { // simple options configuration with just a string - options.var = { uninitialized: mode, initialized: mode}; - options.let = { uninitialized: mode, initialized: mode}; - options.const = { uninitialized: mode, initialized: mode}; + options.var = { uninitialized: mode, initialized: mode }; + options.let = { uninitialized: mode, initialized: mode }; + options.const = { uninitialized: mode, initialized: mode }; } else if (typeof mode === "object") { // options configuration is an object if (mode.hasOwnProperty("var") && typeof mode.var === "string") { - options.var = { uninitialized: mode.var, initialized: mode.var}; + options.var = { uninitialized: mode.var, initialized: mode.var }; } if (mode.hasOwnProperty("let") && typeof mode.let === "string") { - options.let = { uninitialized: mode.let, initialized: mode.let}; + options.let = { uninitialized: mode.let, initialized: mode.let }; } if (mode.hasOwnProperty("const") && typeof mode.const === "string") { - options.const = { uninitialized: mode.const, initialized: mode.const}; + options.const = { uninitialized: mode.const, initialized: mode.const }; } if (mode.hasOwnProperty("uninitialized")) { if (!options.var) { @@ -123,8 +123,8 @@ module.exports = { */ function startBlock() { blockStack.push({ - let: {initialized: false, uninitialized: false}, - const: {initialized: false, uninitialized: false} + let: { initialized: false, uninitialized: false }, + const: { initialized: false, uninitialized: false } }); } @@ -134,7 +134,7 @@ module.exports = { * @private */ function startFunction() { - functionStack.push({initialized: false, uninitialized: false}); + functionStack.push({ initialized: false, uninitialized: false }); startBlock(); } diff --git a/tools/eslint/lib/rules/operator-assignment.js b/tools/eslint/lib/rules/operator-assignment.js index 5e1dd97b996bc7..e003478c7bc427 100644 --- a/tools/eslint/lib/rules/operator-assignment.js +++ b/tools/eslint/lib/rules/operator-assignment.js @@ -70,6 +70,17 @@ function same(a, b) { } } +/** +* Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) +* toString calls regardless of whether assignment shorthand is used) +* @param {ASTNode} node The node on the left side of the expression +* @returns {boolean} `true` if the node can be fixed +*/ +function canBeFixed(node) { + return node.type === "Identifier" || + node.type === "MemberExpression" && node.object.type === "Identifier" && (!node.computed || node.property.type === "Literal"); +} + module.exports = { meta: { docs: { @@ -82,11 +93,24 @@ module.exports = { { enum: ["always", "never"] } - ] + ], + + fixable: "code" }, create(context) { + const sourceCode = context.getSourceCode(); + + /** + * Returns the operator token of an AssignmentExpression or BinaryExpression + * @param {ASTNode} node An AssignmentExpression or BinaryExpression node + * @returns {Token} The operator token in the node + */ + function getOperatorToken(node) { + return sourceCode.getTokensBetween(node.left, node.right).find(token => token.value === node.operator); + } + /** * Ensures that an assignment uses the shorthand form where possible. * @param {ASTNode} node An AssignmentExpression node. @@ -101,13 +125,34 @@ module.exports = { const expr = node.right; const operator = expr.operator; - if (isCommutativeOperatorWithShorthand(operator)) { - if (same(left, expr.left) || same(left, expr.right)) { - context.report(node, "Assignment can be replaced with operator assignment."); - } - } else if (isNonCommutativeOperatorWithShorthand(operator)) { + if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { if (same(left, expr.left)) { - context.report(node, "Assignment can be replaced with operator assignment."); + context.report({ + node, + message: "Assignment can be replaced with operator assignment.", + fix(fixer) { + if (canBeFixed(left)) { + const equalsToken = getOperatorToken(node); + const operatorToken = getOperatorToken(expr); + const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]); + const rightText = sourceCode.getText().slice(operatorToken.range[1], node.range[1]); + + return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`); + } + return null; + } + }); + } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) { + + /* + * This case can't be fixed safely. + * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would + * change the execution order of the valueOf() functions. + */ + context.report({ + node, + message: "Assignment can be replaced with operator assignment." + }); } } } @@ -119,7 +164,20 @@ module.exports = { */ function prohibit(node) { if (node.operator !== "=") { - context.report(node, "Unexpected operator assignment shorthand."); + context.report({ + node, + message: "Unexpected operator assignment shorthand.", + fix(fixer) { + if (canBeFixed(node.left)) { + const operatorToken = getOperatorToken(node); + const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); + const rightText = sourceCode.getText().slice(operatorToken.range[1], node.range[1]); + + return fixer.replaceText(node, `${leftText}= ${leftText}${node.operator.slice(0, -1)}${rightText}`); + } + return null; + } + }); } } diff --git a/tools/eslint/lib/rules/operator-linebreak.js b/tools/eslint/lib/rules/operator-linebreak.js index ce222526e1d410..c8f2b2818e23b2 100644 --- a/tools/eslint/lib/rules/operator-linebreak.js +++ b/tools/eslint/lib/rules/operator-linebreak.js @@ -11,6 +11,8 @@ const astUtils = require("../ast-utils"); // Rule Definition //------------------------------------------------------------------------------ +const LINEBREAK_REGEX = /\r\n|\r|\n|\u2028|\u2029/g; + module.exports = { meta: { docs: { @@ -38,7 +40,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "code" }, create(context) { @@ -62,6 +66,61 @@ module.exports = { // Helpers //-------------------------------------------------------------------------- + /** + * Gets a fixer function to fix rule issues + * @param {Token} operatorToken The operator token of an expression + * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' + * @returns {Function} A fixer function + */ + function getFixer(operatorToken, desiredStyle) { + return fixer => { + const tokenBefore = sourceCode.getTokenBefore(operatorToken); + const tokenAfter = sourceCode.getTokenAfter(operatorToken); + const textBefore = sourceCode.text.slice(tokenBefore.range[1], operatorToken.range[0]); + const textAfter = sourceCode.text.slice(operatorToken.range[1], tokenAfter.range[0]); + const hasLinebreakBefore = !astUtils.isTokenOnSameLine(tokenBefore, operatorToken); + const hasLinebreakAfter = !astUtils.isTokenOnSameLine(operatorToken, tokenAfter); + let newTextBefore, newTextAfter; + + if (hasLinebreakBefore !== hasLinebreakAfter && desiredStyle !== "none") { + + // If there is a comment before and after the operator, don't do a fix. + if (sourceCode.getTokenOrCommentBefore(operatorToken) !== tokenBefore && sourceCode.getTokenOrCommentAfter(operatorToken) !== tokenAfter) { + return null; + } + + /* + * If there is only one linebreak and it's on the wrong side of the operator, swap the text before and after the operator. + * foo && + * bar + * would get fixed to + * foo + * && bar + */ + newTextBefore = textAfter; + newTextAfter = textBefore; + } else { + + // Otherwise, if no linebreak is desired and no comments interfere, replace the linebreaks with empty strings. + newTextBefore = desiredStyle === "before" || textBefore.trim() ? textBefore : textBefore.replace(LINEBREAK_REGEX, ""); + newTextAfter = desiredStyle === "after" || textAfter.trim() ? textAfter : textAfter.replace(LINEBREAK_REGEX, ""); + + // If there was no change (due to interfering comments), don't output a fix. + if (newTextBefore === textBefore && newTextAfter === textAfter) { + return null; + } + } + + if (newTextAfter === "" && tokenAfter.type === "Punctuator" && "+-".includes(operatorToken.value) && tokenAfter.value === operatorToken.value) { + + // To avoid accidentally creating a ++ or -- operator, insert a space if the operator is a +/- and the following token is a unary +/-. + newTextAfter += " "; + } + + return fixer.replaceTextRange([tokenBefore.range[1], tokenAfter.range[0]], newTextBefore + operatorToken.value + newTextAfter); + }; + } + /** * Checks the operator placement * @param {ASTNode} node The node to check @@ -87,12 +146,13 @@ module.exports = { const operator = operatorToken.value; const operatorStyleOverride = styleOverrides[operator]; const style = operatorStyleOverride || globalStyle; + const fix = getFixer(operatorToken, style); // if single line if (astUtils.isTokenOnSameLine(leftToken, operatorToken) && astUtils.isTokenOnSameLine(operatorToken, rightToken)) { - return; + // do nothing. } else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) && !astUtils.isTokenOnSameLine(operatorToken, rightToken)) { @@ -107,7 +167,8 @@ module.exports = { message: "Bad line breaking before and after '{{operator}}'.", data: { operator - } + }, + fix }); } else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) { @@ -121,7 +182,8 @@ module.exports = { message: "'{{operator}}' should be placed at the beginning of the line.", data: { operator - } + }, + fix }); } else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) { @@ -135,7 +197,8 @@ module.exports = { message: "'{{operator}}' should be placed at the end of the line.", data: { operator - } + }, + fix }); } else if (style === "none") { @@ -149,7 +212,8 @@ module.exports = { message: "There should be no line break before or after '{{operator}}'.", data: { operator - } + }, + fix }); } diff --git a/tools/eslint/lib/rules/padded-blocks.js b/tools/eslint/lib/rules/padded-blocks.js index a24d421b0f4f23..2b4da39b360214 100644 --- a/tools/eslint/lib/rules/padded-blocks.js +++ b/tools/eslint/lib/rules/padded-blocks.js @@ -173,7 +173,7 @@ module.exports = { if (!blockHasBottomPadding) { context.report({ node, - loc: {line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, + loc: { line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, fix(fixer) { return fixer.insertTextBefore(closeBrace, "\n"); }, @@ -199,7 +199,7 @@ module.exports = { context.report({ node, - loc: {line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, + loc: { line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, message: NEVER_MESSAGE, fix(fixer) { return fixer.replaceTextRange([previousToken.end, closeBrace.start - closeBrace.loc.start.column], "\n"); diff --git a/tools/eslint/lib/rules/prefer-arrow-callback.js b/tools/eslint/lib/rules/prefer-arrow-callback.js index 034112093bd405..ee385042f1309e 100644 --- a/tools/eslint/lib/rules/prefer-arrow-callback.js +++ b/tools/eslint/lib/rules/prefer-arrow-callback.js @@ -63,7 +63,7 @@ function getVariableOfArguments(scope) { * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`. */ function getCallbackInfo(node) { - const retv = {isCallback: false, isLexicalThis: false}; + const retv = { isCallback: false, isLexicalThis: false }; let parent = node.parent; while (node) { @@ -176,7 +176,7 @@ module.exports = { * @returns {void} */ function enterScope() { - stack.push({this: false, super: false, meta: false}); + stack.push({ this: false, super: false, meta: false }); } /** diff --git a/tools/eslint/lib/rules/prefer-const.js b/tools/eslint/lib/rules/prefer-const.js index 5255f2745c9384..07d8da82a105c4 100644 --- a/tools/eslint/lib/rules/prefer-const.js +++ b/tools/eslint/lib/rules/prefer-const.js @@ -5,12 +5,6 @@ "use strict"; -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ @@ -91,6 +85,17 @@ function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { return null; } + /* + * Due to a bug in acorn, code such as `let foo = 1; let foo = 2;` will not throw a syntax error. As a sanity + * check, make sure that the variable only has one declaration. After the parsing bug is fixed, this check + * will no longer be necessary, because variables declared with `let` or `const` should always have exactly one + * declaration. + * https://github.com/ternjs/acorn/issues/487 + */ + if (variable.defs.length > 1) { + return null; + } + // Finds the unique WriteReference. let writer = null; let isReadBeforeInit = false; @@ -244,8 +249,8 @@ module.exports = { { type: "object", properties: { - destructuring: {enum: ["any", "all"]}, - ignoreReadBeforeAssign: {type: "boolean"} + destructuring: { enum: ["any", "all"] }, + ignoreReadBeforeAssign: { type: "boolean" } }, additionalProperties: false } @@ -254,80 +259,10 @@ module.exports = { create(context) { const options = context.options[0] || {}; + const sourceCode = context.getSourceCode(); const checkingMixedDestructuring = options.destructuring !== "all"; const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; - let variables = null; - - /** - * Reports a given Identifier node. - * - * @param {ASTNode} node - An Identifier node to report. - * @returns {void} - */ - function report(node) { - const reportArgs = { - node, - message: "'{{name}}' is never reassigned. Use 'const' instead.", - data: node - }, - varDeclParent = findUp(node, "VariableDeclaration", function(parentNode) { - return lodash.endsWith(parentNode.type, "Statement"); - }), - isNormalVarDecl = (node.parent.parent.parent.type === "ForInStatement" || - node.parent.parent.parent.type === "ForOfStatement" || - node.parent.init), - - isDestructuringVarDecl = - - // {let {a} = obj} should be written as {const {a} = obj} - (node.parent.parent.type === "ObjectPattern" && - - // If options.destucturing is "all", then this warning will not occur unless - // every assignment in the destructuring should be const. In that case, it's safe - // to apply the fix. Otherwise, it's safe to apply the fix if there's only one - // assignment occurring. If there is more than one assignment and options.destructuring - // is not "all", then it's not clear how the developer would want to resolve the issue, - // so we should not attempt to do it programmatically. - (options.destructuring === "all" || node.parent.parent.properties.length === 1)) || - - // {let [a] = [1]} should be written as {const [a] = [1]} - (node.parent.type === "ArrayPattern" && - - // See note above about fixing multiple warnings at once. - (options.destructuring === "all" || node.parent.elements.length === 1)); - - if (varDeclParent && - (isNormalVarDecl || isDestructuringVarDecl) && - - // If there are multiple variable declarations, like {let a = 1, b = 2}, then - // do not attempt to fix if one of the declarations should be `const`. It's - // too hard to know how the developer would want to automatically resolve the issue. - varDeclParent.declarations.length === 1) { - - reportArgs.fix = function(fixer) { - return fixer.replaceTextRange( - [varDeclParent.start, varDeclParent.start + "let".length], - "const" - ); - }; - } - - context.report(reportArgs); - } - - /** - * Reports a given variable if the variable should be declared as const. - * - * @param {escope.Variable} variable - A variable to report. - * @returns {void} - */ - function checkVariable(variable) { - const node = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); - - if (node) { - report(node); - } - } + const variables = []; /** * Reports given identifier nodes if all of the nodes should be declared @@ -344,25 +279,39 @@ module.exports = { * @returns {void} */ function checkGroup(nodes) { - if (nodes.every(Boolean)) { - nodes.forEach(report); + const nodesToReport = nodes.filter(Boolean); + + if (nodes.length && (checkingMixedDestructuring || nodesToReport.length === nodes.length)) { + const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); + const shouldFix = varDeclParent && + + // If there are multiple variable declarations, like {let a = 1, b = 2}, then + // do not attempt to fix if one of the declarations should be `const`. It's + // too hard to know how the developer would want to automatically resolve the issue. + varDeclParent.declarations.length === 1 && + + // Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop) + (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) && + + // If options.destucturing is "all", then this warning will not occur unless + // every assignment in the destructuring should be const. In that case, it's safe + // to apply the fix. + nodesToReport.length === nodes.length; + + nodesToReport.forEach(node => { + context.report({ + node, + message: "'{{name}}' is never reassigned. Use 'const' instead.", + data: node, + fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null + }); + }); } } return { - Program() { - variables = []; - }, - "Program:exit"() { - if (checkingMixedDestructuring) { - variables.forEach(checkVariable); - } else { - groupByDestructuring(variables, ignoreReadBeforeAssign) - .forEach(checkGroup); - } - - variables = null; + groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); }, VariableDeclaration(node) { diff --git a/tools/eslint/lib/rules/prefer-destructuring.js b/tools/eslint/lib/rules/prefer-destructuring.js new file mode 100644 index 00000000000000..c3fbcaa6310fc8 --- /dev/null +++ b/tools/eslint/lib/rules/prefer-destructuring.js @@ -0,0 +1,173 @@ +/** + * @fileoverview Prefer destructuring from arrays and objects + * @author Alex LaFroscia + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "require destructuring from arrays and/or objects", + category: "ECMAScript 6", + recommended: false + }, + + schema: [ + { + type: "object", + properties: { + array: { + type: "boolean" + }, + object: { + type: "boolean" + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + enforceForRenamedProperties: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + }, + create(context) { + + let checkArrays = true; + let checkObjects = true; + let enforceForRenamedProperties = false; + const enabledTypes = context.options[0]; + const additionalOptions = context.options[1]; + + if (enabledTypes) { + if (typeof enabledTypes.array !== "undefined") { + checkArrays = enabledTypes.array; + } + + if (typeof enabledTypes.object !== "undefined") { + checkObjects = enabledTypes.object; + } + } + + if (additionalOptions) { + if (typeof additionalOptions.enforceForRenamedProperties !== "undefined") { + enforceForRenamedProperties = additionalOptions.enforceForRenamedProperties; + } + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if the given node node is accessing an array index + * + * This is used to differentiate array index access from object property + * access. + * + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node is an integer + */ + function isArrayIndexAccess(node) { + return Number.isInteger(node.property.value); + } + + /** + * Report that the given node should use destructuring + * + * @param {ASTNode} reportNode the node to report + * @param {string} type the type of destructuring that should have been done + * @returns {void} + */ + function report(reportNode, type) { + context.report({ node: reportNode, message: `Use ${type} destructuring` }); + } + + /** + * Check that the `prefer-destructuring` rules are followed based on the + * given left- and right-hand side of the assignment. + * + * Pulled out into a separate method so that VariableDeclarators and + * AssignmentExpressions can share the same verification logic. + * + * @param {ASTNode} leftNode the left-hand side of the assignment + * @param {ASTNode} rightNode the right-hand side of the assignment + * @param {ASTNode} reportNode the node to report the error on + * @returns {void} + */ + function performCheck(leftNode, rightNode, reportNode) { + if (rightNode.type !== "MemberExpression") { + return; + } + + if (checkArrays && isArrayIndexAccess(rightNode)) { + report(reportNode, "array"); + return; + } + + if (checkObjects && enforceForRenamedProperties) { + report(reportNode, "object"); + return; + } + + if (checkObjects) { + const property = rightNode.property; + + if ((property.type === "Literal" && leftNode.name === property.value) || + (property.type === "Identifier" && leftNode.name === property.name)) { + report(reportNode, "object"); + } + } + } + + /** + * Check if a given variable declarator is coming from an property access + * that should be using destructuring instead + * + * @param {ASTNode} node the variable declarator to check + * @returns {void} + */ + function checkVariableDeclarator(node) { + + // Skip if variable is declared without assignment + if (!node.init) { + return; + } + + // We only care about member expressions past this point + if (node.init.type !== "MemberExpression") { + return; + } + + performCheck(node.id, node.init, node); + } + + /** + * Run the `prefer-destructuring` check on an AssignmentExpression + * + * @param {ASTNode} node the AssignmentExpression node + * @returns {void} + */ + function checkAssigmentExpression(node) { + performCheck(node.left, node.right, node); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator: checkVariableDeclarator, + AssignmentExpression: checkAssigmentExpression + }; + } +}; diff --git a/tools/eslint/lib/rules/prefer-reflect.js b/tools/eslint/lib/rules/prefer-reflect.js index 64db836d04dd89..49e20989ecb00d 100644 --- a/tools/eslint/lib/rules/prefer-reflect.js +++ b/tools/eslint/lib/rules/prefer-reflect.js @@ -1,6 +1,7 @@ /** * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods * @author Keith Cirkel + * @deprecated in ESLint v3.9.0 */ "use strict"; @@ -13,9 +14,12 @@ module.exports = { docs: { description: "require `Reflect` methods where applicable", category: "ECMAScript 6", - recommended: false + recommended: false, + replacedBy: [] }, + deprecated: true, + schema: [ { type: "object", @@ -79,10 +83,10 @@ module.exports = { * @returns {void} */ function report(node, existing, substitute) { - context.report(node, "Avoid using {{existing}}, instead use {{substitute}}.", { + context.report({ node, message: "Avoid using {{existing}}, instead use {{substitute}}.", data: { existing, substitute - }); + } }); } return { diff --git a/tools/eslint/lib/rules/quote-props.js b/tools/eslint/lib/rules/quote-props.js index 2129ce6aa99b87..1dcdd461b598fc 100644 --- a/tools/eslint/lib/rules/quote-props.js +++ b/tools/eslint/lib/rules/quote-props.js @@ -162,7 +162,7 @@ module.exports = { context.report({ node, message: MESSAGE_UNNECESSARY, - data: {property: key.value}, + data: { property: key.value }, fix: fixer => fixer.replaceText(key, getUnquotedKey(key)) }); } @@ -170,14 +170,14 @@ module.exports = { context.report({ node, message: MESSAGE_RESERVED, - data: {property: key.name}, + data: { property: key.name }, fix: fixer => fixer.replaceText(key, getQuotedKey(key)) }); } else if (NUMBERS && key.type === "Literal" && typeof key.value === "number") { context.report({ node, message: MESSAGE_NUMERIC, - data: {property: key.value}, + data: { property: key.value }, fix: fixer => fixer.replaceText(key, getQuotedKey(key)) }); } @@ -195,7 +195,7 @@ module.exports = { context.report({ node, message: MESSAGE_UNQUOTED, - data: {property: key.name || key.value}, + data: { property: key.name || key.value }, fix: fixer => fixer.replaceText(key, getQuotedKey(key)) }); } @@ -213,7 +213,7 @@ module.exports = { let keywordKeyName = null, necessaryQuotes = false; - node.properties.forEach(function(property) { + node.properties.forEach(property => { const key = property.key; let tokens; @@ -257,7 +257,7 @@ module.exports = { context.report({ node: property, message: "Properties should be quoted as '{{property}}' is a reserved word.", - data: {property: keywordKeyName}, + data: { property: keywordKeyName }, fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) }); }); @@ -266,7 +266,7 @@ module.exports = { context.report({ node: property, message: "Inconsistently quoted property '{{key}}' found.", - data: {key: property.key.name || property.key.value}, + data: { key: property.key.name || property.key.value }, fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) }); }); diff --git a/tools/eslint/lib/rules/quotes.js b/tools/eslint/lib/rules/quotes.js index 90e68289e05662..5c53c76908c3df 100644 --- a/tools/eslint/lib/rules/quotes.js +++ b/tools/eslint/lib/rules/quotes.js @@ -51,7 +51,7 @@ QUOTE_SETTINGS.backtick.convert = function(str) { if (newQuote === oldQuote) { return str; } - return newQuote + str.slice(1, -1).replace(/\\(\${|\r\n?|\n|.)|["'`]|\${|(\r\n?|\n)/g, function(match, escaped, newline) { + return newQuote + str.slice(1, -1).replace(/\\(\${|\r\n?|\n|.)|["'`]|\${|(\r\n?|\n)/g, (match, escaped, newline) => { if (escaped === oldQuote || oldQuote === "`" && escaped === "${") { return escaped; // unescape } @@ -258,7 +258,11 @@ module.exports = { return; } - const shouldWarn = node.quasis.length === 1 && (node.quasis[0].value.cooked.indexOf("\n") === -1); + /* + * A warning should be produced if the template literal only has one TemplateElement, and has no unescaped newlines. + * An unescaped newline is a newline preceded by an even number of backslashes. + */ + const shouldWarn = node.quasis.length === 1 && !/(^|[^\\])(\\\\)*[\r\n\u2028\u2029]/.test(node.quasis[0].value.raw); if (shouldWarn) { context.report({ @@ -268,6 +272,15 @@ module.exports = { description: settings.description, }, fix(fixer) { + if (isPartOfDirectivePrologue(node)) { + + /* + * TemplateLiterals in a directive prologue aren't actually directives, but if they're + * in the directive prologue, then fixing them might turn them into directives and change + * the behavior of the code. + */ + return null; + } return fixer.replaceText(node, settings.convert(sourceCode.getText(node))); } }); diff --git a/tools/eslint/lib/rules/radix.js b/tools/eslint/lib/rules/radix.js index f36e27d3634b9e..0dfa081b6a3e35 100644 --- a/tools/eslint/lib/rules/radix.js +++ b/tools/eslint/lib/rules/radix.js @@ -145,7 +145,7 @@ module.exports = { // Check `parseInt()` variable = astUtils.getVariableByName(scope, "parseInt"); if (!isShadowed(variable)) { - variable.references.forEach(function(reference) { + variable.references.forEach(reference => { const node = reference.identifier; if (astUtils.isCallee(node)) { @@ -157,7 +157,7 @@ module.exports = { // Check `Number.parseInt()` variable = astUtils.getVariableByName(scope, "Number"); if (!isShadowed(variable)) { - variable.references.forEach(function(reference) { + variable.references.forEach(reference => { const node = reference.identifier.parent; if (isParseIntMethod(node) && astUtils.isCallee(node)) { diff --git a/tools/eslint/lib/rules/require-await.js b/tools/eslint/lib/rules/require-await.js new file mode 100644 index 00000000000000..89b24f75b0f951 --- /dev/null +++ b/tools/eslint/lib/rules/require-await.js @@ -0,0 +1,95 @@ +/** + * @fileoverview Rule to disallow async functions which have no `await` expression. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("../ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Capitalize the 1st letter of the given text. + * + * @param {string} text - The text to capitalize. + * @returns {string} The text that the 1st letter was capitalized. + */ +function capitalizeFirstLetter(text) { + return text[0].toUpperCase() + text.slice(1); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "disallow async functions which have no `await` expression", + category: "Best Practices", + recommended: false + }, + schema: [] + }, + + create(context) { + const sourceCode = context.getSourceCode(); + let scopeInfo = null; + + /** + * Push the scope info object to the stack. + * + * @returns {void} + */ + function enterFunction() { + scopeInfo = { + upper: scopeInfo, + hasAwait: false, + }; + } + + /** + * Pop the top scope info object from the stack. + * Also, it reports the function if needed. + * + * @param {ASTNode} node - The node to report. + * @returns {void} + */ + function exitFunction(node) { + if (node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + message: "{{name}} has no 'await' expression.", + data: { + name: capitalizeFirstLetter( + astUtils.getFunctionNameWithKind(node) + ) + } + }); + } + + scopeInfo = scopeInfo.upper; + } + + return { + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + AwaitExpression() { + scopeInfo.hasAwait = true; + } + }; + } +}; diff --git a/tools/eslint/lib/rules/require-jsdoc.js b/tools/eslint/lib/rules/require-jsdoc.js index 9300fce1baa42b..f1ecde81f959ec 100644 --- a/tools/eslint/lib/rules/require-jsdoc.js +++ b/tools/eslint/lib/rules/require-jsdoc.js @@ -27,6 +27,9 @@ module.exports = { }, FunctionDeclaration: { type: "boolean" + }, + ArrowFunctionExpression: { + type: "boolean" } }, additionalProperties: false @@ -52,7 +55,7 @@ module.exports = { * @returns {void} */ function report(node) { - context.report(node, "Missing JSDoc comment."); + context.report({ node, message: "Missing JSDoc comment." }); } /** @@ -98,6 +101,11 @@ module.exports = { if (options.ClassDeclaration) { checkJsDoc(node); } + }, + ArrowFunctionExpression(node) { + if (options.ArrowFunctionExpression && node.parent.type === "VariableDeclarator") { + checkJsDoc(node); + } } }; } diff --git a/tools/eslint/lib/rules/require-yield.js b/tools/eslint/lib/rules/require-yield.js index 36b4ea11a585aa..5cc2944bc692d6 100644 --- a/tools/eslint/lib/rules/require-yield.js +++ b/tools/eslint/lib/rules/require-yield.js @@ -48,9 +48,7 @@ module.exports = { const countYield = stack.pop(); if (countYield === 0 && node.body.body.length > 0) { - context.report( - node, - "This generator function does not have 'yield'."); + context.report({ node, message: "This generator function does not have 'yield'." }); } } diff --git a/tools/eslint/lib/rules/semi.js b/tools/eslint/lib/rules/semi.js index 2f28f1614d1a42..ee37ab018c82fd 100644 --- a/tools/eslint/lib/rules/semi.js +++ b/tools/eslint/lib/rules/semi.js @@ -39,7 +39,7 @@ module.exports = { { type: "object", properties: { - omitLastInOneLineBlock: {type: "boolean"} + omitLastInOneLineBlock: { type: "boolean" } }, additionalProperties: false } @@ -53,7 +53,7 @@ module.exports = { create(context) { - const OPT_OUT_PATTERN = /^[-[(\/+]$/; // One of [(/+-, but not ++ or -- + const OPT_OUT_PATTERN = /^[-[(/+`]/; // One of [(/+-` const options = context.options[1]; const never = context.options[0] === "never", exceptOneLine = options && options.omitLastInOneLineBlock === true, @@ -127,7 +127,7 @@ module.exports = { const lastTokenLine = lastToken.loc.end.line; const nextTokenLine = nextToken.loc.start.line; - const isOptOutToken = OPT_OUT_PATTERN.test(nextToken.value); + const isOptOutToken = OPT_OUT_PATTERN.test(nextToken.value) && nextToken.value !== "++" && nextToken.value !== "--"; const isDivider = (nextToken.value === "}" || nextToken.value === ";"); return (lastTokenLine !== nextTokenLine && !isOptOutToken) || isDivider; diff --git a/tools/eslint/lib/rules/sort-imports.js b/tools/eslint/lib/rules/sort-imports.js index ae3333c2ac16d7..83f500990239b2 100644 --- a/tools/eslint/lib/rules/sort-imports.js +++ b/tools/eslint/lib/rules/sort-imports.js @@ -39,7 +39,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "code" }, create(context) { @@ -47,7 +49,8 @@ module.exports = { const configuration = context.options[0] || {}, ignoreCase = configuration.ignoreCase || false, ignoreMemberSort = configuration.ignoreMemberSort || false, - memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"]; + memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"], + sourceCode = context.getSourceCode(); let previousDeclaration = null; /** @@ -135,36 +138,49 @@ module.exports = { } } - // Multiple members of an import declaration should also be sorted alphabetically. - if (!ignoreMemberSort && node.specifiers.length > 1) { - let previousSpecifier = null; - let previousSpecifierName = null; + if (!ignoreMemberSort) { + const importSpecifiers = node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"); + const getSortableName = ignoreCase ? specifier => specifier.local.name.toLowerCase() : specifier => specifier.local.name; + const firstUnsortedIndex = importSpecifiers.map(getSortableName).findIndex((name, index, array) => array[index - 1] > name); + + if (firstUnsortedIndex !== -1) { + context.report({ + node: importSpecifiers[firstUnsortedIndex], + message: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", + data: { memberName: importSpecifiers[firstUnsortedIndex].local.name }, + fix(fixer) { + if (importSpecifiers.some(specifier => sourceCode.getComments(specifier).leading.length || sourceCode.getComments(specifier).trailing.length)) { + + // If there are comments in the ImportSpecifier list, don't rearrange the specifiers. + return null; + } - for (let i = 0; i < node.specifiers.length; ++i) { - const currentSpecifier = node.specifiers[i]; + return fixer.replaceTextRange( + [importSpecifiers[0].range[0], importSpecifiers[importSpecifiers.length - 1].range[1]], + importSpecifiers - if (currentSpecifier.type !== "ImportSpecifier") { - continue; - } + // Clone the importSpecifiers array to avoid mutating it + .slice() - let currentSpecifierName = currentSpecifier.local.name; + // Sort the array into the desired order + .sort((specifierA, specifierB) => { + const aName = getSortableName(specifierA); + const bName = getSortableName(specifierB); - if (ignoreCase) { - currentSpecifierName = currentSpecifierName.toLowerCase(); - } + return aName > bName ? 1 : -1; + }) - if (previousSpecifier && currentSpecifierName < previousSpecifierName) { - context.report({ - node: currentSpecifier, - message: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", - data: { - memberName: currentSpecifier.local.name - } - }); - } + // Build a string out of the sorted list of import specifiers and the text between the originals + .reduce((sourceText, specifier, index) => { + const textAfterSpecifier = index === importSpecifiers.length - 1 + ? "" + : sourceCode.getText().slice(importSpecifiers[index].range[1], importSpecifiers[index + 1].range[0]); - previousSpecifier = currentSpecifier; - previousSpecifierName = currentSpecifierName; + return sourceText + sourceCode.getText(specifier) + textAfterSpecifier; + }, "") + ); + } + }); } } diff --git a/tools/eslint/lib/rules/sort-vars.js b/tools/eslint/lib/rules/sort-vars.js index 1e1cf3c959e663..e18cc320ef0553 100644 --- a/tools/eslint/lib/rules/sort-vars.js +++ b/tools/eslint/lib/rules/sort-vars.js @@ -37,7 +37,7 @@ module.exports = { return { VariableDeclaration(node) { - node.declarations.reduce(function(memo, decl) { + node.declarations.reduce((memo, decl) => { if (decl.id.type === "ObjectPattern" || decl.id.type === "ArrayPattern") { return memo; } @@ -51,7 +51,7 @@ module.exports = { } if (currenVariableName < lastVariableName) { - context.report(decl, "Variables within the same declaration block should be sorted alphabetically."); + context.report({ node: decl, message: "Variables within the same declaration block should be sorted alphabetically." }); return memo; } else { return decl; diff --git a/tools/eslint/lib/rules/space-in-parens.js b/tools/eslint/lib/rules/space-in-parens.js index c01170b2bc13b4..af838dfa9e8376 100644 --- a/tools/eslint/lib/rules/space-in-parens.js +++ b/tools/eslint/lib/rules/space-in-parens.js @@ -220,7 +220,7 @@ module.exports = { exceptions = getExceptions(); const tokens = sourceCode.tokensAndComments; - tokens.forEach(function(token, i) { + tokens.forEach((token, i) => { const prevToken = tokens[i - 1]; const nextToken = tokens[i + 1]; diff --git a/tools/eslint/lib/rules/space-infix-ops.js b/tools/eslint/lib/rules/space-infix-ops.js index 9831e8e2af6085..d919a1225a2bf5 100644 --- a/tools/eslint/lib/rules/space-infix-ops.js +++ b/tools/eslint/lib/rules/space-infix-ops.js @@ -57,7 +57,7 @@ module.exports = { const op = tokens[i]; if ( - op.type === "Punctuator" && + (op.type === "Punctuator" || op.type === "Keyword") && OPERATORS.indexOf(op.value) >= 0 && (tokens[i - 1].range[1] >= op.range[0] || op.range[1] >= tokens[i + 1].range[0]) ) { diff --git a/tools/eslint/lib/rules/spaced-comment.js b/tools/eslint/lib/rules/spaced-comment.js index a3dce4fa4e3d30..85abd7360e622a 100644 --- a/tools/eslint/lib/rules/spaced-comment.js +++ b/tools/eslint/lib/rules/spaced-comment.js @@ -240,7 +240,7 @@ module.exports = { const config = context.options[1] || {}; const balanced = config.block && config.block.balanced; - const styleRules = ["block", "line"].reduce(function(rule, type) { + const styleRules = ["block", "line"].reduce((rule, type) => { const markers = parseMarkersOption(config[type] && config[type].markers || config.markers); const exceptions = config[type] && config[type].exceptions || config.exceptions || []; const endNeverPattern = "[ \t]+$"; diff --git a/tools/eslint/lib/rules/strict.js b/tools/eslint/lib/rules/strict.js index 1591bd871465d4..34ed443d92c816 100644 --- a/tools/eslint/lib/rules/strict.js +++ b/tools/eslint/lib/rules/strict.js @@ -135,7 +135,7 @@ module.exports = { */ function reportSlice(nodes, start, end, message, fix) { nodes.slice(start, end).forEach(node => { - context.report({node, message, fix: fix ? getFixFunction(node) : null}); + context.report({ node, message, fix: fix ? getFixFunction(node) : null }); }); } @@ -176,19 +176,19 @@ module.exports = { if (isStrict) { if (!isSimpleParameterList(node.params)) { - context.report(useStrictDirectives[0], messages.nonSimpleParameterList); + context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList }); } else if (isParentStrict) { - context.report({node: useStrictDirectives[0], message: messages.unnecessary, fix: getFixFunction(useStrictDirectives[0])}); + context.report({ node: useStrictDirectives[0], message: messages.unnecessary, fix: getFixFunction(useStrictDirectives[0]) }); } else if (isInClass) { - context.report({node: useStrictDirectives[0], message: messages.unnecessaryInClasses, fix: getFixFunction(useStrictDirectives[0])}); + context.report({ node: useStrictDirectives[0], message: messages.unnecessaryInClasses, fix: getFixFunction(useStrictDirectives[0]) }); } reportAllExceptFirst(useStrictDirectives, messages.multiple, true); } else if (isParentGlobal) { if (isSimpleParameterList(node.params)) { - context.report(node, messages.function); + context.report({ node, message: messages.function }); } else { - context.report(node, messages.wrap); + context.report({ node, message: messages.wrap }); } } @@ -221,7 +221,7 @@ module.exports = { if (isSimpleParameterList(node.params)) { reportAll(useStrictDirectives, messages[mode], shouldFix(mode)); } else { - context.report(useStrictDirectives[0], messages.nonSimpleParameterList); + context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList }); reportAllExceptFirst(useStrictDirectives, messages.multiple, true); } } @@ -237,7 +237,7 @@ module.exports = { if (mode === "global") { if (node.body.length > 0 && useStrictDirectives.length === 0) { - context.report(node, messages.global); + context.report({ node, message: messages.global }); } reportAllExceptFirst(useStrictDirectives, messages.multiple, true); } else { diff --git a/tools/eslint/lib/rules/symbol-description.js b/tools/eslint/lib/rules/symbol-description.js index 37ac8be7276656..3f5ffd7463cd5a 100644 --- a/tools/eslint/lib/rules/symbol-description.js +++ b/tools/eslint/lib/rules/symbol-description.js @@ -51,7 +51,7 @@ module.exports = { const variable = astUtils.getVariableByName(scope, "Symbol"); if (variable && variable.defs.length === 0) { - variable.references.forEach(function(reference) { + variable.references.forEach(reference => { const node = reference.identifier; if (astUtils.isCallee(node)) { diff --git a/tools/eslint/lib/rules/template-curly-spacing.js b/tools/eslint/lib/rules/template-curly-spacing.js index 1ac3262fce2597..1d491a24c9c1e2 100644 --- a/tools/eslint/lib/rules/template-curly-spacing.js +++ b/tools/eslint/lib/rules/template-curly-spacing.js @@ -33,7 +33,7 @@ module.exports = { fixable: "whitespace", schema: [ - {enum: ["always", "never"]} + { enum: ["always", "never"] } ] }, diff --git a/tools/eslint/lib/rules/unicode-bom.js b/tools/eslint/lib/rules/unicode-bom.js index 82692894d4a852..2f16a258509e8b 100644 --- a/tools/eslint/lib/rules/unicode-bom.js +++ b/tools/eslint/lib/rules/unicode-bom.js @@ -36,7 +36,7 @@ module.exports = { Program: function checkUnicodeBOM(node) { const sourceCode = context.getSourceCode(), - location = {column: 0, line: 1}, + location = { column: 0, line: 1 }, requireBOM = context.options[0] || "never"; if (!sourceCode.hasBOM && (requireBOM === "always")) { diff --git a/tools/eslint/lib/rules/use-isnan.js b/tools/eslint/lib/rules/use-isnan.js index b4a978b5efe21b..5ec48a0386e1b5 100644 --- a/tools/eslint/lib/rules/use-isnan.js +++ b/tools/eslint/lib/rules/use-isnan.js @@ -25,7 +25,7 @@ module.exports = { return { BinaryExpression(node) { if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) { - context.report(node, "Use the isNaN function to compare with NaN."); + context.report({ node, message: "Use the isNaN function to compare with NaN." }); } } }; diff --git a/tools/eslint/lib/rules/valid-jsdoc.js b/tools/eslint/lib/rules/valid-jsdoc.js index 09fc684719a4af..66ad1f8d45de1f 100644 --- a/tools/eslint/lib/rules/valid-jsdoc.js +++ b/tools/eslint/lib/rules/valid-jsdoc.js @@ -202,7 +202,7 @@ module.exports = { elements.forEach(validateType.bind(null, jsdocNode)); - typesToCheck.forEach(function(typeToCheck) { + typesToCheck.forEach(typeToCheck => { if (typeToCheck.expectedType && typeToCheck.expectedType !== typeToCheck.currentType) { context.report({ @@ -246,15 +246,15 @@ module.exports = { } catch (ex) { if (/braces/i.test(ex.message)) { - context.report(jsdocNode, "JSDoc type missing brace."); + context.report({ node: jsdocNode, message: "JSDoc type missing brace." }); } else { - context.report(jsdocNode, "JSDoc syntax error."); + context.report({ node: jsdocNode, message: "JSDoc syntax error." }); } return; } - jsdoc.tags.forEach(function(tag) { + jsdoc.tags.forEach(tag => { switch (tag.title.toLowerCase()) { @@ -262,15 +262,15 @@ module.exports = { case "arg": case "argument": if (!tag.type) { - context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name }); + context.report({ node: jsdocNode, message: "Missing JSDoc parameter type for '{{name}}'.", data: { name: tag.name } }); } if (!tag.description && requireParamDescription) { - context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name }); + context.report({ node: jsdocNode, message: "Missing JSDoc parameter description for '{{name}}'.", data: { name: tag.name } }); } if (params[tag.name]) { - context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name }); + context.report({ node: jsdocNode, message: "Duplicate JSDoc parameter '{{name}}'.", data: { name: tag.name } }); } else if (tag.name.indexOf(".") === -1) { params[tag.name] = 1; } @@ -290,11 +290,11 @@ module.exports = { }); } else { if (requireReturnType && !tag.type) { - context.report(jsdocNode, "Missing JSDoc return type."); + context.report({ node: jsdocNode, message: "Missing JSDoc return type." }); } if (!isValidReturnType(tag) && !tag.description && requireReturnDescription) { - context.report(jsdocNode, "Missing JSDoc return description."); + context.report({ node: jsdocNode, message: "Missing JSDoc return description." }); } } @@ -324,7 +324,7 @@ module.exports = { // check tag preferences if (prefer.hasOwnProperty(tag.title) && tag.title !== prefer[tag.title]) { - context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] }); + context.report({ node: jsdocNode, message: "Use @{{name}} instead.", data: { name: prefer[tag.title] } }); } // validate the types @@ -352,7 +352,7 @@ module.exports = { const jsdocParams = Object.keys(params); if (node.params) { - node.params.forEach(function(param, i) { + node.params.forEach((param, i) => { if (param.type === "AssignmentPattern") { param = param.left; } @@ -362,14 +362,14 @@ module.exports = { // TODO(nzakas): Figure out logical things to do with destructured, default, rest params if (param.type === "Identifier") { if (jsdocParams[i] && (name !== jsdocParams[i])) { - context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", { + context.report({ node: jsdocNode, message: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", data: { name, jsdocName: jsdocParams[i] - }); + } }); } else if (!params[name] && !isOverride) { - context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", { + context.report({ node: jsdocNode, message: "Missing JSDoc for parameter '{{name}}'.", data: { name - }); + } }); } } }); @@ -379,7 +379,7 @@ module.exports = { const regex = new RegExp(options.matchDescription); if (!regex.test(jsdoc.description)) { - context.report(jsdocNode, "JSDoc description does not satisfy the regex pattern."); + context.report({ node: jsdocNode, message: "JSDoc description does not satisfy the regex pattern." }); } } diff --git a/tools/eslint/lib/rules/valid-typeof.js b/tools/eslint/lib/rules/valid-typeof.js index ed0a7c017955f2..94b407b600a43c 100644 --- a/tools/eslint/lib/rules/valid-typeof.js +++ b/tools/eslint/lib/rules/valid-typeof.js @@ -62,10 +62,10 @@ module.exports = { const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked; if (VALID_TYPES.indexOf(value) === -1) { - context.report(sibling, "Invalid typeof comparison value."); + context.report({ node: sibling, message: "Invalid typeof comparison value." }); } } else if (requireStringLiterals && !isTypeofExpression(sibling)) { - context.report(sibling, "Typeof comparisons should be to string literals."); + context.report({ node: sibling, message: "Typeof comparisons should be to string literals." }); } } } diff --git a/tools/eslint/lib/rules/vars-on-top.js b/tools/eslint/lib/rules/vars-on-top.js index 92ed08e2d4b5de..f74db905b1908d 100644 --- a/tools/eslint/lib/rules/vars-on-top.js +++ b/tools/eslint/lib/rules/vars-on-top.js @@ -100,7 +100,7 @@ module.exports = { */ function globalVarCheck(node, parent) { if (!isVarOnTop(node, parent.body)) { - context.report(node, errorMessage); + context.report({ node, message: errorMessage }); } } @@ -115,7 +115,7 @@ module.exports = { if (!(/Function/.test(grandParent.type) && parent.type === "BlockStatement" && isVarOnTop(node, parent.body))) { - context.report(node, errorMessage); + context.report({ node, message: errorMessage }); } } diff --git a/tools/eslint/lib/rules/yield-star-spacing.js b/tools/eslint/lib/rules/yield-star-spacing.js index ecd33c5b38fafb..eb20fc01b0b9a9 100644 --- a/tools/eslint/lib/rules/yield-star-spacing.js +++ b/tools/eslint/lib/rules/yield-star-spacing.js @@ -28,8 +28,8 @@ module.exports = { { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"} + before: { type: "boolean" }, + after: { type: "boolean" } }, additionalProperties: false } diff --git a/tools/eslint/lib/rules/yoda.js b/tools/eslint/lib/rules/yoda.js index e463a476ab6be4..ba711c63c2f1ae 100644 --- a/tools/eslint/lib/rules/yoda.js +++ b/tools/eslint/lib/rules/yoda.js @@ -4,6 +4,12 @@ */ "use strict"; +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("../ast-utils"); + //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- @@ -54,13 +60,16 @@ function looksLikeLiteral(node) { /** * Attempts to derive a Literal node from nodes that are treated like literals. * @param {ASTNode} node Node to normalize. - * @returns {ASTNode} The original node if the node is already a Literal, or a - * normalized Literal node with the negative number as the - * value if the node represents a negative number literal, - * otherwise null if the node cannot be converted to a - * normalized literal. + * @param {number} [defaultValue] The default value to be returned if the node + * is not a Literal. + * @returns {ASTNode} One of the following options. + * 1. The original node if the node is already a Literal + * 2. A normalized Literal node with the negative number as the value if the + * node represents a negative number literal. + * 3. The Literal node which has the `defaultValue` argument if it exists. + * 4. Otherwise `null`. */ -function getNormalizedLiteral(node) { +function getNormalizedLiteral(node, defaultValue) { if (node.type === "Literal") { return node; } @@ -73,6 +82,14 @@ function getNormalizedLiteral(node) { }; } + if (defaultValue) { + return { + type: "Literal", + value: defaultValue, + raw: String(defaultValue) + }; + } + return null; } @@ -98,12 +115,26 @@ function same(a, b) { case "Literal": return a.value === b.value; - case "MemberExpression": + case "MemberExpression": { + const nameA = astUtils.getStaticPropertyName(a); + + // x.y = x["y"] + if (nameA) { + return ( + same(a.object, b.object) && + nameA === astUtils.getStaticPropertyName(b) + ); + } // x[0] = x[0] // x[y] = x[y] // x.y = x.y - return same(a.object, b.object) && same(a.property, b.property); + return ( + a.computed === b.computed && + same(a.object, b.object) && + same(a.property, b.property) + ); + } case "ThisExpression": return true; @@ -178,7 +209,7 @@ module.exports = { return (node.operator === "&&" && (leftLiteral = getNormalizedLiteral(left.left)) && - (rightLiteral = getNormalizedLiteral(right.right)) && + (rightLiteral = getNormalizedLiteral(right.right, Number.POSITIVE_INFINITY)) && leftLiteral.value <= rightLiteral.value && same(left.right, right.left)); } @@ -191,7 +222,7 @@ module.exports = { let leftLiteral, rightLiteral; return (node.operator === "||" && - (leftLiteral = getNormalizedLiteral(left.right)) && + (leftLiteral = getNormalizedLiteral(left.right, Number.NEGATIVE_INFINITY)) && (rightLiteral = getNormalizedLiteral(right.left)) && leftLiteral.value <= rightLiteral.value && same(left.left, right.right)); diff --git a/tools/eslint/lib/testers/event-generator-tester.js b/tools/eslint/lib/testers/event-generator-tester.js index d85238e9db0471..89693fe94819df 100644 --- a/tools/eslint/lib/testers/event-generator-tester.js +++ b/tools/eslint/lib/testers/event-generator-tester.js @@ -44,19 +44,19 @@ module.exports = { * @returns {void} */ testEventGeneratorInterface(instance) { - this.describe("should implement EventGenerator interface", function() { - this.it("should have `emitter` property.", function() { + this.describe("should implement EventGenerator interface", () => { + this.it("should have `emitter` property.", () => { assert.equal(typeof instance.emitter, "object"); assert.equal(typeof instance.emitter.emit, "function"); }); - this.it("should have `enterNode` property.", function() { + this.it("should have `enterNode` property.", () => { assert.equal(typeof instance.enterNode, "function"); }); - this.it("should have `leaveNode` property.", function() { + this.it("should have `leaveNode` property.", () => { assert.equal(typeof instance.leaveNode, "function"); }); - }.bind(this)); + }); } }; diff --git a/tools/eslint/lib/testers/rule-tester.js b/tools/eslint/lib/testers/rule-tester.js index 25b86993593c4a..5d327ad28b9360 100644 --- a/tools/eslint/lib/testers/rule-tester.js +++ b/tools/eslint/lib/testers/rule-tester.js @@ -252,8 +252,26 @@ RuleTester.prototype = { run(ruleName, rule, test) { const testerConfig = this.testerConfig, + requiredScenarios = ["valid", "invalid"], + scenarioErrors = [], result = {}; + if (lodash.isNil(test) || typeof test !== "object") { + throw new Error(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`); + } + + requiredScenarios.forEach(scenarioType => { + if (lodash.isNil(test[scenarioType])) { + scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`); + } + }); + + if (scenarioErrors.length > 0) { + throw new Error([ + `Test Scenarios for rule ${ruleName} is invalid:` + ].concat(scenarioErrors).join("\n")); + } + /* eslint-disable no-shadow */ /** @@ -307,9 +325,7 @@ RuleTester.prototype = { if (validateSchema.errors) { throw new Error([ `Schema for rule ${ruleName} is invalid:` - ].concat(validateSchema.errors.map(function(error) { - return `\t${error.field}: ${error.message}`; - })).join("\n")); + ].concat(validateSchema.errors.map(error => `\t${error.field}: ${error.message}`)).join("\n")); } } @@ -321,10 +337,10 @@ RuleTester.prototype = { * running the rule under test. */ eslint.reset(); - eslint.on("Program", function(node) { + eslint.on("Program", node => { beforeAST = cloneDeeplyExcludesParent(node); - eslint.on("Program:exit", function(node) { + eslint.on("Program:exit", node => { afterAST = cloneDeeplyExcludesParent(node); }); }); @@ -448,7 +464,7 @@ RuleTester.prototype = { } if (item.errors[i].type) { - assert.equal(messages[i].nodeType, item.errors[i].type, `Error type should be ${item.errors[i].type}`); + assert.equal(messages[i].nodeType, item.errors[i].type, `Error type should be ${item.errors[i].type}, found ${messages[i].nodeType}`); } if (item.errors[i].hasOwnProperty("line")) { @@ -488,18 +504,18 @@ RuleTester.prototype = { * This creates a mocha test suite and pipes all supplied info through * one of the templates above. */ - RuleTester.describe(ruleName, function() { - RuleTester.describe("valid", function() { - test.valid.forEach(function(valid) { - RuleTester.it(valid.code || valid, function() { + RuleTester.describe(ruleName, () => { + RuleTester.describe("valid", () => { + test.valid.forEach(valid => { + RuleTester.it(valid.code || valid, () => { testValidTemplate(ruleName, valid); }); }); }); - RuleTester.describe("invalid", function() { - test.invalid.forEach(function(invalid) { - RuleTester.it(invalid.code, function() { + RuleTester.describe("invalid", () => { + test.invalid.forEach(invalid => { + RuleTester.it(invalid.code, () => { testInvalidTemplate(ruleName, invalid); }); }); diff --git a/tools/eslint/lib/timing.js b/tools/eslint/lib/timing.js index 627aa5f82f8118..20456628640bf6 100644 --- a/tools/eslint/lib/timing.js +++ b/tools/eslint/lib/timing.js @@ -54,18 +54,16 @@ const ALIGN = [alignLeft, alignRight, alignRight]; function display(data) { let total = 0; const rows = Object.keys(data) - .map(function(key) { + .map(key => { const time = data[key]; total += time; return [key, time]; }) - .sort(function(a, b) { - return b[1] - a[1]; - }) + .sort((a, b) => b[1] - a[1]) .slice(0, 10); - rows.forEach(function(row) { + rows.forEach(row => { row.push(`${(row[1] * 100 / total).toFixed(1)}%`); row[1] = row[1].toFixed(3); }); @@ -74,7 +72,7 @@ function display(data) { const widths = []; - rows.forEach(function(row) { + rows.forEach(row => { const len = row.length; for (let i = 0; i < len; i++) { @@ -86,13 +84,13 @@ function display(data) { } }); - const table = rows.map(function(row) { - return row.map(function(cell, index) { - return ALIGN[index](cell, widths[index]); - }).join(" | "); - }); + const table = rows.map(row => + row + .map((cell, index) => ALIGN[index](cell, widths[index])) + .join(" | ") + ); - table.splice(1, 0, widths.map(function(w, index) { + table.splice(1, 0, widths.map((w, index) => { if (index !== 0 && index !== widths.length - 1) { w++; } @@ -130,7 +128,7 @@ module.exports = (function() { } if (enabled) { - process.on("exit", function() { + process.on("exit", () => { display(data); }); } diff --git a/tools/eslint/lib/util/comment-event-generator.js b/tools/eslint/lib/util/comment-event-generator.js index 47cc68f296f87e..dfa7132ff850ef 100644 --- a/tools/eslint/lib/util/comment-event-generator.js +++ b/tools/eslint/lib/util/comment-event-generator.js @@ -20,7 +20,7 @@ */ function emitComments(comments, emitter, locs, eventName) { if (comments.length > 0) { - comments.forEach(function(node) { + comments.forEach(node => { const index = locs.indexOf(node.loc); if (index >= 0) { diff --git a/tools/eslint/lib/util/glob-util.js b/tools/eslint/lib/util/glob-util.js index cba2e694ad5238..198e069e9f0850 100644 --- a/tools/eslint/lib/util/glob-util.js +++ b/tools/eslint/lib/util/glob-util.js @@ -43,9 +43,7 @@ function processPath(options) { const cwd = (options && options.cwd) || process.cwd(); let extensions = (options && options.extensions) || [".js"]; - extensions = extensions.map(function(ext) { - return ext.charAt(0) === "." ? ext.substr(1) : ext; - }); + extensions = extensions.map(ext => ext.replace(/^\./, "")); let suffix = "/**"; @@ -67,7 +65,7 @@ function processPath(options) { const resolvedPath = path.resolve(cwd, pathname); if (shell.test("-d", resolvedPath)) { - newPath = pathname.replace(/[\/\\]$/, "") + suffix; + newPath = pathname.replace(/[/\\]$/, "") + suffix; } return pathUtil.convertPathToPosix(newPath); @@ -145,12 +143,12 @@ function listFilesToProcess(globPatterns, options) { if (added[filename]) { return; } - files.push({filename, ignored}); + files.push({ filename, ignored }); added[filename] = true; } debug("Creating list of files to process."); - globPatterns.forEach(function(pattern) { + globPatterns.forEach(pattern => { const file = path.resolve(cwd, pattern); if (shell.test("-f", file)) { @@ -160,9 +158,9 @@ function listFilesToProcess(globPatterns, options) { } else { // regex to find .hidden or /.hidden patterns, but not ./relative or ../relative - const globIncludesDotfiles = /(?:(?:^\.)|(?:[\/\\]\.))[^\/\\\.].*/.test(pattern); + const globIncludesDotfiles = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/.test(pattern); - const ignoredPaths = new IgnoredPaths(Object.assign({}, options, {dotfiles: options.dotfiles || globIncludesDotfiles})); + const ignoredPaths = new IgnoredPaths(Object.assign({}, options, { dotfiles: options.dotfiles || globIncludesDotfiles })); const shouldIgnore = ignoredPaths.getIgnoredFoldersGlobChecker(); const globOptions = { nodir: true, @@ -170,7 +168,7 @@ function listFilesToProcess(globPatterns, options) { cwd, }; - new GlobSync(pattern, globOptions, shouldIgnore).found.forEach(function(globMatch) { + new GlobSync(pattern, globOptions, shouldIgnore).found.forEach(globMatch => { addFile(path.resolve(cwd, globMatch), false, ignoredPaths); }); } diff --git a/tools/eslint/lib/util/module-resolver.js b/tools/eslint/lib/util/module-resolver.js index 40c107a70e82bd..505c572822699b 100644 --- a/tools/eslint/lib/util/module-resolver.js +++ b/tools/eslint/lib/util/module-resolver.js @@ -30,18 +30,18 @@ const DEFAULT_OPTIONS = { /** * Resolves modules based on a set of options. - * @param {Object} options The options for resolving modules. - * @param {string[]} options.lookupPaths An array of paths to include in the - * lookup with the highest priority paths coming first. - * @constructor */ -function ModuleResolver(options) { - options = options || {}; +class ModuleResolver { - this.options = Object.assign({}, DEFAULT_OPTIONS, options); -} - -ModuleResolver.prototype = { + /** + * Resolves modules based on a set of options. + * @param {Object} options The options for resolving modules. + * @param {string[]} options.lookupPaths An array of paths to include in the + * lookup with the highest priority paths coming first. + */ + constructor(options) { + this.options = Object.assign({}, DEFAULT_OPTIONS, options || {}); + } /** * Resolves the file location of a given module relative to the configured @@ -75,10 +75,8 @@ ModuleResolver.prototype = { } return result; - } - -}; +} //------------------------------------------------------------------------------ // Public API diff --git a/tools/eslint/lib/util/node-event-generator.js b/tools/eslint/lib/util/node-event-generator.js index 95d9132dd2f3b3..1666ae93f53406 100644 --- a/tools/eslint/lib/util/node-event-generator.js +++ b/tools/eslint/lib/util/node-event-generator.js @@ -20,34 +20,33 @@ * leaveNode(node: ASTNode): void; * } * ``` - * - * @param {EventEmitter} emitter - An event emitter which is the destination of events. - * @returns {NodeEventGenerator} new instance. */ -function NodeEventGenerator(emitter) { - this.emitter = emitter; -} +class NodeEventGenerator { -NodeEventGenerator.prototype = { - constructor: NodeEventGenerator, + /** + * @param {EventEmitter} emitter - An event emitter which is the destination of events. + */ + constructor(emitter) { + this.emitter = emitter; + } /** * Emits an event of entering AST node. * @param {ASTNode} node - A node which was entered. * @returns {void} */ - enterNode: function enterNode(node) { + enterNode(node) { this.emitter.emit(node.type, node); - }, + } /** * Emits an event of leaving AST node. * @param {ASTNode} node - A node which was left. * @returns {void} */ - leaveNode: function leaveNode(node) { + leaveNode(node) { this.emitter.emit(`${node.type}:exit`, node); } -}; +} module.exports = NodeEventGenerator; diff --git a/tools/eslint/lib/util/npm-util.js b/tools/eslint/lib/util/npm-util.js index e9131595e7e822..ef1c0c62936347 100644 --- a/tools/eslint/lib/util/npm-util.js +++ b/tools/eslint/lib/util/npm-util.js @@ -53,7 +53,7 @@ function installSyncSaveDev(packages) { if (Array.isArray(packages)) { packages = packages.join(" "); } - shell.exec(`npm i --save-dev ${packages}`, {stdio: "inherit"}); + shell.exec(`npm i --save-dev ${packages}`, { stdio: "inherit" }); } /** @@ -89,7 +89,7 @@ function check(packages, opt) { if (opt.dependencies && typeof fileJson.dependencies === "object") { deps = deps.concat(Object.keys(fileJson.dependencies)); } - return packages.reduce(function(status, pkg) { + return packages.reduce((status, pkg) => { status[pkg] = deps.indexOf(pkg) !== -1; return status; }, {}); @@ -107,7 +107,7 @@ function check(packages, opt) { * and values are booleans indicating installation. */ function checkDeps(packages, rootDir) { - return check(packages, {dependencies: true, startDir: rootDir}); + return check(packages, { dependencies: true, startDir: rootDir }); } /** @@ -121,7 +121,7 @@ function checkDeps(packages, rootDir) { * and values are booleans indicating installation. */ function checkDevDeps(packages) { - return check(packages, {devDependencies: true}); + return check(packages, { devDependencies: true }); } /** diff --git a/tools/eslint/lib/util/patterns/letters.js b/tools/eslint/lib/util/patterns/letters.js new file mode 100644 index 00000000000000..b212cfc9ebd34a --- /dev/null +++ b/tools/eslint/lib/util/patterns/letters.js @@ -0,0 +1,37 @@ +/** + * @fileoverview Pattern for detecting any letter (even letters outside of ASCII). + * NOTE: This file was generated using this script in JSCS based on the Unicode 7.0.0 standard: https://github.com/jscs-dev/node-jscs/blob/f5ed14427deb7e7aac84f3056a5aab2d9f3e563e/publish/helpers/generate-patterns.js + * Do not edit this file by hand-- please use https://github.com/mathiasbynens/regenerate to regenerate the regular expression exported from this file. + * @author Kevin Partington + * @license MIT License (from JSCS). See below. + */ + +/* + * The MIT License (MIT) + * + * Copyright 2013-2016 Dulin Marat and other contributors + * + * 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. + */ + +"use strict"; + +module.exports = /[A-Za-z\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-\u08B2\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\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\u0C59\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\u0D60\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-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\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\u19C1-\u19C7\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\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\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]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\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]|\uD87E[\uDC00-\uDE1D]/; + diff --git a/tools/eslint/lib/util/source-code-fixer.js b/tools/eslint/lib/util/source-code-fixer.js index 064a0a1f902443..3b702e509e77a4 100644 --- a/tools/eslint/lib/util/source-code-fixer.js +++ b/tools/eslint/lib/util/source-code-fixer.js @@ -72,7 +72,7 @@ SourceCodeFixer.applyFixes = function(sourceCode, messages) { let lastFixPos = text.length + 1, prefix = (sourceCode.hasBOM ? BOM : ""); - messages.forEach(function(problem) { + messages.forEach(problem => { if (problem.hasOwnProperty("fix")) { fixes.push(problem); } else { @@ -84,14 +84,12 @@ SourceCodeFixer.applyFixes = function(sourceCode, messages) { debug("Found fixes to apply"); // sort in reverse order of occurrence - fixes.sort(function(a, b) { - return b.fix.range[1] - a.fix.range[1] || b.fix.range[0] - a.fix.range[0]; - }); + fixes.sort((a, b) => b.fix.range[1] - a.fix.range[1] || b.fix.range[0] - a.fix.range[0]); // split into array of characters for easier manipulation const chars = text.split(""); - fixes.forEach(function(problem) { + fixes.forEach(problem => { const fix = problem.fix; let start = fix.range[0]; const end = fix.range[1]; diff --git a/tools/eslint/lib/util/source-code-util.js b/tools/eslint/lib/util/source-code-util.js index 8e660e0961d330..892c32d22a00e8 100644 --- a/tools/eslint/lib/util/source-code-util.js +++ b/tools/eslint/lib/util/source-code-util.js @@ -29,7 +29,7 @@ const debug = require("debug")("eslint:source-code-util"); */ function getSourceCodeOfFile(filename, options) { debug("getting sourceCode of", filename); - const opts = Object.assign({}, options, { rules: {}}); + const opts = Object.assign({}, options, { rules: {} }); const cli = new CLIEngine(opts); const results = cli.executeOnFiles([filename]); @@ -71,7 +71,7 @@ function getSourceCodeOfFiles(patterns, options, cb) { patterns = [patterns]; } - const defaultOptions = Object.assign({}, baseDefaultOptions, {cwd: process.cwd()}); + const defaultOptions = Object.assign({}, baseDefaultOptions, { cwd: process.cwd() }); if (typeof options === "undefined") { opts = defaultOptions; @@ -84,14 +84,14 @@ function getSourceCodeOfFiles(patterns, options, cb) { debug("constructed options:", opts); patterns = globUtil.resolveFileGlobPatterns(patterns, opts); - const filenames = globUtil.listFilesToProcess(patterns, opts).reduce(function(files, fileInfo) { - return !fileInfo.ignored ? files.concat(fileInfo.filename) : files; - }, []); + const filenames = globUtil.listFilesToProcess(patterns, opts) + .filter(fileInfo => !fileInfo.ignored) + .reduce((files, fileInfo) => files.concat(fileInfo.filename), []); if (filenames.length === 0) { debug(`Did not find any files matching pattern(s): ${patterns}`); } - filenames.forEach(function(filename) { + filenames.forEach(filename => { const sourceCode = getSourceCodeOfFile(filename, opts); if (sourceCode) { diff --git a/tools/eslint/lib/util/source-code.js b/tools/eslint/lib/util/source-code.js index 378bdd328fa50a..5d073039d81cd7 100644 --- a/tools/eslint/lib/util/source-code.js +++ b/tools/eslint/lib/util/source-code.js @@ -117,16 +117,16 @@ function SourceCode(text, ast) { */ this.lines = SourceCode.splitLines(this.text); - this.tokensAndComments = ast.tokens.concat(ast.comments).sort(function(left, right) { - return left.range[0] - right.range[0]; - }); + this.tokensAndComments = ast.tokens + .concat(ast.comments) + .sort((left, right) => left.range[0] - right.range[0]); // create token store methods const tokenStore = createTokenStore(ast.tokens); - Object.keys(tokenStore).forEach(function(methodName) { + Object.keys(tokenStore).forEach(methodName => { this[methodName] = tokenStore[methodName]; - }, this); + }); const tokensAndCommentsStore = createTokenStore(this.tokensAndComments); @@ -280,7 +280,7 @@ SourceCode.prototype = { } }); - return result ? Object.assign({parent: resultParent}, result) : null; + return result ? Object.assign({ parent: resultParent }, result) : null; }, /** diff --git a/tools/eslint/lib/util/traverser.js b/tools/eslint/lib/util/traverser.js index 50d18b045eb6ff..d5710bb8ac7b2d 100644 --- a/tools/eslint/lib/util/traverser.js +++ b/tools/eslint/lib/util/traverser.js @@ -46,9 +46,7 @@ function Traverser() { * @private */ Traverser.getKeys = function(node) { - return Object.keys(node).filter(function(key) { - return KEY_BLACKLIST.indexOf(key) === -1; - }); + return Object.keys(node).filter(key => KEY_BLACKLIST.indexOf(key) === -1); }; module.exports = Traverser; diff --git a/tools/eslint/lib/util/xml-escape.js b/tools/eslint/lib/util/xml-escape.js index 698abaf38eaecf..9f43c99c46a23c 100644 --- a/tools/eslint/lib/util/xml-escape.js +++ b/tools/eslint/lib/util/xml-escape.js @@ -15,7 +15,7 @@ * @private */ module.exports = function(s) { - return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/g, function(c) { // eslint-disable-line no-control-regex + return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/g, c => { // eslint-disable-line no-control-regex switch (c) { case "<": return "<"; diff --git a/tools/eslint/node_modules/.bin/eslint b/tools/eslint/node_modules/.bin/eslint new file mode 120000 index 00000000000000..810e4bcb32af34 --- /dev/null +++ b/tools/eslint/node_modules/.bin/eslint @@ -0,0 +1 @@ +../eslint/bin/eslint.js \ No newline at end of file diff --git a/tools/eslint/node_modules/.bin/strip-json-comments b/tools/eslint/node_modules/.bin/strip-json-comments deleted file mode 120000 index 63d549f96f3b2f..00000000000000 --- a/tools/eslint/node_modules/.bin/strip-json-comments +++ /dev/null @@ -1 +0,0 @@ -../strip-json-comments/cli.js \ No newline at end of file diff --git a/tools/eslint/node_modules/acorn/.tern-project b/tools/eslint/node_modules/acorn/.tern-project deleted file mode 100644 index 6718ce07e1c8a0..00000000000000 --- a/tools/eslint/node_modules/acorn/.tern-project +++ /dev/null @@ -1,6 +0,0 @@ -{ - "plugins": { - "node": true, - "es_modules": true - } -} \ No newline at end of file diff --git a/tools/eslint/node_modules/acorn/AUTHORS b/tools/eslint/node_modules/acorn/AUTHORS index 314d7086cf5bf2..306404542a3b07 100644 --- a/tools/eslint/node_modules/acorn/AUTHORS +++ b/tools/eslint/node_modules/acorn/AUTHORS @@ -25,6 +25,7 @@ Joel Kemp Johannes Herr Jordan Klassen Jürg Lehni +Kai Cataldo keeyipchan Keheliya Gallaba Kevin Irish @@ -32,6 +33,7 @@ Kevin Kwok krator Marijn Haverbeke Martin Carlberg +Mat Garcia Mathias Bynens Mathieu 'p01' Henri Matthew Bastien diff --git a/tools/eslint/node_modules/acorn/bin/generate-identifier-regex.js b/tools/eslint/node_modules/acorn/bin/generate-identifier-regex.js deleted file mode 100644 index 100e8cf280fc56..00000000000000 --- a/tools/eslint/node_modules/acorn/bin/generate-identifier-regex.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -// Which Unicode version should be used? -var version = '9.0.0'; - -var start = require('unicode-' + version + '/Binary_Property/ID_Start/code-points.js') - .filter(function(ch) { return ch > 0x7f; }); -var last = -1; -var cont = [0x200c, 0x200d].concat(require('unicode-' + version + '/Binary_Property/ID_Continue/code-points.js') - .filter(function(ch) { return ch > 0x7f && search(start, ch, last + 1) == -1; })); - -function search(arr, ch, starting) { - for (var i = starting; arr[i] <= ch && i < arr.length; last = i++) - if (arr[i] === ch) - return i; - return -1; -} - -function pad(str, width) { - while (str.length < width) str = "0" + str; - return str; -} - -function esc(code) { - var hex = code.toString(16); - if (hex.length <= 2) return "\\x" + pad(hex, 2); - else return "\\u" + pad(hex, 4); -} - -function generate(chars) { - var astral = [], re = ""; - for (var i = 0, at = 0x10000; i < chars.length; i++) { - var from = chars[i], to = from; - while (i < chars.length - 1 && chars[i + 1] == to + 1) { - i++; - to++; - } - if (to <= 0xffff) { - if (from == to) re += esc(from); - else if (from + 1 == to) re += esc(from) + esc(to); - else re += esc(from) + "-" + esc(to); - } else { - astral.push(from - at, to - from); - at = to; - } - } - return {nonASCII: re, astral: astral}; -} - -var startData = generate(start), contData = generate(cont); - -console.log("let nonASCIIidentifierStartChars = \"" + startData.nonASCII + "\""); -console.log("let nonASCIIidentifierChars = \"" + contData.nonASCII + "\""); -console.log("const astralIdentifierStartCodes = " + JSON.stringify(startData.astral)); -console.log("const astralIdentifierCodes = " + JSON.stringify(contData.astral)); diff --git a/tools/eslint/node_modules/acorn/bin/update_authors.sh b/tools/eslint/node_modules/acorn/bin/update_authors.sh deleted file mode 100755 index e08f57273cdd1e..00000000000000 --- a/tools/eslint/node_modules/acorn/bin/update_authors.sh +++ /dev/null @@ -1,6 +0,0 @@ -# Combine existing list of authors with everyone known in git, sort, add header. -tail --lines=+3 AUTHORS > AUTHORS.tmp -git log --format='%aN' | grep -v abraidwood | grep -v Rich-Harris | grep -v ForbesLindesay >> AUTHORS.tmp -echo -e "List of Acorn contributors. Updated before every release.\n" > AUTHORS -sort -u AUTHORS.tmp >> AUTHORS -rm -f AUTHORS.tmp diff --git a/tools/eslint/node_modules/acorn/dist/acorn.es.js b/tools/eslint/node_modules/acorn/dist/acorn.es.js index adb3dd30f3012a..32dd5954ea0e68 100644 --- a/tools/eslint/node_modules/acorn/dist/acorn.es.js +++ b/tools/eslint/node_modules/acorn/dist/acorn.es.js @@ -1305,7 +1305,12 @@ pp$1.checkVariableExport = function(exports, decls) { } pp$1.shouldParseExportStatement = function() { - return this.type.keyword || this.isLet() || this.isAsyncFunction() + return this.type.keyword === "var" + || this.type.keyword === "const" + || this.type.keyword === "class" + || this.type.keyword === "function" + || this.isLet() + || this.isAsyncFunction() } // Parses a comma-separated list of module exports. @@ -1617,6 +1622,24 @@ pp$2.checkLVal = function(expr, isBinding, checkClashes) { } } +// A recursive descent parser operates by defining functions for all +// syntactic elements, and recursively calling those, each function +// advancing the input stream and returning an AST node. Precedence +// of constructs (for example, the fact that `!x[1]` means `!(x[1])` +// instead of `(!x)[1]` is handled by the fact that the parser +// function that parses unary prefix operators is called first, and +// in turn calls the function that parses `[]` subscripts — that +// way, it'll receive the node for `x[1]` already parsed, and wraps +// *that* in the unary operator node. +// +// Acorn uses an [operator precedence parser][opp] to handle binary +// operator precedence, because it is much more compact than using +// the technique outlined above, which uses different, nesting +// functions to specify precedence, for all of the ten binary +// precedence levels that JavaScript defines. +// +// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + var pp$3 = Parser.prototype // Check if property name clashes with already added. @@ -2481,6 +2504,10 @@ pp$5.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) } +// The algorithm used to determine whether a regexp can appear at a +// given point in the program is loosely based on sweet.js' approach. +// See https://github.com/mozilla/sweet.js/wiki/design + var TokContext = function TokContext(token, isExpr, preserveSpace, override) { this.token = token this.isExpr = !!isExpr @@ -3290,7 +3317,28 @@ pp$7.readWord = function() { return this.finishToken(type, word) } -var version = "4.0.3" +// Acorn is a tiny, fast JavaScript parser written in JavaScript. +// +// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and +// various contributors and released under an MIT license. +// +// Git repositories for Acorn are available at +// +// http://marijnhaverbeke.nl/git/acorn +// https://github.com/ternjs/acorn.git +// +// Please use the [github bug tracker][ghbt] to report issues. +// +// [ghbt]: https://github.com/ternjs/acorn/issues +// +// This file defines the main parser interface. The library also comes +// with a [error-tolerant parser][dammit] and an +// [abstract syntax tree walker][walk], defined in other files. +// +// [dammit]: acorn_loose.js +// [walk]: util/walk.js + +var version = "4.0.4" // The main exported interface (under `self.acorn` when in the // browser) is a `parse` function that takes a code string and diff --git a/tools/eslint/node_modules/acorn/dist/acorn.js b/tools/eslint/node_modules/acorn/dist/acorn.js index 0fc4086bb72fb6..ea572b3ebd3f4b 100644 --- a/tools/eslint/node_modules/acorn/dist/acorn.js +++ b/tools/eslint/node_modules/acorn/dist/acorn.js @@ -2,3362 +2,3410 @@ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.acorn = global.acorn || {}))); -}(this, function (exports) { 'use strict'; - - // Reserved word lists for various dialects of the language - - var reservedWords = { - 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", - 5: "class enum extends super const export import", - 6: "enum", - strict: "implements interface let package private protected public static yield", - strictBind: "eval arguments" - } - - // And the keywords - - var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this" +}(this, (function (exports) { 'use strict'; + +// Reserved word lists for various dialects of the language + +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +} + +// And the keywords + +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this" + +var keywords = { + 5: ecma5AndLessKeywords, + 6: ecma5AndLessKeywords + " const class extends export import super" +} + +// ## Character categories + +// Big ugly regular expressions that match characters in the +// whitespace, identifier, and identifier-start categories. These +// are only applied when a character is found to actually have a +// code point above 128. +// Generated by `bin/generate-identifier-regex.js`. + +var nonASCIIidentifierStartChars = "\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\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\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-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc" +var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f" + +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]") +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]") + +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null + +// These are a run-length and offset encoded representation of the +// >0xffff code points that are a valid part of identifiers. The +// offset starts at 0x10000, and each pair of numbers represents an +// offset to the next range, and then a size of the range. They were +// generated by bin/generate-identifier-regex.js +var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541] +var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239] + +// This has a complexity linear to the value of the code. The +// assumption is that looking up astral identifier characters is +// rare. +function isInAstralSet(code, set) { + var pos = 0x10000 + for (var i = 0; i < set.length; i += 2) { + pos += set[i] + if (pos > code) return false + pos += set[i + 1] + if (pos >= code) return true + } +} + +// Test whether a given character code starts an identifier. + +function isIdentifierStart(code, astral) { + if (code < 65) return code === 36 + if (code < 91) return true + if (code < 97) return code === 95 + if (code < 123) return true + if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) + if (astral === false) return false + return isInAstralSet(code, astralIdentifierStartCodes) +} + +// Test whether a given character is part of an identifier. + +function isIdentifierChar(code, astral) { + if (code < 48) return code === 36 + if (code < 58) return true + if (code < 65) return false + if (code < 91) return true + if (code < 97) return code === 95 + if (code < 123) return true + if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) + if (astral === false) return false + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) +} + +// ## Token types + +// The assignment of fine-grained, information-carrying type objects +// allows the tokenizer to store the information it has about a +// token in a way that is very cheap for the parser to look up. + +// All token type variables start with an underscore, to make them +// easy to recognize. + +// The `beforeExpr` property is used to disambiguate between regular +// expressions and divisions. It is set on all token types that can +// be followed by an expression (thus, a slash after them would be a +// regular expression). +// +// The `startsExpr` property is used to check if the token ends a +// `yield` expression. It is set on all token types that either can +// directly start an expression (like a quotation mark) or can +// continue an expression (like the body of a string). +// +// `isLoop` marks a keyword as starting a loop, which is important +// to know when parsing a label, in order to allow or disallow +// continue jumps to that label. + +var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label + this.keyword = conf.keyword + this.beforeExpr = !!conf.beforeExpr + this.startsExpr = !!conf.startsExpr + this.isLoop = !!conf.isLoop + this.isAssign = !!conf.isAssign + this.prefix = !!conf.prefix + this.postfix = !!conf.postfix + this.binop = conf.binop || null + this.updateContext = null +}; + +function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) +} +var beforeExpr = {beforeExpr: true}; +var startsExpr = {startsExpr: true}; +// Map keyword names to token types. + +var keywordTypes = {} + +// Succinct definitions of keyword token types +function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name + return keywordTypes[name] = new TokenType(name, options) +} + +var tt = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=", 6), + relational: binop("", 7), + bitShift: binop("<>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class"), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import"), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) +} + +// Matches a whole line break (where CRLF is considered a single +// line break). Used to count lines. + +var lineBreak = /\r\n?|\n|\u2028|\u2029/ +var lineBreakG = new RegExp(lineBreak.source, "g") + +function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 +} + +var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/ + +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g + +function isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]" +} + +// Checks if an object has a property. + +function has(obj, propName) { + return Object.prototype.hasOwnProperty.call(obj, propName) +} + +// These are used when `options.locations` is on, for the +// `startLoc` and `endLoc` properties. + +var Position = function Position(line, col) { + this.line = line + this.column = col +}; + +Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) +}; + +var SourceLocation = function SourceLocation(p, start, end) { + this.start = start + this.end = end + if (p.sourceFile !== null) this.source = p.sourceFile +}; + +// The `getLineInfo` function is mostly useful when the +// `locations` option is off (for performance reasons) and you +// want to find the line/column position for a given character +// offset. `input` should be the code string that the offset refers +// into. + +function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreakG.lastIndex = cur + var match = lineBreakG.exec(input) + if (match && match.index < offset) { + ++line + cur = match.index + match[0].length + } else { + return new Position(line, offset - cur) + } + } +} + +// A second optional argument can be given to further configure +// the parser process. These options are recognized: + +var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must + // be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support + // for strict mode, the set of reserved words, and support for + // new syntax features. The default is 7. + ecmaVersion: 7, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // th position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program. + allowImportExportEverywhere: false, + // When enabled, hashbang directive in the beginning of file + // is allowed and treated as a line comment. + allowHashBang: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false, + plugins: {} +} + +// Interpret and default an options object + +function getOptions(opts) { + var options = {} + + for (var opt in defaultOptions) + options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] + + if (options.ecmaVersion >= 2015) + options.ecmaVersion -= 2009 + + if (options.allowReserved == null) + options.allowReserved = options.ecmaVersion < 5 + + if (isArray(options.onToken)) { + var tokens = options.onToken + options.onToken = function (token) { return tokens.push(token); } + } + if (isArray(options.onComment)) + options.onComment = pushComment(options, options.onComment) + + return options +} + +function pushComment(options, array) { + return function (block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? 'Block' : 'Line', + value: text, + start: start, + end: end + } + if (options.locations) + comment.loc = new SourceLocation(this, startLoc, endLoc) + if (options.ranges) + comment.range = [start, end] + array.push(comment) + } +} + +// Registered plugins +var plugins = {} + +function keywordRegexp(words) { + return new RegExp("^(" + words.replace(/ /g, "|") + ")$") +} + +var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options) + this.sourceFile = options.sourceFile + this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]) + var reserved = "" + if (!options.allowReserved) { + for (var v = options.ecmaVersion;; v--) + if (reserved = reservedWords[v]) break + if (options.sourceType == "module") reserved += " await" + } + this.reservedWords = keywordRegexp(reserved) + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict + this.reservedWordsStrict = keywordRegexp(reservedStrict) + this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind) + this.input = String(input) + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false + + // Load plugins + this.loadPlugins(options.plugins) + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1 + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length + } else { + this.pos = this.lineStart = 0 + this.curLine = 1 + } + + // Properties of the current token: + // Its type + this.type = tt.eof + // For tokens that include more information than their type, the value + this.value = null + // Its start and end offset + this.start = this.end = this.pos + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition() + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null + this.lastTokStart = this.lastTokEnd = this.pos + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext() + this.exprAllowed = true + + // Figure out if it's a module code. + this.strict = this.inModule = options.sourceType === "module" + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1 + + // Flags to track whether we are in a function, a generator, an async function. + this.inFunction = this.inGenerator = this.inAsync = false + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = 0 + // Labels in scope. + this.labels = [] + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') + this.skipLineComment(2) +}; + +// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them +Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) }; +Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) }; + +Parser.prototype.extend = function extend (name, f) { + this[name] = f(this[name]) +}; + +Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) { + var this$1 = this; - var keywords = { - 5: ecma5AndLessKeywords, - 6: ecma5AndLessKeywords + " const class extends export import super" + for (var name in pluginConfigs) { + var plugin = plugins[name] + if (!plugin) throw new Error("Plugin '" + name + "' not found") + plugin(this$1, pluginConfigs[name]) } +}; - // ## Character categories +Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode() + this.nextToken() + return this.parseTopLevel(node) +}; - // Big ugly regular expressions that match characters in the - // whitespace, identifier, and identifier-start categories. These - // are only applied when a character is found to actually have a - // code point above 128. - // Generated by `bin/generate-identifier-regex.js`. +var pp = Parser.prototype - var nonASCIIidentifierStartChars = "\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\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\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-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc" - var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f" +// ## Parser utilities - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]") - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]") +// Test whether a statement node is the string literal `"use strict"`. - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null +pp.isUseStrict = function(stmt) { + return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && + stmt.expression.type === "Literal" && + stmt.expression.raw.slice(1, -1) === "use strict" +} - // These are a run-length and offset encoded representation of the - // >0xffff code points that are a valid part of identifiers. The - // offset starts at 0x10000, and each pair of numbers represents an - // offset to the next range, and then a size of the range. They were - // generated by bin/generate-identifier-regex.js - var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541] - var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239] +// Predicate that tests whether the next token is of the given +// type, and if yes, consumes it as a side effect. - // This has a complexity linear to the value of the code. The - // assumption is that looking up astral identifier characters is - // rare. - function isInAstralSet(code, set) { - var pos = 0x10000 - for (var i = 0; i < set.length; i += 2) { - pos += set[i] - if (pos > code) return false - pos += set[i + 1] - if (pos >= code) return true - } +pp.eat = function(type) { + if (this.type === type) { + this.next() + return true + } else { + return false } +} - // Test whether a given character code starts an identifier. - - function isIdentifierStart(code, astral) { - if (code < 65) return code === 36 - if (code < 91) return true - if (code < 97) return code === 95 - if (code < 123) return true - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) - if (astral === false) return false - return isInAstralSet(code, astralIdentifierStartCodes) - } +// Tests whether parsed token is a contextual keyword. - // Test whether a given character is part of an identifier. +pp.isContextual = function(name) { + return this.type === tt.name && this.value === name +} - function isIdentifierChar(code, astral) { - if (code < 48) return code === 36 - if (code < 58) return true - if (code < 65) return false - if (code < 91) return true - if (code < 97) return code === 95 - if (code < 123) return true - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) - if (astral === false) return false - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) - } +// Consumes contextual keyword if possible. - // ## Token types +pp.eatContextual = function(name) { + return this.value === name && this.eat(tt.name) +} - // The assignment of fine-grained, information-carrying type objects - // allows the tokenizer to store the information it has about a - // token in a way that is very cheap for the parser to look up. +// Asserts that following token is given contextual keyword. - // All token type variables start with an underscore, to make them - // easy to recognize. +pp.expectContextual = function(name) { + if (!this.eatContextual(name)) this.unexpected() +} - // The `beforeExpr` property is used to disambiguate between regular - // expressions and divisions. It is set on all token types that can - // be followed by an expression (thus, a slash after them would be a - // regular expression). - // - // The `startsExpr` property is used to check if the token ends a - // `yield` expression. It is set on all token types that either can - // directly start an expression (like a quotation mark) or can - // continue an expression (like the body of a string). - // - // `isLoop` marks a keyword as starting a loop, which is important - // to know when parsing a label, in order to allow or disallow - // continue jumps to that label. - - var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; - - this.label = label - this.keyword = conf.keyword - this.beforeExpr = !!conf.beforeExpr - this.startsExpr = !!conf.startsExpr - this.isLoop = !!conf.isLoop - this.isAssign = !!conf.isAssign - this.prefix = !!conf.prefix - this.postfix = !!conf.postfix - this.binop = conf.binop || null - this.updateContext = null - }; - - function binop(name, prec) { - return new TokenType(name, {beforeExpr: true, binop: prec}) - } - var beforeExpr = {beforeExpr: true}; - var startsExpr = {startsExpr: true}; - // Map keyword names to token types. - - var keywordTypes = {} - - // Succinct definitions of keyword token types - function kw(name, options) { - if ( options === void 0 ) options = {}; - - options.keyword = name - return keywordTypes[name] = new TokenType(name, options) - } - - var tt = { - num: new TokenType("num", startsExpr), - regexp: new TokenType("regexp", startsExpr), - string: new TokenType("string", startsExpr), - name: new TokenType("name", startsExpr), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), - bracketR: new TokenType("]"), - braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), - braceR: new TokenType("}"), - parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), - parenR: new TokenType(")"), - comma: new TokenType(",", beforeExpr), - semi: new TokenType(";", beforeExpr), - colon: new TokenType(":", beforeExpr), - dot: new TokenType("."), - question: new TokenType("?", beforeExpr), - arrow: new TokenType("=>", beforeExpr), - template: new TokenType("template"), - ellipsis: new TokenType("...", beforeExpr), - backQuote: new TokenType("`", startsExpr), - dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", {beforeExpr: true, isAssign: true}), - assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), - incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), - prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}), - logicalOR: binop("||", 1), - logicalAND: binop("&&", 2), - bitwiseOR: binop("|", 3), - bitwiseXOR: binop("^", 4), - bitwiseAND: binop("&", 5), - equality: binop("==/!=", 6), - relational: binop("", 7), - bitShift: binop("<>", 8), - plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), - modulo: binop("%", 10), - star: binop("*", 10), - slash: binop("/", 10), - starstar: new TokenType("**", {beforeExpr: true}), - - // Keyword token types. - _break: kw("break"), - _case: kw("case", beforeExpr), - _catch: kw("catch"), - _continue: kw("continue"), - _debugger: kw("debugger"), - _default: kw("default", beforeExpr), - _do: kw("do", {isLoop: true, beforeExpr: true}), - _else: kw("else", beforeExpr), - _finally: kw("finally"), - _for: kw("for", {isLoop: true}), - _function: kw("function", startsExpr), - _if: kw("if"), - _return: kw("return", beforeExpr), - _switch: kw("switch"), - _throw: kw("throw", beforeExpr), - _try: kw("try"), - _var: kw("var"), - _const: kw("const"), - _while: kw("while", {isLoop: true}), - _with: kw("with"), - _new: kw("new", {beforeExpr: true, startsExpr: true}), - _this: kw("this", startsExpr), - _super: kw("super", startsExpr), - _class: kw("class"), - _extends: kw("extends", beforeExpr), - _export: kw("export"), - _import: kw("import"), - _null: kw("null", startsExpr), - _true: kw("true", startsExpr), - _false: kw("false", startsExpr), - _in: kw("in", {beforeExpr: true, binop: 7}), - _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), - _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), - _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), - _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) - } - - // Matches a whole line break (where CRLF is considered a single - // line break). Used to count lines. - - var lineBreak = /\r\n?|\n|\u2028|\u2029/ - var lineBreakG = new RegExp(lineBreak.source, "g") - - function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 - } - - var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/ - - var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g - - function isArray(obj) { - return Object.prototype.toString.call(obj) === "[object Array]" - } - - // Checks if an object has a property. - - function has(obj, propName) { - return Object.prototype.hasOwnProperty.call(obj, propName) - } - - // These are used when `options.locations` is on, for the - // `startLoc` and `endLoc` properties. - - var Position = function Position(line, col) { - this.line = line - this.column = col - }; - - Position.prototype.offset = function offset (n) { - return new Position(this.line, this.column + n) - }; - - var SourceLocation = function SourceLocation(p, start, end) { - this.start = start - this.end = end - if (p.sourceFile !== null) this.source = p.sourceFile - }; - - // The `getLineInfo` function is mostly useful when the - // `locations` option is off (for performance reasons) and you - // want to find the line/column position for a given character - // offset. `input` should be the code string that the offset refers - // into. - - function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur - var match = lineBreakG.exec(input) - if (match && match.index < offset) { - ++line - cur = match.index + match[0].length - } else { - return new Position(line, offset - cur) - } - } - } +// Test whether a semicolon can be inserted at the current position. - // A second optional argument can be given to further configure - // the parser process. These options are recognized: - - var defaultOptions = { - // `ecmaVersion` indicates the ECMAScript version to parse. Must - // be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support - // for strict mode, the set of reserved words, and support for - // new syntax features. The default is 7. - ecmaVersion: 7, - // `sourceType` indicates the mode the code should be parsed in. - // Can be either `"script"` or `"module"`. This influences global - // strict mode and parsing of `import` and `export` declarations. - sourceType: "script", - // `onInsertedSemicolon` can be a callback that will be called - // when a semicolon is automatically inserted. It will be passed - // th position of the comma as an offset, and if `locations` is - // enabled, it is given the location as a `{line, column}` object - // as second argument. - onInsertedSemicolon: null, - // `onTrailingComma` is similar to `onInsertedSemicolon`, but for - // trailing commas. - onTrailingComma: null, - // By default, reserved words are only enforced if ecmaVersion >= 5. - // Set `allowReserved` to a boolean value to explicitly turn this on - // an off. When this option has the value "never", reserved words - // and keywords can also not be used as property names. - allowReserved: null, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // When enabled, hashbang directive in the beginning of file - // is allowed and treated as a line comment. - allowHashBang: false, - // When `locations` is on, `loc` properties holding objects with - // `start` and `end` properties in `{line, column}` form (with - // line being 1-based and column 0-based) will be attached to the - // nodes. - locations: false, - // A function can be passed as `onToken` option, which will - // cause Acorn to call that function with object in the same - // format as tokens returned from `tokenizer().getToken()`. Note - // that you are not allowed to call the parser from the - // callback—that will corrupt its internal state. - onToken: null, - // A function can be passed as `onComment` option, which will - // cause Acorn to call that function with `(block, text, start, - // end)` parameters whenever a comment is skipped. `block` is a - // boolean indicating whether this is a block (`/* */`) comment, - // `text` is the content of the comment, and `start` and `end` are - // character offsets that denote the start and end of the comment. - // When the `locations` option is on, two more parameters are - // passed, the full `{line, column}` locations of the start and - // end of the comments. Note that you are not allowed to call the - // parser from the callback—that will corrupt its internal state. - onComment: null, - // Nodes have their start and end characters offsets recorded in - // `start` and `end` properties (directly on the node, rather than - // the `loc` object, which holds line/column data. To also add a - // [semi-standardized][range] `range` property holding a `[start, - // end]` array with the same numbers, set the `ranges` option to - // `true`. - // - // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - ranges: false, - // It is possible to parse multiple files into a single AST by - // passing the tree produced by parsing the first file as - // `program` option in subsequent parses. This will add the - // toplevel forms of the parsed file to the `Program` (top) node - // of an existing parse tree. - program: null, - // When `locations` is on, you can pass this to record the source - // file in every node's `loc` object. - sourceFile: null, - // This value, if given, is stored in every node, whether - // `locations` is on or off. - directSourceFile: null, - // When enabled, parenthesized expressions are represented by - // (non-standard) ParenthesizedExpression nodes - preserveParens: false, - plugins: {} - } - - // Interpret and default an options object - - function getOptions(opts) { - var options = {} - - for (var opt in defaultOptions) - options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] - - if (options.ecmaVersion >= 2015) - options.ecmaVersion -= 2009 - - if (options.allowReserved == null) - options.allowReserved = options.ecmaVersion < 5 - - if (isArray(options.onToken)) { - var tokens = options.onToken - options.onToken = function (token) { return tokens.push(token); } - } - if (isArray(options.onComment)) - options.onComment = pushComment(options, options.onComment) +pp.canInsertSemicolon = function() { + return this.type === tt.eof || + this.type === tt.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +} - return options +pp.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc) + return true } +} - function pushComment(options, array) { - return function (block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? 'Block' : 'Line', - value: text, - start: start, - end: end - } - if (options.locations) - comment.loc = new SourceLocation(this, startLoc, endLoc) - if (options.ranges) - comment.range = [start, end] - array.push(comment) - } - } +// Consume a semicolon, or, failing that, see if we are allowed to +// pretend that there is a semicolon at this position. - // Registered plugins - var plugins = {} +pp.semicolon = function() { + if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected() +} - function keywordRegexp(words) { - return new RegExp("^(" + words.replace(/ /g, "|") + ")$") +pp.afterTrailingComma = function(tokType, notNext) { + if (this.type == tokType) { + if (this.options.onTrailingComma) + this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc) + if (!notNext) + this.next() + return true } +} - var Parser = function Parser(options, input, startPos) { - this.options = options = getOptions(options) - this.sourceFile = options.sourceFile - this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]) - var reserved = "" - if (!options.allowReserved) { - for (var v = options.ecmaVersion;; v--) - if (reserved = reservedWords[v]) break - if (options.sourceType == "module") reserved += " await" - } - this.reservedWords = keywordRegexp(reserved) - var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict - this.reservedWordsStrict = keywordRegexp(reservedStrict) - this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind) - this.input = String(input) - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - this.containsEsc = false - - // Load plugins - this.loadPlugins(options.plugins) - - // Set up token state - - // The current position of the tokenizer in the input. - if (startPos) { - this.pos = startPos - this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1 - this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length - } else { - this.pos = this.lineStart = 0 - this.curLine = 1 - } - - // Properties of the current token: - // Its type - this.type = tt.eof - // For tokens that include more information than their type, the value - this.value = null - // Its start and end offset - this.start = this.end = this.pos - // And, if locations are used, the {line, column} object - // corresponding to those offsets - this.startLoc = this.endLoc = this.curPosition() - - // Position information for the previous token - this.lastTokEndLoc = this.lastTokStartLoc = null - this.lastTokStart = this.lastTokEnd = this.pos - - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - this.context = this.initialContext() - this.exprAllowed = true - - // Figure out if it's a module code. - this.strict = this.inModule = options.sourceType === "module" +// Expect a token of a given type. If found, consume it, otherwise, +// raise an unexpected token error. - // Used to signify the start of a potential arrow function - this.potentialArrowAt = -1 +pp.expect = function(type) { + this.eat(type) || this.unexpected() +} - // Flags to track whether we are in a function, a generator, an async function. - this.inFunction = this.inGenerator = this.inAsync = false - // Positions to delayed-check that yield/await does not exist in default parameters. - this.yieldPos = this.awaitPos = 0 - // Labels in scope. - this.labels = [] +// Raise an unexpected token error. - // If enabled, skip leading hashbang line. - if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') - this.skipLineComment(2) - }; +pp.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token") +} - // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them - Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) }; - Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) }; +var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = 0 + this.trailingComma = 0 +}; - Parser.prototype.extend = function extend (name, f) { - this[name] = f(this[name]) - }; +pp.checkPatternErrors = function(refDestructuringErrors, andThrow) { + var trailing = refDestructuringErrors && refDestructuringErrors.trailingComma + if (!andThrow) return !!trailing + if (trailing) this.raise(trailing, "Comma is not permitted after the rest element") +} - Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) { - var this$1 = this; +pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign + if (!andThrow) return !!pos + if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns") +} - for (var name in pluginConfigs) { - var plugin = plugins[name] - if (!plugin) throw new Error("Plugin '" + name + "' not found") - plugin(this$1, pluginConfigs[name]) - } - }; +pp.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + this.raise(this.yieldPos, "Yield expression cannot be a default value") + if (this.awaitPos) + this.raise(this.awaitPos, "Await expression cannot be a default value") +} - Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode() - this.nextToken() - return this.parseTopLevel(node) - }; +var pp$1 = Parser.prototype - var pp = Parser.prototype +// ### Statement parsing - // ## Parser utilities +// Parse a program. Initializes the parser, reads any number of +// statements, and wraps them in a Program node. Optionally takes a +// `program` argument. If present, the statements will be appended +// to its body instead of creating a new node. - // Test whether a statement node is the string literal `"use strict"`. +pp$1.parseTopLevel = function(node) { + var this$1 = this; - pp.isUseStrict = function(stmt) { - return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && - stmt.expression.type === "Literal" && - stmt.expression.raw.slice(1, -1) === "use strict" + var first = true, exports = {} + if (!node.body) node.body = [] + while (this.type !== tt.eof) { + var stmt = this$1.parseStatement(true, true, exports) + node.body.push(stmt) + if (first) { + if (this$1.isUseStrict(stmt)) this$1.setStrict(true) + first = false + } } + this.next() + if (this.options.ecmaVersion >= 6) { + node.sourceType = this.options.sourceType + } + return this.finishNode(node, "Program") +} + +var loopLabel = {kind: "loop"}; +var switchLabel = {kind: "switch"}; +pp$1.isLet = function() { + if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false + skipWhiteSpace.lastIndex = this.pos + var skip = skipWhiteSpace.exec(this.input) + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next) + if (nextCh === 91 || nextCh == 123) return true // '{' and '[' + if (isIdentifierStart(nextCh, true)) { + for (var pos = next + 1; isIdentifierChar(this.input.charCodeAt(pos), true); ++pos) {} + var ident = this.input.slice(next, pos) + if (!this.isKeyword(ident)) return true + } + return false +} + +// check 'async [no LineTerminator here] function' +// - 'async /*foo*/ function' is OK. +// - 'async /*\n*/ function' is invalid. +pp$1.isAsyncFunction = function() { + if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async") + return false - // Predicate that tests whether the next token is of the given - // type, and if yes, consumes it as a side effect. - - pp.eat = function(type) { - if (this.type === type) { + skipWhiteSpace.lastIndex = this.pos + var skip = skipWhiteSpace.exec(this.input) + var next = this.pos + skip[0].length + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) +} + +// Parse a single statement. +// +// If expecting a statement and finding a slash operator, parse a +// regular expression literal. This is to handle cases like +// `if (foo) /blah/.exec(foo)`, where looking at the previous token +// does not help. + +pp$1.parseStatement = function(declaration, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind + + if (this.isLet()) { + starttype = tt._var + kind = "let" + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case tt._debugger: return this.parseDebuggerStatement(node) + case tt._do: return this.parseDoStatement(node) + case tt._for: return this.parseForStatement(node) + case tt._function: + if (!declaration && this.options.ecmaVersion >= 6) this.unexpected() + return this.parseFunctionStatement(node, false) + case tt._class: + if (!declaration) this.unexpected() + return this.parseClass(node, true) + case tt._if: return this.parseIfStatement(node) + case tt._return: return this.parseReturnStatement(node) + case tt._switch: return this.parseSwitchStatement(node) + case tt._throw: return this.parseThrowStatement(node) + case tt._try: return this.parseTryStatement(node) + case tt._const: case tt._var: + kind = kind || this.value + if (!declaration && kind != "var") this.unexpected() + return this.parseVarStatement(node, kind) + case tt._while: return this.parseWhileStatement(node) + case tt._with: return this.parseWithStatement(node) + case tt.braceL: return this.parseBlock() + case tt.semi: return this.parseEmptyStatement(node) + case tt._export: + case tt._import: + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + this.raise(this.start, "'import' and 'export' may only appear at the top level") + if (!this.inModule) + this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'") + } + return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction() && declaration) { this.next() - return true - } else { - return false + return this.parseFunctionStatement(node, true) } + + var maybeName = this.value, expr = this.parseExpression() + if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) + return this.parseLabeledStatement(node, maybeName, expr) + else return this.parseExpressionStatement(node, expr) } +} - // Tests whether parsed token is a contextual keyword. +pp$1.parseBreakContinueStatement = function(node, keyword) { + var this$1 = this; - pp.isContextual = function(name) { - return this.type === tt.name && this.value === name + var isBreak = keyword == "break" + this.next() + if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null + else if (this.type !== tt.name) this.unexpected() + else { + node.label = this.parseIdent() + this.semicolon() } - // Consumes contextual keyword if possible. - - pp.eatContextual = function(name) { - return this.value === name && this.eat(tt.name) + // Verify that there is an actual destination to break or + // continue to. + for (var i = 0; i < this.labels.length; ++i) { + var lab = this$1.labels[i] + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) break + if (node.label && isBreak) break + } + } + if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword) + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") +} + +pp$1.parseDebuggerStatement = function(node) { + this.next() + this.semicolon() + return this.finishNode(node, "DebuggerStatement") +} + +pp$1.parseDoStatement = function(node) { + this.next() + this.labels.push(loopLabel) + node.body = this.parseStatement(false) + this.labels.pop() + this.expect(tt._while) + node.test = this.parseParenExpression() + if (this.options.ecmaVersion >= 6) + this.eat(tt.semi) + else + this.semicolon() + return this.finishNode(node, "DoWhileStatement") +} + +// Disambiguating between a `for` and a `for`/`in` or `for`/`of` +// loop is non-trivial. Basically, we have to parse the init `var` +// statement or expression, disallowing the `in` operator (see +// the second parameter to `parseExpression`), and then check +// whether the next token is `in` or `of`. When there is no init +// part (semicolon immediately after the opening parenthesis), it +// is a regular `for` loop. + +pp$1.parseForStatement = function(node) { + this.next() + this.labels.push(loopLabel) + this.expect(tt.parenL) + if (this.type === tt.semi) return this.parseFor(node, null) + var isLet = this.isLet() + if (this.type === tt._var || this.type === tt._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value + this.next() + this.parseVar(init$1, true, kind) + this.finishNode(init$1, "VariableDeclaration") + if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && + !(kind !== "var" && init$1.declarations[0].init)) + return this.parseForIn(node, init$1) + return this.parseFor(node, init$1) + } + var refDestructuringErrors = new DestructuringErrors + var init = this.parseExpression(true, refDestructuringErrors) + if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + this.checkPatternErrors(refDestructuringErrors, true) + this.toAssignable(init) + this.checkLVal(init) + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true) + } + return this.parseFor(node, init) +} + +pp$1.parseFunctionStatement = function(node, isAsync) { + this.next() + return this.parseFunction(node, true, false, isAsync) +} + +pp$1.isFunction = function() { + return this.type === tt._function || this.isAsyncFunction() +} + +pp$1.parseIfStatement = function(node) { + this.next() + node.test = this.parseParenExpression() + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement(!this.strict && this.isFunction()) + node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null + return this.finishNode(node, "IfStatement") +} + +pp$1.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + this.raise(this.start, "'return' outside of function") + this.next() + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null + else { node.argument = this.parseExpression(); this.semicolon() } + return this.finishNode(node, "ReturnStatement") +} + +pp$1.parseSwitchStatement = function(node) { + var this$1 = this; + + this.next() + node.discriminant = this.parseParenExpression() + node.cases = [] + this.expect(tt.braceL) + this.labels.push(switchLabel) + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + for (var cur, sawDefault = false; this.type != tt.braceR;) { + if (this$1.type === tt._case || this$1.type === tt._default) { + var isCase = this$1.type === tt._case + if (cur) this$1.finishNode(cur, "SwitchCase") + node.cases.push(cur = this$1.startNode()) + cur.consequent = [] + this$1.next() + if (isCase) { + cur.test = this$1.parseExpression() + } else { + if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses") + sawDefault = true + cur.test = null + } + this$1.expect(tt.colon) + } else { + if (!cur) this$1.unexpected() + cur.consequent.push(this$1.parseStatement(true)) + } + } + if (cur) this.finishNode(cur, "SwitchCase") + this.next() // Closing brace + this.labels.pop() + return this.finishNode(node, "SwitchStatement") +} + +pp$1.parseThrowStatement = function(node) { + this.next() + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + this.raise(this.lastTokEnd, "Illegal newline after throw") + node.argument = this.parseExpression() + this.semicolon() + return this.finishNode(node, "ThrowStatement") +} + +// Reused empty array added for node fields that are always empty. + +var empty = [] + +pp$1.parseTryStatement = function(node) { + this.next() + node.block = this.parseBlock() + node.handler = null + if (this.type === tt._catch) { + var clause = this.startNode() + this.next() + this.expect(tt.parenL) + clause.param = this.parseBindingAtom() + this.checkLVal(clause.param, true) + this.expect(tt.parenR) + clause.body = this.parseBlock() + node.handler = this.finishNode(clause, "CatchClause") + } + node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null + if (!node.handler && !node.finalizer) + this.raise(node.start, "Missing catch or finally clause") + return this.finishNode(node, "TryStatement") +} + +pp$1.parseVarStatement = function(node, kind) { + this.next() + this.parseVar(node, false, kind) + this.semicolon() + return this.finishNode(node, "VariableDeclaration") +} + +pp$1.parseWhileStatement = function(node) { + this.next() + node.test = this.parseParenExpression() + this.labels.push(loopLabel) + node.body = this.parseStatement(false) + this.labels.pop() + return this.finishNode(node, "WhileStatement") +} + +pp$1.parseWithStatement = function(node) { + if (this.strict) this.raise(this.start, "'with' in strict mode") + this.next() + node.object = this.parseParenExpression() + node.body = this.parseStatement(false) + return this.finishNode(node, "WithStatement") +} + +pp$1.parseEmptyStatement = function(node) { + this.next() + return this.finishNode(node, "EmptyStatement") +} + +pp$1.parseLabeledStatement = function(node, maybeName, expr) { + var this$1 = this; + + for (var i = 0; i < this.labels.length; ++i) + if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared") + var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null + for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) { + var label = this$1.labels[i$1] + if (label.statementStart == node.start) { + label.statementStart = this$1.start + label.kind = kind + } else break + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}) + node.body = this.parseStatement(true) + this.labels.pop() + node.label = expr + return this.finishNode(node, "LabeledStatement") +} + +pp$1.parseExpressionStatement = function(node, expr) { + node.expression = expr + this.semicolon() + return this.finishNode(node, "ExpressionStatement") +} + +// Parse a semicolon-enclosed block of statements, handling `"use +// strict"` declarations when `allowStrict` is true (used for +// function bodies). + +pp$1.parseBlock = function(allowStrict) { + var this$1 = this; + + var node = this.startNode(), first = true, oldStrict + node.body = [] + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + var stmt = this$1.parseStatement(true) + node.body.push(stmt) + if (first && allowStrict && this$1.isUseStrict(stmt)) { + oldStrict = this$1.strict + this$1.setStrict(this$1.strict = true) + } + first = false + } + if (oldStrict === false) this.setStrict(false) + return this.finishNode(node, "BlockStatement") +} + +// Parse a regular `for` loop. The disambiguation code in +// `parseStatement` will already have parsed the init statement or +// expression. + +pp$1.parseFor = function(node, init) { + node.init = init + this.expect(tt.semi) + node.test = this.type === tt.semi ? null : this.parseExpression() + this.expect(tt.semi) + node.update = this.type === tt.parenR ? null : this.parseExpression() + this.expect(tt.parenR) + node.body = this.parseStatement(false) + this.labels.pop() + return this.finishNode(node, "ForStatement") +} + +// Parse a `for`/`in` and `for`/`of` loop, which are almost +// same from parser's perspective. + +pp$1.parseForIn = function(node, init) { + var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement" + this.next() + node.left = init + node.right = this.parseExpression() + this.expect(tt.parenR) + node.body = this.parseStatement(false) + this.labels.pop() + return this.finishNode(node, type) +} + +// Parse a list of variable declarations. + +pp$1.parseVar = function(node, isFor, kind) { + var this$1 = this; + + node.declarations = [] + node.kind = kind + for (;;) { + var decl = this$1.startNode() + this$1.parseVarId(decl) + if (this$1.eat(tt.eq)) { + decl.init = this$1.parseMaybeAssign(isFor) + } else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { + this$1.unexpected() + } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) { + this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value") + } else { + decl.init = null + } + node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")) + if (!this$1.eat(tt.comma)) break + } + return node +} + +pp$1.parseVarId = function(decl) { + decl.id = this.parseBindingAtom() + this.checkLVal(decl.id, true) +} + +// Parse a function declaration or literal (depending on the +// `isStatement` parameter). + +pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) { + this.initFunction(node) + if (this.options.ecmaVersion >= 6 && !isAsync) + node.generator = this.eat(tt.star) + if (this.options.ecmaVersion >= 8) + node.async = !!isAsync + + if (isStatement) + node.id = this.parseIdent() + + var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos + this.inGenerator = node.generator + this.inAsync = node.async + this.yieldPos = 0 + this.awaitPos = 0 + + if (!isStatement && this.type === tt.name) + node.id = this.parseIdent() + this.parseFunctionParams(node) + this.parseFunctionBody(node, allowExpressionBody) + + this.inGenerator = oldInGen + this.inAsync = oldInAsync + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") +} + +pp$1.parseFunctionParams = function(node) { + this.expect(tt.parenL) + node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8, true) + this.checkYieldAwaitInDefaultParams() +} + +// Parse a class declaration or literal (depending on the +// `isStatement` parameter). + +pp$1.parseClass = function(node, isStatement) { + var this$1 = this; + + this.next() + this.parseClassId(node, isStatement) + this.parseClassSuper(node) + var classBody = this.startNode() + var hadConstructor = false + classBody.body = [] + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + if (this$1.eat(tt.semi)) continue + var method = this$1.startNode() + var isGenerator = this$1.eat(tt.star) + var isAsync = false + var isMaybeStatic = this$1.type === tt.name && this$1.value === "static" + this$1.parsePropertyName(method) + method.static = isMaybeStatic && this$1.type !== tt.parenL + if (method.static) { + if (isGenerator) this$1.unexpected() + isGenerator = this$1.eat(tt.star) + this$1.parsePropertyName(method) + } + if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed && + method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== tt.parenL && + !this$1.canInsertSemicolon()) { + isAsync = true + this$1.parsePropertyName(method) + } + method.kind = "method" + var isGetSet = false + if (!method.computed) { + var key = method.key; + if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) { + isGetSet = true + method.kind = key.name + key = this$1.parsePropertyName(method) + } + if (!method.static && (key.type === "Identifier" && key.name === "constructor" || + key.type === "Literal" && key.value === "constructor")) { + if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class") + if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier") + if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator") + if (isAsync) this$1.raise(key.start, "Constructor can't be an async method") + method.kind = "constructor" + hadConstructor = true + } + } + this$1.parseClassMethod(classBody, method, isGenerator, isAsync) + if (isGetSet) { + var paramCount = method.kind === "get" ? 0 : 1 + if (method.value.params.length !== paramCount) { + var start = method.value.start + if (method.kind === "get") + this$1.raiseRecoverable(start, "getter should have no params") + else + this$1.raiseRecoverable(start, "setter should have exactly one param") + } else { + if (method.kind === "set" && method.value.params[0].type === "RestElement") + this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params") + } + } } + node.body = this.finishNode(classBody, "ClassBody") + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") +} - // Asserts that following token is given contextual keyword. +pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) { + method.value = this.parseMethod(isGenerator, isAsync) + classBody.body.push(this.finishNode(method, "MethodDefinition")) +} - pp.expectContextual = function(name) { - if (!this.eatContextual(name)) this.unexpected() - } +pp$1.parseClassId = function(node, isStatement) { + node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null +} - // Test whether a semicolon can be inserted at the current position. +pp$1.parseClassSuper = function(node) { + node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null +} - pp.canInsertSemicolon = function() { - return this.type === tt.eof || - this.type === tt.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - } +// Parses module export declaration. - pp.insertSemicolon = function() { - if (this.canInsertSemicolon()) { - if (this.options.onInsertedSemicolon) - this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc) - return true +pp$1.parseExport = function(node, exports) { + var this$1 = this; + + this.next() + // export * from '...' + if (this.eat(tt.star)) { + this.expectContextual("from") + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() + this.semicolon() + return this.finishNode(node, "ExportAllDeclaration") + } + if (this.eat(tt._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart) + var parens = this.type == tt.parenL + var expr = this.parseMaybeAssign() + var needsSemi = true + if (!parens && (expr.type == "FunctionExpression" || + expr.type == "ClassExpression")) { + needsSemi = false + if (expr.id) { + expr.type = expr.type == "FunctionExpression" + ? "FunctionDeclaration" + : "ClassDeclaration" + } } + node.declaration = expr + if (needsSemi) this.semicolon() + return this.finishNode(node, "ExportDefaultDeclaration") } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(true) + if (node.declaration.type === "VariableDeclaration") + this.checkVariableExport(exports, node.declaration.declarations) + else + this.checkExport(exports, node.declaration.id.name, node.declaration.id.start) + node.specifiers = [] + node.source = null + } else { // export { x, y as z } [from '...'] + node.declaration = null + node.specifiers = this.parseExportSpecifiers(exports) + if (this.eatContextual("from")) { + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() + } else { + // check for keywords used as local names + for (var i = 0; i < node.specifiers.length; i++) { + if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) { + this$1.unexpected(node.specifiers[i].local.start) + } + } - // Consume a semicolon, or, failing that, see if we are allowed to - // pretend that there is a semicolon at this position. - - pp.semicolon = function() { - if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected() + node.source = null + } + this.semicolon() } - - pp.afterTrailingComma = function(tokType, notNext) { - if (this.type == tokType) { - if (this.options.onTrailingComma) - this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc) - if (!notNext) - this.next() - return true + return this.finishNode(node, "ExportNamedDeclaration") +} + +pp$1.checkExport = function(exports, name, pos) { + if (!exports) return + if (Object.prototype.hasOwnProperty.call(exports, name)) + this.raiseRecoverable(pos, "Duplicate export '" + name + "'") + exports[name] = true +} + +pp$1.checkPatternExport = function(exports, pat) { + var this$1 = this; + + var type = pat.type + if (type == "Identifier") + this.checkExport(exports, pat.name, pat.start) + else if (type == "ObjectPattern") + for (var i = 0; i < pat.properties.length; ++i) + this$1.checkPatternExport(exports, pat.properties[i].value) + else if (type == "ArrayPattern") + for (var i$1 = 0; i$1 < pat.elements.length; ++i$1) { + var elt = pat.elements[i$1] + if (elt) this$1.checkPatternExport(exports, elt) + } + else if (type == "AssignmentPattern") + this.checkPatternExport(exports, pat.left) + else if (type == "ParenthesizedExpression") + this.checkPatternExport(exports, pat.expression) +} + +pp$1.checkVariableExport = function(exports, decls) { + var this$1 = this; + + if (!exports) return + for (var i = 0; i < decls.length; i++) + this$1.checkPatternExport(exports, decls[i].id) +} + +pp$1.shouldParseExportStatement = function() { + return this.type.keyword === "var" + || this.type.keyword === "const" + || this.type.keyword === "class" + || this.type.keyword === "function" + || this.isLet() + || this.isAsyncFunction() +} + +// Parses a comma-separated list of module exports. + +pp$1.parseExportSpecifiers = function(exports) { + var this$1 = this; + + var nodes = [], first = true + // export { x, y as z } [from '...'] + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + if (!first) { + this$1.expect(tt.comma) + if (this$1.afterTrailingComma(tt.braceR)) break + } else first = false + + var node = this$1.startNode() + node.local = this$1.parseIdent(this$1.type === tt._default) + node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local + this$1.checkExport(exports, node.exported.name, node.exported.start) + nodes.push(this$1.finishNode(node, "ExportSpecifier")) + } + return nodes +} + +// Parses import declaration. + +pp$1.parseImport = function(node) { + this.next() + // import '...' + if (this.type === tt.string) { + node.specifiers = empty + node.source = this.parseExprAtom() + } else { + node.specifiers = this.parseImportSpecifiers() + this.expectContextual("from") + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() + } + this.semicolon() + return this.finishNode(node, "ImportDeclaration") +} + +// Parses a comma-separated list of module imports. + +pp$1.parseImportSpecifiers = function() { + var this$1 = this; + + var nodes = [], first = true + if (this.type === tt.name) { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode() + node.local = this.parseIdent() + this.checkLVal(node.local, true) + nodes.push(this.finishNode(node, "ImportDefaultSpecifier")) + if (!this.eat(tt.comma)) return nodes + } + if (this.type === tt.star) { + var node$1 = this.startNode() + this.next() + this.expectContextual("as") + node$1.local = this.parseIdent() + this.checkLVal(node$1.local, true) + nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")) + return nodes + } + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + if (!first) { + this$1.expect(tt.comma) + if (this$1.afterTrailingComma(tt.braceR)) break + } else first = false + + var node$2 = this$1.startNode() + node$2.imported = this$1.parseIdent(true) + if (this$1.eatContextual("as")) { + node$2.local = this$1.parseIdent() + } else { + node$2.local = node$2.imported + if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start) + if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raiseRecoverable(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved") } + this$1.checkLVal(node$2.local, true) + nodes.push(this$1.finishNode(node$2, "ImportSpecifier")) } + return nodes +} - // Expect a token of a given type. If found, consume it, otherwise, - // raise an unexpected token error. - - pp.expect = function(type) { - this.eat(type) || this.unexpected() - } +var pp$2 = Parser.prototype - // Raise an unexpected token error. +// Convert existing expression atom to assignable pattern +// if possible. - pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token") - } +pp$2.toAssignable = function(node, isBinding) { + var this$1 = this; - var DestructuringErrors = function DestructuringErrors() { - this.shorthandAssign = 0 - this.trailingComma = 0 - }; + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + this.raise(node.start, "Can not use 'await' as identifier inside an async function") + break - pp.checkPatternErrors = function(refDestructuringErrors, andThrow) { - var trailing = refDestructuringErrors && refDestructuringErrors.trailingComma - if (!andThrow) return !!trailing - if (trailing) this.raise(trailing, "Comma is not permitted after the rest element") - } + case "ObjectPattern": + case "ArrayPattern": + break - pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { - var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign - if (!andThrow) return !!pos - if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns") - } + case "ObjectExpression": + node.type = "ObjectPattern" + for (var i = 0; i < node.properties.length; i++) { + var prop = node.properties[i] + if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter") + this$1.toAssignable(prop.value, isBinding) + } + break - pp.checkYieldAwaitInDefaultParams = function() { - if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) - this.raise(this.yieldPos, "Yield expression cannot be a default value") - if (this.awaitPos) - this.raise(this.awaitPos, "Await expression cannot be a default value") - } + case "ArrayExpression": + node.type = "ArrayPattern" + this.toAssignableList(node.elements, isBinding) + break - var pp$1 = Parser.prototype + case "AssignmentExpression": + if (node.operator === "=") { + node.type = "AssignmentPattern" + delete node.operator + this.toAssignable(node.left, isBinding) + // falls through to AssignmentPattern + } else { + this.raise(node.left.end, "Only '=' operator can be used for specifying default value.") + break + } - // ### Statement parsing + case "AssignmentPattern": + break - // Parse a program. Initializes the parser, reads any number of - // statements, and wraps them in a Program node. Optionally takes a - // `program` argument. If present, the statements will be appended - // to its body instead of creating a new node. + case "ParenthesizedExpression": + node.expression = this.toAssignable(node.expression, isBinding) + break - pp$1.parseTopLevel = function(node) { - var this$1 = this; + case "MemberExpression": + if (!isBinding) break - var first = true, exports = {} - if (!node.body) node.body = [] - while (this.type !== tt.eof) { - var stmt = this$1.parseStatement(true, true, exports) - node.body.push(stmt) - if (first) { - if (this$1.isUseStrict(stmt)) this$1.setStrict(true) - first = false - } - } - this.next() - if (this.options.ecmaVersion >= 6) { - node.sourceType = this.options.sourceType - } - return this.finishNode(node, "Program") - } - - var loopLabel = {kind: "loop"}; - var switchLabel = {kind: "switch"}; - pp$1.isLet = function() { - if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false - skipWhiteSpace.lastIndex = this.pos - var skip = skipWhiteSpace.exec(this.input) - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next) - if (nextCh === 91 || nextCh == 123) return true // '{' and '[' - if (isIdentifierStart(nextCh, true)) { - for (var pos = next + 1; isIdentifierChar(this.input.charCodeAt(pos), true); ++pos) {} - var ident = this.input.slice(next, pos) - if (!this.isKeyword(ident)) return true + default: + this.raise(node.start, "Assigning to rvalue") } - return false } + return node +} - // check 'async [no LineTerminator here] function' - // - 'async /*foo*/ function' is OK. - // - 'async /*\n*/ function' is invalid. - pp$1.isAsyncFunction = function() { - if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async") - return false +// Convert list of expression atoms to binding list. - skipWhiteSpace.lastIndex = this.pos - var skip = skipWhiteSpace.exec(this.input) - var next = this.pos + skip[0].length - return !lineBreak.test(this.input.slice(this.pos, next)) && - this.input.slice(next, next + 8) === "function" && - (next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) +pp$2.toAssignableList = function(exprList, isBinding) { + var this$1 = this; + + var end = exprList.length + if (end) { + var last = exprList[end - 1] + if (last && last.type == "RestElement") { + --end + } else if (last && last.type == "SpreadElement") { + last.type = "RestElement" + var arg = last.argument + this.toAssignable(arg, isBinding) + if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") + this.unexpected(arg.start) + --end + } + + if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + this.unexpected(last.argument.start) + } + for (var i = 0; i < end; i++) { + var elt = exprList[i] + if (elt) this$1.toAssignable(elt, isBinding) } + return exprList +} - // Parse a single statement. - // - // If expecting a statement and finding a slash operator, parse a - // regular expression literal. This is to handle cases like - // `if (foo) /blah/.exec(foo)`, where looking at the previous token - // does not help. +// Parses spread element. - pp$1.parseStatement = function(declaration, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind +pp$2.parseSpread = function(refDestructuringErrors) { + var node = this.startNode() + this.next() + node.argument = this.parseMaybeAssign(false, refDestructuringErrors) + return this.finishNode(node, "SpreadElement") +} - if (this.isLet()) { - starttype = tt._var - kind = "let" - } +pp$2.parseRest = function(allowNonIdent) { + var node = this.startNode() + this.next() - // Most types of statements are recognized by the keyword they - // start with. Many are trivial to parse, some require a bit of - // complexity. - - switch (starttype) { - case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword) - case tt._debugger: return this.parseDebuggerStatement(node) - case tt._do: return this.parseDoStatement(node) - case tt._for: return this.parseForStatement(node) - case tt._function: - if (!declaration && this.options.ecmaVersion >= 6) this.unexpected() - return this.parseFunctionStatement(node, false) - case tt._class: - if (!declaration) this.unexpected() - return this.parseClass(node, true) - case tt._if: return this.parseIfStatement(node) - case tt._return: return this.parseReturnStatement(node) - case tt._switch: return this.parseSwitchStatement(node) - case tt._throw: return this.parseThrowStatement(node) - case tt._try: return this.parseTryStatement(node) - case tt._const: case tt._var: - kind = kind || this.value - if (!declaration && kind != "var") this.unexpected() - return this.parseVarStatement(node, kind) - case tt._while: return this.parseWhileStatement(node) - case tt._with: return this.parseWithStatement(node) - case tt.braceL: return this.parseBlock() - case tt.semi: return this.parseEmptyStatement(node) - case tt._export: - case tt._import: - if (!this.options.allowImportExportEverywhere) { - if (!topLevel) - this.raise(this.start, "'import' and 'export' may only appear at the top level") - if (!this.inModule) - this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'") - } - return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports) + // RestElement inside of a function parameter must be an identifier + if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected() + else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected() - // If the statement does not start with a statement keyword or a - // brace, it's an ExpressionStatement or LabeledStatement. We - // simply start parsing an expression, and afterwards, if the - // next token is a colon and the expression was a simple - // Identifier node, we switch to interpreting it as a label. - default: - if (this.isAsyncFunction() && declaration) { - this.next() - return this.parseFunctionStatement(node, true) - } + return this.finishNode(node, "RestElement") +} - var maybeName = this.value, expr = this.parseExpression() - if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) - return this.parseLabeledStatement(node, maybeName, expr) - else return this.parseExpressionStatement(node, expr) - } - } +// Parses lvalue (assignable) atom. - pp$1.parseBreakContinueStatement = function(node, keyword) { - var this$1 = this; +pp$2.parseBindingAtom = function() { + if (this.options.ecmaVersion < 6) return this.parseIdent() + switch (this.type) { + case tt.name: + return this.parseIdent() - var isBreak = keyword == "break" + case tt.bracketL: + var node = this.startNode() this.next() - if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null - else if (this.type !== tt.name) this.unexpected() - else { - node.label = this.parseIdent() - this.semicolon() - } + node.elements = this.parseBindingList(tt.bracketR, true, true) + return this.finishNode(node, "ArrayPattern") - // Verify that there is an actual destination to break or - // continue to. - for (var i = 0; i < this.labels.length; ++i) { - var lab = this$1.labels[i] - if (node.label == null || lab.name === node.label.name) { - if (lab.kind != null && (isBreak || lab.kind === "loop")) break - if (node.label && isBreak) break - } - } - if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword) - return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") - } + case tt.braceL: + return this.parseObj(true) - pp$1.parseDebuggerStatement = function(node) { - this.next() - this.semicolon() - return this.finishNode(node, "DebuggerStatement") + default: + this.unexpected() } +} + +pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) { + var this$1 = this; - pp$1.parseDoStatement = function(node) { + var elts = [], first = true + while (!this.eat(close)) { + if (first) first = false + else this$1.expect(tt.comma) + if (allowEmpty && this$1.type === tt.comma) { + elts.push(null) + } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { + break + } else if (this$1.type === tt.ellipsis) { + var rest = this$1.parseRest(allowNonIdent) + this$1.parseBindingListItem(rest) + elts.push(rest) + if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") + this$1.expect(close) + break + } else { + var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc) + this$1.parseBindingListItem(elem) + elts.push(elem) + } + } + return elts +} + +pp$2.parseBindingListItem = function(param) { + return param +} + +// Parses assignment pattern around given atom if possible. + +pp$2.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom() + if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left + var node = this.startNodeAt(startPos, startLoc) + node.left = left + node.right = this.parseMaybeAssign() + return this.finishNode(node, "AssignmentPattern") +} + +// Verify that a node is an lval — something that can be assigned +// to. + +pp$2.checkLVal = function(expr, isBinding, checkClashes) { + var this$1 = this; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + this.raiseRecoverable(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode") + if (checkClashes) { + if (has(checkClashes, expr.name)) + this.raiseRecoverable(expr.start, "Argument name clash") + checkClashes[expr.name] = true + } + break + + case "MemberExpression": + if (isBinding) this.raiseRecoverable(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression") + break + + case "ObjectPattern": + for (var i = 0; i < expr.properties.length; i++) + this$1.checkLVal(expr.properties[i].value, isBinding, checkClashes) + break + + case "ArrayPattern": + for (var i$1 = 0; i$1 < expr.elements.length; i$1++) { + var elem = expr.elements[i$1] + if (elem) this$1.checkLVal(elem, isBinding, checkClashes) + } + break + + case "AssignmentPattern": + this.checkLVal(expr.left, isBinding, checkClashes) + break + + case "RestElement": + this.checkLVal(expr.argument, isBinding, checkClashes) + break + + case "ParenthesizedExpression": + this.checkLVal(expr.expression, isBinding, checkClashes) + break + + default: + this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue") + } +} + +// A recursive descent parser operates by defining functions for all +// syntactic elements, and recursively calling those, each function +// advancing the input stream and returning an AST node. Precedence +// of constructs (for example, the fact that `!x[1]` means `!(x[1])` +// instead of `(!x)[1]` is handled by the fact that the parser +// function that parses unary prefix operators is called first, and +// in turn calls the function that parses `[]` subscripts — that +// way, it'll receive the node for `x[1]` already parsed, and wraps +// *that* in the unary operator node. +// +// Acorn uses an [operator precedence parser][opp] to handle binary +// operator precedence, because it is much more compact than using +// the technique outlined above, which uses different, nesting +// functions to specify precedence, for all of the ten binary +// precedence levels that JavaScript defines. +// +// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + +var pp$3 = Parser.prototype + +// Check if property name clashes with already added. +// Object/class getters and setters are not allowed to clash — +// either with each other or with an init property — and in +// strict mode, init properties are also not allowed to be repeated. + +pp$3.checkPropClash = function(prop, propHash) { + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + return + var key = prop.key; + var name + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property") + propHash.proto = true + } + return + } + name = "$" + name + var other = propHash[name] + if (other) { + var isGetSet = kind !== "init" + if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) + this.raiseRecoverable(key.start, "Redefinition of property") + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + } + } + other[kind] = true +} + +// ### Expression parsing + +// These nest, from the most general expression type at the top to +// 'atomic', nondivisible expression types at the bottom. Most of +// the functions will simply let the function(s) below them parse, +// and, *if* the syntactic construct they handle is present, wrap +// the AST node that the inner parser gave them in another node. + +// Parse a full expression. The optional arguments are used to +// forbid the `in` operator (in for loops initalization expressions) +// and provide reference for storing '=' operator inside shorthand +// property assignment in contexts where both object expression +// and object pattern might appear (so it's possible to raise +// delayed syntax error at correct position). + +pp$3.parseExpression = function(noIn, refDestructuringErrors) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseMaybeAssign(noIn, refDestructuringErrors) + if (this.type === tt.comma) { + var node = this.startNodeAt(startPos, startLoc) + node.expressions = [expr] + while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)) + return this.finishNode(node, "SequenceExpression") + } + return expr +} + +// Parse an assignment expression. This includes applications of +// operators like `+=`. + +pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { + if (this.inGenerator && this.isContextual("yield")) return this.parseYield() + + var ownDestructuringErrors = false + if (!refDestructuringErrors) { + refDestructuringErrors = new DestructuringErrors + ownDestructuringErrors = true + } + var startPos = this.start, startLoc = this.startLoc + if (this.type == tt.parenL || this.type == tt.name) + this.potentialArrowAt = this.start + var left = this.parseMaybeConditional(noIn, refDestructuringErrors) + if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc) + if (this.type.isAssign) { + this.checkPatternErrors(refDestructuringErrors, true) + if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors) + var node = this.startNodeAt(startPos, startLoc) + node.operator = this.value + node.left = this.type === tt.eq ? this.toAssignable(left) : left + refDestructuringErrors.shorthandAssign = 0 // reset because shorthand default was used correctly + this.checkLVal(left) this.next() - this.labels.push(loopLabel) - node.body = this.parseStatement(false) - this.labels.pop() - this.expect(tt._while) - node.test = this.parseParenExpression() - if (this.options.ecmaVersion >= 6) - this.eat(tt.semi) - else - this.semicolon() - return this.finishNode(node, "DoWhileStatement") + node.right = this.parseMaybeAssign(noIn) + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true) } + return left +} - // Disambiguating between a `for` and a `for`/`in` or `for`/`of` - // loop is non-trivial. Basically, we have to parse the init `var` - // statement or expression, disallowing the `in` operator (see - // the second parameter to `parseExpression`), and then check - // whether the next token is `in` or `of`. When there is no init - // part (semicolon immediately after the opening parenthesis), it - // is a regular `for` loop. +// Parse a ternary conditional (`?:`) operator. - pp$1.parseForStatement = function(node) { - this.next() - this.labels.push(loopLabel) - this.expect(tt.parenL) - if (this.type === tt.semi) return this.parseFor(node, null) - var isLet = this.isLet() - if (this.type === tt._var || this.type === tt._const || isLet) { - var init$1 = this.startNode(), kind = isLet ? "let" : this.value +pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseExprOps(noIn, refDestructuringErrors) + if (this.checkExpressionErrors(refDestructuringErrors)) return expr + if (this.eat(tt.question)) { + var node = this.startNodeAt(startPos, startLoc) + node.test = expr + node.consequent = this.parseMaybeAssign() + this.expect(tt.colon) + node.alternate = this.parseMaybeAssign(noIn) + return this.finishNode(node, "ConditionalExpression") + } + return expr +} + +// Start the precedence parser. + +pp$3.parseExprOps = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseMaybeUnary(refDestructuringErrors, false) + if (this.checkExpressionErrors(refDestructuringErrors)) return expr + return this.parseExprOp(expr, startPos, startLoc, -1, noIn) +} + +// Parse binary operators with the operator precedence parsing +// algorithm. `left` is the left-hand side of the operator. +// `minPrec` provides context that allows the function to stop and +// defer further parser to one of its callers when it encounters an +// operator that has a lower precedence than the set it is parsing. + +pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.type.binop + if (prec != null && (!noIn || this.type !== tt._in)) { + if (prec > minPrec) { + var logical = this.type === tt.logicalOR || this.type === tt.logicalAND + var op = this.value this.next() - this.parseVar(init$1, true, kind) - this.finishNode(init$1, "VariableDeclaration") - if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && - !(kind !== "var" && init$1.declarations[0].init)) - return this.parseForIn(node, init$1) - return this.parseFor(node, init$1) + var startPos = this.start, startLoc = this.startLoc + var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn) + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical) + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) + } + } + return left +} + +pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { + var node = this.startNodeAt(startPos, startLoc) + node.left = left + node.operator = op + node.right = right + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") +} + +// Parse unary operators, both prefix and postfix. + +pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc, expr + if (this.inAsync && this.isContextual("await")) { + expr = this.parseAwait(refDestructuringErrors) + sawUnary = true + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === tt.incDec + node.operator = this.value + node.prefix = true + this.next() + node.argument = this.parseMaybeUnary(null, true) + this.checkExpressionErrors(refDestructuringErrors, true) + if (update) this.checkLVal(node.argument) + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + this.raiseRecoverable(node.start, "Deleting local variable in strict mode") + else sawUnary = true + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") + } else { + expr = this.parseExprSubscripts(refDestructuringErrors) + if (this.checkExpressionErrors(refDestructuringErrors)) return expr + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this$1.startNodeAt(startPos, startLoc) + node$1.operator = this$1.value + node$1.prefix = false + node$1.argument = expr + this$1.checkLVal(expr) + this$1.next() + expr = this$1.finishNode(node$1, "UpdateExpression") } - var refDestructuringErrors = new DestructuringErrors - var init = this.parseExpression(true, refDestructuringErrors) - if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { - this.checkPatternErrors(refDestructuringErrors, true) - this.toAssignable(init) - this.checkLVal(init) - return this.parseForIn(node, init) + } + + if (!sawUnary && this.eat(tt.starstar)) + return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) + else + return expr +} + +// Parse call, dot, and `[]`-subscript expressions. + +pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseExprAtom(refDestructuringErrors) + var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")" + if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr + return this.parseSubscripts(expr, startPos, startLoc) +} + +pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { + var this$1 = this; + + for (;;) { + var maybeAsyncArrow = this$1.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && !this$1.canInsertSemicolon() + if (this$1.eat(tt.dot)) { + var node = this$1.startNodeAt(startPos, startLoc) + node.object = base + node.property = this$1.parseIdent(true) + node.computed = false + base = this$1.finishNode(node, "MemberExpression") + } else if (this$1.eat(tt.bracketL)) { + var node$1 = this$1.startNodeAt(startPos, startLoc) + node$1.object = base + node$1.property = this$1.parseExpression() + node$1.computed = true + this$1.expect(tt.bracketR) + base = this$1.finishNode(node$1, "MemberExpression") + } else if (!noCalls && this$1.eat(tt.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos + this$1.yieldPos = 0 + this$1.awaitPos = 0 + var exprList = this$1.parseExprList(tt.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors) + if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(tt.arrow)) { + this$1.checkPatternErrors(refDestructuringErrors, true) + this$1.checkYieldAwaitInDefaultParams() + this$1.yieldPos = oldYieldPos + this$1.awaitPos = oldAwaitPos + return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true) + } + this$1.checkExpressionErrors(refDestructuringErrors, true) + this$1.yieldPos = oldYieldPos || this$1.yieldPos + this$1.awaitPos = oldAwaitPos || this$1.awaitPos + var node$2 = this$1.startNodeAt(startPos, startLoc) + node$2.callee = base + node$2.arguments = exprList + base = this$1.finishNode(node$2, "CallExpression") + } else if (this$1.type === tt.backQuote) { + var node$3 = this$1.startNodeAt(startPos, startLoc) + node$3.tag = base + node$3.quasi = this$1.parseTemplate() + base = this$1.finishNode(node$3, "TaggedTemplateExpression") } else { - this.checkExpressionErrors(refDestructuringErrors, true) + return base } - return this.parseFor(node, init) } +} - pp$1.parseFunctionStatement = function(node, isAsync) { - this.next() - return this.parseFunction(node, true, false, isAsync) - } +// Parse an atomic expression — either a single token that is an +// expression, an expression started by a keyword like `function` or +// `new`, or an expression wrapped in punctuation like `()`, `[]`, +// or `{}`. - pp$1.isFunction = function() { - return this.type === tt._function || this.isAsyncFunction() - } +pp$3.parseExprAtom = function(refDestructuringErrors) { + var node, canBeArrow = this.potentialArrowAt == this.start + switch (this.type) { + case tt._super: + if (!this.inFunction) + this.raise(this.start, "'super' outside of function or class") - pp$1.parseIfStatement = function(node) { + case tt._this: + var type = this.type === tt._this ? "ThisExpression" : "Super" + node = this.startNode() this.next() - node.test = this.parseParenExpression() - // allow function declarations in branches, but only in non-strict mode - node.consequent = this.parseStatement(!this.strict && this.isFunction()) - node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null - return this.finishNode(node, "IfStatement") - } + return this.finishNode(node, type) - pp$1.parseReturnStatement = function(node) { - if (!this.inFunction && !this.options.allowReturnOutsideFunction) - this.raise(this.start, "'return' outside of function") - this.next() + case tt.name: + var startPos = this.start, startLoc = this.startLoc + var id = this.parseIdent(this.type !== tt.name) + if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function)) + return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(tt.arrow)) + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) { + id = this.parseIdent() + if (this.canInsertSemicolon() || !this.eat(tt.arrow)) + this.unexpected() + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) + } + } + return id - // In `return` (and `break`/`continue`), the keywords with - // optional arguments, we eagerly look for a semicolon or the - // possibility to insert one. + case tt.regexp: + var value = this.value + node = this.parseLiteral(value.value) + node.regex = {pattern: value.pattern, flags: value.flags} + return node - if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null - else { node.argument = this.parseExpression(); this.semicolon() } - return this.finishNode(node, "ReturnStatement") - } + case tt.num: case tt.string: + return this.parseLiteral(this.value) - pp$1.parseSwitchStatement = function(node) { - var this$1 = this; + case tt._null: case tt._true: case tt._false: + node = this.startNode() + node.value = this.type === tt._null ? null : this.type === tt._true + node.raw = this.type.keyword + this.next() + return this.finishNode(node, "Literal") + case tt.parenL: + return this.parseParenAndDistinguishExpression(canBeArrow) + + case tt.bracketL: + node = this.startNode() this.next() - node.discriminant = this.parseParenExpression() - node.cases = [] - this.expect(tt.braceL) - this.labels.push(switchLabel) - - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. - - for (var cur, sawDefault = false; this.type != tt.braceR;) { - if (this$1.type === tt._case || this$1.type === tt._default) { - var isCase = this$1.type === tt._case - if (cur) this$1.finishNode(cur, "SwitchCase") - node.cases.push(cur = this$1.startNode()) - cur.consequent = [] - this$1.next() - if (isCase) { - cur.test = this$1.parseExpression() - } else { - if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses") - sawDefault = true - cur.test = null - } - this$1.expect(tt.colon) - } else { - if (!cur) this$1.unexpected() - cur.consequent.push(this$1.parseStatement(true)) - } - } - if (cur) this.finishNode(cur, "SwitchCase") - this.next() // Closing brace - this.labels.pop() - return this.finishNode(node, "SwitchStatement") - } + node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors) + return this.finishNode(node, "ArrayExpression") + + case tt.braceL: + return this.parseObj(false, refDestructuringErrors) - pp$1.parseThrowStatement = function(node) { + case tt._function: + node = this.startNode() this.next() - if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) - this.raise(this.lastTokEnd, "Illegal newline after throw") - node.argument = this.parseExpression() - this.semicolon() - return this.finishNode(node, "ThrowStatement") - } + return this.parseFunction(node, false) - // Reused empty array added for node fields that are always empty. + case tt._class: + return this.parseClass(this.startNode(), false) - var empty = [] + case tt._new: + return this.parseNew() - pp$1.parseTryStatement = function(node) { - this.next() - node.block = this.parseBlock() - node.handler = null - if (this.type === tt._catch) { - var clause = this.startNode() - this.next() - this.expect(tt.parenL) - clause.param = this.parseBindingAtom() - this.checkLVal(clause.param, true) - this.expect(tt.parenR) - clause.body = this.parseBlock() - node.handler = this.finishNode(clause, "CatchClause") - } - node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null - if (!node.handler && !node.finalizer) - this.raise(node.start, "Missing catch or finally clause") - return this.finishNode(node, "TryStatement") - } + case tt.backQuote: + return this.parseTemplate() - pp$1.parseVarStatement = function(node, kind) { - this.next() - this.parseVar(node, false, kind) - this.semicolon() - return this.finishNode(node, "VariableDeclaration") + default: + this.unexpected() } +} - pp$1.parseWhileStatement = function(node) { - this.next() - node.test = this.parseParenExpression() - this.labels.push(loopLabel) - node.body = this.parseStatement(false) - this.labels.pop() - return this.finishNode(node, "WhileStatement") - } +pp$3.parseLiteral = function(value) { + var node = this.startNode() + node.value = value + node.raw = this.input.slice(this.start, this.end) + this.next() + return this.finishNode(node, "Literal") +} - pp$1.parseWithStatement = function(node) { - if (this.strict) this.raise(this.start, "'with' in strict mode") - this.next() - node.object = this.parseParenExpression() - node.body = this.parseStatement(false) - return this.finishNode(node, "WithStatement") - } +pp$3.parseParenExpression = function() { + this.expect(tt.parenL) + var val = this.parseExpression() + this.expect(tt.parenR) + return val +} - pp$1.parseEmptyStatement = function(node) { +pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8 + if (this.options.ecmaVersion >= 6) { this.next() - return this.finishNode(node, "EmptyStatement") - } - pp$1.parseLabeledStatement = function(node, maybeName, expr) { - var this$1 = this; + var innerStartPos = this.start, innerStartLoc = this.startLoc + var exprList = [], first = true, lastIsComma = false + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart + this.yieldPos = 0 + this.awaitPos = 0 + while (this.type !== tt.parenR) { + first ? first = false : this$1.expect(tt.comma) + if (allowTrailingComma && this$1.afterTrailingComma(tt.parenR, true)) { + lastIsComma = true + break + } else if (this$1.type === tt.ellipsis) { + spreadStart = this$1.start + exprList.push(this$1.parseParenItem(this$1.parseRest())) + if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") + break + } else { + if (this$1.type === tt.parenL && !innerParenStart) { + innerParenStart = this$1.start + } + exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)) + } + } + var innerEndPos = this.start, innerEndLoc = this.startLoc + this.expect(tt.parenR) - for (var i = 0; i < this.labels.length; ++i) - if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared") - var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null - for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) { - var label = this$1.labels[i$1] - if (label.statementStart == node.start) { - label.statementStart = this$1.start - label.kind = kind - } else break + if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) { + this.checkPatternErrors(refDestructuringErrors, true) + this.checkYieldAwaitInDefaultParams() + if (innerParenStart) this.unexpected(innerParenStart) + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.parseParenArrowList(startPos, startLoc, exprList) + } + + if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart) + if (spreadStart) this.unexpected(spreadStart) + this.checkExpressionErrors(refDestructuringErrors, true) + this.yieldPos = oldYieldPos || this.yieldPos + this.awaitPos = oldAwaitPos || this.awaitPos + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc) + val.expressions = exprList + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc) + } else { + val = exprList[0] } - this.labels.push({name: maybeName, kind: kind, statementStart: this.start}) - node.body = this.parseStatement(true) - this.labels.pop() - node.label = expr - return this.finishNode(node, "LabeledStatement") + } else { + val = this.parseParenExpression() } - pp$1.parseExpressionStatement = function(node, expr) { - node.expression = expr - this.semicolon() - return this.finishNode(node, "ExpressionStatement") + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc) + par.expression = val + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val } - - // Parse a semicolon-enclosed block of statements, handling `"use - // strict"` declarations when `allowStrict` is true (used for - // function bodies). - - pp$1.parseBlock = function(allowStrict) { - var this$1 = this; - - var node = this.startNode(), first = true, oldStrict - node.body = [] - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - var stmt = this$1.parseStatement(true) - node.body.push(stmt) - if (first && allowStrict && this$1.isUseStrict(stmt)) { - oldStrict = this$1.strict - this$1.setStrict(this$1.strict = true) +} + +pp$3.parseParenItem = function(item) { + return item +} + +pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) +} + +// New's precedence is slightly tricky. It must allow its argument to +// be a `[]` or dot subscript expression, but not a call — at least, +// not without wrapping it in parentheses. Thus, it uses the noCalls +// argument to parseSubscripts to prevent it from consuming the +// argument list. + +var empty$1 = [] + +pp$3.parseNew = function() { + var node = this.startNode() + var meta = this.parseIdent(true) + if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) { + node.meta = meta + node.property = this.parseIdent(true) + if (node.property.name !== "target") + this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target") + if (!this.inFunction) + this.raiseRecoverable(node.start, "new.target can only be used in functions") + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true) + if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false) + else node.arguments = empty$1 + return this.finishNode(node, "NewExpression") +} + +// Parse template expression. + +pp$3.parseTemplateElement = function() { + var elem = this.startNode() + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'), + cooked: this.value + } + this.next() + elem.tail = this.type === tt.backQuote + return this.finishNode(elem, "TemplateElement") +} + +pp$3.parseTemplate = function() { + var this$1 = this; + + var node = this.startNode() + this.next() + node.expressions = [] + var curElt = this.parseTemplateElement() + node.quasis = [curElt] + while (!curElt.tail) { + this$1.expect(tt.dollarBraceL) + node.expressions.push(this$1.parseExpression()) + this$1.expect(tt.braceR) + node.quasis.push(curElt = this$1.parseTemplateElement()) + } + this.next() + return this.finishNode(node, "TemplateLiteral") +} + +// Parse an object literal or binding pattern. + +pp$3.parseObj = function(isPattern, refDestructuringErrors) { + var this$1 = this; + + var node = this.startNode(), first = true, propHash = {} + node.properties = [] + this.next() + while (!this.eat(tt.braceR)) { + if (!first) { + this$1.expect(tt.comma) + if (this$1.afterTrailingComma(tt.braceR)) break + } else first = false + + var prop = this$1.startNode(), isGenerator, isAsync, startPos, startLoc + if (this$1.options.ecmaVersion >= 6) { + prop.method = false + prop.shorthand = false + if (isPattern || refDestructuringErrors) { + startPos = this$1.start + startLoc = this$1.startLoc } - first = false + if (!isPattern) + isGenerator = this$1.eat(tt.star) } - if (oldStrict === false) this.setStrict(false) - return this.finishNode(node, "BlockStatement") - } + this$1.parsePropertyName(prop) + if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && !prop.computed && + prop.key.type === "Identifier" && prop.key.name === "async" && this$1.type !== tt.parenL && + this$1.type !== tt.colon && !this$1.canInsertSemicolon()) { + isAsync = true + this$1.parsePropertyName(prop, refDestructuringErrors) + } else { + isAsync = false + } + this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) + this$1.checkPropClash(prop, propHash) + node.properties.push(this$1.finishNode(prop, "Property")) + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") +} + +pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) { + if ((isGenerator || isAsync) && this.type === tt.colon) + this.unexpected() + + if (this.eat(tt.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors) + prop.kind = "init" + } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) { + if (isPattern) this.unexpected() + prop.kind = "init" + prop.method = true + prop.value = this.parseMethod(isGenerator, isAsync) + } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type != tt.comma && this.type != tt.braceR)) { + if (isGenerator || isAsync || isPattern) this.unexpected() + prop.kind = prop.key.name + this.parsePropertyName(prop) + prop.value = this.parseMethod(false) + var paramCount = prop.kind === "get" ? 0 : 1 + if (prop.value.params.length !== paramCount) { + var start = prop.value.start + if (prop.kind === "get") + this.raiseRecoverable(start, "getter should have no params") + else + this.raiseRecoverable(start, "setter should have exactly one param") + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params") + } + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (this.keywords.test(prop.key.name) || + (this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) || + (this.inGenerator && prop.key.name == "yield") || + (this.inAsync && prop.key.name == "await")) + this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property") + prop.kind = "init" + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) + } else if (this.type === tt.eq && refDestructuringErrors) { + if (!refDestructuringErrors.shorthandAssign) + refDestructuringErrors.shorthandAssign = this.start + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) + } else { + prop.value = prop.key + } + prop.shorthand = true + } else this.unexpected() +} + +pp$3.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(tt.bracketL)) { + prop.computed = true + prop.key = this.parseMaybeAssign() + this.expect(tt.bracketR) + return prop.key + } else { + prop.computed = false + } + } + return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true) +} + +// Initialize empty function node. + +pp$3.initFunction = function(node) { + node.id = null + if (this.options.ecmaVersion >= 6) { + node.generator = false + node.expression = false + } + if (this.options.ecmaVersion >= 8) + node.async = false +} + +// Parse object or class method. + +pp$3.parseMethod = function(isGenerator, isAsync) { + var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos + + this.initFunction(node) + if (this.options.ecmaVersion >= 6) + node.generator = isGenerator + if (this.options.ecmaVersion >= 8) + node.async = !!isAsync + + this.inGenerator = node.generator + this.inAsync = node.async + this.yieldPos = 0 + this.awaitPos = 0 + + this.expect(tt.parenL) + node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8) + this.checkYieldAwaitInDefaultParams() + this.parseFunctionBody(node, false) + + this.inGenerator = oldInGen + this.inAsync = oldInAsync + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.finishNode(node, "FunctionExpression") +} + +// Parse arrow function expression with given parameters. + +pp$3.parseArrowExpression = function(node, params, isAsync) { + var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos + + this.initFunction(node) + if (this.options.ecmaVersion >= 8) + node.async = !!isAsync + + this.inGenerator = false + this.inAsync = node.async + this.yieldPos = 0 + this.awaitPos = 0 + + node.params = this.toAssignableList(params, true) + this.parseFunctionBody(node, true) + + this.inGenerator = oldInGen + this.inAsync = oldInAsync + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.finishNode(node, "ArrowFunctionExpression") +} + +// Parse function body and check parameters. + +pp$3.parseFunctionBody = function(node, isArrowFunction) { + var isExpression = isArrowFunction && this.type !== tt.braceL + + if (isExpression) { + node.body = this.parseMaybeAssign() + node.expression = true + } else { + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldInFunc = this.inFunction, oldLabels = this.labels + this.inFunction = true; this.labels = [] + node.body = this.parseBlock(true) + node.expression = false + this.inFunction = oldInFunc; this.labels = oldLabels + } + + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + var useStrict = (!isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) ? node.body.body[0] : null + if (useStrict && this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)) + this.raiseRecoverable(useStrict.start, "Illegal 'use strict' directive in function with non-simple parameter list") + + if (this.strict || useStrict) { + var oldStrict = this.strict + this.strict = true + if (node.id) + this.checkLVal(node.id, true) + this.checkParams(node) + this.strict = oldStrict + } else if (isArrowFunction || !this.isSimpleParamList(node.params)) { + this.checkParams(node) + } +} + +pp$3.isSimpleParamList = function(params) { + for (var i = 0; i < params.length; i++) + if (params[i].type !== "Identifier") return false + return true +} + +// Checks function params for various disallowed patterns such as using "eval" +// or "arguments" and duplicate parameters. + +pp$3.checkParams = function(node) { + var this$1 = this; + + var nameHash = {} + for (var i = 0; i < node.params.length; i++) this$1.checkLVal(node.params[i], true, nameHash) +} + +// Parses a comma-separated list of expressions, and returns them as +// an array. `close` is the token type that ends the list, and +// `allowEmpty` can be turned on to allow subsequent commas with +// nothing in between them to be parsed as `null` (which is needed +// for array literals). + +pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var this$1 = this; + + var elts = [], first = true + while (!this.eat(close)) { + if (!first) { + this$1.expect(tt.comma) + if (allowTrailingComma && this$1.afterTrailingComma(close)) break + } else first = false + + var elt + if (allowEmpty && this$1.type === tt.comma) + elt = null + else if (this$1.type === tt.ellipsis) { + elt = this$1.parseSpread(refDestructuringErrors) + if (this$1.type === tt.comma && refDestructuringErrors && !refDestructuringErrors.trailingComma) { + refDestructuringErrors.trailingComma = this$1.start + } + } else + elt = this$1.parseMaybeAssign(false, refDestructuringErrors) + elts.push(elt) + } + return elts +} + +// Parse the next token as an identifier. If `liberal` is true (used +// when parsing properties), it will also convert keywords into +// identifiers. + +pp$3.parseIdent = function(liberal) { + var node = this.startNode() + if (liberal && this.options.allowReserved == "never") liberal = false + if (this.type === tt.name) { + if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && + (this.options.ecmaVersion >= 6 || + this.input.slice(this.start, this.end).indexOf("\\") == -1)) + this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved") + if (this.inGenerator && this.value === "yield") + this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator") + if (this.inAsync && this.value === "await") + this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function") + node.name = this.value + } else if (liberal && this.type.keyword) { + node.name = this.type.keyword + } else { + this.unexpected() + } + this.next() + return this.finishNode(node, "Identifier") +} + +// Parses yield expression inside generator. + +pp$3.parseYield = function() { + if (!this.yieldPos) this.yieldPos = this.start + + var node = this.startNode() + this.next() + if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) { + node.delegate = false + node.argument = null + } else { + node.delegate = this.eat(tt.star) + node.argument = this.parseMaybeAssign() + } + return this.finishNode(node, "YieldExpression") +} + +pp$3.parseAwait = function() { + if (!this.awaitPos) this.awaitPos = this.start + + var node = this.startNode() + this.next() + node.argument = this.parseMaybeUnary(null, true) + return this.finishNode(node, "AwaitExpression") +} + +var pp$4 = Parser.prototype + +// This function is used to raise exceptions on parse errors. It +// takes an offset integer (into the current `input`) to indicate +// the location of the error, attaches the position to the end +// of the error message, and then raises a `SyntaxError` with that +// message. + +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos) + message += " (" + loc.line + ":" + loc.column + ")" + var err = new SyntaxError(message) + err.pos = pos; err.loc = loc; err.raisedAt = this.pos + throw err +} + +pp$4.raiseRecoverable = pp$4.raise + +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } +} + +var Node = function Node(parser, pos, loc) { + this.type = "" + this.start = pos + this.end = 0 + if (parser.options.locations) + this.loc = new SourceLocation(parser, loc) + if (parser.options.directSourceFile) + this.sourceFile = parser.options.directSourceFile + if (parser.options.ranges) + this.range = [pos, 0] +}; + +// Start an AST node, attaching a start offset. + +var pp$5 = Parser.prototype + +pp$5.startNode = function() { + return new Node(this, this.start, this.startLoc) +} + +pp$5.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) +} + +// Finish an AST node, adding `type` and `end` properties. + +function finishNodeAt(node, type, pos, loc) { + node.type = type + node.end = pos + if (this.options.locations) + node.loc.end = loc + if (this.options.ranges) + node.range[1] = pos + return node +} + +pp$5.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) +} + +// Finish node at given position + +pp$5.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) +} + +// The algorithm used to determine whether a regexp can appear at a +// given point in the program is loosely based on sweet.js' approach. +// See https://github.com/mozilla/sweet.js/wiki/design + +var TokContext = function TokContext(token, isExpr, preserveSpace, override) { + this.token = token + this.isExpr = !!isExpr + this.preserveSpace = !!preserveSpace + this.override = override +}; + +var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", true), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }), + f_expr: new TokContext("function", true) +} + +var pp$6 = Parser.prototype + +pp$6.initialContext = function() { + return [types.b_stat] +} + +pp$6.braceIsBlock = function(prevType) { + if (prevType === tt.colon) { + var parent = this.curContext() + if (parent === types.b_stat || parent === types.b_expr) + return !parent.isExpr + } + if (prevType === tt._return) + return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) + return true + if (prevType == tt.braceL) + return this.curContext() === types.b_stat + return !this.exprAllowed +} + +pp$6.updateContext = function(prevType) { + var update, type = this.type + if (type.keyword && prevType == tt.dot) + this.exprAllowed = false + else if (update = type.updateContext) + update.call(this, prevType) + else + this.exprAllowed = type.beforeExpr +} - // Parse a regular `for` loop. The disambiguation code in - // `parseStatement` will already have parsed the init statement or - // expression. +// Token-specific context update code - pp$1.parseFor = function(node, init) { - node.init = init - this.expect(tt.semi) - node.test = this.type === tt.semi ? null : this.parseExpression() - this.expect(tt.semi) - node.update = this.type === tt.parenR ? null : this.parseExpression() - this.expect(tt.parenR) - node.body = this.parseStatement(false) - this.labels.pop() - return this.finishNode(node, "ForStatement") +tt.parenR.updateContext = tt.braceR.updateContext = function() { + if (this.context.length == 1) { + this.exprAllowed = true + return } - - // Parse a `for`/`in` and `for`/`of` loop, which are almost - // same from parser's perspective. - - pp$1.parseForIn = function(node, init) { - var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement" - this.next() - node.left = init - node.right = this.parseExpression() - this.expect(tt.parenR) - node.body = this.parseStatement(false) - this.labels.pop() - return this.finishNode(node, type) + var out = this.context.pop() + if (out === types.b_stat && this.curContext() === types.f_expr) { + this.context.pop() + this.exprAllowed = false + } else if (out === types.b_tmpl) { + this.exprAllowed = true + } else { + this.exprAllowed = !out.isExpr + } +} + +tt.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr) + this.exprAllowed = true +} + +tt.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl) + this.exprAllowed = true +} + +tt.parenL.updateContext = function(prevType) { + var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while + this.context.push(statementParens ? types.p_stat : types.p_expr) + this.exprAllowed = true +} + +tt.incDec.updateContext = function() { + // tokExprAllowed stays unchanged +} + +tt._function.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else && + !((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat)) + this.context.push(types.f_expr) + this.exprAllowed = false +} + +tt.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) + this.context.pop() + else + this.context.push(types.q_tmpl) + this.exprAllowed = false +} + +// Object type used to represent tokens. Note that normally, tokens +// simply exist as properties on the parser object. This is only +// used for the onToken callback and the external tokenizer. + +var Token = function Token(p) { + this.type = p.type + this.value = p.value + this.start = p.start + this.end = p.end + if (p.options.locations) + this.loc = new SourceLocation(p, p.startLoc, p.endLoc) + if (p.options.ranges) + this.range = [p.start, p.end] +}; + +// ## Tokenizer + +var pp$7 = Parser.prototype + +// Are we running under Rhino? +var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]" + +// Move to the next token + +pp$7.next = function() { + if (this.options.onToken) + this.options.onToken(new Token(this)) + + this.lastTokEnd = this.end + this.lastTokStart = this.start + this.lastTokEndLoc = this.endLoc + this.lastTokStartLoc = this.startLoc + this.nextToken() +} + +pp$7.getToken = function() { + this.next() + return new Token(this) +} + +// If we're in an ES6 environment, make parsers iterable +if (typeof Symbol !== "undefined") + pp$7[Symbol.iterator] = function () { + var self = this + return {next: function () { + var token = self.getToken() + return { + done: token.type === tt.eof, + value: token + } + }} } - // Parse a list of variable declarations. +// Toggle strict mode. Re-reads the next number or string to please +// pedantic tests (`"use strict"; 010;` should fail). - pp$1.parseVar = function(node, isFor, kind) { - var this$1 = this; +pp$7.setStrict = function(strict) { + var this$1 = this; - node.declarations = [] - node.kind = kind - for (;;) { - var decl = this$1.startNode() - this$1.parseVarId(decl) - if (this$1.eat(tt.eq)) { - decl.init = this$1.parseMaybeAssign(isFor) - } else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { - this$1.unexpected() - } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) { - this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value") - } else { - decl.init = null - } - node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")) - if (!this$1.eat(tt.comma)) break + this.strict = strict + if (this.type !== tt.num && this.type !== tt.string) return + this.pos = this.start + if (this.options.locations) { + while (this.pos < this.lineStart) { + this$1.lineStart = this$1.input.lastIndexOf("\n", this$1.lineStart - 2) + 1 + --this$1.curLine } - return node - } - - pp$1.parseVarId = function(decl) { - decl.id = this.parseBindingAtom() - this.checkLVal(decl.id, true) } + this.nextToken() +} - // Parse a function declaration or literal (depending on the - // `isStatement` parameter). +pp$7.curContext = function() { + return this.context[this.context.length - 1] +} - pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) { - this.initFunction(node) - if (this.options.ecmaVersion >= 6 && !isAsync) - node.generator = this.eat(tt.star) - if (this.options.ecmaVersion >= 8) - node.async = !!isAsync +// Read a single token, updating the parser object's token-related +// properties. - if (isStatement) - node.id = this.parseIdent() +pp$7.nextToken = function() { + var curContext = this.curContext() + if (!curContext || !curContext.preserveSpace) this.skipSpace() - var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos - this.inGenerator = node.generator - this.inAsync = node.async - this.yieldPos = 0 - this.awaitPos = 0 + this.start = this.pos + if (this.options.locations) this.startLoc = this.curPosition() + if (this.pos >= this.input.length) return this.finishToken(tt.eof) - if (!isStatement && this.type === tt.name) - node.id = this.parseIdent() - this.parseFunctionParams(node) - this.parseFunctionBody(node, allowExpressionBody) + if (curContext.override) return curContext.override(this) + else this.readToken(this.fullCharCodeAtPos()) +} - this.inGenerator = oldInGen - this.inAsync = oldInAsync - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") - } +pp$7.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + return this.readWord() - pp$1.parseFunctionParams = function(node) { - this.expect(tt.parenL) - node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8, true) - this.checkYieldAwaitInDefaultParams() - } + return this.getTokenFromCode(code) +} - // Parse a class declaration or literal (depending on the - // `isStatement` parameter). +pp$7.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos) + if (code <= 0xd7ff || code >= 0xe000) return code + var next = this.input.charCodeAt(this.pos + 1) + return (code << 10) + next - 0x35fdc00 +} - pp$1.parseClass = function(node, isStatement) { - var this$1 = this; +pp$7.skipBlockComment = function() { + var this$1 = this; - this.next() - this.parseClassId(node, isStatement) - this.parseClassSuper(node) - var classBody = this.startNode() - var hadConstructor = false - classBody.body = [] - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - if (this$1.eat(tt.semi)) continue - var method = this$1.startNode() - var isGenerator = this$1.eat(tt.star) - var isAsync = false - var isMaybeStatic = this$1.type === tt.name && this$1.value === "static" - this$1.parsePropertyName(method) - method.static = isMaybeStatic && this$1.type !== tt.parenL - if (method.static) { - if (isGenerator) this$1.unexpected() - isGenerator = this$1.eat(tt.star) - this$1.parsePropertyName(method) - } - if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed && - method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== tt.parenL && - !this$1.canInsertSemicolon()) { - isAsync = true - this$1.parsePropertyName(method) - } - method.kind = "method" - var isGetSet = false - if (!method.computed) { - var key = method.key; - if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) { - isGetSet = true - method.kind = key.name - key = this$1.parsePropertyName(method) - } - if (!method.static && (key.type === "Identifier" && key.name === "constructor" || - key.type === "Literal" && key.value === "constructor")) { - if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class") - if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier") - if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator") - if (isAsync) this$1.raise(key.start, "Constructor can't be an async method") - method.kind = "constructor" - hadConstructor = true - } - } - this$1.parseClassMethod(classBody, method, isGenerator, isAsync) - if (isGetSet) { - var paramCount = method.kind === "get" ? 0 : 1 - if (method.value.params.length !== paramCount) { - var start = method.value.start - if (method.kind === "get") - this$1.raiseRecoverable(start, "getter should have no params") - else - this$1.raiseRecoverable(start, "setter should have exactly one param") - } else { - if (method.kind === "set" && method.value.params[0].type === "RestElement") - this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params") - } - } + var startLoc = this.options.onComment && this.curPosition() + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2) + if (end === -1) this.raise(this.pos - 2, "Unterminated comment") + this.pos = end + 2 + if (this.options.locations) { + lineBreakG.lastIndex = start + var match + while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { + ++this$1.curLine + this$1.lineStart = match.index + match[0].length } - node.body = this.finishNode(classBody, "ClassBody") - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") } + if (this.options.onComment) + this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()) +} - pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) { - method.value = this.parseMethod(isGenerator, isAsync) - classBody.body.push(this.finishNode(method, "MethodDefinition")) - } +pp$7.skipLineComment = function(startSkip) { + var this$1 = this; - pp$1.parseClassId = function(node, isStatement) { - node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null + var start = this.pos + var startLoc = this.options.onComment && this.curPosition() + var ch = this.input.charCodeAt(this.pos+=startSkip) + while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { + ++this$1.pos + ch = this$1.input.charCodeAt(this$1.pos) } + if (this.options.onComment) + this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()) +} - pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null - } +// Called at the start of the parse and after every token. Skips +// whitespace and comments, and. - // Parses module export declaration. +pp$7.skipSpace = function() { + var this$1 = this; - pp$1.parseExport = function(node, exports) { - var this$1 = this; - - this.next() - // export * from '...' - if (this.eat(tt.star)) { - this.expectContextual("from") - node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() - this.semicolon() - return this.finishNode(node, "ExportAllDeclaration") - } - if (this.eat(tt._default)) { // export default ... - this.checkExport(exports, "default", this.lastTokStart) - var parens = this.type == tt.parenL - var expr = this.parseMaybeAssign() - var needsSemi = true - if (!parens && (expr.type == "FunctionExpression" || - expr.type == "ClassExpression")) { - needsSemi = false - if (expr.id) { - expr.type = expr.type == "FunctionExpression" - ? "FunctionDeclaration" - : "ClassDeclaration" - } - } - node.declaration = expr - if (needsSemi) this.semicolon() - return this.finishNode(node, "ExportDefaultDeclaration") - } - // export var|const|let|function|class ... - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(true) - if (node.declaration.type === "VariableDeclaration") - this.checkVariableExport(exports, node.declaration.declarations) - else - this.checkExport(exports, node.declaration.id.name, node.declaration.id.start) - node.specifiers = [] - node.source = null - } else { // export { x, y as z } [from '...'] - node.declaration = null - node.specifiers = this.parseExportSpecifiers(exports) - if (this.eatContextual("from")) { - node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() - } else { - // check for keywords used as local names - for (var i = 0; i < node.specifiers.length; i++) { - if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) { - this$1.unexpected(node.specifiers[i].local.start) - } - } - - node.source = null - } - this.semicolon() - } - return this.finishNode(node, "ExportNamedDeclaration") - } - - pp$1.checkExport = function(exports, name, pos) { - if (!exports) return - if (Object.prototype.hasOwnProperty.call(exports, name)) - this.raiseRecoverable(pos, "Duplicate export '" + name + "'") - exports[name] = true - } - - pp$1.checkPatternExport = function(exports, pat) { - var this$1 = this; - - var type = pat.type - if (type == "Identifier") - this.checkExport(exports, pat.name, pat.start) - else if (type == "ObjectPattern") - for (var i = 0; i < pat.properties.length; ++i) - this$1.checkPatternExport(exports, pat.properties[i].value) - else if (type == "ArrayPattern") - for (var i$1 = 0; i$1 < pat.elements.length; ++i$1) { - var elt = pat.elements[i$1] - if (elt) this$1.checkPatternExport(exports, elt) - } - else if (type == "AssignmentPattern") - this.checkPatternExport(exports, pat.left) - else if (type == "ParenthesizedExpression") - this.checkPatternExport(exports, pat.expression) - } - - pp$1.checkVariableExport = function(exports, decls) { - var this$1 = this; - - if (!exports) return - for (var i = 0; i < decls.length; i++) - this$1.checkPatternExport(exports, decls[i].id) - } - - pp$1.shouldParseExportStatement = function() { - return this.type.keyword || this.isLet() || this.isAsyncFunction() - } - - // Parses a comma-separated list of module exports. - - pp$1.parseExportSpecifiers = function(exports) { - var this$1 = this; - - var nodes = [], first = true - // export { x, y as z } [from '...'] - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - if (!first) { - this$1.expect(tt.comma) - if (this$1.afterTrailingComma(tt.braceR)) break - } else first = false - - var node = this$1.startNode() - node.local = this$1.parseIdent(this$1.type === tt._default) - node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local - this$1.checkExport(exports, node.exported.name, node.exported.start) - nodes.push(this$1.finishNode(node, "ExportSpecifier")) - } - return nodes - } - - // Parses import declaration. - - pp$1.parseImport = function(node) { - this.next() - // import '...' - if (this.type === tt.string) { - node.specifiers = empty - node.source = this.parseExprAtom() - } else { - node.specifiers = this.parseImportSpecifiers() - this.expectContextual("from") - node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() - } - this.semicolon() - return this.finishNode(node, "ImportDeclaration") - } - - // Parses a comma-separated list of module imports. - - pp$1.parseImportSpecifiers = function() { - var this$1 = this; - - var nodes = [], first = true - if (this.type === tt.name) { - // import defaultObj, { x, y as z } from '...' - var node = this.startNode() - node.local = this.parseIdent() - this.checkLVal(node.local, true) - nodes.push(this.finishNode(node, "ImportDefaultSpecifier")) - if (!this.eat(tt.comma)) return nodes - } - if (this.type === tt.star) { - var node$1 = this.startNode() - this.next() - this.expectContextual("as") - node$1.local = this.parseIdent() - this.checkLVal(node$1.local, true) - nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")) - return nodes - } - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - if (!first) { - this$1.expect(tt.comma) - if (this$1.afterTrailingComma(tt.braceR)) break - } else first = false - - var node$2 = this$1.startNode() - node$2.imported = this$1.parseIdent(true) - if (this$1.eatContextual("as")) { - node$2.local = this$1.parseIdent() - } else { - node$2.local = node$2.imported - if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start) - if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raiseRecoverable(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved") - } - this$1.checkLVal(node$2.local, true) - nodes.push(this$1.finishNode(node$2, "ImportSpecifier")) - } - return nodes - } - - var pp$2 = Parser.prototype - - // Convert existing expression atom to assignable pattern - // if possible. - - pp$2.toAssignable = function(node, isBinding) { - var this$1 = this; - - if (this.options.ecmaVersion >= 6 && node) { - switch (node.type) { - case "Identifier": - if (this.inAsync && node.name === "await") - this.raise(node.start, "Can not use 'await' as identifier inside an async function") - break - - case "ObjectPattern": - case "ArrayPattern": - break - - case "ObjectExpression": - node.type = "ObjectPattern" - for (var i = 0; i < node.properties.length; i++) { - var prop = node.properties[i] - if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter") - this$1.toAssignable(prop.value, isBinding) - } - break - - case "ArrayExpression": - node.type = "ArrayPattern" - this.toAssignableList(node.elements, isBinding) - break - - case "AssignmentExpression": - if (node.operator === "=") { - node.type = "AssignmentPattern" - delete node.operator - this.toAssignable(node.left, isBinding) - // falls through to AssignmentPattern - } else { - this.raise(node.left.end, "Only '=' operator can be used for specifying default value.") - break - } - - case "AssignmentPattern": - break - - case "ParenthesizedExpression": - node.expression = this.toAssignable(node.expression, isBinding) - break - - case "MemberExpression": - if (!isBinding) break - - default: - this.raise(node.start, "Assigning to rvalue") - } - } - return node - } - - // Convert list of expression atoms to binding list. - - pp$2.toAssignableList = function(exprList, isBinding) { - var this$1 = this; - - var end = exprList.length - if (end) { - var last = exprList[end - 1] - if (last && last.type == "RestElement") { - --end - } else if (last && last.type == "SpreadElement") { - last.type = "RestElement" - var arg = last.argument - this.toAssignable(arg, isBinding) - if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") - this.unexpected(arg.start) - --end - } - - if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") - this.unexpected(last.argument.start) - } - for (var i = 0; i < end; i++) { - var elt = exprList[i] - if (elt) this$1.toAssignable(elt, isBinding) - } - return exprList - } - - // Parses spread element. - - pp$2.parseSpread = function(refDestructuringErrors) { - var node = this.startNode() - this.next() - node.argument = this.parseMaybeAssign(false, refDestructuringErrors) - return this.finishNode(node, "SpreadElement") - } - - pp$2.parseRest = function(allowNonIdent) { - var node = this.startNode() - this.next() - - // RestElement inside of a function parameter must be an identifier - if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected() - else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected() - - return this.finishNode(node, "RestElement") - } - - // Parses lvalue (assignable) atom. - - pp$2.parseBindingAtom = function() { - if (this.options.ecmaVersion < 6) return this.parseIdent() - switch (this.type) { - case tt.name: - return this.parseIdent() - - case tt.bracketL: - var node = this.startNode() - this.next() - node.elements = this.parseBindingList(tt.bracketR, true, true) - return this.finishNode(node, "ArrayPattern") - - case tt.braceL: - return this.parseObj(true) - - default: - this.unexpected() - } - } - - pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) { - var this$1 = this; - - var elts = [], first = true - while (!this.eat(close)) { - if (first) first = false - else this$1.expect(tt.comma) - if (allowEmpty && this$1.type === tt.comma) { - elts.push(null) - } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { - break - } else if (this$1.type === tt.ellipsis) { - var rest = this$1.parseRest(allowNonIdent) - this$1.parseBindingListItem(rest) - elts.push(rest) - if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") - this$1.expect(close) - break - } else { - var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc) - this$1.parseBindingListItem(elem) - elts.push(elem) - } - } - return elts - } - - pp$2.parseBindingListItem = function(param) { - return param - } - - // Parses assignment pattern around given atom if possible. - - pp$2.parseMaybeDefault = function(startPos, startLoc, left) { - left = left || this.parseBindingAtom() - if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left - var node = this.startNodeAt(startPos, startLoc) - node.left = left - node.right = this.parseMaybeAssign() - return this.finishNode(node, "AssignmentPattern") - } - - // Verify that a node is an lval — something that can be assigned - // to. - - pp$2.checkLVal = function(expr, isBinding, checkClashes) { - var this$1 = this; - - switch (expr.type) { - case "Identifier": - if (this.strict && this.reservedWordsStrictBind.test(expr.name)) - this.raiseRecoverable(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode") - if (checkClashes) { - if (has(checkClashes, expr.name)) - this.raiseRecoverable(expr.start, "Argument name clash") - checkClashes[expr.name] = true - } - break - - case "MemberExpression": - if (isBinding) this.raiseRecoverable(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression") - break - - case "ObjectPattern": - for (var i = 0; i < expr.properties.length; i++) - this$1.checkLVal(expr.properties[i].value, isBinding, checkClashes) - break - - case "ArrayPattern": - for (var i$1 = 0; i$1 < expr.elements.length; i$1++) { - var elem = expr.elements[i$1] - if (elem) this$1.checkLVal(elem, isBinding, checkClashes) - } - break - - case "AssignmentPattern": - this.checkLVal(expr.left, isBinding, checkClashes) - break - - case "RestElement": - this.checkLVal(expr.argument, isBinding, checkClashes) - break - - case "ParenthesizedExpression": - this.checkLVal(expr.expression, isBinding, checkClashes) - break - - default: - this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue") - } - } - - var pp$3 = Parser.prototype - - // Check if property name clashes with already added. - // Object/class getters and setters are not allowed to clash — - // either with each other or with an init property — and in - // strict mode, init properties are also not allowed to be repeated. - - pp$3.checkPropClash = function(prop, propHash) { - if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) - return - var key = prop.key; - var name - switch (key.type) { - case "Identifier": name = key.name; break - case "Literal": name = String(key.value); break - default: return - } - var kind = prop.kind; - if (this.options.ecmaVersion >= 6) { - if (name === "__proto__" && kind === "init") { - if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property") - propHash.proto = true - } - return - } - name = "$" + name - var other = propHash[name] - if (other) { - var isGetSet = kind !== "init" - if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) - this.raiseRecoverable(key.start, "Redefinition of property") - } else { - other = propHash[name] = { - init: false, - get: false, - set: false - } - } - other[kind] = true - } - - // ### Expression parsing - - // These nest, from the most general expression type at the top to - // 'atomic', nondivisible expression types at the bottom. Most of - // the functions will simply let the function(s) below them parse, - // and, *if* the syntactic construct they handle is present, wrap - // the AST node that the inner parser gave them in another node. - - // Parse a full expression. The optional arguments are used to - // forbid the `in` operator (in for loops initalization expressions) - // and provide reference for storing '=' operator inside shorthand - // property assignment in contexts where both object expression - // and object pattern might appear (so it's possible to raise - // delayed syntax error at correct position). - - pp$3.parseExpression = function(noIn, refDestructuringErrors) { - var this$1 = this; - - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseMaybeAssign(noIn, refDestructuringErrors) - if (this.type === tt.comma) { - var node = this.startNodeAt(startPos, startLoc) - node.expressions = [expr] - while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)) - return this.finishNode(node, "SequenceExpression") - } - return expr - } - - // Parse an assignment expression. This includes applications of - // operators like `+=`. - - pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { - if (this.inGenerator && this.isContextual("yield")) return this.parseYield() - - var ownDestructuringErrors = false - if (!refDestructuringErrors) { - refDestructuringErrors = new DestructuringErrors - ownDestructuringErrors = true - } - var startPos = this.start, startLoc = this.startLoc - if (this.type == tt.parenL || this.type == tt.name) - this.potentialArrowAt = this.start - var left = this.parseMaybeConditional(noIn, refDestructuringErrors) - if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc) - if (this.type.isAssign) { - this.checkPatternErrors(refDestructuringErrors, true) - if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors) - var node = this.startNodeAt(startPos, startLoc) - node.operator = this.value - node.left = this.type === tt.eq ? this.toAssignable(left) : left - refDestructuringErrors.shorthandAssign = 0 // reset because shorthand default was used correctly - this.checkLVal(left) - this.next() - node.right = this.parseMaybeAssign(noIn) - return this.finishNode(node, "AssignmentExpression") - } else { - if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true) - } - return left - } - - // Parse a ternary conditional (`?:`) operator. - - pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseExprOps(noIn, refDestructuringErrors) - if (this.checkExpressionErrors(refDestructuringErrors)) return expr - if (this.eat(tt.question)) { - var node = this.startNodeAt(startPos, startLoc) - node.test = expr - node.consequent = this.parseMaybeAssign() - this.expect(tt.colon) - node.alternate = this.parseMaybeAssign(noIn) - return this.finishNode(node, "ConditionalExpression") - } - return expr - } - - // Start the precedence parser. - - pp$3.parseExprOps = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseMaybeUnary(refDestructuringErrors, false) - if (this.checkExpressionErrors(refDestructuringErrors)) return expr - return this.parseExprOp(expr, startPos, startLoc, -1, noIn) - } - - // Parse binary operators with the operator precedence parsing - // algorithm. `left` is the left-hand side of the operator. - // `minPrec` provides context that allows the function to stop and - // defer further parser to one of its callers when it encounters an - // operator that has a lower precedence than the set it is parsing. - - pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { - var prec = this.type.binop - if (prec != null && (!noIn || this.type !== tt._in)) { - if (prec > minPrec) { - var logical = this.type === tt.logicalOR || this.type === tt.logicalAND - var op = this.value - this.next() - var startPos = this.start, startLoc = this.startLoc - var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn) - var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical) - return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) - } - } - return left - } - - pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { - var node = this.startNodeAt(startPos, startLoc) - node.left = left - node.operator = op - node.right = right - return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") - } - - // Parse unary operators, both prefix and postfix. - - pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { - var this$1 = this; - - var startPos = this.start, startLoc = this.startLoc, expr - if (this.inAsync && this.isContextual("await")) { - expr = this.parseAwait(refDestructuringErrors) - sawUnary = true - } else if (this.type.prefix) { - var node = this.startNode(), update = this.type === tt.incDec - node.operator = this.value - node.prefix = true - this.next() - node.argument = this.parseMaybeUnary(null, true) - this.checkExpressionErrors(refDestructuringErrors, true) - if (update) this.checkLVal(node.argument) - else if (this.strict && node.operator === "delete" && - node.argument.type === "Identifier") - this.raiseRecoverable(node.start, "Deleting local variable in strict mode") - else sawUnary = true - expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") - } else { - expr = this.parseExprSubscripts(refDestructuringErrors) - if (this.checkExpressionErrors(refDestructuringErrors)) return expr - while (this.type.postfix && !this.canInsertSemicolon()) { - var node$1 = this$1.startNodeAt(startPos, startLoc) - node$1.operator = this$1.value - node$1.prefix = false - node$1.argument = expr - this$1.checkLVal(expr) - this$1.next() - expr = this$1.finishNode(node$1, "UpdateExpression") - } - } - - if (!sawUnary && this.eat(tt.starstar)) - return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) - else - return expr - } - - // Parse call, dot, and `[]`-subscript expressions. - - pp$3.parseExprSubscripts = function(refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseExprAtom(refDestructuringErrors) - var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")" - if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr - return this.parseSubscripts(expr, startPos, startLoc) - } - - pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { - var this$1 = this; - - for (;;) { - var maybeAsyncArrow = this$1.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && !this$1.canInsertSemicolon() - if (this$1.eat(tt.dot)) { - var node = this$1.startNodeAt(startPos, startLoc) - node.object = base - node.property = this$1.parseIdent(true) - node.computed = false - base = this$1.finishNode(node, "MemberExpression") - } else if (this$1.eat(tt.bracketL)) { - var node$1 = this$1.startNodeAt(startPos, startLoc) - node$1.object = base - node$1.property = this$1.parseExpression() - node$1.computed = true - this$1.expect(tt.bracketR) - base = this$1.finishNode(node$1, "MemberExpression") - } else if (!noCalls && this$1.eat(tt.parenL)) { - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos - this$1.yieldPos = 0 - this$1.awaitPos = 0 - var exprList = this$1.parseExprList(tt.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors) - if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(tt.arrow)) { - this$1.checkPatternErrors(refDestructuringErrors, true) - this$1.checkYieldAwaitInDefaultParams() - this$1.yieldPos = oldYieldPos - this$1.awaitPos = oldAwaitPos - return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true) - } - this$1.checkExpressionErrors(refDestructuringErrors, true) - this$1.yieldPos = oldYieldPos || this$1.yieldPos - this$1.awaitPos = oldAwaitPos || this$1.awaitPos - var node$2 = this$1.startNodeAt(startPos, startLoc) - node$2.callee = base - node$2.arguments = exprList - base = this$1.finishNode(node$2, "CallExpression") - } else if (this$1.type === tt.backQuote) { - var node$3 = this$1.startNodeAt(startPos, startLoc) - node$3.tag = base - node$3.quasi = this$1.parseTemplate() - base = this$1.finishNode(node$3, "TaggedTemplateExpression") - } else { - return base - } - } - } - - // Parse an atomic expression — either a single token that is an - // expression, an expression started by a keyword like `function` or - // `new`, or an expression wrapped in punctuation like `()`, `[]`, - // or `{}`. - - pp$3.parseExprAtom = function(refDestructuringErrors) { - var node, canBeArrow = this.potentialArrowAt == this.start - switch (this.type) { - case tt._super: - if (!this.inFunction) - this.raise(this.start, "'super' outside of function or class") - - case tt._this: - var type = this.type === tt._this ? "ThisExpression" : "Super" - node = this.startNode() - this.next() - return this.finishNode(node, type) - - case tt.name: - var startPos = this.start, startLoc = this.startLoc - var id = this.parseIdent(this.type !== tt.name) - if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function)) - return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) - if (canBeArrow && !this.canInsertSemicolon()) { - if (this.eat(tt.arrow)) - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) - if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) { - id = this.parseIdent() - if (this.canInsertSemicolon() || !this.eat(tt.arrow)) - this.unexpected() - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) - } - } - return id - - case tt.regexp: - var value = this.value - node = this.parseLiteral(value.value) - node.regex = {pattern: value.pattern, flags: value.flags} - return node - - case tt.num: case tt.string: - return this.parseLiteral(this.value) - - case tt._null: case tt._true: case tt._false: - node = this.startNode() - node.value = this.type === tt._null ? null : this.type === tt._true - node.raw = this.type.keyword - this.next() - return this.finishNode(node, "Literal") - - case tt.parenL: - return this.parseParenAndDistinguishExpression(canBeArrow) - - case tt.bracketL: - node = this.startNode() - this.next() - node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors) - return this.finishNode(node, "ArrayExpression") - - case tt.braceL: - return this.parseObj(false, refDestructuringErrors) - - case tt._function: - node = this.startNode() - this.next() - return this.parseFunction(node, false) - - case tt._class: - return this.parseClass(this.startNode(), false) - - case tt._new: - return this.parseNew() - - case tt.backQuote: - return this.parseTemplate() - - default: - this.unexpected() - } - } - - pp$3.parseLiteral = function(value) { - var node = this.startNode() - node.value = value - node.raw = this.input.slice(this.start, this.end) - this.next() - return this.finishNode(node, "Literal") - } - - pp$3.parseParenExpression = function() { - this.expect(tt.parenL) - var val = this.parseExpression() - this.expect(tt.parenR) - return val - } - - pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { - var this$1 = this; - - var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8 - if (this.options.ecmaVersion >= 6) { - this.next() - - var innerStartPos = this.start, innerStartLoc = this.startLoc - var exprList = [], first = true, lastIsComma = false - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart - this.yieldPos = 0 - this.awaitPos = 0 - while (this.type !== tt.parenR) { - first ? first = false : this$1.expect(tt.comma) - if (allowTrailingComma && this$1.afterTrailingComma(tt.parenR, true)) { - lastIsComma = true - break - } else if (this$1.type === tt.ellipsis) { - spreadStart = this$1.start - exprList.push(this$1.parseParenItem(this$1.parseRest())) - if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") - break - } else { - if (this$1.type === tt.parenL && !innerParenStart) { - innerParenStart = this$1.start - } - exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)) - } - } - var innerEndPos = this.start, innerEndLoc = this.startLoc - this.expect(tt.parenR) - - if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) { - this.checkPatternErrors(refDestructuringErrors, true) - this.checkYieldAwaitInDefaultParams() - if (innerParenStart) this.unexpected(innerParenStart) - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.parseParenArrowList(startPos, startLoc, exprList) - } - - if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart) - if (spreadStart) this.unexpected(spreadStart) - this.checkExpressionErrors(refDestructuringErrors, true) - this.yieldPos = oldYieldPos || this.yieldPos - this.awaitPos = oldAwaitPos || this.awaitPos - - if (exprList.length > 1) { - val = this.startNodeAt(innerStartPos, innerStartLoc) - val.expressions = exprList - this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc) - } else { - val = exprList[0] - } - } else { - val = this.parseParenExpression() - } - - if (this.options.preserveParens) { - var par = this.startNodeAt(startPos, startLoc) - par.expression = val - return this.finishNode(par, "ParenthesizedExpression") - } else { - return val - } - } - - pp$3.parseParenItem = function(item) { - return item - } - - pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) - } - - // New's precedence is slightly tricky. It must allow its argument to - // be a `[]` or dot subscript expression, but not a call — at least, - // not without wrapping it in parentheses. Thus, it uses the noCalls - // argument to parseSubscripts to prevent it from consuming the - // argument list. - - var empty$1 = [] - - pp$3.parseNew = function() { - var node = this.startNode() - var meta = this.parseIdent(true) - if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) { - node.meta = meta - node.property = this.parseIdent(true) - if (node.property.name !== "target") - this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target") - if (!this.inFunction) - this.raiseRecoverable(node.start, "new.target can only be used in functions") - return this.finishNode(node, "MetaProperty") - } - var startPos = this.start, startLoc = this.startLoc - node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true) - if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false) - else node.arguments = empty$1 - return this.finishNode(node, "NewExpression") - } - - // Parse template expression. - - pp$3.parseTemplateElement = function() { - var elem = this.startNode() - elem.value = { - raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'), - cooked: this.value - } - this.next() - elem.tail = this.type === tt.backQuote - return this.finishNode(elem, "TemplateElement") - } - - pp$3.parseTemplate = function() { - var this$1 = this; - - var node = this.startNode() - this.next() - node.expressions = [] - var curElt = this.parseTemplateElement() - node.quasis = [curElt] - while (!curElt.tail) { - this$1.expect(tt.dollarBraceL) - node.expressions.push(this$1.parseExpression()) - this$1.expect(tt.braceR) - node.quasis.push(curElt = this$1.parseTemplateElement()) - } - this.next() - return this.finishNode(node, "TemplateLiteral") - } - - // Parse an object literal or binding pattern. - - pp$3.parseObj = function(isPattern, refDestructuringErrors) { - var this$1 = this; - - var node = this.startNode(), first = true, propHash = {} - node.properties = [] - this.next() - while (!this.eat(tt.braceR)) { - if (!first) { - this$1.expect(tt.comma) - if (this$1.afterTrailingComma(tt.braceR)) break - } else first = false - - var prop = this$1.startNode(), isGenerator, isAsync, startPos, startLoc - if (this$1.options.ecmaVersion >= 6) { - prop.method = false - prop.shorthand = false - if (isPattern || refDestructuringErrors) { - startPos = this$1.start - startLoc = this$1.startLoc - } - if (!isPattern) - isGenerator = this$1.eat(tt.star) - } - this$1.parsePropertyName(prop) - if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && !prop.computed && - prop.key.type === "Identifier" && prop.key.name === "async" && this$1.type !== tt.parenL && - this$1.type !== tt.colon && !this$1.canInsertSemicolon()) { - isAsync = true - this$1.parsePropertyName(prop, refDestructuringErrors) - } else { - isAsync = false - } - this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) - this$1.checkPropClash(prop, propHash) - node.properties.push(this$1.finishNode(prop, "Property")) - } - return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") - } - - pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) { - if ((isGenerator || isAsync) && this.type === tt.colon) - this.unexpected() - - if (this.eat(tt.colon)) { - prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors) - prop.kind = "init" - } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) { - if (isPattern) this.unexpected() - prop.kind = "init" - prop.method = true - prop.value = this.parseMethod(isGenerator, isAsync) - } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && - (prop.key.name === "get" || prop.key.name === "set") && - (this.type != tt.comma && this.type != tt.braceR)) { - if (isGenerator || isAsync || isPattern) this.unexpected() - prop.kind = prop.key.name - this.parsePropertyName(prop) - prop.value = this.parseMethod(false) - var paramCount = prop.kind === "get" ? 0 : 1 - if (prop.value.params.length !== paramCount) { - var start = prop.value.start - if (prop.kind === "get") - this.raiseRecoverable(start, "getter should have no params") - else - this.raiseRecoverable(start, "setter should have exactly one param") - } else { - if (prop.kind === "set" && prop.value.params[0].type === "RestElement") - this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params") - } - } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { - if (this.keywords.test(prop.key.name) || - (this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) || - (this.inGenerator && prop.key.name == "yield") || - (this.inAsync && prop.key.name == "await")) - this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property") - prop.kind = "init" - if (isPattern) { - prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) - } else if (this.type === tt.eq && refDestructuringErrors) { - if (!refDestructuringErrors.shorthandAssign) - refDestructuringErrors.shorthandAssign = this.start - prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) - } else { - prop.value = prop.key - } - prop.shorthand = true - } else this.unexpected() - } - - pp$3.parsePropertyName = function(prop) { - if (this.options.ecmaVersion >= 6) { - if (this.eat(tt.bracketL)) { - prop.computed = true - prop.key = this.parseMaybeAssign() - this.expect(tt.bracketR) - return prop.key - } else { - prop.computed = false - } - } - return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true) - } - - // Initialize empty function node. - - pp$3.initFunction = function(node) { - node.id = null - if (this.options.ecmaVersion >= 6) { - node.generator = false - node.expression = false - } - if (this.options.ecmaVersion >= 8) - node.async = false - } - - // Parse object or class method. - - pp$3.parseMethod = function(isGenerator, isAsync) { - var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos - - this.initFunction(node) - if (this.options.ecmaVersion >= 6) - node.generator = isGenerator - if (this.options.ecmaVersion >= 8) - node.async = !!isAsync - - this.inGenerator = node.generator - this.inAsync = node.async - this.yieldPos = 0 - this.awaitPos = 0 - - this.expect(tt.parenL) - node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8) - this.checkYieldAwaitInDefaultParams() - this.parseFunctionBody(node, false) - - this.inGenerator = oldInGen - this.inAsync = oldInAsync - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.finishNode(node, "FunctionExpression") - } - - // Parse arrow function expression with given parameters. - - pp$3.parseArrowExpression = function(node, params, isAsync) { - var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos - - this.initFunction(node) - if (this.options.ecmaVersion >= 8) - node.async = !!isAsync - - this.inGenerator = false - this.inAsync = node.async - this.yieldPos = 0 - this.awaitPos = 0 - - node.params = this.toAssignableList(params, true) - this.parseFunctionBody(node, true) - - this.inGenerator = oldInGen - this.inAsync = oldInAsync - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.finishNode(node, "ArrowFunctionExpression") - } - - // Parse function body and check parameters. - - pp$3.parseFunctionBody = function(node, isArrowFunction) { - var isExpression = isArrowFunction && this.type !== tt.braceL - - if (isExpression) { - node.body = this.parseMaybeAssign() - node.expression = true - } else { - // Start a new scope with regard to labels and the `inFunction` - // flag (restore them to their old value afterwards). - var oldInFunc = this.inFunction, oldLabels = this.labels - this.inFunction = true; this.labels = [] - node.body = this.parseBlock(true) - node.expression = false - this.inFunction = oldInFunc; this.labels = oldLabels - } - - // If this is a strict mode function, verify that argument names - // are not repeated, and it does not try to bind the words `eval` - // or `arguments`. - var useStrict = (!isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) ? node.body.body[0] : null - if (useStrict && this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)) - this.raiseRecoverable(useStrict.start, "Illegal 'use strict' directive in function with non-simple parameter list") - - if (this.strict || useStrict) { - var oldStrict = this.strict - this.strict = true - if (node.id) - this.checkLVal(node.id, true) - this.checkParams(node) - this.strict = oldStrict - } else if (isArrowFunction || !this.isSimpleParamList(node.params)) { - this.checkParams(node) - } - } - - pp$3.isSimpleParamList = function(params) { - for (var i = 0; i < params.length; i++) - if (params[i].type !== "Identifier") return false - return true - } - - // Checks function params for various disallowed patterns such as using "eval" - // or "arguments" and duplicate parameters. - - pp$3.checkParams = function(node) { - var this$1 = this; - - var nameHash = {} - for (var i = 0; i < node.params.length; i++) this$1.checkLVal(node.params[i], true, nameHash) - } - - // Parses a comma-separated list of expressions, and returns them as - // an array. `close` is the token type that ends the list, and - // `allowEmpty` can be turned on to allow subsequent commas with - // nothing in between them to be parsed as `null` (which is needed - // for array literals). - - pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { - var this$1 = this; - - var elts = [], first = true - while (!this.eat(close)) { - if (!first) { - this$1.expect(tt.comma) - if (allowTrailingComma && this$1.afterTrailingComma(close)) break - } else first = false - - var elt - if (allowEmpty && this$1.type === tt.comma) - elt = null - else if (this$1.type === tt.ellipsis) { - elt = this$1.parseSpread(refDestructuringErrors) - if (this$1.type === tt.comma && refDestructuringErrors && !refDestructuringErrors.trailingComma) { - refDestructuringErrors.trailingComma = this$1.start - } - } else - elt = this$1.parseMaybeAssign(false, refDestructuringErrors) - elts.push(elt) - } - return elts - } - - // Parse the next token as an identifier. If `liberal` is true (used - // when parsing properties), it will also convert keywords into - // identifiers. - - pp$3.parseIdent = function(liberal) { - var node = this.startNode() - if (liberal && this.options.allowReserved == "never") liberal = false - if (this.type === tt.name) { - if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && - (this.options.ecmaVersion >= 6 || - this.input.slice(this.start, this.end).indexOf("\\") == -1)) - this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved") - if (this.inGenerator && this.value === "yield") - this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator") - if (this.inAsync && this.value === "await") - this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function") - node.name = this.value - } else if (liberal && this.type.keyword) { - node.name = this.type.keyword - } else { - this.unexpected() - } - this.next() - return this.finishNode(node, "Identifier") - } - - // Parses yield expression inside generator. - - pp$3.parseYield = function() { - if (!this.yieldPos) this.yieldPos = this.start - - var node = this.startNode() - this.next() - if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) { - node.delegate = false - node.argument = null - } else { - node.delegate = this.eat(tt.star) - node.argument = this.parseMaybeAssign() - } - return this.finishNode(node, "YieldExpression") - } - - pp$3.parseAwait = function() { - if (!this.awaitPos) this.awaitPos = this.start - - var node = this.startNode() - this.next() - node.argument = this.parseMaybeUnary(null, true) - return this.finishNode(node, "AwaitExpression") - } - - var pp$4 = Parser.prototype - - // This function is used to raise exceptions on parse errors. It - // takes an offset integer (into the current `input`) to indicate - // the location of the error, attaches the position to the end - // of the error message, and then raises a `SyntaxError` with that - // message. - - pp$4.raise = function(pos, message) { - var loc = getLineInfo(this.input, pos) - message += " (" + loc.line + ":" + loc.column + ")" - var err = new SyntaxError(message) - err.pos = pos; err.loc = loc; err.raisedAt = this.pos - throw err - } - - pp$4.raiseRecoverable = pp$4.raise - - pp$4.curPosition = function() { - if (this.options.locations) { - return new Position(this.curLine, this.pos - this.lineStart) - } - } - - var Node = function Node(parser, pos, loc) { - this.type = "" - this.start = pos - this.end = 0 - if (parser.options.locations) - this.loc = new SourceLocation(parser, loc) - if (parser.options.directSourceFile) - this.sourceFile = parser.options.directSourceFile - if (parser.options.ranges) - this.range = [pos, 0] - }; - - // Start an AST node, attaching a start offset. - - var pp$5 = Parser.prototype - - pp$5.startNode = function() { - return new Node(this, this.start, this.startLoc) - } - - pp$5.startNodeAt = function(pos, loc) { - return new Node(this, pos, loc) - } - - // Finish an AST node, adding `type` and `end` properties. - - function finishNodeAt(node, type, pos, loc) { - node.type = type - node.end = pos - if (this.options.locations) - node.loc.end = loc - if (this.options.ranges) - node.range[1] = pos - return node - } - - pp$5.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) - } - - // Finish node at given position - - pp$5.finishNodeAt = function(node, type, pos, loc) { - return finishNodeAt.call(this, node, type, pos, loc) - } - - var TokContext = function TokContext(token, isExpr, preserveSpace, override) { - this.token = token - this.isExpr = !!isExpr - this.preserveSpace = !!preserveSpace - this.override = override - }; - - var types = { - b_stat: new TokContext("{", false), - b_expr: new TokContext("{", true), - b_tmpl: new TokContext("${", true), - p_stat: new TokContext("(", false), - p_expr: new TokContext("(", true), - q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }), - f_expr: new TokContext("function", true) - } - - var pp$6 = Parser.prototype - - pp$6.initialContext = function() { - return [types.b_stat] - } - - pp$6.braceIsBlock = function(prevType) { - if (prevType === tt.colon) { - var parent = this.curContext() - if (parent === types.b_stat || parent === types.b_expr) - return !parent.isExpr - } - if (prevType === tt._return) - return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) - return true - if (prevType == tt.braceL) - return this.curContext() === types.b_stat - return !this.exprAllowed - } - - pp$6.updateContext = function(prevType) { - var update, type = this.type - if (type.keyword && prevType == tt.dot) - this.exprAllowed = false - else if (update = type.updateContext) - update.call(this, prevType) - else - this.exprAllowed = type.beforeExpr - } - - // Token-specific context update code - - tt.parenR.updateContext = tt.braceR.updateContext = function() { - if (this.context.length == 1) { - this.exprAllowed = true - return - } - var out = this.context.pop() - if (out === types.b_stat && this.curContext() === types.f_expr) { - this.context.pop() - this.exprAllowed = false - } else if (out === types.b_tmpl) { - this.exprAllowed = true - } else { - this.exprAllowed = !out.isExpr - } - } - - tt.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr) - this.exprAllowed = true - } - - tt.dollarBraceL.updateContext = function() { - this.context.push(types.b_tmpl) - this.exprAllowed = true - } - - tt.parenL.updateContext = function(prevType) { - var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while - this.context.push(statementParens ? types.p_stat : types.p_expr) - this.exprAllowed = true - } - - tt.incDec.updateContext = function() { - // tokExprAllowed stays unchanged - } - - tt._function.updateContext = function(prevType) { - if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else && - !((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat)) - this.context.push(types.f_expr) - this.exprAllowed = false - } - - tt.backQuote.updateContext = function() { - if (this.curContext() === types.q_tmpl) - this.context.pop() - else - this.context.push(types.q_tmpl) - this.exprAllowed = false - } - - // Object type used to represent tokens. Note that normally, tokens - // simply exist as properties on the parser object. This is only - // used for the onToken callback and the external tokenizer. - - var Token = function Token(p) { - this.type = p.type - this.value = p.value - this.start = p.start - this.end = p.end - if (p.options.locations) - this.loc = new SourceLocation(p, p.startLoc, p.endLoc) - if (p.options.ranges) - this.range = [p.start, p.end] - }; - - // ## Tokenizer - - var pp$7 = Parser.prototype - - // Are we running under Rhino? - var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]" - - // Move to the next token - - pp$7.next = function() { - if (this.options.onToken) - this.options.onToken(new Token(this)) - - this.lastTokEnd = this.end - this.lastTokStart = this.start - this.lastTokEndLoc = this.endLoc - this.lastTokStartLoc = this.startLoc - this.nextToken() - } - - pp$7.getToken = function() { - this.next() - return new Token(this) - } - - // If we're in an ES6 environment, make parsers iterable - if (typeof Symbol !== "undefined") - pp$7[Symbol.iterator] = function () { - var self = this - return {next: function () { - var token = self.getToken() - return { - done: token.type === tt.eof, - value: token - } - }} - } - - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). - - pp$7.setStrict = function(strict) { - var this$1 = this; - - this.strict = strict - if (this.type !== tt.num && this.type !== tt.string) return - this.pos = this.start - if (this.options.locations) { - while (this.pos < this.lineStart) { - this$1.lineStart = this$1.input.lastIndexOf("\n", this$1.lineStart - 2) + 1 - --this$1.curLine - } - } - this.nextToken() - } - - pp$7.curContext = function() { - return this.context[this.context.length - 1] - } - - // Read a single token, updating the parser object's token-related - // properties. - - pp$7.nextToken = function() { - var curContext = this.curContext() - if (!curContext || !curContext.preserveSpace) this.skipSpace() - - this.start = this.pos - if (this.options.locations) this.startLoc = this.curPosition() - if (this.pos >= this.input.length) return this.finishToken(tt.eof) - - if (curContext.override) return curContext.override(this) - else this.readToken(this.fullCharCodeAtPos()) - } - - pp$7.readToken = function(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) - return this.readWord() - - return this.getTokenFromCode(code) - } - - pp$7.fullCharCodeAtPos = function() { - var code = this.input.charCodeAt(this.pos) - if (code <= 0xd7ff || code >= 0xe000) return code - var next = this.input.charCodeAt(this.pos + 1) - return (code << 10) + next - 0x35fdc00 - } - - pp$7.skipBlockComment = function() { - var this$1 = this; - - var startLoc = this.options.onComment && this.curPosition() - var start = this.pos, end = this.input.indexOf("*/", this.pos += 2) - if (end === -1) this.raise(this.pos - 2, "Unterminated comment") - this.pos = end + 2 - if (this.options.locations) { - lineBreakG.lastIndex = start - var match - while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { - ++this$1.curLine - this$1.lineStart = match.index + match[0].length - } - } - if (this.options.onComment) - this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, - startLoc, this.curPosition()) - } - - pp$7.skipLineComment = function(startSkip) { - var this$1 = this; - - var start = this.pos - var startLoc = this.options.onComment && this.curPosition() - var ch = this.input.charCodeAt(this.pos+=startSkip) - while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { - ++this$1.pos - ch = this$1.input.charCodeAt(this$1.pos) - } - if (this.options.onComment) - this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, - startLoc, this.curPosition()) - } - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - pp$7.skipSpace = function() { - var this$1 = this; - - loop: while (this.pos < this.input.length) { - var ch = this$1.input.charCodeAt(this$1.pos) - switch (ch) { - case 32: case 160: // ' ' - ++this$1.pos - break - case 13: - if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { - ++this$1.pos - } - case 10: case 8232: case 8233: + loop: while (this.pos < this.input.length) { + var ch = this$1.input.charCodeAt(this$1.pos) + switch (ch) { + case 32: case 160: // ' ' + ++this$1.pos + break + case 13: + if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { ++this$1.pos - if (this$1.options.locations) { - ++this$1.curLine - this$1.lineStart = this$1.pos - } - break - case 47: // '/' - switch (this$1.input.charCodeAt(this$1.pos + 1)) { - case 42: // '*' - this$1.skipBlockComment() - break - case 47: - this$1.skipLineComment(2) - break - default: - break loop - } - break - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this$1.pos - } else { + } + case 10: case 8232: case 8233: + ++this$1.pos + if (this$1.options.locations) { + ++this$1.curLine + this$1.lineStart = this$1.pos + } + break + case 47: // '/' + switch (this$1.input.charCodeAt(this$1.pos + 1)) { + case 42: // '*' + this$1.skipBlockComment() + break + case 47: + this$1.skipLineComment(2) + break + default: break loop - } - } - } - } - - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. - - pp$7.finishToken = function(type, val) { - this.end = this.pos - if (this.options.locations) this.endLoc = this.curPosition() - var prevType = this.type - this.type = type - this.value = val - - this.updateContext(prevType) - } - - // ### Token reading - - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - pp$7.readToken_dot = function() { - var next = this.input.charCodeAt(this.pos + 1) - if (next >= 48 && next <= 57) return this.readNumber(true) - var next2 = this.input.charCodeAt(this.pos + 2) - if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' - this.pos += 3 - return this.finishToken(tt.ellipsis) - } else { - ++this.pos - return this.finishToken(tt.dot) - } - } - - pp$7.readToken_slash = function() { // '/' - var next = this.input.charCodeAt(this.pos + 1) - if (this.exprAllowed) {++this.pos; return this.readRegexp()} - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(tt.slash, 1) - } - - pp$7.readToken_mult_modulo_exp = function(code) { // '%*' - var next = this.input.charCodeAt(this.pos + 1) - var size = 1 - var tokentype = code === 42 ? tt.star : tt.modulo - - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && next === 42) { - ++size - tokentype = tt.starstar - next = this.input.charCodeAt(this.pos + 2) - } - - if (next === 61) return this.finishOp(tt.assign, size + 1) - return this.finishOp(tokentype, size) - } - - pp$7.readToken_pipe_amp = function(code) { // '|&' - var next = this.input.charCodeAt(this.pos + 1) - if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2) - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1) - } - - pp$7.readToken_caret = function() { // '^' - var next = this.input.charCodeAt(this.pos + 1) - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(tt.bitwiseXOR, 1) - } - - pp$7.readToken_plus_min = function(code) { // '+-' - var next = this.input.charCodeAt(this.pos + 1) - if (next === code) { - if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && - lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) { - // A `-->` line comment - this.skipLineComment(3) - this.skipSpace() - return this.nextToken() - } - return this.finishOp(tt.incDec, 2) + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this$1.pos + } else { + break loop + } } - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(tt.plusMin, 1) } - - pp$7.readToken_lt_gt = function(code) { // '<>' - var next = this.input.charCodeAt(this.pos + 1) - var size = 1 - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2 - if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1) - return this.finishOp(tt.bitShift, size) - } - if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && - this.input.charCodeAt(this.pos + 3) == 45) { - if (this.inModule) this.unexpected() - // `` line comment + this.skipLineComment(3) this.skipSpace() return this.nextToken() } - if (next === 61) size = 2 - return this.finishOp(tt.relational, size) - } + return this.finishOp(tt.incDec, 2) + } + if (next === 61) return this.finishOp(tt.assign, 2) + return this.finishOp(tt.plusMin, 1) +} + +pp$7.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1) + var size = 1 + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2 + if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1) + return this.finishOp(tt.bitShift, size) + } + if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && + this.input.charCodeAt(this.pos + 3) == 45) { + if (this.inModule) this.unexpected() + // ` @@ -163,6 +149,11 @@ target.bundle = function(argsArray) { All commands run synchronously, unless otherwise stated. +All commands accept standard bash globbing characters (`*`, `?`, etc.), +compatible with the [node glob module](https://github.com/isaacs/node-glob). + +For less-commonly used commands and features, please check out our [wiki +page](https://github.com/shelljs/shelljs/wiki). ### cd([dir]) @@ -220,17 +211,21 @@ Available options: + `-f`: force (default behavior) + `-n`: no-clobber -+ `-r, -R`: recursive ++ `-u`: only copy if source is newer than dest ++ `-r`, `-R`: recursive ++ `-L`: follow symlinks ++ `-P`: don't follow symlinks Examples: ```javascript cp('file1', 'dir1'); +cp('-R', 'path/to/dir/', '~/newCopy/'); cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above ``` -Copies files. The wildcard `*` is accepted. +Copies files. ### rm([options,] file [, file ...]) @@ -248,7 +243,7 @@ rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` -Removes files. The wildcard `*` is accepted. +Removes files. ### mv([options ,] source [, source ...], dest') @@ -266,7 +261,7 @@ mv('file1', 'file2', 'dir/'); mv(['file1', 'file2'], 'dir/'); // same as above ``` -Moves files. The wildcard `*` is accepted. +Moves files. ### mkdir([options,] dir [, dir ...]) @@ -320,10 +315,44 @@ var str = cat(['file1', 'file2']); // same as above Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is -introduced between each file). Wildcard `*` accepted. +introduced between each file). + + +### head([{'-n': \},] file [, file ...]) +### head([{'-n': \},] file_array) +Available options: + ++ `-n `: Show the first `` lines of the files + +Examples: + +```javascript +var str = head({'-n': 1}, 'file*.txt'); +var str = head('file1', 'file2'); +var str = head(['file1', 'file2']); // same as above +``` + +Read the start of a file. + + +### tail([{'-n': \},] file [, file ...]) +### tail([{'-n': \},] file_array) +Available options: + ++ `-n `: Show the last `` lines of the files + +Examples: + +```javascript +var str = tail({'-n': 1}, 'file*.txt'); +var str = tail('file1', 'file2'); +var str = tail(['file1', 'file2']); // same as above +``` + +Read the end of a file. -### 'string'.to(file) +### ShellString.prototype.to(file) Examples: @@ -331,11 +360,12 @@ Examples: cat('input.txt').to('output.txt'); ``` -Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as -those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ +Analogous to the redirection operator `>` in Unix, but works with +ShellStrings (such as those returned by `cat`, `grep`, etc). _Like Unix +redirections, `to()` will overwrite any existing file!_ -### 'string'.toEnd(file) +### ShellString.prototype.toEnd(file) Examples: @@ -343,8 +373,8 @@ Examples: cat('input.txt').toEnd('output.txt'); ``` -Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as -those returned by `cat`, `grep`, etc). +Analogous to the redirect-and-append operator `>>` in Unix, but works with +ShellStrings (such as those returned by `cat`, `grep`, etc). ### sed([options,] search_regex, replacement, file [, file ...]) @@ -364,11 +394,48 @@ Reads an input string from `files` and performs a JavaScript `replace()` on the using the given search regex and replacement string or function. Returns the new string after replacement. +### sort([options,] file [, file ...]) +### sort([options,] file_array) +Available options: + ++ `-r`: Reverse the result of comparisons ++ `-n`: Compare according to numerical value + +Examples: + +```javascript +sort('foo.txt', 'bar.txt'); +sort('-r', 'foo.txt'); +``` + +Return the contents of the files, sorted line-by-line. Sorting multiple +files mixes their content, just like unix sort does. + + +### uniq([options,] [input, [output]]) +Available options: + ++ `-i`: Ignore case while comparing ++ `-c`: Prefix lines by the number of occurrences ++ `-d`: Only print duplicate lines, one for each group of identical lines + +Examples: + +```javascript +uniq('foo.txt'); +uniq('-i', 'foo.txt'); +uniq('-cd', 'foo.txt', 'bar.txt'); +``` + +Filter adjacent matching lines from input + + ### grep([options,] regex_filter, file [, file ...]) ### grep([options,] regex_filter, file_array) Available options: + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. ++ `-l`: Print only filenames of matching files Examples: @@ -378,7 +445,7 @@ grep('GLOBAL_VARIABLE', '*.js'); ``` Reads input string from given files and returns a string containing all lines of the -file that match the given `regex_filter`. Wildcard `*` accepted. +file that match the given `regex_filter`. ### which(command) @@ -394,7 +461,10 @@ Searches for `command` in the system's PATH. On Windows, this uses the Returns string containing the absolute path to the command. -### echo(string [, string ...]) +### echo([options,] string [, string ...]) +Available options: + ++ `-e`: interpret backslash escapes (default) Examples: @@ -517,9 +587,13 @@ exec('some_long_running_process', function(code, stdout, stderr) { ``` Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous -mode returns the object `{ code:..., stdout:... , stderr:... }`, containing the program's -`stdout`, `stderr`, and its exit `code`. Otherwise returns the child process object, -and the `callback` gets the arguments `(code, stdout, stderr)`. +mode, this returns a ShellString (compatible with ShellJS v0.6.x, which returns an object +of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process +object, and the `callback` gets the arguments `(code, stdout, stderr)`. + +Not seeing the behavior you want? `exec()` runs everything through `sh` +by default (or `cmd.exe` on Windows), which differs from `bash`. If you +need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. **Note:** For long-lived processes, it's best to run `exec()` asynchronously as the current synchronous implementation uses a lot of CPU. This should be getting @@ -553,7 +627,8 @@ Notable exceptions: + There is no "quiet" option since default behavior is to run silent. -### touch([options,] file) +### touch([options,] file [, file ...]) +### touch([options,] file_array) Available options: + `-a`: Change only the access time @@ -580,6 +655,7 @@ Available options: + `+/-e`: exit upon error (`config.fatal`) + `+/-v`: verbose: show all commands (`config.verbose`) ++ `+/-f`: disable filename expansion (globbing) Examples: @@ -607,14 +683,45 @@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.ht ### error() -Tests if error occurred in the last command. Returns `null` if no error occurred, -otherwise returns string explaining the error +Tests if error occurred in the last command. Returns a truthy value if an +error returned and a falsy value otherwise. +**Note**: do not rely on the +return value to be an error message. If you need the last error message, use +the `.stderr` attribute from the last command's return value instead. + + +### ShellString(str) + +Examples: + +```javascript +var foo = ShellString('hello world'); +``` + +Turns a regular string into a string-like object similar to what each +command returns. This has special methods, like `.to()` and `.toEnd()` + + +### Pipes + +Examples: + +```javascript +grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); +echo('files with o\'s in the name:\n' + ls().grep('o')); +cat('test.js').exec('node'); // pipe to exec() call +``` + +Commands can send their output to another command in a pipe-like fashion. +`sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand +side of a pipe. Pipes can be chained. ## Configuration ### config.silent + Example: ```javascript @@ -629,19 +736,22 @@ Suppresses all command output if `true`, except for `echo()` calls. Default is `false`. ### config.fatal + Example: ```javascript require('shelljs/global'); config.fatal = true; // or set('-e'); -cp('this_file_does_not_exist', '/dev/null'); // dies here +cp('this_file_does_not_exist', '/dev/null'); // throws Error here /* more commands... */ ``` -If `true` the script will die on errors. Default is `false`. This is -analogous to Bash's `set -e` +If `true` the script will throw a Javascript error when any shell.js +command encounters an error. Default is `false`. This is analogous to +Bash's `set -e` ### config.verbose + Example: ```javascript @@ -656,3 +766,19 @@ Will print each command as follows: cd dir/ ls subdir/ ``` + +### config.globOptions + +Example: + +```javascript +config.globOptions = {nodir: true}; +``` + +Use this value for calls to `glob.sync()` instead of the default options. + +## Team + +| [![Nate Fischer](https://avatars.githubusercontent.com/u/5801521?s=130)](https://github.com/nfischer) | [![Ari Porad](https://avatars1.githubusercontent.com/u/1817508?v=3&s=130)](http://github.com/ariporad) | +|:---:|:---:| +| [Nate Fischer](https://github.com/nfischer) | [Ari Porad](http://github.com/ariporad) | diff --git a/tools/eslint/node_modules/shelljs/bin/shjs b/tools/eslint/node_modules/shelljs/bin/shjs index aae3bc64ce2b68..75ca58b9d9ac3c 100755 --- a/tools/eslint/node_modules/shelljs/bin/shjs +++ b/tools/eslint/node_modules/shelljs/bin/shjs @@ -32,24 +32,8 @@ for (var i = 0, l = args.length; i < l; i++) { } } -if (scriptName.match(/\.coffee$/)) { - // - // CoffeeScript - // - if (which('coffee')) { - exec('coffee "' + scriptName + '" ' + args.join(' '), function(code) { - process.exit(code); - }); - } else { - console.log('ShellJS: CoffeeScript interpreter not found'); - console.log(); - process.exit(1); - } -} else { - // - // JavaScript - // - exec('node "' + scriptName + '" ' + args.join(' '), function(code) { - process.exit(code); - }); -} +var path = require('path'); +var extensions = require('interpret').extensions; +var rechoir = require('rechoir'); +rechoir.prepare(extensions, scriptName); +require(require.resolve(path.resolve(process.cwd(), scriptName))); diff --git a/tools/eslint/node_modules/shelljs/global.js b/tools/eslint/node_modules/shelljs/global.js index 97f0033cc15303..b232e66d5e9cbc 100644 --- a/tools/eslint/node_modules/shelljs/global.js +++ b/tools/eslint/node_modules/shelljs/global.js @@ -1,3 +1,12 @@ +/* eslint no-extend-native: 0 */ var shell = require('./shell.js'); -for (var cmd in shell) +var common = require('./src/common'); +Object.keys(shell).forEach(function (cmd) { global[cmd] = shell[cmd]; +}); + +var _to = require('./src/to'); +String.prototype.to = common.wrap('to', _to); + +var _toEnd = require('./src/toEnd'); +String.prototype.toEnd = common.wrap('toEnd', _toEnd); diff --git a/tools/eslint/node_modules/shelljs/package.json b/tools/eslint/node_modules/shelljs/package.json index 5dc19b8f524e00..b6cfe9545d9ac0 100644 --- a/tools/eslint/node_modules/shelljs/package.json +++ b/tools/eslint/node_modules/shelljs/package.json @@ -2,53 +2,49 @@ "_args": [ [ { - "raw": "shelljs@^0.6.0", + "raw": "shelljs@^0.7.5", "scope": null, "escapedName": "shelljs", "name": "shelljs", - "rawSpec": "^0.6.0", - "spec": ">=0.6.0 <0.7.0", + "rawSpec": "^0.7.5", + "spec": ">=0.7.5 <0.8.0", "type": "range" }, "/Users/trott/io.js/tools/node_modules/eslint" ] ], - "_from": "shelljs@>=0.6.0 <0.7.0", - "_id": "shelljs@0.6.1", + "_from": "shelljs@>=0.7.5 <0.8.0", + "_id": "shelljs@0.7.5", "_inCache": true, "_location": "/shelljs", - "_nodeVersion": "6.0.0", + "_nodeVersion": "6.7.0", "_npmOperationalInternal": { - "host": "packages-16-east.internal.npmjs.com", - "tmp": "tmp/shelljs-0.6.1.tgz_1470519555022_0.9348916830495" + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/shelljs-0.7.5.tgz_1477547417527_0.3151172921061516" }, "_npmUser": { "name": "nfischer", "email": "ntfschr@gmail.com" }, - "_npmVersion": "3.5.2", + "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { - "raw": "shelljs@^0.6.0", + "raw": "shelljs@^0.7.5", "scope": null, "escapedName": "shelljs", "name": "shelljs", - "rawSpec": "^0.6.0", - "spec": ">=0.6.0 <0.7.0", + "rawSpec": "^0.7.5", + "spec": ">=0.7.5 <0.8.0", "type": "range" }, "_requiredBy": [ "/eslint" ], - "_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.6.1.tgz", - "_shasum": "ec6211bed1920442088fe0f70b2837232ed2c8a8", + "_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.7.5.tgz", + "_shasum": "2eef7a50a21e1ccf37da00df767ec69e30ad0675", "_shrinkwrap": null, - "_spec": "shelljs@^0.6.0", + "_spec": "shelljs@^0.7.5", "_where": "/Users/trott/io.js/tools/node_modules/eslint", - "author": { - "name": "Artur Adib", - "email": "arturadib@gmail.com" - }, "bin": { "shjs": "./bin/shjs" }, @@ -63,26 +59,39 @@ }, { "name": "Nate Fischer", - "email": "ntfschr@gmail.com" + "email": "ntfschr@gmail.com", + "url": "https://github.com/nfischer" } ], - "dependencies": {}, + "dependencies": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + }, "description": "Portable Unix shell commands for Node.js", "devDependencies": { "coffee-script": "^1.10.0", - "jshint": "~2.1.11" + "eslint": "^2.0.0", + "eslint-config-airbnb-base": "^3.0.0", + "eslint-plugin-import": "^1.11.1", + "shelljs-changelog": "^0.2.0", + "shelljs-release": "^0.2.0", + "travis-check-changes": "^0.2.0" }, "directories": {}, "dist": { - "shasum": "ec6211bed1920442088fe0f70b2837232ed2c8a8", - "tarball": "https://registry.npmjs.org/shelljs/-/shelljs-0.6.1.tgz" + "shasum": "2eef7a50a21e1ccf37da00df767ec69e30ad0675", + "tarball": "https://registry.npmjs.org/shelljs/-/shelljs-0.7.5.tgz" }, "engines": { - "node": ">=0.10.0" + "iojs": "*", + "node": ">=0.11.0" }, - "gitHead": "a5b9e2a64ffdf9f837d6ceb15d7f42221875542b", + "gitHead": "1a15022f2747d322d771dd7ae0c00840e469a52a", "homepage": "http://github.com/shelljs/shelljs", "keywords": [ + "shelljs", + "bash", "unix", "shell", "makefile", @@ -114,7 +123,15 @@ "url": "git://github.com/shelljs/shelljs.git" }, "scripts": { + "after-travis": "travis-check-changes", + "changelog": "shelljs-changelog", + "gendocs": "node scripts/generate-docs", + "lint": "eslint .", + "posttest": "npm run lint", + "release:major": "shelljs-release major", + "release:minor": "shelljs-release minor", + "release:patch": "shelljs-release patch", "test": "node scripts/run-tests" }, - "version": "0.6.1" + "version": "0.7.5" } diff --git a/tools/eslint/node_modules/shelljs/plugin.js b/tools/eslint/node_modules/shelljs/plugin.js new file mode 100644 index 00000000000000..f879ab320e666a --- /dev/null +++ b/tools/eslint/node_modules/shelljs/plugin.js @@ -0,0 +1,16 @@ +// Various utilties exposed to plugins + +require('./shell'); // Create the ShellJS instance (mandatory) + +var common = require('./src/common'); + +var exportedAttributes = [ + 'error', // For signaling errors from within commands + 'parseOptions', // For custom option parsing + 'readFromPipe', // For commands with the .canReceivePipe attribute + 'register', // For registering plugins +]; + +exportedAttributes.forEach(function (attr) { + exports[attr] = common[attr]; +}); diff --git a/tools/eslint/node_modules/shelljs/scripts/generate-docs.js b/tools/eslint/node_modules/shelljs/scripts/generate-docs.js index 3a31a91abd2a13..f777c8ad263612 100755 --- a/tools/eslint/node_modules/shelljs/scripts/generate-docs.js +++ b/tools/eslint/node_modules/shelljs/scripts/generate-docs.js @@ -1,5 +1,5 @@ #!/usr/bin/env node -/* globals cat, cd, echo, grep, sed */ +/* globals cat, cd, echo, grep, sed, ShellString */ require('../global'); echo('Appending docs to README.md'); @@ -7,18 +7,19 @@ echo('Appending docs to README.md'); cd(__dirname + '/..'); // Extract docs from shell.js -var docs = grep('//@', 'shell.js'); +var docs = grep('^//@', 'shell.js'); -docs = docs.replace(/\/\/\@include (.+)/g, function(match, path) { - var file = path.match('.js$') ? path : path+'.js'; - return grep('//@', file); +// Now extract docs from the appropriate src/*.js files +docs = docs.replace(/\/\/@include (.+)/g, function (match, path) { + var file = path.match('.js$') ? path : path + '.js'; + return grep('^//@', file); }); // Remove '//@' -docs = docs.replace(/\/\/\@ ?/g, ''); +docs = docs.replace(/\/\/@ ?/g, ''); // Wipe out the old docs -cat('README.md').replace(/## Command reference(.|\n)*/, '## Command reference').to('README.md'); +ShellString(cat('README.md').replace(/## Command reference(.|\n)*\n## Team/, '## Command reference\n## Team')).to('README.md'); // Append new docs to README sed('-i', /## Command reference/, '## Command reference\n\n' + docs, 'README.md'); diff --git a/tools/eslint/node_modules/shelljs/scripts/run-tests.js b/tools/eslint/node_modules/shelljs/scripts/run-tests.js index e8e7ff2f879a82..99205623f9ed6b 100755 --- a/tools/eslint/node_modules/shelljs/scripts/run-tests.js +++ b/tools/eslint/node_modules/shelljs/scripts/run-tests.js @@ -1,55 +1,29 @@ #!/usr/bin/env node -/* globals cd, echo, exec, exit, ls, pwd, test */ +/* globals cd, echo, exec, exit, ls */ require('../global'); -var common = require('../src/common'); var failed = false; -// -// Lint -// -var JSHINT_BIN = 'node_modules/jshint/bin/jshint'; -cd(__dirname + '/..'); - -if (!test('-f', JSHINT_BIN)) { - echo('JSHint not found. Run `npm install` in the root dir first.'); - exit(1); -} - -var jsfiles = common.expand([pwd() + '/*.js', - pwd() + '/scripts/*.js', - pwd() + '/src/*.js', - pwd() + '/test/*.js' - ]).join(' '); -if (exec('node ' + pwd() + '/' + JSHINT_BIN + ' ' + jsfiles).code !== 0) { - failed = true; - echo('*** JSHINT FAILED! (return code != 0)'); - echo(); -} else { - echo('All JSHint tests passed'); - echo(); -} - // // Unit tests // cd(__dirname + '/../test'); -ls('*.js').forEach(function(file) { +ls('*.js').forEach(function (file) { echo('Running test:', file); - if (exec('node ' + file).code !== 123) { // 123 avoids false positives (e.g. premature exit) + if (exec(JSON.stringify(process.execPath) + ' ' + file).code !== 123) { // 123 avoids false positives (e.g. premature exit) failed = true; echo('*** TEST FAILED! (missing exit code "123")'); echo(); } }); +echo(); + if (failed) { - echo(); echo('*******************************************************'); echo('WARNING: Some tests did not pass!'); echo('*******************************************************'); exit(1); } else { - echo(); echo('All tests passed.'); } diff --git a/tools/eslint/node_modules/shelljs/shell.js b/tools/eslint/node_modules/shelljs/shell.js index 93aff709a3931f..9e49ef5e799cdb 100644 --- a/tools/eslint/node_modules/shelljs/shell.js +++ b/tools/eslint/node_modules/shelljs/shell.js @@ -8,86 +8,95 @@ var common = require('./src/common'); - //@ //@ All commands run synchronously, unless otherwise stated. +//@ All commands accept standard bash globbing characters (`*`, `?`, etc.), +//@ compatible with the [node glob module](https://github.com/isaacs/node-glob). +//@ +//@ For less-commonly used commands and features, please check out our [wiki +//@ page](https://github.com/shelljs/shelljs/wiki). //@ +// Boilerplate +// ----------- +// Copy the code block below here & replace variables with appropiate values +// ``` +// //@include ./src/fileName +// var functionName = require('./src/fileName'); +// exports.nameOfCommand = common.wrap(nameOfCommand, functionName, {globStart: firstIndexToExpand}); +// ``` +// +// The //@include includes the docs for that command +// +// firstIndexToExpand should usually be 1 (so, put {globStart: 1}) +// Increase this value if the command takes arguments that shouldn't be expanded +// with wildcards, such as with the regexes for sed & grep + //@include ./src/cd -var _cd = require('./src/cd'); -exports.cd = common.wrap('cd', _cd); +require('./src/cd'); //@include ./src/pwd -var _pwd = require('./src/pwd'); -exports.pwd = common.wrap('pwd', _pwd); +require('./src/pwd'); //@include ./src/ls -var _ls = require('./src/ls'); -exports.ls = common.wrap('ls', _ls); +require('./src/ls'); //@include ./src/find -var _find = require('./src/find'); -exports.find = common.wrap('find', _find); +require('./src/find'); //@include ./src/cp -var _cp = require('./src/cp'); -exports.cp = common.wrap('cp', _cp); +require('./src/cp'); //@include ./src/rm -var _rm = require('./src/rm'); -exports.rm = common.wrap('rm', _rm); +require('./src/rm'); //@include ./src/mv -var _mv = require('./src/mv'); -exports.mv = common.wrap('mv', _mv); +require('./src/mv'); //@include ./src/mkdir -var _mkdir = require('./src/mkdir'); -exports.mkdir = common.wrap('mkdir', _mkdir); +require('./src/mkdir'); //@include ./src/test -var _test = require('./src/test'); -exports.test = common.wrap('test', _test); +require('./src/test'); //@include ./src/cat -var _cat = require('./src/cat'); -exports.cat = common.wrap('cat', _cat); +require('./src/cat'); + +//@include ./src/head +require('./src/head'); + +//@include ./src/tail +require('./src/tail'); //@include ./src/to -var _to = require('./src/to'); -String.prototype.to = common.wrap('to', _to); +require('./src/to'); //@include ./src/toEnd -var _toEnd = require('./src/toEnd'); -String.prototype.toEnd = common.wrap('toEnd', _toEnd); +require('./src/toEnd'); //@include ./src/sed -var _sed = require('./src/sed'); -exports.sed = common.wrap('sed', _sed); +require('./src/sed'); + +//@include ./src/sort +require('./src/sort'); + +//@include ./src/uniq +require('./src/uniq'); //@include ./src/grep -var _grep = require('./src/grep'); -exports.grep = common.wrap('grep', _grep); +require('./src/grep'); //@include ./src/which -var _which = require('./src/which'); -exports.which = common.wrap('which', _which); +require('./src/which'); //@include ./src/echo -var _echo = require('./src/echo'); -exports.echo = _echo; // don't common.wrap() as it could parse '-options' +require('./src/echo'); //@include ./src/dirs -var _dirs = require('./src/dirs').dirs; -exports.dirs = common.wrap("dirs", _dirs); -var _pushd = require('./src/dirs').pushd; -exports.pushd = common.wrap('pushd', _pushd); -var _popd = require('./src/dirs').popd; -exports.popd = common.wrap("popd", _popd); +require('./src/dirs'); //@include ./src/ln -var _ln = require('./src/ln'); -exports.ln = common.wrap('ln', _ln); +require('./src/ln'); //@ //@ ### exit(code) @@ -100,20 +109,16 @@ exports.exit = process.exit; exports.env = process.env; //@include ./src/exec -var _exec = require('./src/exec'); -exports.exec = common.wrap('exec', _exec, {notUnix:true}); +require('./src/exec'); //@include ./src/chmod -var _chmod = require('./src/chmod'); -exports.chmod = common.wrap('chmod', _chmod); +require('./src/chmod'); //@include ./src/touch -var _touch = require('./src/touch'); -exports.touch = common.wrap('touch', _touch); +require('./src/touch'); //@include ./src/set -var _set = require('./src/set'); -exports.set = common.wrap('set', _set); +require('./src/set'); //@ @@ -121,15 +126,29 @@ exports.set = common.wrap('set', _set); //@ //@include ./src/tempdir -var _tempDir = require('./src/tempdir'); -exports.tempdir = common.wrap('tempdir', _tempDir); - +require('./src/tempdir'); //@include ./src/error -var _error = require('./src/error'); -exports.error = _error; +exports.error = require('./src/error'); + +//@include ./src/common +exports.ShellString = common.ShellString; +//@ +//@ ### Pipes +//@ +//@ Examples: +//@ +//@ ```javascript +//@ grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); +//@ echo('files with o\'s in the name:\n' + ls().grep('o')); +//@ cat('test.js').exec('node'); // pipe to exec() call +//@ ``` +//@ +//@ Commands can send their output to another command in a pipe-like fashion. +//@ `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand +//@ side of a pipe. Pipes can be chained. //@ //@ ## Configuration @@ -139,6 +158,7 @@ exports.config = common.config; //@ //@ ### config.silent +//@ //@ Example: //@ //@ ```javascript @@ -154,20 +174,23 @@ exports.config = common.config; //@ //@ ### config.fatal +//@ //@ Example: //@ //@ ```javascript //@ require('shelljs/global'); //@ config.fatal = true; // or set('-e'); -//@ cp('this_file_does_not_exist', '/dev/null'); // dies here +//@ cp('this_file_does_not_exist', '/dev/null'); // throws Error here //@ /* more commands... */ //@ ``` //@ -//@ If `true` the script will die on errors. Default is `false`. This is -//@ analogous to Bash's `set -e` +//@ If `true` the script will throw a Javascript error when any shell.js +//@ command encounters an error. Default is `false`. This is analogous to +//@ Bash's `set -e` //@ //@ ### config.verbose +//@ //@ Example: //@ //@ ```javascript @@ -182,3 +205,14 @@ exports.config = common.config; //@ cd dir/ //@ ls subdir/ //@ ``` + +//@ +//@ ### config.globOptions +//@ +//@ Example: +//@ +//@ ```javascript +//@ config.globOptions = {nodir: true}; +//@ ``` +//@ +//@ Use this value for calls to `glob.sync()` instead of the default options. diff --git a/tools/eslint/node_modules/shelljs/src/cat.js b/tools/eslint/node_modules/shelljs/src/cat.js index 5840b4ea77b590..a74a25c8424d16 100644 --- a/tools/eslint/node_modules/shelljs/src/cat.js +++ b/tools/eslint/node_modules/shelljs/src/cat.js @@ -1,6 +1,10 @@ var common = require('./common'); var fs = require('fs'); +common.register('cat', _cat, { + canReceivePipe: true, +}); + //@ //@ ### cat(file [, file ...]) //@ ### cat(file_array) @@ -15,26 +19,22 @@ var fs = require('fs'); //@ //@ Returns a string containing the given file, or a concatenated string //@ containing the files if more than one file is given (a new line character is -//@ introduced between each file). Wildcard `*` accepted. +//@ introduced between each file). function _cat(options, files) { - var cat = ''; - - if (!files) - common.error('no paths given'); + var cat = common.readFromPipe(); - if (typeof files === 'string') - files = [].slice.call(arguments, 1); - // if it's array leave it as it is + if (!files && !cat) common.error('no paths given'); - files = common.expand(files); + files = [].slice.call(arguments, 1); - files.forEach(function(file) { - if (!fs.existsSync(file)) + files.forEach(function (file) { + if (!fs.existsSync(file)) { common.error('no such file or directory: ' + file); + } cat += fs.readFileSync(file, 'utf8'); }); - return common.ShellString(cat); + return cat; } module.exports = _cat; diff --git a/tools/eslint/node_modules/shelljs/src/cd.js b/tools/eslint/node_modules/shelljs/src/cd.js index b7b9931b8f41df..634ed835cb0925 100644 --- a/tools/eslint/node_modules/shelljs/src/cd.js +++ b/tools/eslint/node_modules/shelljs/src/cd.js @@ -1,28 +1,38 @@ var fs = require('fs'); var common = require('./common'); +common.register('cd', _cd, {}); + //@ //@ ### cd([dir]) //@ Changes to directory `dir` for the duration of the script. Changes to home //@ directory if no argument is supplied. function _cd(options, dir) { - if (!dir) - dir = common.getUserHome(); + if (!dir) dir = common.getUserHome(); if (dir === '-') { - if (!common.state.previousDir) + if (!process.env.OLDPWD) { common.error('could not find previous directory'); - else - dir = common.state.previousDir; + } else { + dir = process.env.OLDPWD; + } } - if (!fs.existsSync(dir)) - common.error('no such file or directory: ' + dir); - - if (!fs.statSync(dir).isDirectory()) - common.error('not a directory: ' + dir); - - common.state.previousDir = process.cwd(); - process.chdir(dir); + try { + var curDir = process.cwd(); + process.chdir(dir); + process.env.OLDPWD = curDir; + } catch (e) { + // something went wrong, let's figure out the error + var err; + try { + fs.statSync(dir); // if this succeeds, it must be some sort of file + err = 'not a directory: ' + dir; + } catch (e2) { + err = 'no such file or directory: ' + dir; + } + if (err) common.error(err); + } + return ''; } module.exports = _cd; diff --git a/tools/eslint/node_modules/shelljs/src/chmod.js b/tools/eslint/node_modules/shelljs/src/chmod.js index 6c6de10ce12e49..a1afd90e75684f 100644 --- a/tools/eslint/node_modules/shelljs/src/chmod.js +++ b/tools/eslint/node_modules/shelljs/src/chmod.js @@ -4,30 +4,32 @@ var path = require('path'); var PERMS = (function (base) { return { - OTHER_EXEC : base.EXEC, - OTHER_WRITE : base.WRITE, - OTHER_READ : base.READ, + OTHER_EXEC: base.EXEC, + OTHER_WRITE: base.WRITE, + OTHER_READ: base.READ, - GROUP_EXEC : base.EXEC << 3, - GROUP_WRITE : base.WRITE << 3, - GROUP_READ : base.READ << 3, + GROUP_EXEC: base.EXEC << 3, + GROUP_WRITE: base.WRITE << 3, + GROUP_READ: base.READ << 3, - OWNER_EXEC : base.EXEC << 6, - OWNER_WRITE : base.WRITE << 6, - OWNER_READ : base.READ << 6, + OWNER_EXEC: base.EXEC << 6, + OWNER_WRITE: base.WRITE << 6, + OWNER_READ: base.READ << 6, - // Literal octal numbers are apparently not allowed in "strict" javascript. Using parseInt is - // the preferred way, else a jshint warning is thrown. - STICKY : parseInt('01000', 8), - SETGID : parseInt('02000', 8), - SETUID : parseInt('04000', 8), + // Literal octal numbers are apparently not allowed in "strict" javascript. + STICKY: parseInt('01000', 8), + SETGID: parseInt('02000', 8), + SETUID: parseInt('04000', 8), - TYPE_MASK : parseInt('0770000', 8) + TYPE_MASK: parseInt('0770000', 8) }; -})({ - EXEC : 1, - WRITE : 2, - READ : 4 +}({ + EXEC: 1, + WRITE: 2, + READ: 4 +})); + +common.register('chmod', _chmod, { }); //@ @@ -62,11 +64,8 @@ function _chmod(options, mode, filePattern) { // Special case where the specified file permissions started with - to subtract perms, which // get picked up by the option parser as command flags. // If we are down by one argument and options starts with -, shift everything over. - filePattern = mode; - mode = options; - options = ''; - } - else { + [].unshift.call(arguments, ''); + } else { common.error('You must specify a file.'); } } @@ -77,15 +76,14 @@ function _chmod(options, mode, filePattern) { 'v': 'verbose' }); - if (typeof filePattern === 'string') { - filePattern = [ filePattern ]; - } + filePattern = [].slice.call(arguments, 2); var files; + // TODO: replace this with a call to common.expand() if (options.recursive) { files = []; - common.expand(filePattern).forEach(function addFile(expandedFile) { + filePattern.forEach(function addFile(expandedFile) { var stat = fs.lstatSync(expandedFile); if (!stat.isSymbolicLink()) { @@ -98,9 +96,8 @@ function _chmod(options, mode, filePattern) { } } }); - } - else { - files = common.expand(filePattern); + } else { + files = filePattern; } files.forEach(function innerChmod(file) { @@ -124,7 +121,6 @@ function _chmod(options, mode, filePattern) { if (isNaN(parseInt(mode, 8))) { // parse options mode.split(',').forEach(function (symbolicMode) { - /*jshint regexdash:true */ var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; var matches = pattern.exec(symbolicMode); @@ -133,19 +129,20 @@ function _chmod(options, mode, filePattern) { var operator = matches[2]; var change = matches[3]; - var changeOwner = applyTo.indexOf('u') != -1 || applyTo === 'a' || applyTo === ''; - var changeGroup = applyTo.indexOf('g') != -1 || applyTo === 'a' || applyTo === ''; - var changeOther = applyTo.indexOf('o') != -1 || applyTo === 'a' || applyTo === ''; + var changeOwner = applyTo.indexOf('u') !== -1 || applyTo === 'a' || applyTo === ''; + var changeGroup = applyTo.indexOf('g') !== -1 || applyTo === 'a' || applyTo === ''; + var changeOther = applyTo.indexOf('o') !== -1 || applyTo === 'a' || applyTo === ''; - var changeRead = change.indexOf('r') != -1; - var changeWrite = change.indexOf('w') != -1; - var changeExec = change.indexOf('x') != -1; - var changeExecDir = change.indexOf('X') != -1; - var changeSticky = change.indexOf('t') != -1; - var changeSetuid = change.indexOf('s') != -1; + var changeRead = change.indexOf('r') !== -1; + var changeWrite = change.indexOf('w') !== -1; + var changeExec = change.indexOf('x') !== -1; + var changeExecDir = change.indexOf('X') !== -1; + var changeSticky = change.indexOf('t') !== -1; + var changeSetuid = change.indexOf('s') !== -1; - if (changeExecDir && isDir) + if (changeExecDir && isDir) { changeExec = true; + } var mask = 0; if (changeOwner) { @@ -175,35 +172,37 @@ function _chmod(options, mode, filePattern) { case '=': newPerms = type + mask; - // According to POSIX, when using = to explicitly set the permissions, setuid and setgid can never be cleared. + // According to POSIX, when using = to explicitly set the + // permissions, setuid and setgid can never be cleared. if (fs.statSync(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } break; + default: + common.error('Could not recognize operator: `' + operator + '`'); } if (options.verbose) { console.log(file + ' -> ' + newPerms.toString(8)); } - if (perms != newPerms) { + if (perms !== newPerms) { if (!options.verbose && options.changes) { console.log(file + ' -> ' + newPerms.toString(8)); } fs.chmodSync(file, newPerms); perms = newPerms; // for the next round of changes! } - } - else { + } else { common.error('Invalid symbolic mode change: ' + symbolicMode); } }); - } - else { + } else { // they gave us a full number newPerms = type + parseInt(mode, 8); - // POSIX rules are that setuid and setgid can only be added using numeric form, but not cleared. + // POSIX rules are that setuid and setgid can only be added using numeric + // form, but not cleared. if (fs.statSync(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } @@ -211,5 +210,6 @@ function _chmod(options, mode, filePattern) { fs.chmodSync(file, newPerms); } }); + return ''; } module.exports = _chmod; diff --git a/tools/eslint/node_modules/shelljs/src/common.js b/tools/eslint/node_modules/shelljs/src/common.js index 33198bd8a0a265..8211feff4e4d29 100644 --- a/tools/eslint/node_modules/shelljs/src/common.js +++ b/tools/eslint/node_modules/shelljs/src/common.js @@ -1,68 +1,132 @@ +// Ignore warning about 'new String()' +/* eslint no-new-wrappers: 0 */ +'use strict'; + var os = require('os'); var fs = require('fs'); -var _ls = require('./ls'); +var glob = require('glob'); +var shell = require('..'); + +var shellMethods = Object.create(shell); // Module globals var config = { silent: false, fatal: false, verbose: false, + noglob: false, + globOptions: {}, + maxdepth: 255 }; exports.config = config; var state = { error: null, + errorCode: 0, currentCmd: 'shell.js', - previousDir: null, tempDir: null }; exports.state = state; +delete process.env.OLDPWD; // initially, there's no previous directory + var platform = os.type().match(/^Win/) ? 'win' : 'unix'; exports.platform = platform; +// This is populated by calls to commonl.wrap() +var pipeMethods = []; + function log() { - if (!config.silent) + if (!config.silent) { console.error.apply(console, arguments); + } } exports.log = log; -// Shows error message. Throws unless _continue or config.fatal are true -function error(msg, _continue) { - if (state.error === null) - state.error = ''; - var log_entry = state.currentCmd + ': ' + msg; - if (state.error === '') - state.error = log_entry; - else - state.error += '\n' + log_entry; +// Shows error message. Throws if config.fatal is true +function error(msg, _code, options) { + // Validate input + if (typeof msg !== 'string') throw new Error('msg must be a string'); + + var DEFAULT_OPTIONS = { + continue: false, + code: 1, + prefix: state.currentCmd + ': ', + silent: false, + }; + + if (typeof _code === 'number' && typeof options === 'object') { + options.code = _code; + } else if (typeof _code === 'object') { // no 'code' + options = _code; + } else if (typeof _code === 'number') { // no 'options' + options = { code: _code }; + } else if (typeof _code !== 'number') { // only 'msg' + options = {}; + } + options = objectAssign({}, DEFAULT_OPTIONS, options); + + if (!state.errorCode) state.errorCode = options.code; - if (msg.length > 0) - log(log_entry); + var logEntry = options.prefix + msg; + state.error = state.error ? state.error + '\n' : ''; + state.error += logEntry; - if (config.fatal) - process.exit(1); + // Throw an error, or log the entry + if (config.fatal) throw new Error(logEntry); + if (msg.length > 0 && !options.silent) log(logEntry); - if (!_continue) - throw ''; + if (!options.continue) { + throw { + msg: 'earlyExit', + retValue: (new ShellString('', state.error, state.errorCode)) + }; + } } exports.error = error; -// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings. -// For now, this is a dummy function to bookmark places we need such strings -function ShellString(str) { - return str; +//@ +//@ ### ShellString(str) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var foo = ShellString('hello world'); +//@ ``` +//@ +//@ Turns a regular string into a string-like object similar to what each +//@ command returns. This has special methods, like `.to()` and `.toEnd()` +function ShellString(stdout, stderr, code) { + var that; + if (stdout instanceof Array) { + that = stdout; + that.stdout = stdout.join('\n'); + if (stdout.length > 0) that.stdout += '\n'; + } else { + that = new String(stdout); + that.stdout = stdout; + } + that.stderr = stderr; + that.code = code; + // A list of all commands that can appear on the right-hand side of a pipe + // (populated by calls to common.wrap()) + pipeMethods.forEach(function (cmd) { + that[cmd] = shellMethods[cmd].bind(that); + }); + return that; } + exports.ShellString = ShellString; // Return the home directory in a platform-agnostic way, with consideration for // older versions of node function getUserHome() { var result; - if (os.homedir) + if (os.homedir) { result = os.homedir(); // node 3+ - else + } else { result = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; + } return result; } exports.getUserHome = getUserHome; @@ -72,49 +136,50 @@ exports.getUserHome = getUserHome; // Returns {'reference': 'string-value', 'bob': false} when passed two dictionaries of the form: // parseOptions({'-r': 'string-value'}, {'r':'reference', 'b':'bob'}); function parseOptions(opt, map) { - if (!map) - error('parseOptions() internal error: no map given'); + if (!map) error('parseOptions() internal error: no map given'); // All options are false by default var options = {}; - for (var letter in map) { - if (map[letter][0] !== '!') + Object.keys(map).forEach(function (letter) { + if (map[letter][0] !== '!') { options[map[letter]] = false; - } + } + }); - if (!opt) - return options; // defaults + if (!opt) return options; // defaults var optionName; if (typeof opt === 'string') { - if (opt[0] !== '-') + if (opt[0] !== '-') { return options; + } // e.g. chars = ['R', 'f'] var chars = opt.slice(1).split(''); - chars.forEach(function(c) { + chars.forEach(function (c) { if (c in map) { optionName = map[c]; - if (optionName[0] === '!') - options[optionName.slice(1, optionName.length-1)] = false; - else + if (optionName[0] === '!') { + options[optionName.slice(1)] = false; + } else { options[optionName] = true; + } } else { - error('option not recognized: '+c); + error('option not recognized: ' + c); } }); } else if (typeof opt === 'object') { - for (var key in opt) { + Object.keys(opt).forEach(function (key) { // key is a string of the form '-r', '-d', etc. var c = key[1]; if (c in map) { optionName = map[c]; options[optionName] = opt[key]; // assign the given value } else { - error('option not recognized: '+c); + error('option not recognized: ' + c); } - } + }); } else { error('options must be strings or key-value pairs'); } @@ -127,29 +192,18 @@ exports.parseOptions = parseOptions; // expand(['file*.js']) = ['file1.js', 'file2.js', ...] // (if the files 'file1.js', 'file2.js', etc, exist in the current dir) function expand(list) { + if (!Array.isArray(list)) { + throw new TypeError('must be an array'); + } var expanded = []; - list.forEach(function(listEl) { - // Wildcard present on directory names ? - if(listEl.search(/\*[^\/]*\//) > -1 || listEl.search(/\*\*[^\/]*\//) > -1) { - var match = listEl.match(/^([^*]+\/|)(.*)/); - var root = match[1]; - var rest = match[2]; - var restRegex = rest.replace(/\*\*/g, ".*").replace(/\*/g, "[^\\/]*"); - restRegex = new RegExp(restRegex); - - _ls('-R', root).filter(function (e) { - return restRegex.test(e); - }).forEach(function(file) { - expanded.push(file); - }); - } - // Wildcard present on file names ? - else if (listEl.search(/\*/) > -1) { - _ls('', listEl).forEach(function(file) { - expanded.push(file); - }); - } else { + list.forEach(function (listEl) { + // Don't expand non-strings + if (typeof listEl !== 'string') { expanded.push(listEl); + } else { + var ret = glob.sync(listEl, config.globOptions); + // if glob fails, interpret the string literally + expanded = expanded.concat(ret.length > 0 ? ret : [listEl]); } }); return expanded; @@ -161,7 +215,7 @@ exports.expand = expand; function unlinkSync(file) { try { fs.unlinkSync(file); - } catch(e) { + } catch (e) { // Try to override file permission if (e.code === 'EPERM') { fs.chmodSync(file, '0666'); @@ -176,78 +230,133 @@ exports.unlinkSync = unlinkSync; // e.g. 'shelljs_a5f185d0443ca...' function randomFileName() { function randomHash(count) { - if (count === 1) - return parseInt(16*Math.random(), 10).toString(16); - else { - var hash = ''; - for (var i=0; i= common.config.maxdepth) { + // Max depth has been reached, end copy. + return; + } + opts.depth++; + + // Create the directory where all our junk is moving to; read the mode of the + // source directory and mirror it try { + var checkDir = fs.statSync(sourceDir); fs.mkdirSync(destDir, checkDir.mode); } catch (e) { - //if the directory already exists, that's okay + // if the directory already exists, that's okay if (e.code !== 'EEXIST') throw e; } var files = fs.readdirSync(sourceDir); for (var i = 0; i < files.length; i++) { - var srcFile = sourceDir + "/" + files[i]; - var destFile = destDir + "/" + files[i]; + var srcFile = sourceDir + '/' + files[i]; + var destFile = destDir + '/' + files[i]; var srcFileStat = fs.lstatSync(srcFile); + var symlinkFull; + if (opts.followsymlink) { + if (cpcheckcycle(sourceDir, srcFile)) { + // Cycle link found. + console.error('Cycle link found.'); + symlinkFull = fs.readlinkSync(srcFile); + fs.symlinkSync(symlinkFull, destFile, os.platform() === 'win32' ? 'junction' : null); + continue; + } + } if (srcFileStat.isDirectory()) { /* recursion this thing right on back. */ cpdirSyncRecursive(srcFile, destFile, opts); - } else if (srcFileStat.isSymbolicLink()) { - var symlinkFull = fs.readlinkSync(srcFile); - fs.symlinkSync(symlinkFull, destFile, os.platform() === "win32" ? "junction" : null); + } else if (srcFileStat.isSymbolicLink() && !opts.followsymlink) { + symlinkFull = fs.readlinkSync(srcFile); + try { + fs.lstatSync(destFile); + common.unlinkSync(destFile); // re-link it + } catch (e) { + // it doesn't exist, so no work needs to be done + } + fs.symlinkSync(symlinkFull, destFile, os.platform() === 'win32' ? 'junction' : null); + } else if (srcFileStat.isSymbolicLink() && opts.followsymlink) { + srcFileStat = fs.statSync(srcFile); + if (srcFileStat.isDirectory()) { + cpdirSyncRecursive(srcFile, destFile, opts); + } else { + copyFileSync(srcFile, destFile, opts); + } } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ if (fs.existsSync(destFile) && opts.no_force) { common.log('skipping existing file: ' + files[i]); } else { - copyFileSync(srcFile, destFile); + copyFileSync(srcFile, destFile, opts); } } - } // for files } // cpdirSyncRecursive +function cpcheckcycle(sourceDir, srcFile) { + var srcFileStat = fs.lstatSync(srcFile); + if (srcFileStat.isSymbolicLink()) { + // Do cycle check. For example: + // $ mkdir -p 1/2/3/4 + // $ cd 1/2/3/4 + // $ ln -s ../../3 link + // $ cd ../../../.. + // $ cp -RL 1 copy + var cyclecheck = fs.statSync(srcFile); + if (cyclecheck.isDirectory()) { + var sourcerealpath = fs.realpathSync(sourceDir); + var symlinkrealpath = fs.realpathSync(srcFile); + var re = new RegExp(symlinkrealpath); + if (re.test(sourcerealpath)) { + return true; + } + } + } + return false; +} //@ //@ ### cp([options,] source [, source ...], dest) @@ -94,117 +183,92 @@ function cpdirSyncRecursive(sourceDir, destDir, opts) { //@ //@ + `-f`: force (default behavior) //@ + `-n`: no-clobber -//@ + `-r, -R`: recursive +//@ + `-u`: only copy if source is newer than dest +//@ + `-r`, `-R`: recursive +//@ + `-L`: follow symlinks +//@ + `-P`: don't follow symlinks //@ //@ Examples: //@ //@ ```javascript //@ cp('file1', 'dir1'); +//@ cp('-R', 'path/to/dir/', '~/newCopy/'); //@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); //@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above //@ ``` //@ -//@ Copies files. The wildcard `*` is accepted. +//@ Copies files. function _cp(options, sources, dest) { - options = common.parseOptions(options, { - 'f': '!no_force', - 'n': 'no_force', - 'R': 'recursive', - 'r': 'recursive' - }); + // If we're missing -R, it actually implies -L (unless -P is explicit) + if (options.followsymlink) { + options.noFollowsymlink = false; + } + if (!options.recursive && !options.noFollowsymlink) { + options.followsymlink = true; + } // Get sources, dest if (arguments.length < 3) { common.error('missing and/or '); - } else if (arguments.length > 3) { + } else { sources = [].slice.call(arguments, 1, arguments.length - 1); dest = arguments[arguments.length - 1]; - } else if (typeof sources === 'string') { - sources = [sources]; - } else if ('length' in sources) { - sources = sources; // no-op for array - } else { - common.error('invalid arguments'); } - var exists = fs.existsSync(dest), - stats = exists && fs.statSync(dest); + var destExists = fs.existsSync(dest); + var destStat = destExists && fs.statSync(dest); // Dest is not existing dir, but multiple sources given - if ((!exists || !stats.isDirectory()) && sources.length > 1) + if ((!destExists || !destStat.isDirectory()) && sources.length > 1) { common.error('dest is not a directory (too many sources)'); - - // Dest is an existing file, but no -f given - if (exists && stats.isFile() && options.no_force) - common.error('dest file already exists: ' + dest); - - if (options.recursive) { - // Recursive allows the shortcut syntax "sourcedir/" for "sourcedir/*" - // (see Github issue #15) - sources.forEach(function(src, i) { - if (src[src.length - 1] === '/') { - sources[i] += '*'; - // If src is a directory and dest doesn't exist, 'cp -r src dest' should copy src/* into dest - } else if (fs.statSync(src).isDirectory() && !exists) { - sources[i] += '/*'; - } - }); - - // Create dest - try { - fs.mkdirSync(dest, parseInt('0777', 8)); - } catch (e) { - // like Unix's cp, keep going even if we can't create dest dir - } } - sources = common.expand(sources); + // Dest is an existing file, but -n is given + if (destExists && destStat.isFile() && options.no_force) { + return new common.ShellString('', '', 0); + } - sources.forEach(function(src) { + sources.forEach(function (src) { if (!fs.existsSync(src)) { - common.error('no such file or directory: '+src, true); + common.error('no such file or directory: ' + src, { continue: true }); return; // skip file } - - // If here, src exists - if (fs.statSync(src).isDirectory()) { + var srcStat = fs.statSync(src); + if (!options.noFollowsymlink && srcStat.isDirectory()) { if (!options.recursive) { // Non-Recursive - common.log(src + ' is a directory (not copied)'); + common.error("omitting directory '" + src + "'", { continue: true }); } else { // Recursive // 'cp /a/source dest' should create 'source' in 'dest' - var newDest = path.join(dest, path.basename(src)), - checkDir = fs.statSync(src); + var newDest = (destStat && destStat.isDirectory()) ? + path.join(dest, path.basename(src)) : + dest; + try { - fs.mkdirSync(newDest, checkDir.mode); + fs.statSync(path.dirname(dest)); + cpdirSyncRecursive(src, newDest, { no_force: options.no_force, followsymlink: options.followsymlink }); } catch (e) { - //if the directory already exists, that's okay - if (e.code !== 'EEXIST') { - common.error('dest file no such file or directory: ' + newDest, true); - throw e; - } + common.error("cannot create directory '" + dest + "': No such file or directory"); } - - cpdirSyncRecursive(src, newDest, {no_force: options.no_force}); } - return; // done with dir - } + } else { + // If here, src is a file - // If here, src is a file + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (destStat && destStat.isDirectory()) { + thisDest = path.normalize(dest + '/' + path.basename(src)); + } - // When copying to '/path/dir': - // thisDest = '/path/dir/file1' - var thisDest = dest; - if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) - thisDest = path.normalize(dest + '/' + path.basename(src)); + if (fs.existsSync(thisDest) && options.no_force) { + return; // skip file + } - if (fs.existsSync(thisDest) && options.no_force) { - common.error('dest file already exists: ' + thisDest, true); - return; // skip file + copyFileSync(src, thisDest, options); } - - copyFileSync(src, thisDest); }); // forEach(src) + return new common.ShellString('', common.state.error, common.state.errorCode); } module.exports = _cp; diff --git a/tools/eslint/node_modules/shelljs/src/dirs.js b/tools/eslint/node_modules/shelljs/src/dirs.js index 58fae8b3c6fae3..cf5fe02f50c593 100644 --- a/tools/eslint/node_modules/shelljs/src/dirs.js +++ b/tools/eslint/node_modules/shelljs/src/dirs.js @@ -2,6 +2,16 @@ var common = require('./common'); var _cd = require('./cd'); var path = require('path'); +common.register('dirs', _dirs, { + wrapOutput: false, +}); +common.register('pushd', _pushd, { + wrapOutput: false, +}); +common.register('popd', _popd, { + wrapOutput: false, +}); + // Pushd/popd/dirs internals var _dirStack = []; @@ -13,9 +23,8 @@ function _parseStackIndex(index) { if (_isStackIndex(index)) { if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd return (/^-/).test(index) ? Number(index) - 1 : Number(index); - } else { - common.error(index + ': directory stack index out of range'); } + common.error(index + ': directory stack index out of range'); } else { common.error(index + ': invalid number'); } @@ -54,7 +63,7 @@ function _pushd(options, dir) { } options = common.parseOptions(options, { - 'n' : 'no-cd' + 'n': 'no-cd' }); var dirs = _actualDirStack(); @@ -120,7 +129,7 @@ function _popd(options, index) { } options = common.parseOptions(options, { - 'n' : 'no-cd' + 'n': 'no-cd' }); if (!_dirStack.length) { @@ -163,10 +172,10 @@ function _dirs(options, index) { } options = common.parseOptions(options, { - 'c' : 'clear' + 'c': 'clear' }); - if (options['clear']) { + if (options.clear) { _dirStack = []; return _dirStack; } diff --git a/tools/eslint/node_modules/shelljs/src/echo.js b/tools/eslint/node_modules/shelljs/src/echo.js index b574adc5c38465..2b0e7d9198186f 100644 --- a/tools/eslint/node_modules/shelljs/src/echo.js +++ b/tools/eslint/node_modules/shelljs/src/echo.js @@ -1,7 +1,14 @@ var common = require('./common'); +common.register('echo', _echo, { + allowGlobbing: false, +}); + +//@ +//@ ### echo([options,] string [, string ...]) +//@ Available options: //@ -//@ ### echo(string [, string ...]) +//@ + `-e`: interpret backslash escapes (default) //@ //@ Examples: //@ @@ -12,9 +19,16 @@ var common = require('./common'); //@ //@ Prints string to stdout, and returns string with additional utility methods //@ like `.to()`. -function _echo() { - var messages = [].slice.call(arguments, 0); +function _echo(opts, messages) { + // allow strings starting with '-', see issue #20 + messages = [].slice.call(arguments, opts ? 0 : 1); + + if (messages[0] === '-e') { + // ignore -e + messages.shift(); + } + console.log.apply(console, messages); - return common.ShellString(messages.join(' ')); + return messages.join(' '); } module.exports = _echo; diff --git a/tools/eslint/node_modules/shelljs/src/error.js b/tools/eslint/node_modules/shelljs/src/error.js index 112563db80311e..507c86ddd7131e 100644 --- a/tools/eslint/node_modules/shelljs/src/error.js +++ b/tools/eslint/node_modules/shelljs/src/error.js @@ -2,8 +2,12 @@ var common = require('./common'); //@ //@ ### error() -//@ Tests if error occurred in the last command. Returns `null` if no error occurred, -//@ otherwise returns string explaining the error +//@ Tests if error occurred in the last command. Returns a truthy value if an +//@ error returned and a falsy value otherwise. +//@ +//@ **Note**: do not rely on the +//@ return value to be an error message. If you need the last error message, use +//@ the `.stderr` attribute from the last command's return value instead. function error() { return common.state.error; } diff --git a/tools/eslint/node_modules/shelljs/src/exec.js b/tools/eslint/node_modules/shelljs/src/exec.js index 4174adbd32d317..f6875b1e5fc4ae 100644 --- a/tools/eslint/node_modules/shelljs/src/exec.js +++ b/tools/eslint/node_modules/shelljs/src/exec.js @@ -5,85 +5,95 @@ var path = require('path'); var fs = require('fs'); var child = require('child_process'); -var DEFAULT_MAXBUFFER_SIZE = 20*1024*1024; +var DEFAULT_MAXBUFFER_SIZE = 20 * 1024 * 1024; + +common.register('exec', _exec, { + unix: false, + canReceivePipe: true, + wrapOutput: false, +}); // Hack to run child_process.exec() synchronously (sync avoids callback hell) // Uses a custom wait loop that checks for a flag file, created when the child process is done. // (Can't do a wait loop that checks for internal Node variables/messages as // Node is single-threaded; callbacks and other internal state changes are done in the // event loop). -function execSync(cmd, opts) { +function execSync(cmd, opts, pipe) { var tempDir = _tempDir(); - var stdoutFile = path.resolve(tempDir+'/'+common.randomFileName()), - stderrFile = path.resolve(tempDir+'/'+common.randomFileName()), - codeFile = path.resolve(tempDir+'/'+common.randomFileName()), - scriptFile = path.resolve(tempDir+'/'+common.randomFileName()), - sleepFile = path.resolve(tempDir+'/'+common.randomFileName()); + var stdoutFile = path.resolve(tempDir + '/' + common.randomFileName()); + var stderrFile = path.resolve(tempDir + '/' + common.randomFileName()); + var codeFile = path.resolve(tempDir + '/' + common.randomFileName()); + var scriptFile = path.resolve(tempDir + '/' + common.randomFileName()); + var sleepFile = path.resolve(tempDir + '/' + common.randomFileName()); opts = common.extend({ silent: common.config.silent, - cwd: _pwd(), + cwd: _pwd().toString(), env: process.env, maxBuffer: DEFAULT_MAXBUFFER_SIZE }, opts); - var previousStdoutContent = '', - previousStderrContent = ''; + var previousStdoutContent = ''; + var previousStderrContent = ''; // Echoes stdout and stderr changes from running process, if not silent function updateStream(streamFile) { - if (opts.silent || !fs.existsSync(streamFile)) + if (opts.silent || !fs.existsSync(streamFile)) { return; + } - var previousStreamContent, - proc_stream; + var previousStreamContent; + var procStream; if (streamFile === stdoutFile) { previousStreamContent = previousStdoutContent; - proc_stream = process.stdout; + procStream = process.stdout; } else { // assume stderr previousStreamContent = previousStderrContent; - proc_stream = process.stderr; + procStream = process.stderr; } var streamContent = fs.readFileSync(streamFile, 'utf8'); // No changes since last time? - if (streamContent.length <= previousStreamContent.length) + if (streamContent.length <= previousStreamContent.length) { return; + } - proc_stream.write(streamContent.substr(previousStreamContent.length)); + procStream.write(streamContent.substr(previousStreamContent.length)); previousStreamContent = streamContent; } - function escape(str) { - return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0"); - } - if (fs.existsSync(scriptFile)) common.unlinkSync(scriptFile); if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile); if (fs.existsSync(stderrFile)) common.unlinkSync(stderrFile); if (fs.existsSync(codeFile)) common.unlinkSync(codeFile); - var execCommand = '"'+process.execPath+'" '+scriptFile; + var execCommand = JSON.stringify(process.execPath) + ' ' + JSON.stringify(scriptFile); var script; + opts.cwd = path.resolve(opts.cwd); + var optString = JSON.stringify(opts); + if (typeof child.execSync === 'function') { script = [ "var child = require('child_process')", " , fs = require('fs');", - "var childProcess = child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: "+opts.maxBuffer+"}, function(err) {", - " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');", - "});", - "var stdoutStream = fs.createWriteStream('"+escape(stdoutFile)+"');", - "var stderrStream = fs.createWriteStream('"+escape(stderrFile)+"');", - "childProcess.stdout.pipe(stdoutStream, {end: false});", - "childProcess.stderr.pipe(stderrStream, {end: false});", - "childProcess.stdout.pipe(process.stdout);", - "childProcess.stderr.pipe(process.stderr);", - "var stdoutEnded = false, stderrEnded = false;", - "function tryClosingStdout(){ if(stdoutEnded){ stdoutStream.end(); } }", - "function tryClosingStderr(){ if(stderrEnded){ stderrStream.end(); } }", - "childProcess.stdout.on('end', function(){ stdoutEnded = true; tryClosingStdout(); });", - "childProcess.stderr.on('end', function(){ stderrEnded = true; tryClosingStderr(); });" - ].join('\n'); + 'var childProcess = child.exec(' + JSON.stringify(cmd) + ', ' + optString + ', function(err) {', + ' fs.writeFileSync(' + JSON.stringify(codeFile) + ", err ? err.code.toString() : '0');", + '});', + 'var stdoutStream = fs.createWriteStream(' + JSON.stringify(stdoutFile) + ');', + 'var stderrStream = fs.createWriteStream(' + JSON.stringify(stderrFile) + ');', + 'childProcess.stdout.pipe(stdoutStream, {end: false});', + 'childProcess.stderr.pipe(stderrStream, {end: false});', + 'childProcess.stdout.pipe(process.stdout);', + 'childProcess.stderr.pipe(process.stderr);' + ].join('\n') + + (pipe ? '\nchildProcess.stdin.end(' + JSON.stringify(pipe) + ');\n' : '\n') + + [ + 'var stdoutEnded = false, stderrEnded = false;', + 'function tryClosingStdout(){ if(stdoutEnded){ stdoutStream.end(); } }', + 'function tryClosingStderr(){ if(stderrEnded){ stderrStream.end(); } }', + "childProcess.stdout.on('end', function(){ stdoutEnded = true; tryClosingStdout(); });", + "childProcess.stderr.on('end', function(){ stderrEnded = true; tryClosingStderr(); });" + ].join('\n'); fs.writeFileSync(scriptFile, script); @@ -94,17 +104,27 @@ function execSync(cmd, opts) { } // Welcome to the future - child.execSync(execCommand, opts); + try { + child.execSync(execCommand, opts); + } catch (e) { + // Clean up immediately if we have an exception + try { common.unlinkSync(scriptFile); } catch (e2) {} + try { common.unlinkSync(stdoutFile); } catch (e2) {} + try { common.unlinkSync(stderrFile); } catch (e2) {} + try { common.unlinkSync(codeFile); } catch (e2) {} + throw e; + } } else { - cmd += ' > '+stdoutFile+' 2> '+stderrFile; // works on both win/unix + cmd += ' > ' + stdoutFile + ' 2> ' + stderrFile; // works on both win/unix script = [ "var child = require('child_process')", " , fs = require('fs');", - "var childProcess = child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: "+opts.maxBuffer+"}, function(err) {", - " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');", - "});" - ].join('\n'); + 'var childProcess = child.exec(' + JSON.stringify(cmd) + ', ' + optString + ', function(err) {', + ' fs.writeFileSync(' + JSON.stringify(codeFile) + ", err ? err.code.toString() : '0');", + '});' + ].join('\n') + + (pipe ? '\nchildProcess.stdin.end(' + JSON.stringify(pipe) + ');\n' : '\n'); fs.writeFileSync(scriptFile, script); @@ -117,6 +137,7 @@ function execSync(cmd, opts) { while (!fs.existsSync(codeFile)) { updateStream(stdoutFile); fs.writeFileSync(sleepFile, 'a'); } while (!fs.existsSync(stdoutFile)) { updateStream(stdoutFile); fs.writeFileSync(sleepFile, 'a'); } while (!fs.existsSync(stderrFile)) { updateStream(stderrFile); fs.writeFileSync(sleepFile, 'a'); } + try { common.unlinkSync(sleepFile); } catch (e) {} } // At this point codeFile exists, but it's not necessarily flushed yet. @@ -130,53 +151,46 @@ function execSync(cmd, opts) { var stderr = fs.readFileSync(stderrFile, 'utf8'); // No biggie if we can't erase the files now -- they're in a temp dir anyway - try { common.unlinkSync(scriptFile); } catch(e) {} - try { common.unlinkSync(stdoutFile); } catch(e) {} - try { common.unlinkSync(stderrFile); } catch(e) {} - try { common.unlinkSync(codeFile); } catch(e) {} - try { common.unlinkSync(sleepFile); } catch(e) {} - - // some shell return codes are defined as errors, per http://tldp.org/LDP/abs/html/exitcodes.html - if (code === 1 || code === 2 || code >= 126) { - common.error('', true); // unix/shell doesn't really give an error message after non-zero exit codes + try { common.unlinkSync(scriptFile); } catch (e) {} + try { common.unlinkSync(stdoutFile); } catch (e) {} + try { common.unlinkSync(stderrFile); } catch (e) {} + try { common.unlinkSync(codeFile); } catch (e) {} + + if (code !== 0) { + common.error('', code, { continue: true }); } - // True if successful, false if not - var obj = { - code: code, - output: stdout, // deprecated - stdout: stdout, - stderr: stderr - }; + var obj = common.ShellString(stdout, stderr, code); return obj; } // execSync() // Wrapper around exec() to enable echoing output to console in real time -function execAsync(cmd, opts, callback) { +function execAsync(cmd, opts, pipe, callback) { var stdout = ''; var stderr = ''; opts = common.extend({ silent: common.config.silent, - cwd: _pwd(), + cwd: _pwd().toString(), env: process.env, maxBuffer: DEFAULT_MAXBUFFER_SIZE }, opts); - var c = child.exec(cmd, opts, function(err) { - if (callback) + var c = child.exec(cmd, opts, function (err) { + if (callback) { callback(err ? err.code : 0, stdout, stderr); + } }); - c.stdout.on('data', function(data) { + if (pipe) c.stdin.end(pipe); + + c.stdout.on('data', function (data) { stdout += data; - if (!opts.silent) - process.stdout.write(data); + if (!opts.silent) process.stdout.write(data); }); - c.stderr.on('data', function(data) { + c.stderr.on('data', function (data) { stderr += data; - if (!opts.silent) - process.stderr.write(data); + if (!opts.silent) process.stderr.write(data); }); return c; @@ -210,16 +224,22 @@ function execAsync(cmd, opts, callback) { //@ ``` //@ //@ Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous -//@ mode returns the object `{ code:..., stdout:... , stderr:... }`, containing the program's -//@ `stdout`, `stderr`, and its exit `code`. Otherwise returns the child process object, -//@ and the `callback` gets the arguments `(code, stdout, stderr)`. +//@ mode, this returns a ShellString (compatible with ShellJS v0.6.x, which returns an object +//@ of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process +//@ object, and the `callback` gets the arguments `(code, stdout, stderr)`. +//@ +//@ Not seeing the behavior you want? `exec()` runs everything through `sh` +//@ by default (or `cmd.exe` on Windows), which differs from `bash`. If you +//@ need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. //@ //@ **Note:** For long-lived processes, it's best to run `exec()` asynchronously as //@ the current synchronous implementation uses a lot of CPU. This should be getting //@ fixed soon. function _exec(command, options, callback) { - if (!command) - common.error('must specify command'); + options = options || {}; + if (!command) common.error('must specify command'); + + var pipe = common.readFromPipe(); // Callback is defined instead of options. if (typeof options === 'function') { @@ -238,10 +258,11 @@ function _exec(command, options, callback) { }, options); try { - if (options.async) - return execAsync(command, options, callback); - else - return execSync(command, options); + if (options.async) { + return execAsync(command, options, pipe, callback); + } else { + return execSync(command, options, pipe); + } } catch (e) { common.error('internal error'); } diff --git a/tools/eslint/node_modules/shelljs/src/find.js b/tools/eslint/node_modules/shelljs/src/find.js index c96fb2f7ad51e7..f96a51e7830a62 100644 --- a/tools/eslint/node_modules/shelljs/src/find.js +++ b/tools/eslint/node_modules/shelljs/src/find.js @@ -1,7 +1,10 @@ var fs = require('fs'); +var path = require('path'); var common = require('./common'); var _ls = require('./ls'); +common.register('find', _find, {}); + //@ //@ ### find(path [, path ...]) //@ ### find(path_array) @@ -18,30 +21,30 @@ var _ls = require('./ls'); //@ The main difference from `ls('-R', path)` is that the resulting file names //@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`. function _find(options, paths) { - if (!paths) + if (!paths) { common.error('no path specified'); - else if (typeof paths === 'object') - paths = paths; // assume array - else if (typeof paths === 'string') + } else if (typeof paths === 'string') { paths = [].slice.call(arguments, 1); + } var list = []; function pushFile(file) { - if (common.platform === 'win') + if (common.platform === 'win') { file = file.replace(/\\/g, '/'); + } list.push(file); } // why not simply do ls('-R', paths)? because the output wouldn't give the base dirs // to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory - paths.forEach(function(file) { + paths.forEach(function (file) { pushFile(file); if (fs.statSync(file).isDirectory()) { - _ls('-RA', file+'/*').forEach(function(subfile) { - pushFile(subfile); + _ls({ recursive: true, all: true }, file).forEach(function (subfile) { + pushFile(path.join(file, subfile)); }); } }); diff --git a/tools/eslint/node_modules/shelljs/src/grep.js b/tools/eslint/node_modules/shelljs/src/grep.js index 78008ce19e6d2f..30842bcb859441 100644 --- a/tools/eslint/node_modules/shelljs/src/grep.js +++ b/tools/eslint/node_modules/shelljs/src/grep.js @@ -1,12 +1,22 @@ var common = require('./common'); var fs = require('fs'); +common.register('grep', _grep, { + globStart: 2, // don't glob-expand the regex + canReceivePipe: true, + cmdOptions: { + 'v': 'inverse', + 'l': 'nameOnly', + }, +}); + //@ //@ ### grep([options,] regex_filter, file [, file ...]) //@ ### grep([options,] regex_filter, file_array) //@ Available options: //@ //@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. +//@ + `-l`: Print only filenames of matching files //@ //@ Examples: //@ @@ -16,37 +26,42 @@ var fs = require('fs'); //@ ``` //@ //@ Reads input string from given files and returns a string containing all lines of the -//@ file that match the given `regex_filter`. Wildcard `*` accepted. +//@ file that match the given `regex_filter`. function _grep(options, regex, files) { - options = common.parseOptions(options, { - 'v': 'inverse' - }); + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); - if (!files) - common.error('no paths given'); + if (!files && !pipe) common.error('no paths given', 2); - if (typeof files === 'string') - files = [].slice.call(arguments, 2); - // if it's array leave it as it is + files = [].slice.call(arguments, 2); - files = common.expand(files); + if (pipe) { + files.unshift('-'); + } - var grep = ''; - files.forEach(function(file) { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file, true); + var grep = []; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, 2, { continue: true }); return; } - var contents = fs.readFileSync(file, 'utf8'), - lines = contents.split(/\r*\n/); - lines.forEach(function(line) { - var matched = line.match(regex); - if ((options.inverse && !matched) || (!options.inverse && matched)) - grep += line + '\n'; - }); + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + var lines = contents.split(/\r*\n/); + if (options.nameOnly) { + if (contents.match(regex)) { + grep.push(file); + } + } else { + lines.forEach(function (line) { + var matched = line.match(regex); + if ((options.inverse && !matched) || (!options.inverse && matched)) { + grep.push(line); + } + }); + } }); - return common.ShellString(grep); + return grep.join('\n') + '\n'; } module.exports = _grep; diff --git a/tools/eslint/node_modules/shelljs/src/head.js b/tools/eslint/node_modules/shelljs/src/head.js new file mode 100644 index 00000000000000..13d5829775e8b2 --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/head.js @@ -0,0 +1,104 @@ +var common = require('./common'); +var fs = require('fs'); + +common.register('head', _head, { + canReceivePipe: true, + cmdOptions: { + 'n': 'numLines', + }, +}); + +// This reads n or more lines, or the entire file, whichever is less. +function readSomeLines(file, numLines) { + var BUF_LENGTH = 64 * 1024; + var buf = new Buffer(BUF_LENGTH); + var bytesRead = BUF_LENGTH; + var pos = 0; + var fdr = null; + + try { + fdr = fs.openSync(file, 'r'); + } catch (e) { + common.error('cannot read file: ' + file); + } + + var numLinesRead = 0; + var ret = ''; + while (bytesRead === BUF_LENGTH && numLinesRead < numLines) { + bytesRead = fs.readSync(fdr, buf, 0, BUF_LENGTH, pos); + var bufStr = buf.toString('utf8', 0, bytesRead); + numLinesRead += bufStr.split('\n').length - 1; + ret += bufStr; + pos += bytesRead; + } + + fs.closeSync(fdr); + return ret; +} +//@ +//@ ### head([{'-n': \},] file [, file ...]) +//@ ### head([{'-n': \},] file_array) +//@ Available options: +//@ +//@ + `-n `: Show the first `` lines of the files +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = head({'-n': 1}, 'file*.txt'); +//@ var str = head('file1', 'file2'); +//@ var str = head(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Read the start of a file. +function _head(options, files) { + var head = []; + var pipe = common.readFromPipe(); + + if (!files && !pipe) common.error('no paths given'); + + var idx = 1; + if (options.numLines === true) { + idx = 2; + options.numLines = Number(arguments[1]); + } else if (options.numLines === false) { + options.numLines = 10; + } + files = [].slice.call(arguments, idx); + + if (pipe) { + files.unshift('-'); + } + + var shouldAppendNewline = false; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, { continue: true }); + return; + } + + var contents; + if (file === '-') { + contents = pipe; + } else if (options.numLines < 0) { + contents = fs.readFileSync(file, 'utf8'); + } else { + contents = readSomeLines(file, options.numLines); + } + + var lines = contents.split('\n'); + var hasTrailingNewline = (lines[lines.length - 1] === ''); + if (hasTrailingNewline) { + lines.pop(); + } + shouldAppendNewline = (hasTrailingNewline || options.numLines < lines.length); + + head = head.concat(lines.slice(0, options.numLines)); + }); + + if (shouldAppendNewline) { + head.push(''); // to add a trailing newline once we join + } + return head.join('\n'); +} +module.exports = _head; diff --git a/tools/eslint/node_modules/shelljs/src/ln.js b/tools/eslint/node_modules/shelljs/src/ln.js index 878fda13e23d45..7393d9fcdca7d8 100644 --- a/tools/eslint/node_modules/shelljs/src/ln.js +++ b/tools/eslint/node_modules/shelljs/src/ln.js @@ -2,6 +2,13 @@ var fs = require('fs'); var path = require('path'); var common = require('./common'); +common.register('ln', _ln, { + cmdOptions: { + 's': 'symlink', + 'f': 'force', + }, +}); + //@ //@ ### ln([options,] source, dest) //@ Available options: @@ -18,11 +25,6 @@ var common = require('./common'); //@ //@ Links source to dest. Use -f to force the link, should dest already exist. function _ln(options, source, dest) { - options = common.parseOptions(options, { - 's': 'symlink', - 'f': 'force' - }); - if (!source || !dest) { common.error('Missing and/or '); } @@ -34,7 +36,7 @@ function _ln(options, source, dest) { if (fs.existsSync(dest)) { if (!options.force) { - common.error('Destination file exists', true); + common.error('Destination file exists', { continue: true }); } fs.unlinkSync(dest); @@ -45,19 +47,19 @@ function _ln(options, source, dest) { var linkType = isWindows ? 'file' : null; var resolvedSourcePath = isAbsolute ? sourcePath : path.resolve(process.cwd(), path.dirname(dest), source); if (!fs.existsSync(resolvedSourcePath)) { - common.error('Source file does not exist', true); + common.error('Source file does not exist', { continue: true }); } else if (isWindows && fs.statSync(resolvedSourcePath).isDirectory()) { - linkType = 'junction'; + linkType = 'junction'; } try { - fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath: source, dest, linkType); + fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath : source, dest, linkType); } catch (err) { common.error(err.message); } } else { if (!fs.existsSync(source)) { - common.error('Source file does not exist', true); + common.error('Source file does not exist', { continue: true }); } try { fs.linkSync(source, dest); @@ -65,5 +67,6 @@ function _ln(options, source, dest) { common.error(err.message); } } + return ''; } module.exports = _ln; diff --git a/tools/eslint/node_modules/shelljs/src/ls.js b/tools/eslint/node_modules/shelljs/src/ls.js index 6a54b3a8d8426a..7f25056cd34d7a 100644 --- a/tools/eslint/node_modules/shelljs/src/ls.js +++ b/tools/eslint/node_modules/shelljs/src/ls.js @@ -1,8 +1,19 @@ var path = require('path'); var fs = require('fs'); var common = require('./common'); -var _cd = require('./cd'); -var _pwd = require('./pwd'); +var glob = require('glob'); + +var globPatternRecursive = path.sep + '**' + path.sep + '*'; + +common.register('ls', _ls, { + cmdOptions: { + 'R': 'recursive', + 'A': 'all', + 'a': 'all_deprecated', + 'd': 'directory', + 'l': 'long', + }, +}); //@ //@ ### ls([options,] [path, ...]) @@ -28,14 +39,6 @@ var _pwd = require('./pwd'); //@ //@ Returns array of files in the given path, or in current directory if no path provided. function _ls(options, paths) { - options = common.parseOptions(options, { - 'R': 'recursive', - 'A': 'all', - 'a': 'all_deprecated', - 'd': 'directory', - 'l': 'long' - }); - if (options.all_deprecated) { // We won't support the -a option as it's hard to image why it's useful // (it includes '.' and '..' in addition to '.*' files) @@ -44,125 +47,75 @@ function _ls(options, paths) { options.all = true; } - if (!paths) + if (!paths) { paths = ['.']; - else if (typeof paths === 'object') - paths = paths; // assume array - else if (typeof paths === 'string') + } else { paths = [].slice.call(arguments, 1); + } var list = []; - // Conditionally pushes file to list - returns true if pushed, false otherwise - // (e.g. prevents hidden files to be included unless explicitly told so) - function pushFile(file, query) { - var name = file.name || file; - // hidden file? - if (path.basename(name)[0] === '.') { - // not explicitly asking for hidden files? - if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1)) - return false; + function pushFile(abs, relName, stat) { + if (process.platform === 'win32') { + relName = relName.replace(/\\/g, '/'); } - - if (common.platform === 'win') - name = name.replace(/\\/g, '/'); - - if (file.name) { - file.name = name; + if (options.long) { + stat = stat || fs.lstatSync(abs); + list.push(addLsAttributes(relName, stat)); } else { - file = name; + // list.push(path.relative(rel || '.', file)); + list.push(relName); } - list.push(file); - return true; } - paths.forEach(function(p) { - if (fs.existsSync(p)) { - var stats = ls_stat(p); - // Simple file? - if (stats.isFile()) { - if (options.long) { - pushFile(stats, p); - } else { - pushFile(p, p); - } - return; // continue - } + paths.forEach(function (p) { + var stat; - // Simple dir? - if (options.directory) { - pushFile(p, p); - return; - } else if (stats.isDirectory()) { - // Iterate over p contents - fs.readdirSync(p).forEach(function(file) { - var orig_file = file; - if (options.long) - file = ls_stat(path.join(p, file)); - if (!pushFile(file, p)) - return; + try { + stat = fs.lstatSync(p); + } catch (e) { + common.error('no such file or directory: ' + p, 2, { continue: true }); + return; + } - // Recursive? - if (options.recursive) { - var oldDir = _pwd(); - _cd('', p); - if (fs.statSync(orig_file).isDirectory()) - list = list.concat(_ls('-R'+(options.all?'A':''), orig_file+'/*')); - _cd('', oldDir); + // If the stat succeeded + if (stat.isDirectory() && !options.directory) { + if (options.recursive) { + // use glob, because it's simple + glob.sync(p + globPatternRecursive, { dot: options.all }) + .forEach(function (item) { + pushFile(item, path.relative(p, item)); + }); + } else if (options.all) { + // use fs.readdirSync, because it's fast + fs.readdirSync(p).forEach(function (item) { + pushFile(path.join(p, item), item); + }); + } else { + // use fs.readdirSync and then filter out secret files + fs.readdirSync(p).forEach(function (item) { + if (item[0] !== '.') { + pushFile(path.join(p, item), item); } }); - return; // continue } + } else { + pushFile(p, p, stat); } - - // p does not exist - possible wildcard present - - var basename = path.basename(p); - var dirname = path.dirname(p); - // Wildcard present on an existing dir? (e.g. '/tmp/*.js') - if (basename.search(/\*/) > -1 && fs.existsSync(dirname) && fs.statSync(dirname).isDirectory) { - // Escape special regular expression chars - var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1'); - // Translates wildcard into regex - regexp = '^' + regexp.replace(/\*/g, '.*') + '$'; - // Iterate over directory contents - fs.readdirSync(dirname).forEach(function(file) { - if (file.match(new RegExp(regexp))) { - var file_path = path.join(dirname, file); - file_path = options.long ? ls_stat(file_path) : file_path; - if (file_path.name) - file_path.name = path.normalize(file_path.name); - else - file_path = path.normalize(file_path); - if (!pushFile(file_path, basename)) - return; - - // Recursive? - if (options.recursive) { - var pp = dirname + '/' + file; - if (fs.lstatSync(pp).isDirectory()) - list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*')); - } // recursive - } // if file matches - }); // forEach - return; - } - - common.error('no such file or directory: ' + p, true); }); + // Add methods, to make this more compatible with ShellStrings return list; } -module.exports = _ls; - -function ls_stat(path) { - var stats = fs.statSync(path); +function addLsAttributes(pathName, stats) { // Note: this object will contain more information than .toString() returns - stats.name = path; - stats.toString = function() { + stats.name = pathName; + stats.toString = function () { // Return a string resembling unix's `ls -l` format return [this.mode, this.nlink, this.uid, this.gid, this.size, this.mtime, this.name].join(' '); }; return stats; } + +module.exports = _ls; diff --git a/tools/eslint/node_modules/shelljs/src/mkdir.js b/tools/eslint/node_modules/shelljs/src/mkdir.js index 8b4fd99075053a..f211bc89b3fbaf 100644 --- a/tools/eslint/node_modules/shelljs/src/mkdir.js +++ b/tools/eslint/node_modules/shelljs/src/mkdir.js @@ -2,10 +2,23 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('mkdir', _mkdir, { + cmdOptions: { + 'p': 'fullpath', + }, +}); + // Recursively creates 'dir' function mkdirSyncRecursive(dir) { var baseDir = path.dirname(dir); + // Prevents some potential problems arising from malformed UNCs or + // insufficient permissions. + /* istanbul ignore next */ + if (baseDir === dir) { + common.error('dirname() failed: [' + dir + ']'); + } + // Base dir exists, no recursion necessary if (fs.existsSync(baseDir)) { fs.mkdirSync(dir, parseInt('0777', 8)); @@ -35,34 +48,45 @@ function mkdirSyncRecursive(dir) { //@ //@ Creates directories. function _mkdir(options, dirs) { - options = common.parseOptions(options, { - 'p': 'fullpath' - }); - if (!dirs) - common.error('no paths given'); + if (!dirs) common.error('no paths given'); - if (typeof dirs === 'string') + if (typeof dirs === 'string') { dirs = [].slice.call(arguments, 1); + } // if it's array leave it as it is - dirs.forEach(function(dir) { - if (fs.existsSync(dir)) { - if (!options.fullpath) - common.error('path already exists: ' + dir, true); + dirs.forEach(function (dir) { + try { + fs.lstatSync(dir); + if (!options.fullpath) { + common.error('path already exists: ' + dir, { continue: true }); + } return; // skip dir + } catch (e) { + // do nothing } // Base dir does not exist, and no -p option given var baseDir = path.dirname(dir); if (!fs.existsSync(baseDir) && !options.fullpath) { - common.error('no such file or directory: ' + baseDir, true); + common.error('no such file or directory: ' + baseDir, { continue: true }); return; // skip dir } - if (options.fullpath) - mkdirSyncRecursive(dir); - else - fs.mkdirSync(dir, parseInt('0777', 8)); + try { + if (options.fullpath) { + mkdirSyncRecursive(dir); + } else { + fs.mkdirSync(dir, parseInt('0777', 8)); + } + } catch (e) { + if (e.code === 'EACCES') { + common.error('cannot create directory ' + dir + ': Permission denied'); + } else { + throw e; + } + } }); + return ''; } // mkdir module.exports = _mkdir; diff --git a/tools/eslint/node_modules/shelljs/src/mv.js b/tools/eslint/node_modules/shelljs/src/mv.js index 69cc03fe1ebe2b..c09bbbc76903c6 100644 --- a/tools/eslint/node_modules/shelljs/src/mv.js +++ b/tools/eslint/node_modules/shelljs/src/mv.js @@ -1,6 +1,15 @@ var fs = require('fs'); var path = require('path'); var common = require('./common'); +var cp = require('./cp'); +var rm = require('./rm'); + +common.register('mv', _mv, { + cmdOptions: { + 'f': '!no_force', + 'n': 'no_force', + }, +}); //@ //@ ### mv([options ,] source [, source ...], dest') @@ -18,13 +27,8 @@ var common = require('./common'); //@ mv(['file1', 'file2'], 'dir/'); // same as above //@ ``` //@ -//@ Moves files. The wildcard `*` is accepted. +//@ Moves files. function _mv(options, sources, dest) { - options = common.parseOptions(options, { - 'f': '!no_force', - 'n': 'no_force' - }); - // Get sources, dest if (arguments.length < 3) { common.error('missing and/or '); @@ -33,28 +37,26 @@ function _mv(options, sources, dest) { dest = arguments[arguments.length - 1]; } else if (typeof sources === 'string') { sources = [sources]; - } else if ('length' in sources) { - sources = sources; // no-op for array } else { common.error('invalid arguments'); } - sources = common.expand(sources); - - var exists = fs.existsSync(dest), - stats = exists && fs.statSync(dest); + var exists = fs.existsSync(dest); + var stats = exists && fs.statSync(dest); // Dest is not existing dir, but multiple sources given - if ((!exists || !stats.isDirectory()) && sources.length > 1) + if ((!exists || !stats.isDirectory()) && sources.length > 1) { common.error('dest is not a directory (too many sources)'); + } // Dest is an existing file, but no -f given - if (exists && stats.isFile() && options.no_force) + if (exists && stats.isFile() && options.no_force) { common.error('dest file already exists: ' + dest); + } - sources.forEach(function(src) { + sources.forEach(function (src) { if (!fs.existsSync(src)) { - common.error('no such file or directory: '+src, true); + common.error('no such file or directory: ' + src, { continue: true }); return; // skip file } @@ -63,20 +65,31 @@ function _mv(options, sources, dest) { // When copying to '/path/dir': // thisDest = '/path/dir/file1' var thisDest = dest; - if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) + if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) { thisDest = path.normalize(dest + '/' + path.basename(src)); + } if (fs.existsSync(thisDest) && options.no_force) { - common.error('dest file already exists: ' + thisDest, true); + common.error('dest file already exists: ' + thisDest, { continue: true }); return; // skip file } if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { - common.error('cannot move to self: '+src, true); + common.error('cannot move to self: ' + src, { continue: true }); return; // skip file } - fs.renameSync(src, thisDest); + try { + fs.renameSync(src, thisDest); + } catch (e) { + if (e.code === 'EXDEV') { // external partition + // if either of these fails, the appropriate error message will bubble + // up to the top level automatically + cp('-r', src, thisDest); + rm('-rf', src); + } + } }); // forEach(src) + return ''; } // mv module.exports = _mv; diff --git a/tools/eslint/node_modules/shelljs/src/popd.js b/tools/eslint/node_modules/shelljs/src/popd.js index 11ea24fa464a04..d9eac3f56d1303 100644 --- a/tools/eslint/node_modules/shelljs/src/popd.js +++ b/tools/eslint/node_modules/shelljs/src/popd.js @@ -1 +1 @@ -// see dirs.js \ No newline at end of file +// see dirs.js diff --git a/tools/eslint/node_modules/shelljs/src/pushd.js b/tools/eslint/node_modules/shelljs/src/pushd.js index 11ea24fa464a04..d9eac3f56d1303 100644 --- a/tools/eslint/node_modules/shelljs/src/pushd.js +++ b/tools/eslint/node_modules/shelljs/src/pushd.js @@ -1 +1 @@ -// see dirs.js \ No newline at end of file +// see dirs.js diff --git a/tools/eslint/node_modules/shelljs/src/pwd.js b/tools/eslint/node_modules/shelljs/src/pwd.js index 26cefe0a0454d0..38618518b549f6 100644 --- a/tools/eslint/node_modules/shelljs/src/pwd.js +++ b/tools/eslint/node_modules/shelljs/src/pwd.js @@ -1,11 +1,15 @@ var path = require('path'); var common = require('./common'); +common.register('pwd', _pwd, { + allowGlobbing: false, +}); + //@ //@ ### pwd() //@ Returns the current directory. function _pwd() { var pwd = path.resolve(process.cwd()); - return common.ShellString(pwd); + return pwd; } module.exports = _pwd; diff --git a/tools/eslint/node_modules/shelljs/src/rm.js b/tools/eslint/node_modules/shelljs/src/rm.js index cf2e95b6d816bc..d6e484a085cfee 100644 --- a/tools/eslint/node_modules/shelljs/src/rm.js +++ b/tools/eslint/node_modules/shelljs/src/rm.js @@ -1,6 +1,14 @@ var common = require('./common'); var fs = require('fs'); +common.register('rm', _rm, { + cmdOptions: { + 'f': 'force', + 'r': 'recursive', + 'R': 'recursive', + }, +}); + // Recursively removes 'dir' // Adapted from https://github.com/ryanmcgrath/wrench-js // @@ -15,32 +23,21 @@ function rmdirSyncRecursive(dir, force) { files = fs.readdirSync(dir); // Loop through and delete everything in the sub-tree after checking it - for(var i = 0; i < files.length; i++) { - var file = dir + "/" + files[i], - currFile = fs.lstatSync(file); + for (var i = 0; i < files.length; i++) { + var file = dir + '/' + files[i]; + var currFile = fs.lstatSync(file); - if(currFile.isDirectory()) { // Recursive function back to the beginning + if (currFile.isDirectory()) { // Recursive function back to the beginning rmdirSyncRecursive(file, force); - } - - else if(currFile.isSymbolicLink()) { // Unlink symlinks + } else { // Assume it's a file - perhaps a try/catch belongs here? if (force || isWriteable(file)) { try { common.unlinkSync(file); } catch (e) { - common.error('could not remove file (code '+e.code+'): ' + file, true); + common.error('could not remove file (code ' + e.code + '): ' + file, { continue: true }); } } } - - else // Assume it's a file - perhaps a try/catch belongs here? - if (force || isWriteable(file)) { - try { - common.unlinkSync(file); - } catch (e) { - common.error('could not remove file (code '+e.code+'): ' + file, true); - } - } } // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. @@ -53,13 +50,13 @@ function rmdirSyncRecursive(dir, force) { while (true) { try { result = fs.rmdirSync(dir); - if (fs.existsSync(dir)) throw { code: "EAGAIN" }; + if (fs.existsSync(dir)) throw { code: 'EAGAIN' }; break; - } catch(er) { + } catch (er) { // In addition to error codes, also check if the directory still exists and loop again if true - if (process.platform === "win32" && (er.code === "ENOTEMPTY" || er.code === "EBUSY" || er.code === "EPERM" || er.code === "EAGAIN")) { + if (process.platform === 'win32' && (er.code === 'ENOTEMPTY' || er.code === 'EBUSY' || er.code === 'EPERM' || er.code === 'EAGAIN')) { if (Date.now() - start > 1000) throw er; - } else if (er.code === "ENOENT") { + } else if (er.code === 'ENOENT') { // Directory did not exist, deletion was successful break; } else { @@ -67,8 +64,8 @@ function rmdirSyncRecursive(dir, force) { } } } - } catch(e) { - common.error('could not remove directory (code '+e.code+'): ' + dir, true); + } catch (e) { + common.error('could not remove directory (code ' + e.code + '): ' + dir, { continue: true }); } return result; @@ -81,7 +78,7 @@ function isWriteable(file) { try { var __fd = fs.openSync(file, 'a'); fs.closeSync(__fd); - } catch(e) { + } catch (e) { writePermission = false; } @@ -104,53 +101,45 @@ function isWriteable(file) { //@ rm(['some_file.txt', 'another_file.txt']); // same as above //@ ``` //@ -//@ Removes files. The wildcard `*` is accepted. +//@ Removes files. function _rm(options, files) { - options = common.parseOptions(options, { - 'f': 'force', - 'r': 'recursive', - 'R': 'recursive' - }); - if (!files) - common.error('no paths given'); - - if (typeof files === 'string') - files = [].slice.call(arguments, 1); - // if it's array leave it as it is + if (!files) common.error('no paths given'); - files = common.expand(files); + // Convert to array + files = [].slice.call(arguments, 1); - files.forEach(function(file) { - if (!fs.existsSync(file)) { + files.forEach(function (file) { + var stats; + try { + stats = fs.lstatSync(file); // test for existence + } catch (e) { // Path does not exist, no force flag given - if (!options.force) - common.error('no such file or directory: '+file, true); - + if (!options.force) { + common.error('no such file or directory: ' + file, { continue: true }); + } return; // skip file } // If here, path exists - - var stats = fs.lstatSync(file); if (stats.isFile() || stats.isSymbolicLink()) { - // Do not check for file writing permissions if (options.force) { common.unlinkSync(file); return; } - if (isWriteable(file)) + if (isWriteable(file)) { common.unlinkSync(file); - else - common.error('permission denied: '+file, true); + } else { + common.error('permission denied: ' + file, { continue: true }); + } return; } // simple file // Path is an existing directory, but no -r flag given if (stats.isDirectory() && !options.recursive) { - common.error('path is a directory', true); + common.error('path is a directory', { continue: true }); return; // skip path } @@ -159,5 +148,6 @@ function _rm(options, files) { rmdirSyncRecursive(file, options.force); } }); // forEach(file) + return ''; } // rm module.exports = _rm; diff --git a/tools/eslint/node_modules/shelljs/src/sed.js b/tools/eslint/node_modules/shelljs/src/sed.js index baa385ba1167d4..590ba74ffca2f7 100644 --- a/tools/eslint/node_modules/shelljs/src/sed.js +++ b/tools/eslint/node_modules/shelljs/src/sed.js @@ -1,6 +1,14 @@ var common = require('./common'); var fs = require('fs'); +common.register('sed', _sed, { + globStart: 3, // don't glob-expand regexes + canReceivePipe: true, + cmdOptions: { + 'i': 'inplace', + }, +}); + //@ //@ ### sed([options,] search_regex, replacement, file [, file ...]) //@ ### sed([options,] search_regex, replacement, file_array) @@ -18,47 +26,52 @@ var fs = require('fs'); //@ Reads an input string from `files` and performs a JavaScript `replace()` on the input //@ using the given search regex and replacement string or function. Returns the new string after replacement. function _sed(options, regex, replacement, files) { - options = common.parseOptions(options, { - 'i': 'inplace' - }); + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); - if (typeof replacement === 'string' || typeof replacement === 'function') - replacement = replacement; // no-op - else if (typeof replacement === 'number') - replacement = replacement.toString(); // fallback - else - common.error('invalid replacement string'); + if (typeof replacement !== 'string' && typeof replacement !== 'function') { + if (typeof replacement === 'number') { + replacement = replacement.toString(); // fallback + } else { + common.error('invalid replacement string'); + } + } // Convert all search strings to RegExp - if (typeof regex === 'string') + if (typeof regex === 'string') { regex = RegExp(regex); + } - if (!files) + if (!files && !pipe) { common.error('no files given'); + } - if (typeof files === 'string') - files = [].slice.call(arguments, 3); - // if it's array leave it as it is + files = [].slice.call(arguments, 3); - files = common.expand(files); + if (pipe) { + files.unshift('-'); + } var sed = []; - files.forEach(function(file) { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file, true); + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, 2, { continue: true }); return; } - var result = fs.readFileSync(file, 'utf8').split('\n').map(function (line) { + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + var lines = contents.split(/\r*\n/); + var result = lines.map(function (line) { return line.replace(regex, replacement); }).join('\n'); sed.push(result); - if (options.inplace) + if (options.inplace) { fs.writeFileSync(file, result, 'utf8'); + } }); - return common.ShellString(sed.join('\n')); + return sed.join('\n'); } module.exports = _sed; diff --git a/tools/eslint/node_modules/shelljs/src/set.js b/tools/eslint/node_modules/shelljs/src/set.js index 19e26d979d3f4b..3402cd6609b06f 100644 --- a/tools/eslint/node_modules/shelljs/src/set.js +++ b/tools/eslint/node_modules/shelljs/src/set.js @@ -1,11 +1,17 @@ var common = require('./common'); +common.register('set', _set, { + allowGlobbing: false, + wrapOutput: false, +}); + //@ //@ ### set(options) //@ Available options: //@ //@ + `+/-e`: exit upon error (`config.fatal`) //@ + `+/-v`: verbose: show all commands (`config.verbose`) +//@ + `+/-f`: disable filename expansion (globbing) //@ //@ Examples: //@ @@ -18,8 +24,7 @@ var common = require('./common'); function _set(options) { if (!options) { var args = [].slice.call(arguments, 0); - if (args.length < 2) - common.error('must provide an argument'); + if (args.length < 2) common.error('must provide an argument'); options = args[1]; } var negate = (options[0] === '+'); @@ -28,22 +33,23 @@ function _set(options) { } options = common.parseOptions(options, { 'e': 'fatal', - 'v': 'verbose' + 'v': 'verbose', + 'f': 'noglob' }); - var key; if (negate) { - for (key in options) + Object.keys(options).forEach(function (key) { options[key] = !options[key]; + }); } - for (key in options) { + Object.keys(options).forEach(function (key) { // Only change the global config if `negate` is false and the option is true // or if `negate` is true and the option is false (aka negate !== option) if (negate !== options[key]) { common.config[key] = options[key]; } - } + }); return; } module.exports = _set; diff --git a/tools/eslint/node_modules/shelljs/src/sort.js b/tools/eslint/node_modules/shelljs/src/sort.js new file mode 100644 index 00000000000000..041b037725121c --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/sort.js @@ -0,0 +1,91 @@ +var common = require('./common'); +var fs = require('fs'); + +common.register('sort', _sort, { + canReceivePipe: true, + cmdOptions: { + 'r': 'reverse', + 'n': 'numerical', + }, +}); + +// parse out the number prefix of a line +function parseNumber(str) { + var match = str.match(/^\s*(\d*)\s*(.*)$/); + return { num: Number(match[1]), value: match[2] }; +} + +// compare two strings case-insensitively, but examine case for strings that are +// case-insensitive equivalent +function unixCmp(a, b) { + var aLower = a.toLowerCase(); + var bLower = b.toLowerCase(); + return (aLower === bLower ? + -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does + aLower.localeCompare(bLower)); +} + +// compare two strings in the fashion that unix sort's -n option works +function numericalCmp(a, b) { + var objA = parseNumber(a); + var objB = parseNumber(b); + if (objA.hasOwnProperty('num') && objB.hasOwnProperty('num')) { + return ((objA.num !== objB.num) ? + (objA.num - objB.num) : + unixCmp(objA.value, objB.value)); + } else { + return unixCmp(objA.value, objB.value); + } +} + +//@ +//@ ### sort([options,] file [, file ...]) +//@ ### sort([options,] file_array) +//@ Available options: +//@ +//@ + `-r`: Reverse the result of comparisons +//@ + `-n`: Compare according to numerical value +//@ +//@ Examples: +//@ +//@ ```javascript +//@ sort('foo.txt', 'bar.txt'); +//@ sort('-r', 'foo.txt'); +//@ ``` +//@ +//@ Return the contents of the files, sorted line-by-line. Sorting multiple +//@ files mixes their content, just like unix sort does. +function _sort(options, files) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); + + if (!files && !pipe) common.error('no files given'); + + files = [].slice.call(arguments, 1); + + if (pipe) { + files.unshift('-'); + } + + var lines = []; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + // exit upon any sort of error + common.error('no such file or directory: ' + file); + } + + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + lines = lines.concat(contents.trimRight().split(/\r*\n/)); + }); + + var sorted; + sorted = lines.sort(options.numerical ? numericalCmp : unixCmp); + + if (options.reverse) { + sorted = sorted.reverse(); + } + + return sorted.join('\n') + '\n'; +} + +module.exports = _sort; diff --git a/tools/eslint/node_modules/shelljs/src/tail.js b/tools/eslint/node_modules/shelljs/src/tail.js new file mode 100644 index 00000000000000..7ece654b1ea3a0 --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/tail.js @@ -0,0 +1,72 @@ +var common = require('./common'); +var fs = require('fs'); + +common.register('tail', _tail, { + canReceivePipe: true, + cmdOptions: { + 'n': 'numLines', + }, +}); + +//@ +//@ ### tail([{'-n': \},] file [, file ...]) +//@ ### tail([{'-n': \},] file_array) +//@ Available options: +//@ +//@ + `-n `: Show the last `` lines of the files +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = tail({'-n': 1}, 'file*.txt'); +//@ var str = tail('file1', 'file2'); +//@ var str = tail(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Read the end of a file. +function _tail(options, files) { + var tail = []; + var pipe = common.readFromPipe(); + + if (!files && !pipe) common.error('no paths given'); + + var idx = 1; + if (options.numLines === true) { + idx = 2; + options.numLines = Number(arguments[1]); + } else if (options.numLines === false) { + options.numLines = 10; + } + options.numLines = -1 * Math.abs(options.numLines); + files = [].slice.call(arguments, idx); + + if (pipe) { + files.unshift('-'); + } + + var shouldAppendNewline = false; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, { continue: true }); + return; + } + + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + + var lines = contents.split('\n'); + if (lines[lines.length - 1] === '') { + lines.pop(); + shouldAppendNewline = true; + } else { + shouldAppendNewline = false; + } + + tail = tail.concat(lines.slice(options.numLines)); + }); + + if (shouldAppendNewline) { + tail.push(''); // to add a trailing newline once we join + } + return tail.join('\n'); +} +module.exports = _tail; diff --git a/tools/eslint/node_modules/shelljs/src/tempdir.js b/tools/eslint/node_modules/shelljs/src/tempdir.js index 79b949f0d4f15b..cfd56b3792e427 100644 --- a/tools/eslint/node_modules/shelljs/src/tempdir.js +++ b/tools/eslint/node_modules/shelljs/src/tempdir.js @@ -2,15 +2,18 @@ var common = require('./common'); var os = require('os'); var fs = require('fs'); +common.register('tempdir', _tempDir, { + allowGlobbing: false, + wrapOutput: false, +}); + // Returns false if 'dir' is not a writeable directory, 'dir' otherwise function writeableDir(dir) { - if (!dir || !fs.existsSync(dir)) - return false; + if (!dir || !fs.existsSync(dir)) return false; - if (!fs.statSync(dir).isDirectory()) - return false; + if (!fs.statSync(dir).isDirectory()) return false; - var testFile = dir+'/'+common.randomFileName(); + var testFile = dir + '/' + common.randomFileName(); try { fs.writeFileSync(testFile, ' '); common.unlinkSync(testFile); @@ -34,15 +37,14 @@ function writeableDir(dir) { //@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). function _tempDir() { var state = common.state; - if (state.tempDir) - return state.tempDir; // from cache + if (state.tempDir) return state.tempDir; // from cache state.tempDir = writeableDir(os.tmpdir && os.tmpdir()) || // node 0.10+ writeableDir(os.tmpDir && os.tmpDir()) || // node 0.8+ - writeableDir(process.env['TMPDIR']) || - writeableDir(process.env['TEMP']) || - writeableDir(process.env['TMP']) || - writeableDir(process.env['Wimp$ScrapDir']) || // RiscOS + writeableDir(process.env.TMPDIR) || + writeableDir(process.env.TEMP) || + writeableDir(process.env.TMP) || + writeableDir(process.env.Wimp$ScrapDir) || // RiscOS writeableDir('C:\\TEMP') || // Windows writeableDir('C:\\TMP') || // Windows writeableDir('\\TEMP') || // Windows diff --git a/tools/eslint/node_modules/shelljs/src/test.js b/tools/eslint/node_modules/shelljs/src/test.js index 068a1ce06ef4c9..3fb38aec43992d 100644 --- a/tools/eslint/node_modules/shelljs/src/test.js +++ b/tools/eslint/node_modules/shelljs/src/test.js @@ -1,6 +1,22 @@ var common = require('./common'); var fs = require('fs'); +common.register('test', _test, { + cmdOptions: { + 'b': 'block', + 'c': 'character', + 'd': 'directory', + 'e': 'exists', + 'f': 'file', + 'L': 'link', + 'p': 'pipe', + 'S': 'socket', + }, + wrapOutput: false, + allowGlobbing: false, +}); + + //@ //@ ### test(expression) //@ Available expression primaries: @@ -23,63 +39,43 @@ var fs = require('fs'); //@ //@ Evaluates expression using the available primaries and returns corresponding value. function _test(options, path) { - if (!path) - common.error('no path given'); - - // hack - only works with unary primaries - options = common.parseOptions(options, { - 'b': 'block', - 'c': 'character', - 'd': 'directory', - 'e': 'exists', - 'f': 'file', - 'L': 'link', - 'p': 'pipe', - 'S': 'socket' - }); + if (!path) common.error('no path given'); var canInterpret = false; - for (var key in options) + Object.keys(options).forEach(function (key) { if (options[key] === true) { canInterpret = true; - break; } + }); - if (!canInterpret) - common.error('could not interpret expression'); + if (!canInterpret) common.error('could not interpret expression'); if (options.link) { try { return fs.lstatSync(path).isSymbolicLink(); - } catch(e) { + } catch (e) { return false; } } - if (!fs.existsSync(path)) - return false; + if (!fs.existsSync(path)) return false; - if (options.exists) - return true; + if (options.exists) return true; var stats = fs.statSync(path); - if (options.block) - return stats.isBlockDevice(); + if (options.block) return stats.isBlockDevice(); + + if (options.character) return stats.isCharacterDevice(); - if (options.character) - return stats.isCharacterDevice(); + if (options.directory) return stats.isDirectory(); - if (options.directory) - return stats.isDirectory(); + if (options.file) return stats.isFile(); - if (options.file) - return stats.isFile(); + if (options.pipe) return stats.isFIFO(); - if (options.pipe) - return stats.isFIFO(); + if (options.socket) return stats.isSocket(); - if (options.socket) - return stats.isSocket(); + return false; // fallback } // test module.exports = _test; diff --git a/tools/eslint/node_modules/shelljs/src/to.js b/tools/eslint/node_modules/shelljs/src/to.js index 65d6d54af90837..99f194e687b460 100644 --- a/tools/eslint/node_modules/shelljs/src/to.js +++ b/tools/eslint/node_modules/shelljs/src/to.js @@ -2,8 +2,13 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('to', _to, { + pipeOnly: true, + wrapOutput: false, +}); + //@ -//@ ### 'string'.to(file) +//@ ### ShellString.prototype.to(file) //@ //@ Examples: //@ @@ -11,20 +16,21 @@ var path = require('path'); //@ cat('input.txt').to('output.txt'); //@ ``` //@ -//@ Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as -//@ those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ +//@ Analogous to the redirection operator `>` in Unix, but works with +//@ ShellStrings (such as those returned by `cat`, `grep`, etc). _Like Unix +//@ redirections, `to()` will overwrite any existing file!_ function _to(options, file) { - if (!file) - common.error('wrong arguments'); + if (!file) common.error('wrong arguments'); - if (!fs.existsSync( path.dirname(file) )) - common.error('no such file or directory: ' + path.dirname(file)); + if (!fs.existsSync(path.dirname(file))) { + common.error('no such file or directory: ' + path.dirname(file)); + } try { - fs.writeFileSync(file, this.toString(), 'utf8'); + fs.writeFileSync(file, this.stdout || this.toString(), 'utf8'); return this; - } catch(e) { - common.error('could not write to file (code '+e.code+'): '+file, true); + } catch (e) { + common.error('could not write to file (code ' + e.code + '): ' + file, { continue: true }); } } module.exports = _to; diff --git a/tools/eslint/node_modules/shelljs/src/toEnd.js b/tools/eslint/node_modules/shelljs/src/toEnd.js index bf29a6526d0f97..cf91c9401c4ced 100644 --- a/tools/eslint/node_modules/shelljs/src/toEnd.js +++ b/tools/eslint/node_modules/shelljs/src/toEnd.js @@ -2,8 +2,13 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('toEnd', _toEnd, { + pipeOnly: true, + wrapOutput: false, +}); + //@ -//@ ### 'string'.toEnd(file) +//@ ### ShellString.prototype.toEnd(file) //@ //@ Examples: //@ @@ -11,20 +16,20 @@ var path = require('path'); //@ cat('input.txt').toEnd('output.txt'); //@ ``` //@ -//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as -//@ those returned by `cat`, `grep`, etc). +//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with +//@ ShellStrings (such as those returned by `cat`, `grep`, etc). function _toEnd(options, file) { - if (!file) - common.error('wrong arguments'); + if (!file) common.error('wrong arguments'); - if (!fs.existsSync( path.dirname(file) )) - common.error('no such file or directory: ' + path.dirname(file)); + if (!fs.existsSync(path.dirname(file))) { + common.error('no such file or directory: ' + path.dirname(file)); + } try { - fs.appendFileSync(file, this.toString(), 'utf8'); + fs.appendFileSync(file, this.stdout || this.toString(), 'utf8'); return this; - } catch(e) { - common.error('could not append to file (code '+e.code+'): '+file, true); + } catch (e) { + common.error('could not append to file (code ' + e.code + '): ' + file, { continue: true }); } } module.exports = _toEnd; diff --git a/tools/eslint/node_modules/shelljs/src/touch.js b/tools/eslint/node_modules/shelljs/src/touch.js index bbc2c1968654ab..b672b2d25528b4 100644 --- a/tools/eslint/node_modules/shelljs/src/touch.js +++ b/tools/eslint/node_modules/shelljs/src/touch.js @@ -1,8 +1,19 @@ var common = require('./common'); var fs = require('fs'); +common.register('touch', _touch, { + cmdOptions: { + 'a': 'atime_only', + 'c': 'no_create', + 'd': 'date', + 'm': 'mtime_only', + 'r': 'reference', + }, +}); + //@ -//@ ### touch([options,] file) +//@ ### touch([options,] file [, file ...]) +//@ ### touch([options,] file_array) //@ Available options: //@ //@ + `-a`: Change only the access time @@ -23,28 +34,18 @@ var fs = require('fs'); //@ A FILE argument that does not exist is created empty, unless -c is supplied. //@ This is a partial implementation of *[touch(1)](http://linux.die.net/man/1/touch)*. function _touch(opts, files) { - opts = common.parseOptions(opts, { - 'a': 'atime_only', - 'c': 'no_create', - 'd': 'date', - 'm': 'mtime_only', - 'r': 'reference', - }); - if (!files) { - common.error('no paths given'); - } - - if (Array.isArray(files)) { - files.forEach(function(f) { - touchFile(opts, f); - }); + common.error('no files given'); } else if (typeof files === 'string') { - touchFile(opts, files); + files = [].slice.call(arguments, 1); } else { common.error('file arg should be a string file path or an Array of string file paths'); } + files.forEach(function (f) { + touchFile(opts, f); + }); + return ''; } function touchFile(opts, file) { diff --git a/tools/eslint/node_modules/shelljs/src/uniq.js b/tools/eslint/node_modules/shelljs/src/uniq.js new file mode 100644 index 00000000000000..8f5da00285a3a5 --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/uniq.js @@ -0,0 +1,80 @@ +var common = require('./common'); +var fs = require('fs'); + +// add c spaces to the left of str +function lpad(c, str) { + var res = '' + str; + if (res.length < c) { + res = Array((c - res.length) + 1).join(' ') + res; + } + return res; +} + +common.register('uniq', _uniq, { + canReceivePipe: true, + cmdOptions: { + 'i': 'ignoreCase', + 'c': 'count', + 'd': 'duplicates', + }, +}); + +//@ +//@ ### uniq([options,] [input, [output]]) +//@ Available options: +//@ +//@ + `-i`: Ignore case while comparing +//@ + `-c`: Prefix lines by the number of occurrences +//@ + `-d`: Only print duplicate lines, one for each group of identical lines +//@ +//@ Examples: +//@ +//@ ```javascript +//@ uniq('foo.txt'); +//@ uniq('-i', 'foo.txt'); +//@ uniq('-cd', 'foo.txt', 'bar.txt'); +//@ ``` +//@ +//@ Filter adjacent matching lines from input +function _uniq(options, input, output) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); + + if (!input && !pipe) common.error('no input given'); + + var lines = (input ? fs.readFileSync(input, 'utf8') : pipe). + trimRight(). + split(/\r*\n/); + + var compare = function (a, b) { + return options.ignoreCase ? + a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase()) : + a.localeCompare(b); + }; + var uniqed = lines.reduceRight(function (res, e) { + // Perform uniq -c on the input + if (res.length === 0) { + return [{ count: 1, ln: e }]; + } else if (compare(res[0].ln, e) === 0) { + return [{ count: res[0].count + 1, ln: e }].concat(res.slice(1)); + } else { + return [{ count: 1, ln: e }].concat(res); + } + }, []).filter(function (obj) { + // Do we want only duplicated objects? + return options.duplicates ? obj.count > 1 : true; + }).map(function (obj) { + // Are we tracking the counts of each line? + return (options.count ? (lpad(7, obj.count) + ' ') : '') + obj.ln; + }).join('\n') + '\n'; + + if (output) { + (new common.ShellString(uniqed)).to(output); + // if uniq writes to output, nothing is passed to the next command in the pipeline (if any) + return ''; + } else { + return uniqed; + } +} + +module.exports = _uniq; diff --git a/tools/eslint/node_modules/shelljs/src/which.js b/tools/eslint/node_modules/shelljs/src/which.js index d17634ee941d96..ef5d185eb0e462 100644 --- a/tools/eslint/node_modules/shelljs/src/which.js +++ b/tools/eslint/node_modules/shelljs/src/which.js @@ -2,23 +2,27 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('which', _which, { + allowGlobbing: false, +}); + // XP's system default value for PATHEXT system variable, just in case it's not // set on Windows. var XP_DEFAULT_PATHEXT = '.com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh'; // Cross-platform method for splitting environment PATH variables function splitPath(p) { - if (!p) - return []; + if (!p) return []; - if (common.platform === 'win') + if (common.platform === 'win') { return p.split(';'); - else + } else { return p.split(':'); + } } -function checkPath(path) { - return fs.existsSync(path) && !fs.statSync(path).isDirectory(); +function checkPath(pathName) { + return fs.existsSync(pathName) && !fs.statSync(pathName).isDirectory(); } //@ @@ -34,19 +38,17 @@ function checkPath(path) { //@ `PATHEXT` variable to append the extension if it's not already executable. //@ Returns string containing the absolute path to the command. function _which(options, cmd) { - if (!cmd) - common.error('must specify command'); + if (!cmd) common.error('must specify command'); - var pathEnv = process.env.path || process.env.Path || process.env.PATH, - pathArray = splitPath(pathEnv), - where = null; + var pathEnv = process.env.path || process.env.Path || process.env.PATH; + var pathArray = splitPath(pathEnv); + var where = null; // No relative/absolute paths provided? if (cmd.search(/\//) === -1) { // Search for command in PATH - pathArray.forEach(function(dir) { - if (where) - return; // already found it + pathArray.forEach(function (dir) { + if (where) return; // already found it var attempt = path.resolve(dir, cmd); @@ -88,11 +90,10 @@ function _which(options, cmd) { } // Command not found anywhere? - if (!checkPath(cmd) && !where) - return null; + if (!checkPath(cmd) && !where) return null; where = where || path.resolve(cmd); - return common.ShellString(where); + return where; } module.exports = _which; diff --git a/tools/eslint/node_modules/string-width/package.json b/tools/eslint/node_modules/string-width/package.json index 6fc310fca4230d..b0e9dfdea93cf7 100644 --- a/tools/eslint/node_modules/string-width/package.json +++ b/tools/eslint/node_modules/string-width/package.json @@ -38,8 +38,7 @@ "type": "range" }, "_requiredBy": [ - "/inquirer", - "/table" + "/inquirer" ], "_resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", "_shasum": "118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3", diff --git a/tools/eslint/node_modules/strip-ansi/package.json b/tools/eslint/node_modules/strip-ansi/package.json index dced2726e06f26..323a21ebb41a8c 100644 --- a/tools/eslint/node_modules/strip-ansi/package.json +++ b/tools/eslint/node_modules/strip-ansi/package.json @@ -40,7 +40,8 @@ "_requiredBy": [ "/chalk", "/inquirer", - "/string-width" + "/string-width", + "/table/string-width" ], "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "_shasum": "6a385fb8853d952d5ff05d0e8aaf94278dc63dcf", diff --git a/tools/eslint/node_modules/strip-json-comments/cli.js b/tools/eslint/node_modules/strip-json-comments/cli.js deleted file mode 100755 index aec5aa20e4a073..00000000000000 --- a/tools/eslint/node_modules/strip-json-comments/cli.js +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env node -'use strict'; -var fs = require('fs'); -var strip = require('./strip-json-comments'); -var input = process.argv[2]; - - -function getStdin(cb) { - var ret = ''; - - process.stdin.setEncoding('utf8'); - - process.stdin.on('data', function (data) { - ret += data; - }); - - process.stdin.on('end', function () { - cb(ret); - }); -} - -if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) { - console.log('strip-json-comments input-file > output-file'); - console.log('or'); - console.log('strip-json-comments < input-file > output-file'); - return; -} - -if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) { - console.log(require('./package').version); - return; -} - -if (input) { - process.stdout.write(strip(fs.readFileSync(input, 'utf8'))); - return; -} - -getStdin(function (data) { - process.stdout.write(strip(data)); -}); diff --git a/tools/eslint/node_modules/strip-json-comments/index.js b/tools/eslint/node_modules/strip-json-comments/index.js new file mode 100644 index 00000000000000..4e6576e6d3c388 --- /dev/null +++ b/tools/eslint/node_modules/strip-json-comments/index.js @@ -0,0 +1,70 @@ +'use strict'; +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +module.exports = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; diff --git a/tools/eslint/node_modules/strip-json-comments/package.json b/tools/eslint/node_modules/strip-json-comments/package.json index de43cb650fbdcb..6bbd9d717fbf7b 100644 --- a/tools/eslint/node_modules/strip-json-comments/package.json +++ b/tools/eslint/node_modules/strip-json-comments/package.json @@ -2,75 +2,76 @@ "_args": [ [ { - "raw": "strip-json-comments@~1.0.1", + "raw": "strip-json-comments@~2.0.1", "scope": null, "escapedName": "strip-json-comments", "name": "strip-json-comments", - "rawSpec": "~1.0.1", - "spec": ">=1.0.1 <1.1.0", + "rawSpec": "~2.0.1", + "spec": ">=2.0.1 <2.1.0", "type": "range" }, "/Users/trott/io.js/tools/node_modules/eslint" ] ], - "_from": "strip-json-comments@>=1.0.1 <1.1.0", - "_id": "strip-json-comments@1.0.4", + "_from": "strip-json-comments@>=2.0.1 <2.1.0", + "_id": "strip-json-comments@2.0.1", "_inCache": true, "_location": "/strip-json-comments", - "_nodeVersion": "0.12.5", + "_nodeVersion": "4.2.4", + "_npmOperationalInternal": { + "host": "packages-9-west.internal.npmjs.com", + "tmp": "tmp/strip-json-comments-2.0.1.tgz_1455006605207_0.8280157081317157" + }, "_npmUser": { "name": "sindresorhus", "email": "sindresorhus@gmail.com" }, - "_npmVersion": "2.11.2", + "_npmVersion": "3.7.2", "_phantomChildren": {}, "_requested": { - "raw": "strip-json-comments@~1.0.1", + "raw": "strip-json-comments@~2.0.1", "scope": null, "escapedName": "strip-json-comments", "name": "strip-json-comments", - "rawSpec": "~1.0.1", - "spec": ">=1.0.1 <1.1.0", + "rawSpec": "~2.0.1", + "spec": ">=2.0.1 <2.1.0", "type": "range" }, "_requiredBy": [ "/eslint" ], - "_resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", - "_shasum": "1e15fbcac97d3ee99bf2d73b4c656b082bbafb91", + "_resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "_shasum": "3c531942e908c2697c0ec344858c286c7ca0a60a", "_shrinkwrap": null, - "_spec": "strip-json-comments@~1.0.1", + "_spec": "strip-json-comments@~2.0.1", "_where": "/Users/trott/io.js/tools/node_modules/eslint", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, - "bin": { - "strip-json-comments": "cli.js" - }, "bugs": { "url": "https://github.com/sindresorhus/strip-json-comments/issues" }, "dependencies": {}, "description": "Strip comments from JSON. Lets you use comments in your JSON files!", "devDependencies": { - "mocha": "*" + "ava": "*", + "xo": "*" }, "directories": {}, "dist": { - "shasum": "1e15fbcac97d3ee99bf2d73b4c656b082bbafb91", - "tarball": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz" + "shasum": "3c531942e908c2697c0ec344858c286c7ca0a60a", + "tarball": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz" }, "engines": { - "node": ">=0.8.0" + "node": ">=0.10.0" }, "files": [ - "cli.js", - "strip-json-comments.js" + "index.js" ], - "gitHead": "f58348696368583cc5bb18525fe31eacc9bd00e1", - "homepage": "https://github.com/sindresorhus/strip-json-comments", + "gitHead": "1aef99eaa70d07981156e8aaa722e750c3b4eaf9", + "homepage": "https://github.com/sindresorhus/strip-json-comments#readme", "keywords": [ "json", "strip", @@ -86,12 +87,9 @@ "settings", "util", "env", - "environment", - "cli", - "bin" + "environment" ], "license": "MIT", - "main": "strip-json-comments", "maintainers": [ { "name": "sindresorhus", @@ -106,7 +104,7 @@ "url": "git+https://github.com/sindresorhus/strip-json-comments.git" }, "scripts": { - "test": "mocha --ui tdd" + "test": "xo && ava" }, - "version": "1.0.4" + "version": "2.0.1" } diff --git a/tools/eslint/node_modules/strip-json-comments/readme.md b/tools/eslint/node_modules/strip-json-comments/readme.md index 63ce165b23809f..0ee58dfe3a2e9b 100644 --- a/tools/eslint/node_modules/strip-json-comments/readme.md +++ b/tools/eslint/node_modules/strip-json-comments/readme.md @@ -11,34 +11,23 @@ This is now possible: } ``` -It will remove single-line comments `//` and multi-line comments `/**/`. +It will replace single-line comments `//` and multi-line comments `/**/` with whitespace. This allows JSON error positions to remain as close as possible to the original source. Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin. -- - -*There's also [`json-comments`](https://npmjs.org/package/json-comments), but it's only for Node.js, inefficient, bloated as it also minifies, and comes with a `require` hook, which is :(* - ## Install -```sh -$ npm install --save strip-json-comments -``` - -```sh -$ bower install --save strip-json-comments ``` - -```sh -$ component install sindresorhus/strip-json-comments +$ npm install --save strip-json-comments ``` ## Usage ```js -var json = '{/*rainbows*/"unicorn":"cake"}'; +const json = '{/*rainbows*/"unicorn":"cake"}'; + JSON.parse(stripJsonComments(json)); //=> {unicorn: 'cake'} ``` @@ -46,7 +35,7 @@ JSON.parse(stripJsonComments(json)); ## API -### stripJsonComments(input) +### stripJsonComments(input, [options]) #### input @@ -54,25 +43,20 @@ Type: `string` Accepts a string with JSON and returns a string without comments. +#### options -## CLI +##### whitespace -```sh -$ npm install --global strip-json-comments -``` +Type: `boolean` +Default: `true` -```sh -$ strip-json-comments --help - -strip-json-comments input-file > output-file -# or -strip-json-comments < input-file > output-file -``` +Replace comments with whitespace instead of stripping them entirely. ## Related -- [`strip-css-comments`](https://github.com/sindresorhus/strip-css-comments) +- [strip-json-comments-cli](https://github.com/sindresorhus/strip-json-comments-cli) - CLI for this module +- [strip-css-comments](https://github.com/sindresorhus/strip-css-comments) - Strip comments from CSS ## License diff --git a/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js b/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js deleted file mode 100644 index eb77ce7456b8e5..00000000000000 --- a/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js +++ /dev/null @@ -1,73 +0,0 @@ -/*! - strip-json-comments - Strip comments from JSON. Lets you use comments in your JSON files! - https://github.com/sindresorhus/strip-json-comments - by Sindre Sorhus - MIT License -*/ -(function () { - 'use strict'; - - var singleComment = 1; - var multiComment = 2; - - function stripJsonComments(str) { - var currentChar; - var nextChar; - var insideString = false; - var insideComment = false; - var ret = ''; - - for (var i = 0; i < str.length; i++) { - currentChar = str[i]; - nextChar = str[i + 1]; - - if (!insideComment && currentChar === '"') { - var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; - if (!insideComment && !escaped && currentChar === '"') { - insideString = !insideString; - } - } - - if (insideString) { - ret += currentChar; - continue; - } - - if (!insideComment && currentChar + nextChar === '//') { - insideComment = singleComment; - i++; - } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { - insideComment = false; - i++; - ret += currentChar; - ret += nextChar; - continue; - } else if (insideComment === singleComment && currentChar === '\n') { - insideComment = false; - } else if (!insideComment && currentChar + nextChar === '/*') { - insideComment = multiComment; - i++; - continue; - } else if (insideComment === multiComment && currentChar + nextChar === '*/') { - insideComment = false; - i++; - continue; - } - - if (insideComment) { - continue; - } - - ret += currentChar; - } - - return ret; - } - - if (typeof module !== 'undefined' && module.exports) { - module.exports = stripJsonComments; - } else { - window.stripJsonComments = stripJsonComments; - } -})(); diff --git a/tools/eslint/node_modules/table/dist/alignString.js.map b/tools/eslint/node_modules/table/dist/alignString.js.map deleted file mode 100644 index 9d6e8b84e39b13..00000000000000 --- a/tools/eslint/node_modules/table/dist/alignString.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["alignString.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;;;AAEA,IAAI,oBAAJ;IACI,kBADJ;IAEI,mBAFJ;IAGI,mBAHJ;;AAKA,aAAa,CACT,MADS,EAET,OAFS,EAGT,QAHS,CAAb;;;;;;;AAWA,YAAY,mBAAC,OAAD,EAAU,KAAV,EAAoB;AAC5B,WAAO,UAAU,sBAAS,GAAT,EAAc,KAAd,CAAjB;AACH,CAFD;;;;;;;AASA,aAAa,oBAAC,OAAD,EAAU,KAAV,EAAoB;AAC7B,WAAO,sBAAS,GAAT,EAAc,KAAd,IAAuB,OAA9B;AACH,CAFD;;;;;;;AASA,cAAc,qBAAC,OAAD,EAAU,KAAV,EAAoB;AAC9B,QAAI,kBAAJ;;AAEA,gBAAY,QAAQ,CAApB;;AAEA,QAAI,YAAY,CAAZ,KAAkB,CAAtB,EAAyB;AACrB,eAAO,sBAAS,GAAT,EAAc,SAAd,IAA2B,OAA3B,GAAqC,sBAAS,GAAT,EAAc,SAAd,CAA5C;AACH,KAFD,MAEO;AACH,oBAAY,qBAAQ,SAAR,CAAZ;;AAEA,eAAO,sBAAS,GAAT,EAAc,SAAd,IAA2B,OAA3B,GAAqC,sBAAS,GAAT,EAAc,YAAY,CAA1B,CAA5C;AACH;AACJ,CAZD;;;;;;;;;;;;kBAuBe,UAAC,OAAD,EAAU,cAAV,EAA0B,SAA1B,EAAwC;AACnD,QAAI,uBAAJ;QACI,qBADJ;;AAGA,QAAI,CAAC,wBAAW,OAAX,CAAL,EAA0B;AACtB,cAAM,IAAI,KAAJ,CAAU,2CAAV,CAAN;AACH;;AAED,QAAI,CAAC,wBAAW,cAAX,CAAL,EAAiC;AAC7B,cAAM,IAAI,KAAJ,CAAU,mDAAV,CAAN;AACH;;AAED,mBAAe,2BAAY,OAAZ,CAAf;;AAEA,QAAI,eAAe,cAAnB,EAAmC;;;AAG/B,cAAM,IAAI,KAAJ,CAAU,2EAAV,CAAN;AACH;;AAED,QAAI,CAAC,wBAAW,SAAX,CAAL,EAA4B;AACxB,cAAM,IAAI,KAAJ,CAAU,6CAAV,CAAN;AACH;;AAED,QAAI,WAAW,OAAX,CAAmB,SAAnB,MAAkC,CAAC,CAAvC,EAA0C;AACtC,cAAM,IAAI,KAAJ,CAAU,4FAAV,CAAN;AACH;;AAED,QAAI,iBAAiB,CAArB,EAAwB;AACpB,eAAO,sBAAS,GAAT,EAAc,cAAd,CAAP;AACH;;AAED,qBAAiB,iBAAiB,YAAlC;;AAEA,QAAI,cAAc,MAAlB,EAA0B;AACtB,eAAO,UAAU,OAAV,EAAmB,cAAnB,CAAP;AACH;;AAED,QAAI,cAAc,OAAlB,EAA2B;AACvB,eAAO,WAAW,OAAX,EAAoB,cAApB,CAAP;AACH;;AAED,WAAO,YAAY,OAAZ,EAAqB,cAArB,CAAP;AACH,C","file":"alignString.js","sourcesContent":["import _ from 'lodash';\nimport stringWidth from 'string-width';\n\nlet alignCenter,\n alignLeft,\n alignRight,\n alignments;\n\nalignments = [\n 'left',\n 'right',\n 'center'\n];\n\n/**\n * @param {string} subject\n * @param {number} width\n * @returns {string}\n */\nalignLeft = (subject, width) => {\n return subject + _.repeat(' ', width);\n};\n\n/**\n * @param {string} subject\n * @param {number} width\n * @returns {string}\n */\nalignRight = (subject, width) => {\n return _.repeat(' ', width) + subject;\n};\n\n/**\n * @param {string} subject\n * @param {number} width\n * @returns {string}\n */\nalignCenter = (subject, width) => {\n let halfWidth;\n\n halfWidth = width / 2;\n\n if (halfWidth % 2 === 0) {\n return _.repeat(' ', halfWidth) + subject + _.repeat(' ', halfWidth);\n } else {\n halfWidth = _.floor(halfWidth);\n\n return _.repeat(' ', halfWidth) + subject + _.repeat(' ', halfWidth + 1);\n }\n};\n\n/**\n * Pads a string to the left and/or right to position the subject\n * text in a desired alignment within a container.\n *\n * @param {string} subject\n * @param {number} containerWidth\n * @param {string} alignment One of the valid options (left, right, center).\n * @returns {string}\n */\nexport default (subject, containerWidth, alignment) => {\n let availableWidth,\n subjectWidth;\n\n if (!_.isString(subject)) {\n throw new Error('Subject parameter value must be a string.');\n }\n\n if (!_.isNumber(containerWidth)) {\n throw new Error('Container width parameter value must be a number.');\n }\n\n subjectWidth = stringWidth(subject);\n\n if (subjectWidth > containerWidth) {\n // console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);\n\n throw new Error('Subject parameter value width cannot be greater than the container width.');\n }\n\n if (!_.isString(alignment)) {\n throw new Error('Alignment parameter value must be a string.');\n }\n\n if (alignments.indexOf(alignment) === -1) {\n throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');\n }\n\n if (subjectWidth === 0) {\n return _.repeat(' ', containerWidth);\n }\n\n availableWidth = containerWidth - subjectWidth;\n\n if (alignment === 'left') {\n return alignLeft(subject, availableWidth);\n }\n\n if (alignment === 'right') {\n return alignRight(subject, availableWidth);\n }\n\n return alignCenter(subject, availableWidth);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/alignTableData.js.map b/tools/eslint/node_modules/table/dist/alignTableData.js.map deleted file mode 100644 index 45aea74993674f..00000000000000 --- a/tools/eslint/node_modules/table/dist/alignTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["alignTableData.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;kBAOe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,UAAC,KAAD,EAAQ,MAAR,EAAmB;AACnC,gBAAI,eAAJ;;AAEA,qBAAS,OAAO,OAAP,CAAe,MAAf,CAAT;;AAEA,gBAAI,2BAAY,KAAZ,MAAuB,OAAO,KAAlC,EAAyC;AACrC,uBAAO,KAAP;AACH,aAFD,MAEO;AACH,uBAAO,2BAAY,KAAZ,EAAmB,OAAO,KAA1B,EAAiC,OAAO,SAAxC,CAAP;AACH;AACJ,SAVM,CAAP;AAWH,KAZM,CAAP;AAaH,C","file":"alignTableData.js","sourcesContent":["import _ from 'lodash';\nimport alignString from './alignString';\nimport stringWidth from 'string-width';\n\n/**\n * @param {table~row[]} rows\n * @param {Object} config\n * @return {table~row[]}\n */\nexport default (rows, config) => {\n return _.map(rows, (cells) => {\n return _.map(cells, (value, index1) => {\n let column;\n\n column = config.columns[index1];\n\n if (stringWidth(value) === column.width) {\n return value;\n } else {\n return alignString(value, column.width, column.alignment);\n }\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateCellHeight.js b/tools/eslint/node_modules/table/dist/calculateCellHeight.js index f90110adb11d51..b5ec6998d58d0e 100644 --- a/tools/eslint/node_modules/table/dist/calculateCellHeight.js +++ b/tools/eslint/node_modules/table/dist/calculateCellHeight.js @@ -25,7 +25,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {number} */ exports.default = function (value, columnWidth) { - let useWrapWord = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; + let useWrapWord = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!_lodash2.default.isString(value)) { throw new Error('Value must be a string.'); diff --git a/tools/eslint/node_modules/table/dist/calculateCellHeight.js.map b/tools/eslint/node_modules/table/dist/calculateCellHeight.js.map deleted file mode 100644 index 184fdbf02cd47c..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateCellHeight.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateCellHeight.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,KAAD,EAAQ,WAAR,EAA6C;AAAA,QAAxB,WAAwB,yDAAV,KAAU;;AACxD,QAAI,CAAC,wBAAW,KAAX,CAAL,EAAwB;AACpB,cAAM,IAAI,KAAJ,CAAU,yBAAV,CAAN;AACH;;AAED,QAAI,CAAC,yBAAY,WAAZ,CAAL,EAA+B;AAC3B,cAAM,IAAI,KAAJ,CAAU,kCAAV,CAAN;AACH;;AAED,QAAI,cAAc,CAAlB,EAAqB;AACjB,cAAM,IAAI,KAAJ,CAAU,sCAAV,CAAN;AACH;;AAED,QAAI,WAAJ,EAAiB;AACb,eAAO,wBAAS,KAAT,EAAgB,WAAhB,EAA6B,MAApC;AACH;;AAED,WAAO,oBAAO,2BAAY,KAAZ,IAAqB,WAA5B,CAAP;AACH,C","file":"calculateCellHeight.js","sourcesContent":["import _ from 'lodash';\nimport stringWidth from 'string-width';\nimport wrapWord from './wrapWord';\n\n/**\n * @param {string} value\n * @param {number} columnWidth\n * @param {boolean} useWrapWord\n * @returns {number}\n */\nexport default (value, columnWidth, useWrapWord = false) => {\n if (!_.isString(value)) {\n throw new Error('Value must be a string.');\n }\n\n if (!_.isInteger(columnWidth)) {\n throw new Error('Column width must be an integer.');\n }\n\n if (columnWidth < 1) {\n throw new Error('Column width must be greater than 0.');\n }\n\n if (useWrapWord) {\n return wrapWord(value, columnWidth).length;\n }\n\n return _.ceil(stringWidth(value) / columnWidth);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateCellWidthIndex.js.map b/tools/eslint/node_modules/table/dist/calculateCellWidthIndex.js.map deleted file mode 100644 index 112a04e8ee6c35..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateCellWidthIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateCellWidthIndex.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,KAAD,EAAW;AACtB,WAAO,mBAAM,KAAN,EAAa,UAAC,KAAD,EAAW;AAC3B,eAAO,2BAAY,KAAZ,CAAP;AACH,KAFM,CAAP;AAGH,C","file":"calculateCellWidthIndex.js","sourcesContent":["import _ from 'lodash';\nimport stringWidth from 'string-width';\n\n/**\n * Calculates width of each cell contents.\n *\n * @param {string[]} cells\n * @return {number[]}\n */\nexport default (cells) => {\n return _.map(cells, (value) => {\n return stringWidth(value);\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateMaximumColumnWidthIndex.js.map b/tools/eslint/node_modules/table/dist/calculateMaximumColumnWidthIndex.js.map deleted file mode 100644 index ea1e5e9ce49b3e..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateMaximumColumnWidthIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateMaximumColumnWidthIndex.js"],"names":[],"mappings":";;;;;;;;;;;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,IAAD,EAAU;AACrB,QAAI,gBAAJ;;AAEA,QAAI,CAAC,KAAK,CAAL,CAAL,EAAc;AACV,cAAM,IAAI,KAAJ,CAAU,qCAAV,CAAN;AACH;;AAED,cAAU,oBAAO,MAAM,KAAK,CAAL,EAAQ,MAAd,CAAP,EAA8B,CAA9B,CAAV;;AAEA,2BAAU,IAAV,EAAgB,UAAC,GAAD,EAAS;AACrB,YAAI,yBAAJ;;AAEA,2BAAmB,uCAAwB,GAAxB,CAAnB;;AAEA,+BAAU,gBAAV,EAA4B,UAAC,UAAD,EAAa,MAAb,EAAwB;AAChD,gBAAI,QAAQ,MAAR,IAAkB,UAAtB,EAAkC;AAC9B,wBAAQ,MAAR,IAAkB,UAAlB;AACH;AACJ,SAJD;AAKH,KAVD;;AAYA,WAAO,OAAP;AACH,C","file":"calculateMaximumColumnWidthIndex.js","sourcesContent":["import _ from 'lodash';\nimport calculateCellWidthIndex from './calculateCellWidthIndex';\n\n/**\n * Produces an array of values that describe the largest value length (width) in every column.\n *\n * @param {Array[]} rows\n * @return {number[]}\n */\nexport default (rows) => {\n let columns;\n\n if (!rows[0]) {\n throw new Error('Dataset must have at least one row.');\n }\n\n columns = _.fill(Array(rows[0].length), 0);\n\n _.forEach(rows, (row) => {\n let columnWidthIndex;\n\n columnWidthIndex = calculateCellWidthIndex(row);\n\n _.forEach(columnWidthIndex, (valueWidth, index0) => {\n if (columns[index0] < valueWidth) {\n columns[index0] = valueWidth;\n }\n });\n });\n\n return columns;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateRowHeightIndex.js.map b/tools/eslint/node_modules/table/dist/calculateRowHeightIndex.js.map deleted file mode 100644 index 9816a50a9a99a9..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateRowHeightIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateRowHeightIndex.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA;;;;;;;;;;;;;;kBASe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,QAAI,qBAAJ;QACI,mBADJ;;AAGA,iBAAa,KAAK,CAAL,EAAQ,MAArB;;AAEA,mBAAe,EAAf;;AAEA,2BAAU,IAAV,EAAgB,UAAC,KAAD,EAAW;AACvB,YAAI,wBAAJ;;AAEA,0BAAkB,oBAAO,MAAM,UAAN,CAAP,EAA0B,CAA1B,CAAlB;;AAEA,+BAAU,KAAV,EAAiB,UAAC,KAAD,EAAQ,MAAR,EAAmB;AAChC,gBAAI,CAAC,wBAAW,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAlC,CAAL,EAA+C;AAC3C,sBAAM,IAAI,KAAJ,CAAU,uCAAV,CAAN;AACH;;AAED,gBAAI,CAAC,yBAAY,OAAO,OAAP,CAAe,MAAf,EAAuB,QAAnC,CAAL,EAAmD;AAC/C,sBAAM,IAAI,KAAJ,CAAU,2CAAV,CAAN;AACH;;AAED,4BAAgB,MAAhB,IAA0B,mCAAoB,KAApB,EAA2B,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAlD,EAAyD,OAAO,OAAP,CAAe,MAAf,EAAuB,QAAhF,CAA1B;AACH,SAVD;;AAYA,qBAAa,IAAb,CAAkB,mBAAM,eAAN,CAAlB;AACH,KAlBD;;AAoBA,WAAO,YAAP;AACH,C","file":"calculateRowHeightIndex.js","sourcesContent":["import _ from 'lodash';\nimport calculateCellHeight from './calculateCellHeight';\n\n/**\n * Calculates the vertical row span index.\n *\n * @param {Array[]} rows\n * @param {Object} config\n * @return {number[]}\n */\nexport default (rows, config) => {\n let rowSpanIndex,\n tableWidth;\n\n tableWidth = rows[0].length;\n\n rowSpanIndex = [];\n\n _.forEach(rows, (cells) => {\n let cellHeightIndex;\n\n cellHeightIndex = _.fill(Array(tableWidth), 1);\n\n _.forEach(cells, (value, index1) => {\n if (!_.isNumber(config.columns[index1].width)) {\n throw new Error('column[index].width must be a number.');\n }\n\n if (!_.isBoolean(config.columns[index1].wrapWord)) {\n throw new Error('column[index].wrapWord must be a boolean.');\n }\n\n cellHeightIndex[index1] = calculateCellHeight(value, config.columns[index1].width, config.columns[index1].wrapWord);\n });\n\n rowSpanIndex.push(_.max(cellHeightIndex));\n });\n\n return rowSpanIndex;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/createStream.js b/tools/eslint/node_modules/table/dist/createStream.js index 1175ec66538da7..f9c3df5035be45 100644 --- a/tools/eslint/node_modules/table/dist/createStream.js +++ b/tools/eslint/node_modules/table/dist/createStream.js @@ -123,7 +123,7 @@ const append = (row, columnWidthIndex, config) => { */ exports.default = function () { - let userConfig = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; const config = (0, _makeStreamConfig2.default)(userConfig); diff --git a/tools/eslint/node_modules/table/dist/createStream.js.map b/tools/eslint/node_modules/table/dist/createStream.js.map deleted file mode 100644 index b3a2563cda052a..00000000000000 --- a/tools/eslint/node_modules/table/dist/createStream.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["createStream.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;;;AACA;;;;AACA;;AAOA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;;;AAEA,IAAI,eAAJ;IACI,eADJ;IAEI,oBAFJ;;;;;;;;AAUA,SAAS,gBAAC,GAAD,EAAM,gBAAN,EAAwB,MAAxB,EAAmC;AACxC,QAAI,aAAJ;QACI,eADJ;QAEI,aAFJ;;AAIA,WAAO,YAAY,CAAC,GAAD,CAAZ,EAAmB,MAAnB,CAAP;;AAEA,WAAO,mBAAM,IAAN,EAAY,UAAC,UAAD,EAAgB;AAC/B,eAAO,uBAAQ,UAAR,EAAoB,OAAO,MAA3B,CAAP;AACH,KAFM,EAEJ,IAFI,CAEC,EAFD,CAAP;;AAIA,aAAS,EAAT;AACA,cAAU,+BAAc,gBAAd,EAAgC,OAAO,MAAvC,CAAV;AACA,cAAU,IAAV;AACA,cAAU,kCAAiB,gBAAjB,EAAmC,OAAO,MAA1C,CAAV;;AAEA,aAAS,uBAAU,MAAV,CAAT;;AAEA,YAAQ,MAAR,CAAe,KAAf,CAAqB,MAArB;AACH,CAnBD;;;;;;;;AA2BA,SAAS,gBAAC,GAAD,EAAM,gBAAN,EAAwB,MAAxB,EAAmC;AACxC,QAAI,aAAJ;QACI,eADJ;QAEI,aAFJ;;AAIA,WAAO,YAAY,CAAC,GAAD,CAAZ,EAAmB,MAAnB,CAAP;;;;AAIA,WAAO,mBAAM,IAAN,EAAY,UAAC,UAAD,EAAgB;AAC/B,eAAO,uBAAQ,UAAR,EAAoB,OAAO,MAA3B,CAAP;AACH,KAFM,EAEJ,IAFI,CAEC,EAFD,CAAP;;AAIA,aAAS,UAAT;AACA,cAAU,gCAAe,gBAAf,EAAiC,OAAO,MAAxC,CAAV;AACA,cAAU,IAAV;AACA,cAAU,kCAAiB,gBAAjB,EAAmC,OAAO,MAA1C,CAAV;;AAEA,aAAS,uBAAU,MAAV,CAAT;;AAEA,YAAQ,MAAR,CAAe,KAAf,CAAqB,MAArB;AACH,CArBD;;;;;;;AA4BA,cAAc,qBAAC,IAAD,EAAO,MAAP,EAAkB;AAC5B,QAAI,uBAAJ;QACI,aADJ;;AAGA,WAAO,kCAAmB,IAAnB,CAAP;;AAEA,WAAO,iCAAkB,IAAlB,EAAwB,MAAxB,CAAP;;AAEA,qBAAiB,uCAAwB,IAAxB,EAA8B,MAA9B,CAAjB;;AAEA,WAAO,0CAA2B,IAA3B,EAAiC,cAAjC,EAAiD,MAAjD,CAAP;AACA,WAAO,8BAAe,IAAf,EAAqB,MAArB,CAAP;AACA,WAAO,4BAAa,IAAb,EAAmB,MAAnB,CAAP;;AAEA,WAAO,IAAP;AACH,CAfD;;;;;;;kBAqBe,YAAqB;AAAA,QAApB,UAAoB,yDAAP,EAAO;;AAChC,QAAI,yBAAJ;QACI,eADJ;QAEI,cAFJ;;AAIA,aAAS,gCAAiB,UAAjB,CAAT;;AAEA,uBAAmB,yBAAY,OAAO,OAAnB,EAA4B,UAAC,MAAD,EAAY;AACvD,eAAO,OAAO,KAAP,GAAe,OAAO,WAAtB,GAAoC,OAAO,YAAlD;AACH,KAFkB,CAAnB;;AAIA,YAAQ,IAAR;;AAEA,WAAO;;;;;AAKH,eAAO,eAAC,GAAD,EAAS;AACZ,gBAAI,IAAI,MAAJ,KAAe,OAAO,WAA1B,EAAuC;AACnC,sBAAM,IAAI,KAAJ,CAAU,uDAAV,CAAN;AACH;;AAED,gBAAI,KAAJ,EAAW;AACP,wBAAQ,KAAR;;AAEA,uBAAO,OAAO,GAAP,EAAY,gBAAZ,EAA8B,MAA9B,CAAP;AACH,aAJD,MAIO;AACH,uBAAO,OAAO,GAAP,EAAY,gBAAZ,EAA8B,MAA9B,CAAP;AACH;AACJ;AAjBE,KAAP;AAmBH,C","file":"createStream.js","sourcesContent":["import makeStreamConfig from './makeStreamConfig';\nimport drawRow from './drawRow';\nimport {\n drawBorderBottom,\n drawBorderJoin,\n drawBorderTop\n} from './drawBorder';\nimport _ from 'lodash';\n\nimport stringifyTableData from './stringifyTableData';\nimport truncateTableData from './truncateTableData';\nimport mapDataUsingRowHeightIndex from './mapDataUsingRowHeightIndex';\nimport alignTableData from './alignTableData';\nimport padTableData from './padTableData';\nimport calculateRowHeightIndex from './calculateRowHeightIndex';\n\nlet append,\n create,\n prepareData;\n\n/**\n * @param {string[]} row\n * @param {number[]} columnWidthIndex\n * @param {Object} config\n * @returns {undefined}\n */\ncreate = (row, columnWidthIndex, config) => {\n let body,\n output,\n rows;\n\n rows = prepareData([row], config);\n\n body = _.map(rows, (literalRow) => {\n return drawRow(literalRow, config.border);\n }).join('');\n\n output = '';\n output += drawBorderTop(columnWidthIndex, config.border);\n output += body;\n output += drawBorderBottom(columnWidthIndex, config.border);\n\n output = _.trimEnd(output);\n\n process.stdout.write(output);\n};\n\n/**\n * @param {string[]} row\n * @param {number[]} columnWidthIndex\n * @param {Object} config\n * @returns {undefined}\n */\nappend = (row, columnWidthIndex, config) => {\n let body,\n output,\n rows;\n\n rows = prepareData([row], config);\n\n // console.log('rows', rows);\n\n body = _.map(rows, (literalRow) => {\n return drawRow(literalRow, config.border);\n }).join('');\n\n output = '\\r\\x1b[K';\n output += drawBorderJoin(columnWidthIndex, config.border);\n output += body;\n output += drawBorderBottom(columnWidthIndex, config.border);\n\n output = _.trimEnd(output);\n\n process.stdout.write(output);\n};\n\n/**\n * @param {Array} data\n * @param {Object} config\n * @returns {Array}\n */\nprepareData = (data, config) => {\n let rowHeightIndex,\n rows;\n\n rows = stringifyTableData(data);\n\n rows = truncateTableData(data, config);\n\n rowHeightIndex = calculateRowHeightIndex(rows, config);\n\n rows = mapDataUsingRowHeightIndex(rows, rowHeightIndex, config);\n rows = alignTableData(rows, config);\n rows = padTableData(rows, config);\n\n return rows;\n};\n\n/**\n * @param {Object} userConfig\n * @return {Object}\n */\nexport default (userConfig = {}) => {\n let columnWidthIndex,\n config,\n empty;\n\n config = makeStreamConfig(userConfig);\n\n columnWidthIndex = _.mapValues(config.columns, (column) => {\n return column.width + column.paddingLeft + column.paddingRight;\n });\n\n empty = true;\n\n return {\n /**\n * @param {string[]} row\n * @returns {undefined}\n */\n write: (row) => {\n if (row.length !== config.columnCount) {\n throw new Error('Row cell count does not match the config.columnCount.');\n }\n\n if (empty) {\n empty = false;\n\n return create(row, columnWidthIndex, config);\n } else {\n return append(row, columnWidthIndex, config);\n }\n }\n };\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/drawBorder.js.map b/tools/eslint/node_modules/table/dist/drawBorder.js.map deleted file mode 100644 index adbf9d7403d2f9..00000000000000 --- a/tools/eslint/node_modules/table/dist/drawBorder.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["drawBorder.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAEA,IAAI,mBAAJ;IACI,yBADJ;IAEI,uBAFJ;IAGI,sBAHJ;;;;;;;;;;;;;;;AAkBA,QA+EI,UA/EJ,gBAAa,oBAAC,eAAD,EAAkB,KAAlB,EAA4B;AACrC,QAAI,gBAAJ;;AAEA,cAAU,mBAAM,eAAN,EAAuB,UAAC,IAAD,EAAU;AACvC,eAAO,sBAAS,MAAM,IAAf,EAAqB,IAArB,CAAP;AACH,KAFS,CAAV;;AAIA,cAAU,QAAQ,IAAR,CAAa,MAAM,IAAnB,CAAV;;AAEA,WAAO,MAAM,IAAN,GAAa,OAAb,GAAuB,MAAM,KAA7B,GAAqC,IAA5C;AACH,CAVD;;;;;;;;;;;;;;;AAyBA,QAuDI,aAvDJ,mBAAgB,uBAAC,eAAD,EAAkB,KAAlB,EAA4B;AACxC,WAAO,WAAW,eAAX,EAA4B;AAC/B,cAAM,MAAM,OADmB;AAE/B,eAAO,MAAM,QAFkB;AAG/B,cAAM,MAAM,OAHmB;AAI/B,cAAM,MAAM;AAJmB,KAA5B,CAAP;AAMH,CAPD;;;;;;;;;;;;;;;AAsBA,QAkCI,cAlCJ,oBAAiB,wBAAC,eAAD,EAAkB,KAAlB,EAA4B;AACzC,WAAO,WAAW,eAAX,EAA4B;AAC/B,cAAM,MAAM,QADmB;AAE/B,eAAO,MAAM,SAFkB;AAG/B,cAAM,MAAM,QAHmB;AAI/B,cAAM,MAAM;AAJmB,KAA5B,CAAP;AAMH,CAPD;;;;;;;;;;;;;;;AAsBA,QAaI,gBAbJ,sBAAmB,0BAAC,eAAD,EAAkB,KAAlB,EAA4B;AAC3C,WAAO,WAAW,eAAX,EAA4B;AAC/B,cAAM,MAAM,UADmB;AAE/B,eAAO,MAAM,WAFkB;AAG/B,cAAM,MAAM,UAHmB;AAI/B,cAAM,MAAM;AAJmB,KAA5B,CAAP;AAMH,CAPD;;QAUI,U,GAAA,U;QACA,a,GAAA,a;QACA,c,GAAA,c;QACA,gB,GAAA,gB","file":"drawBorder.js","sourcesContent":["import _ from 'lodash';\n\nlet drawBorder,\n drawBorderBottom,\n drawBorderJoin,\n drawBorderTop;\n\n/**\n * @typedef drawBorder~parts\n * @property {string} left\n * @property {string} right\n * @property {string} body\n * @property {string} join\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorder~parts} parts\n * @returns {string}\n */\ndrawBorder = (columnSizeIndex, parts) => {\n let columns;\n\n columns = _.map(columnSizeIndex, (size) => {\n return _.repeat(parts.body, size);\n });\n\n columns = columns.join(parts.join);\n\n return parts.left + columns + parts.right + '\\n';\n};\n\n/**\n * @typedef drawBorderTop~parts\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} topBody\n * @property {string} topJoin\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorderTop~parts} parts\n * @return {string}\n */\ndrawBorderTop = (columnSizeIndex, parts) => {\n return drawBorder(columnSizeIndex, {\n left: parts.topLeft,\n right: parts.topRight,\n body: parts.topBody,\n join: parts.topJoin\n });\n};\n\n/**\n * @typedef drawBorderJoin~parts\n * @property {string} joinLeft\n * @property {string} joinRight\n * @property {string} joinBody\n * @property {string} joinJoin\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorderJoin~parts} parts\n * @returns {string}\n */\ndrawBorderJoin = (columnSizeIndex, parts) => {\n return drawBorder(columnSizeIndex, {\n left: parts.joinLeft,\n right: parts.joinRight,\n body: parts.joinBody,\n join: parts.joinJoin\n });\n};\n\n/**\n * @typedef drawBorderBottom~parts\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} topBody\n * @property {string} topJoin\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorderBottom~parts} parts\n * @returns {string}\n */\ndrawBorderBottom = (columnSizeIndex, parts) => {\n return drawBorder(columnSizeIndex, {\n left: parts.bottomLeft,\n right: parts.bottomRight,\n body: parts.bottomBody,\n join: parts.bottomJoin\n });\n};\n\nexport {\n drawBorder,\n drawBorderTop,\n drawBorderJoin,\n drawBorderBottom\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/drawRow.js.map b/tools/eslint/node_modules/table/dist/drawRow.js.map deleted file mode 100644 index 5cef8565f4cc23..00000000000000 --- a/tools/eslint/node_modules/table/dist/drawRow.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["drawRow.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;kBAYe,UAAC,OAAD,EAAU,MAAV,EAAqB;AAChC,SAAO,OAAO,QAAP,GAAkB,QAAQ,IAAR,CAAa,OAAO,QAApB,CAAlB,GAAkD,OAAO,SAAzD,GAAqE,IAA5E;AACH,C","file":"drawRow.js","sourcesContent":["/**\n * @typedef {Object} drawRow~border\n * @property {string} bodyLeft\n * @property {string} bodyRight\n * @property {string} bodyJoin\n */\n\n/**\n * @param {number[]} columns\n * @param {drawRow~border} border\n * @return {string}\n */\nexport default (columns, border) => {\n return border.bodyLeft + columns.join(border.bodyJoin) + border.bodyRight + '\\n';\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/drawTable.js.map b/tools/eslint/node_modules/table/dist/drawTable.js.map deleted file mode 100644 index 8534c44da3fad4..00000000000000 --- a/tools/eslint/node_modules/table/dist/drawTable.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["drawTable.js"],"names":[],"mappings":";;;;;;;;;;AACA;;AAKA;;;;;;;;;;;;;;;kBAUe,UAAC,IAAD,EAAO,MAAP,EAAe,eAAf,EAAgC,YAAhC,EAA8C,kBAA9C,EAAqE;AAChF,QAAI,eAAJ;QACI,qBADJ;QAEI,iBAFJ;QAGI,kBAHJ;;AAKA,eAAW,KAAK,MAAhB;;AAEA,mBAAe,CAAf;;AAEA,aAAS,EAAT;;AAEA,QAAI,mBAAmB,YAAnB,EAAiC,QAAjC,CAAJ,EAAgD;AAC5C,kBAAU,+BAAc,eAAd,EAA+B,MAA/B,CAAV;AACH;;AAED,2BAAU,IAAV,EAAgB,UAAC,GAAD,EAAM,MAAN,EAAiB;AAC7B,kBAAU,uBAAQ,GAAR,EAAa,MAAb,CAAV;;AAEA,YAAI,CAAC,SAAL,EAAgB;AACZ,wBAAY,aAAa,YAAb,CAAZ;;AAEA;AACH;;AAED;;AAEA,YAAI,cAAc,CAAd,IAAmB,WAAW,WAAW,CAAzC,IAA8C,mBAAmB,YAAnB,EAAiC,QAAjC,CAAlD,EAA8F;AAC1F,sBAAU,gCAAe,eAAf,EAAgC,MAAhC,CAAV;AACH;AACJ,KAdD;;AAgBA,QAAI,mBAAmB,YAAnB,EAAiC,QAAjC,CAAJ,EAAgD;AAC5C,kBAAU,kCAAiB,eAAjB,EAAkC,MAAlC,CAAV;AACH;;AAED,WAAO,MAAP;AACH,C","file":"drawTable.js","sourcesContent":["import _ from 'lodash';\nimport {\n drawBorderTop,\n drawBorderJoin,\n drawBorderBottom\n} from './drawBorder';\nimport drawRow from './drawRow';\n\n/**\n * @param {Array} rows\n * @param {Object} border\n * @param {Array} columnSizeIndex\n * @param {Array} rowSpanIndex\n * @param {Function} drawHorizontalLine\n * @returns {string}\n */\nexport default (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine) => {\n let output,\n realRowIndex,\n rowCount,\n rowHeight;\n\n rowCount = rows.length;\n\n realRowIndex = 0;\n\n output = '';\n\n if (drawHorizontalLine(realRowIndex, rowCount)) {\n output += drawBorderTop(columnSizeIndex, border);\n }\n\n _.forEach(rows, (row, index0) => {\n output += drawRow(row, border);\n\n if (!rowHeight) {\n rowHeight = rowSpanIndex[realRowIndex];\n\n realRowIndex++;\n }\n\n rowHeight--;\n\n if (rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) {\n output += drawBorderJoin(columnSizeIndex, border);\n }\n });\n\n if (drawHorizontalLine(realRowIndex, rowCount)) {\n output += drawBorderBottom(columnSizeIndex, border);\n }\n\n return output;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/getBorderCharacters.js.map b/tools/eslint/node_modules/table/dist/getBorderCharacters.js.map deleted file mode 100644 index 36ba03bf8c00e4..00000000000000 --- a/tools/eslint/node_modules/table/dist/getBorderCharacters.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["getBorderCharacters.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAyBe,UAAC,IAAD,EAAU;AACrB,QAAI,SAAS,WAAb,EAA0B;AACtB,eAAO;AACH,qBAAS,GADN;AAEH,qBAAS,GAFN;AAGH,qBAAS,GAHN;AAIH,sBAAU,GAJP;;AAMH,wBAAY,GANT;AAOH,wBAAY,GAPT;AAQH,wBAAY,GART;AASH,yBAAa,GATV;;AAWH,sBAAU,GAXP;AAYH,uBAAW,GAZR;AAaH,sBAAU,GAbP;;AAeH,sBAAU,GAfP;AAgBH,sBAAU,GAhBP;AAiBH,uBAAW,GAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,QAAI,SAAS,MAAb,EAAqB;AACjB,eAAO;AACH,qBAAS,GADN;AAEH,qBAAS,GAFN;AAGH,qBAAS,GAHN;AAIH,sBAAU,GAJP;;AAMH,wBAAY,GANT;AAOH,wBAAY,GAPT;AAQH,wBAAY,GART;AASH,yBAAa,GATV;;AAWH,sBAAU,GAXP;AAYH,uBAAW,GAZR;AAaH,sBAAU,GAbP;;AAeH,sBAAU,GAfP;AAgBH,sBAAU,GAhBP;AAiBH,uBAAW,GAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,QAAI,SAAS,OAAb,EAAsB;AAClB,eAAO;AACH,qBAAS,GADN;AAEH,qBAAS,GAFN;AAGH,qBAAS,GAHN;AAIH,sBAAU,GAJP;;AAMH,wBAAY,GANT;AAOH,wBAAY,GAPT;AAQH,wBAAY,GART;AASH,yBAAa,GATV;;AAWH,sBAAU,GAXP;AAYH,uBAAW,GAZR;AAaH,sBAAU,GAbP;;AAeH,sBAAU,GAfP;AAgBH,sBAAU,GAhBP;AAiBH,uBAAW,GAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,QAAI,SAAS,MAAb,EAAqB;AACjB,eAAO;AACH,qBAAS,EADN;AAEH,qBAAS,EAFN;AAGH,qBAAS,EAHN;AAIH,sBAAU,EAJP;;AAMH,wBAAY,EANT;AAOH,wBAAY,EAPT;AAQH,wBAAY,EART;AASH,yBAAa,EATV;;AAWH,sBAAU,EAXP;AAYH,uBAAW,EAZR;AAaH,sBAAU,EAbP;;AAeH,sBAAU,EAfP;AAgBH,sBAAU,EAhBP;AAiBH,uBAAW,EAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,UAAM,IAAI,KAAJ,CAAU,oCAAV,CAAN;AACH,C","file":"getBorderCharacters.js","sourcesContent":["/* eslint-disable sorting/sort-object-props */\n\n/**\n * @typedef border\n * @property {string} topBody\n * @property {string} topJoin\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} bottomBody\n * @property {string} bottomJoin\n * @property {string} bottomLeft\n * @property {string} bottomRight\n * @property {string} bodyLeft\n * @property {string} bodyRight\n * @property {string} bodyJoin\n * @property {string} joinBody\n * @property {string} joinLeft\n * @property {string} joinRight\n * @property {string} joinJoin\n */\n\n/**\n * @param {string} name\n * @returns {border}\n */\nexport default (name) => {\n if (name === 'honeywell') {\n return {\n topBody: '═',\n topJoin: '╤',\n topLeft: '╔',\n topRight: '╗',\n\n bottomBody: '═',\n bottomJoin: '╧',\n bottomLeft: '╚',\n bottomRight: '╝',\n\n bodyLeft: '║',\n bodyRight: '║',\n bodyJoin: '│',\n\n joinBody: '─',\n joinLeft: '╟',\n joinRight: '╢',\n joinJoin: '┼'\n };\n }\n\n if (name === 'norc') {\n return {\n topBody: '─',\n topJoin: '┬',\n topLeft: '┌',\n topRight: '┐',\n\n bottomBody: '─',\n bottomJoin: '┴',\n bottomLeft: '└',\n bottomRight: '┘',\n\n bodyLeft: '│',\n bodyRight: '│',\n bodyJoin: '│',\n\n joinBody: '─',\n joinLeft: '├',\n joinRight: '┤',\n joinJoin: '┼'\n };\n }\n\n if (name === 'ramac') {\n return {\n topBody: '-',\n topJoin: '+',\n topLeft: '+',\n topRight: '+',\n\n bottomBody: '-',\n bottomJoin: '+',\n bottomLeft: '+',\n bottomRight: '+',\n\n bodyLeft: '|',\n bodyRight: '|',\n bodyJoin: '|',\n\n joinBody: '-',\n joinLeft: '|',\n joinRight: '|',\n joinJoin: '|'\n };\n }\n\n if (name === 'void') {\n return {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n\n bodyLeft: '',\n bodyRight: '',\n bodyJoin: '',\n\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: ''\n };\n }\n\n throw new Error('Unknown border template \"${name}\".');\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/index.js.map b/tools/eslint/node_modules/table/dist/index.js.map deleted file mode 100644 index dcf5ef8d344cad..00000000000000 --- a/tools/eslint/node_modules/table/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["index.js"],"names":[],"mappings":";;;;;;;AAAA;;;;AACA;;;;AACA;;;;;;QAGI,Y;QACA,mB","file":"index.js","sourcesContent":["import table from './table';\nimport createStream from './createStream';\nimport getBorderCharacters from './getBorderCharacters';\n\nexport {\n createStream,\n getBorderCharacters\n};\n\nexport default table;\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/makeConfig.js b/tools/eslint/node_modules/table/dist/makeConfig.js index 830ece67ef10ff..45ad8e899ce4be 100644 --- a/tools/eslint/node_modules/table/dist/makeConfig.js +++ b/tools/eslint/node_modules/table/dist/makeConfig.js @@ -29,7 +29,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Object} */ const makeBorder = function makeBorder() { - let border = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let border = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return _lodash2.default.assign({}, (0, _getBorderCharacters2.default)('honeywell'), border); }; @@ -44,8 +44,8 @@ const makeBorder = function makeBorder() { * @returns {Object} */ const makeColumns = function makeColumns(rows) { - let columns = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - let columnDefault = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + let columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let columnDefault = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const maximumColumnWidthIndex = (0, _calculateMaximumColumnWidthIndex2.default)(rows); @@ -77,7 +77,7 @@ const makeColumns = function makeColumns(rows) { */ exports.default = function (rows) { - let userConfig = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + let userConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; (0, _validateConfig2.default)('config.json', userConfig); diff --git a/tools/eslint/node_modules/table/dist/makeConfig.js.map b/tools/eslint/node_modules/table/dist/makeConfig.js.map deleted file mode 100644 index 25c7051d2758e4..00000000000000 --- a/tools/eslint/node_modules/table/dist/makeConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["makeConfig.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;AACA;;;;;;AAEA,IAAI,mBAAJ;IACI,oBADJ;;;;;;;;AASA,aAAa,sBAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC1B,WAAO,sBAAS,EAAT,EAAa,mCAAoB,WAApB,CAAb,EAA+C,MAA/C,CAAP;AACH,CAFD;;;;;;;;;;;AAaA,cAAc,qBAAC,IAAD,EAA4C;AAAA,QAArC,OAAqC,yDAA3B,EAA2B;AAAA,QAAvB,aAAuB,yDAAP,EAAO;;AACtD,QAAI,gCAAJ;;AAEA,8BAA0B,gDAAiC,IAAjC,CAA1B;;AAEA,yBAAQ,KAAK,CAAL,EAAQ,MAAhB,EAAwB,UAAC,KAAD,EAAW;AAC/B,YAAI,2BAAc,QAAQ,KAAR,CAAd,CAAJ,EAAmC;AAC/B,oBAAQ,KAAR,IAAiB,EAAjB;AACH;;AAED,gBAAQ,KAAR,IAAiB,sBAAS;AACtB,uBAAW,MADW;AAEtB,mBAAO,wBAAwB,KAAxB,CAFe;AAGtB,sBAAU,KAHY;AAItB,sBAAU,QAJY;AAKtB,yBAAa,CALS;AAMtB,0BAAc;AANQ,SAAT,EAOd,aAPc,EAOC,QAAQ,KAAR,CAPD,CAAjB;AAQH,KAbD;;AAeA,WAAO,OAAP;AACH,CArBD;;;;;;;;;;;kBA+Be,UAAC,IAAD,EAA2B;AAAA,QAApB,UAAoB,yDAAP,EAAO;;AACtC,QAAI,eAAJ;;AAEA,kCAAe,UAAf;;AAEA,aAAS,yBAAY,UAAZ,CAAT;;AAEA,WAAO,MAAP,GAAgB,WAAW,OAAO,MAAlB,CAAhB;AACA,WAAO,OAAP,GAAiB,YAAY,IAAZ,EAAkB,OAAO,OAAzB,EAAkC,OAAO,aAAzC,CAAjB;;AAEA,QAAI,CAAC,OAAO,kBAAZ,EAAgC;;;;AAI5B,eAAO,kBAAP,GAA4B,YAAM;AAC9B,mBAAO,IAAP;AACH,SAFD;AAGH;;AAED,WAAO,MAAP;AACH,C","file":"makeConfig.js","sourcesContent":["import _ from 'lodash';\nimport getBorderCharacters from './getBorderCharacters';\nimport validateConfig from './validateConfig';\nimport calculateMaximumColumnWidthIndex from './calculateMaximumColumnWidthIndex';\n\nlet makeBorder,\n makeColumns;\n\n/**\n * Merges user provided border characters with the default border (\"honeywell\") characters.\n *\n * @param {Object} border\n * @returns {Object}\n */\nmakeBorder = (border = {}) => {\n return _.assign({}, getBorderCharacters('honeywell'), border);\n};\n\n/**\n * Creates a configuration for every column using default\n * values for the missing configuration properties.\n *\n * @param {Array[]} rows\n * @param {Object} columns\n * @param {Object} columnDefault\n * @returns {Object}\n */\nmakeColumns = (rows, columns = {}, columnDefault = {}) => {\n let maximumColumnWidthIndex;\n\n maximumColumnWidthIndex = calculateMaximumColumnWidthIndex(rows);\n\n _.times(rows[0].length, (index) => {\n if (_.isUndefined(columns[index])) {\n columns[index] = {};\n }\n\n columns[index] = _.assign({\n alignment: 'left',\n width: maximumColumnWidthIndex[index],\n wrapWord: false,\n truncate: Infinity,\n paddingLeft: 1,\n paddingRight: 1\n }, columnDefault, columns[index]);\n });\n\n return columns;\n};\n\n/**\n * Makes a new configuration object out of the userConfig object\n * using default values for the missing configuration properties.\n *\n * @param {Array[]} rows\n * @param {Object} userConfig\n * @returns {Object}\n */\nexport default (rows, userConfig = {}) => {\n let config;\n\n validateConfig(userConfig);\n\n config = _.cloneDeep(userConfig);\n\n config.border = makeBorder(config.border);\n config.columns = makeColumns(rows, config.columns, config.columnDefault);\n\n if (!config.drawHorizontalLine) {\n /**\n * @returns {boolean}\n */\n config.drawHorizontalLine = () => {\n return true;\n };\n }\n\n return config;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/makeStreamConfig.js b/tools/eslint/node_modules/table/dist/makeStreamConfig.js index 06e212adbfe498..1482dae079ec0d 100644 --- a/tools/eslint/node_modules/table/dist/makeStreamConfig.js +++ b/tools/eslint/node_modules/table/dist/makeStreamConfig.js @@ -25,7 +25,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Object} */ const makeBorder = function makeBorder() { - let border = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let border = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return _lodash2.default.assign({}, (0, _getBorderCharacters2.default)('honeywell'), border); }; @@ -40,8 +40,8 @@ const makeBorder = function makeBorder() { * @returns {Object} */ const makeColumns = function makeColumns(columnCount) { - let columns = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - let columnDefault = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + let columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let columnDefault = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; _lodash2.default.times(columnCount, index => { if (_lodash2.default.isUndefined(columns[index])) { @@ -86,7 +86,7 @@ const makeColumns = function makeColumns(columnCount) { */ exports.default = function () { - let userConfig = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; (0, _validateConfig2.default)('streamConfig.json', userConfig); diff --git a/tools/eslint/node_modules/table/dist/makeStreamConfig.js.map b/tools/eslint/node_modules/table/dist/makeStreamConfig.js.map deleted file mode 100644 index c3c0437ec1e42a..00000000000000 --- a/tools/eslint/node_modules/table/dist/makeStreamConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["makeStreamConfig.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;;;AAEA,IAAI,mBAAJ;IACI,oBADJ;;;;;;;;AASA,aAAa,sBAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC1B,WAAO,sBAAS,EAAT,EAAa,mCAAoB,WAApB,CAAb,EAA+C,MAA/C,CAAP;AACH,CAFD;;;;;;;;;;;AAaA,cAAc,qBAAC,WAAD,EAAmD;AAAA,QAArC,OAAqC,yDAA3B,EAA2B;AAAA,QAAvB,aAAuB,yDAAP,EAAO;;AAC7D,yBAAQ,WAAR,EAAqB,UAAC,KAAD,EAAW;AAC5B,YAAI,2BAAc,QAAQ,KAAR,CAAd,CAAJ,EAAmC;AAC/B,oBAAQ,KAAR,IAAiB,EAAjB;AACH;;AAED,gBAAQ,KAAR,IAAiB,sBAAS;AACtB,uBAAW,MADW;;AAGtB,sBAAU,KAHY;AAItB,sBAAU,QAJY;AAKtB,yBAAa,CALS;AAMtB,0BAAc;AANQ,SAAT,EAOd,aAPc,EAOC,QAAQ,KAAR,CAPD,CAAjB;AAQH,KAbD;;AAeA,WAAO,OAAP;AACH,CAjBD;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA2Ce,YAAqB;AAAA,QAApB,UAAoB,yDAAP,EAAO;;AAChC,QAAI,eAAJ;;AAEA,wCAAqB,UAArB;;AAEA,aAAS,yBAAY,UAAZ,CAAT;;AAEA,QAAI,CAAC,OAAO,aAAR,IAAyB,CAAC,OAAO,aAAP,CAAqB,KAAnD,EAA0D;AACtD,cAAM,IAAI,KAAJ,CAAU,iEAAV,CAAN;AACH;;AAED,QAAI,CAAC,OAAO,WAAZ,EAAyB;AACrB,cAAM,IAAI,KAAJ,CAAU,kCAAV,CAAN;AACH;;AAED,WAAO,MAAP,GAAgB,WAAW,OAAO,MAAlB,CAAhB;AACA,WAAO,OAAP,GAAiB,YAAY,OAAO,WAAnB,EAAgC,OAAO,OAAvC,EAAgD,OAAO,aAAvD,CAAjB;;AAEA,WAAO,MAAP;AACH,C","file":"makeStreamConfig.js","sourcesContent":["import _ from 'lodash';\nimport getBorderCharacters from './getBorderCharacters';\nimport validateStreamConfig from './validateStreamConfig';\n\nlet makeBorder,\n makeColumns;\n\n/**\n * Merges user provided border characters with the default border (\"honeywell\") characters.\n *\n * @param {Object} border\n * @returns {Object}\n */\nmakeBorder = (border = {}) => {\n return _.assign({}, getBorderCharacters('honeywell'), border);\n};\n\n/**\n * Creates a configuration for every column using default\n * values for the missing configuration properties.\n *\n * @param {number} columnCount\n * @param {Object} columns\n * @param {Object} columnDefault\n * @returns {Object}\n */\nmakeColumns = (columnCount, columns = {}, columnDefault = {}) => {\n _.times(columnCount, (index) => {\n if (_.isUndefined(columns[index])) {\n columns[index] = {};\n }\n\n columns[index] = _.assign({\n alignment: 'left',\n // width: columnDefault.width,\n wrapWord: false,\n truncate: Infinity,\n paddingLeft: 1,\n paddingRight: 1\n }, columnDefault, columns[index]);\n });\n\n return columns;\n};\n\n/**\n * @typedef {Object} columnConfig\n * @property {string} alignment\n * @property {number} width\n * @property {number} truncate\n * @property {number} paddingLeft\n * @property {number} paddingRight\n */\n\n/**\n * @typedef {Object} streamConfig\n * @property {columnConfig} columnDefault\n * @property {Object} border\n * @property {columnConfig[]}\n * @property {number} columnCount Number of columns in the table (required).\n */\n\n/**\n * Makes a new configuration object out of the userConfig object\n * using default values for the missing configuration properties.\n *\n * @param {streamConfig} userConfig\n * @returns {Object}\n */\nexport default (userConfig = {}) => {\n let config;\n\n validateStreamConfig(userConfig);\n\n config = _.cloneDeep(userConfig);\n\n if (!config.columnDefault || !config.columnDefault.width) {\n throw new Error('Must provide config.columnDefault.width when creating a stream.');\n }\n\n if (!config.columnCount) {\n throw new Error('Must provide config.columnCount.');\n }\n\n config.border = makeBorder(config.border);\n config.columns = makeColumns(config.columnCount, config.columns, config.columnDefault);\n\n return config;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/mapDataUsingRowHeightIndex.js.map b/tools/eslint/node_modules/table/dist/mapDataUsingRowHeightIndex.js.map deleted file mode 100644 index 4b11dec7deceb3..00000000000000 --- a/tools/eslint/node_modules/table/dist/mapDataUsingRowHeightIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["mapDataUsingRowHeightIndex.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,YAAD,EAAe,cAAf,EAA+B,MAA/B,EAA0C;AACrD,QAAI,mBAAJ;QACI,mBADJ;;AAGA,iBAAa,aAAa,CAAb,EAAgB,MAA7B;;;;AAIA,iBAAa,mBAAM,YAAN,EAAoB,UAAC,KAAD,EAAQ,MAAR,EAAmB;AAChD,YAAI,kBAAJ;;AAEA,oBAAY,mBAAM,MAAM,eAAe,MAAf,CAAN,CAAN,EAAqC,YAAM;AACnD,mBAAO,oBAAO,MAAM,UAAN,CAAP,EAA0B,EAA1B,CAAP;AACH,SAFW,CAAZ;;;;;;;;AAUA,+BAAU,KAAV,EAAiB,UAAC,KAAD,EAAQ,MAAR,EAAmB;AAChC,gBAAI,qBAAJ;;AAEA,gBAAI,OAAO,OAAP,CAAe,MAAf,EAAuB,QAA3B,EAAqC;AACjC,+BAAe,wBAAS,KAAT,EAAgB,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAvC,CAAf;AACH,aAFD,MAEO;AACH,+BAAe,0BAAW,KAAX,EAAkB,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAzC,CAAf;AACH;;;;AAID,mCAAU,YAAV,EAAwB,UAAC,IAAD,EAAO,MAAP,EAAkB;;;AAGtC,0BAAU,MAAV,EAAkB,MAAlB,IAA4B,IAA5B;AACH,aAJD;AAKH,SAhBD;;AAkBA,eAAO,SAAP;AACH,KAhCY,CAAb;;AAkCA,WAAO,uBAAU,UAAV,CAAP;AACH,C","file":"mapDataUsingRowHeightIndex.js","sourcesContent":["import _ from 'lodash';\nimport wrapString from './wrapString';\nimport wrapWord from './wrapWord';\n\n/**\n * @param {Array} unmappedRows\n * @param {number[]} rowHeightIndex\n * @param {Object} config\n * @return {Array}\n */\nexport default (unmappedRows, rowHeightIndex, config) => {\n let mappedRows,\n tableWidth;\n\n tableWidth = unmappedRows[0].length;\n\n // console.log('unmappedRows', unmappedRows, 'rowHeightIndex', rowHeightIndex, 'config', config, 'tableWidth', tableWidth);\n\n mappedRows = _.map(unmappedRows, (cells, index0) => {\n let rowHeight;\n\n rowHeight = _.map(Array(rowHeightIndex[index0]), () => {\n return _.fill(Array(tableWidth), '');\n });\n\n // console.log('rowHeight', rowHeight);\n\n // rowHeight\n // [{row index within rowSaw; index2}]\n // [{cell index within a virtual row; index1}]\n\n _.forEach(cells, (value, index1) => {\n let chunkedValue;\n\n if (config.columns[index1].wrapWord) {\n chunkedValue = wrapWord(value, config.columns[index1].width);\n } else {\n chunkedValue = wrapString(value, config.columns[index1].width);\n }\n\n // console.log('chunkedValue', chunkedValue.length, 'rowHeight', rowHeight.length);\n\n _.forEach(chunkedValue, (part, index2) => {\n // console.log(rowHeight[index2]);\n\n rowHeight[index2][index1] = part;\n });\n });\n\n return rowHeight;\n });\n\n return _.flatten(mappedRows);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/padTableData.js.map b/tools/eslint/node_modules/table/dist/padTableData.js.map deleted file mode 100644 index e900566a567aa3..00000000000000 --- a/tools/eslint/node_modules/table/dist/padTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["padTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;kBAOe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,UAAC,KAAD,EAAQ,MAAR,EAAmB;AACnC,gBAAI,eAAJ;;AAEA,qBAAS,OAAO,OAAP,CAAe,MAAf,CAAT;;AAEA,mBAAO,sBAAS,GAAT,EAAc,OAAO,WAArB,IAAoC,KAApC,GAA4C,sBAAS,GAAT,EAAc,OAAO,YAArB,CAAnD;AACH,SANM,CAAP;AAOH,KARM,CAAP;AASH,C","file":"padTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * @param {table~row[]} rows\n * @param {Object} config\n * @return {table~row[]}\n */\nexport default (rows, config) => {\n return _.map(rows, (cells) => {\n return _.map(cells, (value, index1) => {\n let column;\n\n column = config.columns[index1];\n\n return _.repeat(' ', column.paddingLeft) + value + _.repeat(' ', column.paddingRight);\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/stringifyTableData.js.map b/tools/eslint/node_modules/table/dist/stringifyTableData.js.map deleted file mode 100644 index c38e20fa838218..00000000000000 --- a/tools/eslint/node_modules/table/dist/stringifyTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["stringifyTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;kBAQe,UAAC,IAAD,EAAU;AACrB,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,MAAb,CAAP;AACH,KAFM,CAAP;AAGH,C","file":"stringifyTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * Casts all cell values to a string.\n *\n * @param {table~row[]} rows\n * @return {table~row[]}\n */\nexport default (rows) => {\n return _.map(rows, (cells) => {\n return _.map(cells, String);\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/table.js b/tools/eslint/node_modules/table/dist/table.js index 9066efaee82854..b62ffd2b747c8f 100644 --- a/tools/eslint/node_modules/table/dist/table.js +++ b/tools/eslint/node_modules/table/dist/table.js @@ -109,7 +109,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {string} */ exports.default = function (data) { - let userConfig = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + let userConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let rows; diff --git a/tools/eslint/node_modules/table/dist/table.js.map b/tools/eslint/node_modules/table/dist/table.js.map deleted file mode 100644 index 843d2e105c9f17..00000000000000 --- a/tools/eslint/node_modules/table/dist/table.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["table.js"],"names":[],"mappings":";;;;;;AAAA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAgEe,UAAC,IAAD,EAA2B;AAAA,MAApB,UAAoB,yDAAP,EAAO;;AACtC,MAAI,uBAAJ;MACI,eADJ;MAEI,uBAFJ;MAGI,aAHJ;;AAKA,mCAAkB,IAAlB;;AAEA,SAAO,kCAAmB,IAAnB,CAAP;;AAEA,WAAS,0BAAW,IAAX,EAAiB,UAAjB,CAAT;;AAEA,SAAO,iCAAkB,IAAlB,EAAwB,MAAxB,CAAP;;AAEA,mBAAiB,uCAAwB,IAAxB,EAA8B,MAA9B,CAAjB;;AAEA,SAAO,0CAA2B,IAA3B,EAAiC,cAAjC,EAAiD,MAAjD,CAAP;AACA,SAAO,8BAAe,IAAf,EAAqB,MAArB,CAAP;AACA,SAAO,4BAAa,IAAb,EAAmB,MAAnB,CAAP;;AAEA,mBAAiB,uCAAwB,KAAK,CAAL,CAAxB,CAAjB;;AAEA,SAAO,yBAAU,IAAV,EAAgB,OAAO,MAAvB,EAA+B,cAA/B,EAA+C,cAA/C,EAA+D,OAAO,kBAAtE,CAAP;AACH,C","file":"table.js","sourcesContent":["import drawTable from './drawTable';\nimport calculateCellWidthIndex from './calculateCellWidthIndex';\nimport makeConfig from './makeConfig';\nimport calculateRowHeightIndex from './calculateRowHeightIndex';\nimport mapDataUsingRowHeightIndex from './mapDataUsingRowHeightIndex';\nimport alignTableData from './alignTableData';\nimport padTableData from './padTableData';\nimport validateTableData from './validateTableData';\nimport stringifyTableData from './stringifyTableData';\nimport truncateTableData from './truncateTableData';\n\n/**\n * @typedef {string} table~cell\n */\n\n/**\n * @typedef {table~cell[]} table~row\n */\n\n/**\n * @typedef {Object} table~columns\n * @property {string} alignment Cell content alignment (enum: left, center, right) (default: left).\n * @property {number} width Column width (default: auto).\n * @property {number} truncate Number of characters are which the content will be truncated (default: Infinity).\n * @property {number} paddingLeft Cell content padding width left (default: 1).\n * @property {number} paddingRight Cell content padding width right (default: 1).\n */\n\n/**\n * @typedef {Object} table~border\n * @property {string} topBody\n * @property {string} topJoin\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} bottomBody\n * @property {string} bottomJoin\n * @property {string} bottomLeft\n * @property {string} bottomRight\n * @property {string} bodyLeft\n * @property {string} bodyRight\n * @property {string} bodyJoin\n * @property {string} joinBody\n * @property {string} joinLeft\n * @property {string} joinRight\n * @property {string} joinJoin\n */\n\n/**\n * Used to tell whether to draw a horizontal line.\n * This callback is called for each non-content line of the table.\n * The default behavior is to always return true.\n *\n * @typedef {Function} drawHorizontalLine\n * @param {number} index\n * @param {number} size\n * @return {boolean}\n */\n\n/**\n * @typedef {Object} table~config\n * @property {table~border} border\n * @property {table~columns[]} columns Column specific configuration.\n * @property {table~columns} columnDefault Default values for all columns. Column specific settings overwrite the default values.\n * @property {table~drawHorizontalLine} drawHorizontalLine\n */\n\n/**\n * Generates a text table.\n *\n * @param {table~row[]} data\n * @param {table~config} userConfig\n * @return {string}\n */\nexport default (data, userConfig = {}) => {\n let cellWidthIndex,\n config,\n rowHeightIndex,\n rows;\n\n validateTableData(data);\n\n rows = stringifyTableData(data);\n\n config = makeConfig(rows, userConfig);\n\n rows = truncateTableData(data, config);\n\n rowHeightIndex = calculateRowHeightIndex(rows, config);\n\n rows = mapDataUsingRowHeightIndex(rows, rowHeightIndex, config);\n rows = alignTableData(rows, config);\n rows = padTableData(rows, config);\n\n cellWidthIndex = calculateCellWidthIndex(rows[0]);\n\n return drawTable(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/truncateTableData.js.map b/tools/eslint/node_modules/table/dist/truncateTableData.js.map deleted file mode 100644 index dca05c3b51cdce..00000000000000 --- a/tools/eslint/node_modules/table/dist/truncateTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["truncateTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;kBAQe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,UAAC,OAAD,EAAU,KAAV,EAAoB;AACpC,mBAAO,wBAAW,OAAX,EAAoB;AACvB,wBAAQ,OAAO,OAAP,CAAe,KAAf,EAAsB;AADP,aAApB,CAAP;AAGH,SAJM,CAAP;AAKH,KANM,CAAP;AAOH,C","file":"truncateTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * @todo Make it work with ASCII content.\n * @param {table~row[]} rows\n * @param {Object} config\n * @return {table~row[]}\n */\nexport default (rows, config) => {\n return _.map(rows, (cells) => {\n return _.map(cells, (content, index) => {\n return _.truncate(content, {\n length: config.columns[index].truncate\n });\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateConfig.js b/tools/eslint/node_modules/table/dist/validateConfig.js index 965ddc5db4654c..caba30134de2e6 100644 --- a/tools/eslint/node_modules/table/dist/validateConfig.js +++ b/tools/eslint/node_modules/table/dist/validateConfig.js @@ -1,62 +1,756 @@ 'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _ajv = require('ajv'); - -var _ajv2 = _interopRequireDefault(_ajv); - -var _ajvKeywords = require('ajv-keywords'); - -var _ajvKeywords2 = _interopRequireDefault(_ajvKeywords); - -var _config = require('./schemas/config.json'); - -var _config2 = _interopRequireDefault(_config); - -var _streamConfig = require('./schemas/streamConfig.json'); - -var _streamConfig2 = _interopRequireDefault(_streamConfig); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const ajv = new _ajv2.default({ - allErrors: true -}); - -(0, _ajvKeywords2.default)(ajv, 'typeof'); - -ajv.addSchema(_config2.default); -ajv.addSchema(_streamConfig2.default); - -/** - * @param {string} schemaId - * @param {formatData~config} config - * @returns {undefined} - */ - -exports.default = function (schemaId) { - let config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - - if (!ajv.validate(schemaId, config)) { - const errors = ajv.errors.map(error => { - return { - dataPath: error.dataPath, - message: error.message, - params: error.params, - schemaPath: error.schemaPath +var equal = require('ajv/lib/compile/equal'); +var validate = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + var refVal = []; + var refVal1 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.topBody !== undefined) { + var errs_1 = errors; + if (!refVal2(data.topBody, (dataPath || '') + '.topBody', data, 'topBody', rootData)) { + if (vErrors === null) vErrors = refVal2.errors; + else vErrors = vErrors.concat(refVal2.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topJoin, (dataPath || '') + '.topJoin', data, 'topJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topLeft, (dataPath || '') + '.topLeft', data, 'topLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topRight, (dataPath || '') + '.topRight', data, 'topRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomBody, (dataPath || '') + '.bottomBody', data, 'bottomBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomJoin, (dataPath || '') + '.bottomJoin', data, 'bottomJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomLeft, (dataPath || '') + '.bottomLeft', data, 'bottomLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomRight, (dataPath || '') + '.bottomRight', data, 'bottomRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyLeft, (dataPath || '') + '.bodyLeft', data, 'bodyLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyRight, (dataPath || '') + '.bodyRight', data, 'bodyRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyJoin, (dataPath || '') + '.bodyJoin', data, 'bodyJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinBody, (dataPath || '') + '.joinBody', data, 'joinBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinLeft, (dataPath || '') + '.joinLeft', data, 'joinLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinRight, (dataPath || '') + '.joinRight', data, 'joinRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinJoin, (dataPath || '') + '.joinJoin', data, 'joinJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal1.schema = { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }; + refVal1.errors = null; + refVal[1] = refVal1; + var refVal2 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if (typeof data !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal2.schema = { + "type": "string" + }; + refVal2.errors = null; + refVal[2] = refVal2; + var refVal3 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || pattern0.test(key0)); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + for (var key0 in data) { + if (pattern0.test(key0)) { + var errs_1 = errors; + if (!refVal4(data[key0], (dataPath || '') + '[\'' + key0 + '\']', data, key0, rootData)) { + if (vErrors === null) vErrors = refVal4.errors; + else vErrors = vErrors.concat(refVal4.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal3.schema = { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }; + refVal3.errors = null; + refVal[3] = refVal3; + var refVal4 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + var data1 = data.alignment; + if (data1 !== undefined) { + var errs_1 = errors; + var schema1 = validate.schema.properties.alignment.enum; + var valid1; + valid1 = false; + for (var i1 = 0; i1 < schema1.length; i1++) + if (equal(data1, schema1[i1])) { + valid1 = true; + break; + } + if (!valid1) { + var err = { + keyword: 'enum', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/enum', + params: { + allowedValues: schema1 + }, + message: 'should be equal to one of the allowed values' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + if (typeof data1 !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.width !== undefined) { + var errs_1 = errors; + if (typeof data.width !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.width', + schemaPath: '#/properties/width/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.wrapWord !== undefined) { + var errs_1 = errors; + if (typeof data.wrapWord !== "boolean") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.wrapWord', + schemaPath: '#/properties/wrapWord/type', + params: { + type: 'boolean' + }, + message: 'should be boolean' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.truncate !== undefined) { + var errs_1 = errors; + if (typeof data.truncate !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.truncate', + schemaPath: '#/properties/truncate/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingLeft !== undefined) { + var errs_1 = errors; + if (typeof data.paddingLeft !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingLeft', + schemaPath: '#/properties/paddingLeft/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingRight !== undefined) { + var errs_1 = errors; + if (typeof data.paddingRight !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingRight', + schemaPath: '#/properties/paddingRight/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal4.schema = { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }; + refVal4.errors = null; + refVal[4] = refVal4; + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || key0 == 'border' || key0 == 'columns' || key0 == 'columnDefault' || key0 == 'drawHorizontalLine'); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.border !== undefined) { + var errs_1 = errors; + if (!refVal1(data.border, (dataPath || '') + '.border', data, 'border', rootData)) { + if (vErrors === null) vErrors = refVal1.errors; + else vErrors = vErrors.concat(refVal1.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columns !== undefined) { + var errs_1 = errors; + if (!refVal3(data.columns, (dataPath || '') + '.columns', data, 'columns', rootData)) { + if (vErrors === null) vErrors = refVal3.errors; + else vErrors = vErrors.concat(refVal3.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columnDefault !== undefined) { + var errs_1 = errors; + if (!refVal[4](data.columnDefault, (dataPath || '') + '.columnDefault', data, 'columnDefault', rootData)) { + if (vErrors === null) vErrors = refVal[4].errors; + else vErrors = vErrors.concat(refVal[4].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.drawHorizontalLine !== undefined) { + var errs_1 = errors; + var errs__1 = errors; + var valid1; + if (!(typeof data.drawHorizontalLine == "function")) { + if (errs__1 == errors) { + var err = { + keyword: 'typeof', + dataPath: (dataPath || '') + '.drawHorizontalLine', + schemaPath: '#/properties/drawHorizontalLine/typeof', + params: { + keyword: 'typeof' + }, + message: 'should pass "typeof" keyword validation' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } else { + for (var i1 = errs__1; i1 < errors; i1++) { + var ruleErr1 = vErrors[i1]; + if (ruleErr1.dataPath === undefined) { + ruleErr1.dataPath = (dataPath || '') + '.drawHorizontalLine'; + } + if (ruleErr1.schemaPath === undefined) { + ruleErr1.schemaPath = "#/properties/drawHorizontalLine/typeof"; + } + } + } + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' }; - }); - - /* eslint-disable no-console */ - console.log('config', config); - console.log('errors', errors); - /* eslint-enable no-console */ - - throw new Error('Invalid config.'); + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; +})(); +validate.schema = { + "id": "config.json", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "border": { + "$ref": "#/definitions/borders" + }, + "columns": { + "$ref": "#/definitions/columns" + }, + "columnDefault": { + "$ref": "#/definitions/column" + }, + "drawHorizontalLine": { + "typeof": "function" + } + }, + "additionalProperties": false, + "definitions": { + "columns": { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }, + "column": { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }, + "borders": { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }, + "border": { + "type": "string" + } } }; - -module.exports = exports['default']; \ No newline at end of file +validate.errors = null; +module.exports = validate; \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateConfig.js.map b/tools/eslint/node_modules/table/dist/validateConfig.js.map deleted file mode 100644 index ad5e82b80bd67e..00000000000000 --- a/tools/eslint/node_modules/table/dist/validateConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["validateConfig.js"],"names":[],"mappings":";;;;;;AAAA;;;;AACA;;;;;;;;;;;;;;;;;;;kBAce,YAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC5B,QAAI,eAAJ;;AAEA,aAAS,aAAI,cAAJ,CAAmB,MAAnB,mBAAT;;AAEA,QAAI,CAAC,OAAO,KAAZ,EAAmB;;AAEf,gBAAQ,GAAR,CAAY,QAAZ,EAAsB,MAAtB;AACA,gBAAQ,GAAR,CAAY,OAAZ,EAAqB;AACjB,qBAAS,OAAO,KAAP,CAAa,OADL;AAEjB,oBAAQ,OAAO,KAAP,CAAa,MAFJ;AAGjB,sBAAU,OAAO,KAAP,CAAa,QAHN;AAIjB,wBAAY,OAAO,KAAP,CAAa;AAJR,SAArB;;;AAQA,cAAM,IAAI,KAAJ,CAAU,iBAAV,CAAN;AACH;AACJ,C","file":"validateConfig.js","sourcesContent":["import schema from './schemas/config.json';\nimport tv4 from 'tv4';\n\n/**\n * @typedef {string} cell\n */\n\n/**\n * @typedef {cell[]} validateData~column\n */\n\n/**\n * @param {formatData~config} config\n * @returns {undefined}\n */\nexport default (config = {}) => {\n let result;\n\n result = tv4.validateResult(config, schema);\n\n if (!result.valid) {\n /* eslint-disable no-console */\n console.log('config', config);\n console.log('error', {\n message: result.error.message,\n params: result.error.params,\n dataPath: result.error.dataPath,\n schemaPath: result.error.schemaPath\n });\n /* eslint-enable no-console */\n\n throw new Error('Invalid config.');\n }\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateStreamConfig.js b/tools/eslint/node_modules/table/dist/validateStreamConfig.js index e5cc85e3046282..09ea2aac925158 100644 --- a/tools/eslint/node_modules/table/dist/validateStreamConfig.js +++ b/tools/eslint/node_modules/table/dist/validateStreamConfig.js @@ -1,53 +1,742 @@ 'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _streamConfig = require('./schemas/streamConfig.json'); - -var _streamConfig2 = _interopRequireDefault(_streamConfig); - -var _tv = require('tv4'); - -var _tv2 = _interopRequireDefault(_tv); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @typedef {string} cell - */ - -/** - * @typedef {cell[]} validateData~column - */ - -/** - * @param {formatData~config} config - * @returns {undefined} - */ - -exports.default = function () { - var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; - - var result = void 0; - - result = _tv2.default.validateResult(config, _streamConfig2.default); - - if (!result.valid) { - /* eslint-disable no-console */ - console.log('config', config); - console.log('error', { - message: result.error.message, - params: result.error.params, - dataPath: result.error.dataPath, - schemaPath: result.error.schemaPath - }); - /* eslint-enable no-console */ - - throw new Error('Invalid config.'); +var equal = require('ajv/lib/compile/equal'); +var validate = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + var refVal = []; + var refVal1 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.topBody !== undefined) { + var errs_1 = errors; + if (!refVal2(data.topBody, (dataPath || '') + '.topBody', data, 'topBody', rootData)) { + if (vErrors === null) vErrors = refVal2.errors; + else vErrors = vErrors.concat(refVal2.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topJoin, (dataPath || '') + '.topJoin', data, 'topJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topLeft, (dataPath || '') + '.topLeft', data, 'topLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topRight, (dataPath || '') + '.topRight', data, 'topRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomBody, (dataPath || '') + '.bottomBody', data, 'bottomBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomJoin, (dataPath || '') + '.bottomJoin', data, 'bottomJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomLeft, (dataPath || '') + '.bottomLeft', data, 'bottomLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomRight, (dataPath || '') + '.bottomRight', data, 'bottomRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyLeft, (dataPath || '') + '.bodyLeft', data, 'bodyLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyRight, (dataPath || '') + '.bodyRight', data, 'bodyRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyJoin, (dataPath || '') + '.bodyJoin', data, 'bodyJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinBody, (dataPath || '') + '.joinBody', data, 'joinBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinLeft, (dataPath || '') + '.joinLeft', data, 'joinLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinRight, (dataPath || '') + '.joinRight', data, 'joinRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinJoin, (dataPath || '') + '.joinJoin', data, 'joinJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal1.schema = { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }; + refVal1.errors = null; + refVal[1] = refVal1; + var refVal2 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if (typeof data !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal2.schema = { + "type": "string" + }; + refVal2.errors = null; + refVal[2] = refVal2; + var refVal3 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || pattern0.test(key0)); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + for (var key0 in data) { + if (pattern0.test(key0)) { + var errs_1 = errors; + if (!refVal4(data[key0], (dataPath || '') + '[\'' + key0 + '\']', data, key0, rootData)) { + if (vErrors === null) vErrors = refVal4.errors; + else vErrors = vErrors.concat(refVal4.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal3.schema = { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }; + refVal3.errors = null; + refVal[3] = refVal3; + var refVal4 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + var data1 = data.alignment; + if (data1 !== undefined) { + var errs_1 = errors; + var schema1 = validate.schema.properties.alignment.enum; + var valid1; + valid1 = false; + for (var i1 = 0; i1 < schema1.length; i1++) + if (equal(data1, schema1[i1])) { + valid1 = true; + break; + } + if (!valid1) { + var err = { + keyword: 'enum', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/enum', + params: { + allowedValues: schema1 + }, + message: 'should be equal to one of the allowed values' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + if (typeof data1 !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.width !== undefined) { + var errs_1 = errors; + if (typeof data.width !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.width', + schemaPath: '#/properties/width/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.wrapWord !== undefined) { + var errs_1 = errors; + if (typeof data.wrapWord !== "boolean") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.wrapWord', + schemaPath: '#/properties/wrapWord/type', + params: { + type: 'boolean' + }, + message: 'should be boolean' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.truncate !== undefined) { + var errs_1 = errors; + if (typeof data.truncate !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.truncate', + schemaPath: '#/properties/truncate/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingLeft !== undefined) { + var errs_1 = errors; + if (typeof data.paddingLeft !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingLeft', + schemaPath: '#/properties/paddingLeft/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingRight !== undefined) { + var errs_1 = errors; + if (typeof data.paddingRight !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingRight', + schemaPath: '#/properties/paddingRight/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal4.schema = { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }; + refVal4.errors = null; + refVal[4] = refVal4; + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || key0 == 'border' || key0 == 'columns' || key0 == 'columnDefault' || key0 == 'columnCount'); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.border !== undefined) { + var errs_1 = errors; + if (!refVal1(data.border, (dataPath || '') + '.border', data, 'border', rootData)) { + if (vErrors === null) vErrors = refVal1.errors; + else vErrors = vErrors.concat(refVal1.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columns !== undefined) { + var errs_1 = errors; + if (!refVal3(data.columns, (dataPath || '') + '.columns', data, 'columns', rootData)) { + if (vErrors === null) vErrors = refVal3.errors; + else vErrors = vErrors.concat(refVal3.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columnDefault !== undefined) { + var errs_1 = errors; + if (!refVal[4](data.columnDefault, (dataPath || '') + '.columnDefault', data, 'columnDefault', rootData)) { + if (vErrors === null) vErrors = refVal[4].errors; + else vErrors = vErrors.concat(refVal[4].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columnCount !== undefined) { + var errs_1 = errors; + if (typeof data.columnCount !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.columnCount', + schemaPath: '#/properties/columnCount/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; } + validate.errors = vErrors; + return errors === 0; + }; +})(); +validate.schema = { + "id": "streamConfig.json", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "border": { + "$ref": "#/definitions/borders" + }, + "columns": { + "$ref": "#/definitions/columns" + }, + "columnDefault": { + "$ref": "#/definitions/column" + }, + "columnCount": { + "type": "number" + } + }, + "additionalProperties": false, + "definitions": { + "columns": { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }, + "column": { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }, + "borders": { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }, + "border": { + "type": "string" + } + } }; - -module.exports = exports['default']; -//# sourceMappingURL=validateStreamConfig.js.map +validate.errors = null; +module.exports = validate; \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateStreamConfig.js.map b/tools/eslint/node_modules/table/dist/validateStreamConfig.js.map deleted file mode 100644 index c43bee9d5f1e1e..00000000000000 --- a/tools/eslint/node_modules/table/dist/validateStreamConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["validateStreamConfig.js"],"names":[],"mappings":";;;;;;AAAA;;;;AACA;;;;;;;;;;;;;;;;;;;kBAce,YAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC5B,QAAI,eAAJ;;AAEA,aAAS,aAAI,cAAJ,CAAmB,MAAnB,yBAAT;;AAEA,QAAI,CAAC,OAAO,KAAZ,EAAmB;;AAEf,gBAAQ,GAAR,CAAY,QAAZ,EAAsB,MAAtB;AACA,gBAAQ,GAAR,CAAY,OAAZ,EAAqB;AACjB,qBAAS,OAAO,KAAP,CAAa,OADL;AAEjB,oBAAQ,OAAO,KAAP,CAAa,MAFJ;AAGjB,sBAAU,OAAO,KAAP,CAAa,QAHN;AAIjB,wBAAY,OAAO,KAAP,CAAa;AAJR,SAArB;;;AAQA,cAAM,IAAI,KAAJ,CAAU,iBAAV,CAAN;AACH;AACJ,C","file":"validateStreamConfig.js","sourcesContent":["import schema from './schemas/streamConfig.json';\nimport tv4 from 'tv4';\n\n/**\n * @typedef {string} cell\n */\n\n/**\n * @typedef {cell[]} validateData~column\n */\n\n/**\n * @param {formatData~config} config\n * @returns {undefined}\n */\nexport default (config = {}) => {\n let result;\n\n result = tv4.validateResult(config, schema);\n\n if (!result.valid) {\n /* eslint-disable no-console */\n console.log('config', config);\n console.log('error', {\n message: result.error.message,\n params: result.error.params,\n dataPath: result.error.dataPath,\n schemaPath: result.error.schemaPath\n });\n /* eslint-enable no-console */\n\n throw new Error('Invalid config.');\n }\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateTableData.js.map b/tools/eslint/node_modules/table/dist/validateTableData.js.map deleted file mode 100644 index 92092051fad066..00000000000000 --- a/tools/eslint/node_modules/table/dist/validateTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["validateTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAce,UAAC,IAAD,EAAU;AACrB,QAAI,qBAAJ;;AAEA,QAAI,CAAC,uBAAU,IAAV,CAAL,EAAsB;AAClB,cAAM,IAAI,KAAJ,CAAU,8BAAV,CAAN;AACH;;AAED,QAAI,KAAK,MAAL,KAAgB,CAApB,EAAuB;AACnB,cAAM,IAAI,KAAJ,CAAU,qCAAV,CAAN;AACH;;AAED,QAAI,KAAK,CAAL,EAAQ,MAAR,KAAmB,CAAvB,EAA0B;AACtB,cAAM,IAAI,KAAJ,CAAU,wCAAV,CAAN;AACH;;AAED,mBAAe,KAAK,CAAL,EAAQ,MAAvB;;AAEA,2BAAU,IAAV,EAAgB,UAAC,KAAD,EAAW;AACvB,YAAI,CAAC,uBAAU,KAAV,CAAL,EAAuB;AACnB,kBAAM,IAAI,KAAJ,CAAU,kCAAV,CAAN;AACH;;AAED,YAAI,MAAM,MAAN,KAAiB,YAArB,EAAmC;AAC/B,kBAAM,IAAI,KAAJ,CAAU,+CAAV,CAAN;AACH;;;;AAID,+BAAU,KAAV,EAAiB,UAAC,IAAD,EAAU;AACvB,gBAAI,cAAc,IAAd,CAAmB,IAAnB,CAAJ,EAA8B;AAC1B,sBAAM,IAAI,KAAJ,CAAU,iDAAV,CAAN;AACH;AACJ,SAJD;AAKH,KAhBD;AAiBH,C","file":"validateTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * @typedef {string} cell\n */\n\n/**\n * @typedef {cell[]} validateData~column\n */\n\n/**\n * @param {column[]} rows\n * @returns {undefined}\n */\nexport default (rows) => {\n let columnNumber;\n\n if (!_.isArray(rows)) {\n throw new Error('Table data must be an array.');\n }\n\n if (rows.length === 0) {\n throw new Error('Table must define at least one row.');\n }\n\n if (rows[0].length === 0) {\n throw new Error('Table must define at least one column.');\n }\n\n columnNumber = rows[0].length;\n\n _.forEach(rows, (cells) => {\n if (!_.isArray(cells)) {\n throw new Error('Table row data must be an array.');\n }\n\n if (cells.length !== columnNumber) {\n throw new Error('Table must have a consistent number of cells.');\n }\n\n // @todo Make an exception for newline characters.\n // @see https://github.com/gajus/table/issues/9\n _.forEach(cells, (cell) => {\n if (/[\\x01-\\x1A]/.test(cell)) {\n throw new Error('Table data must not contain control characters.');\n }\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/wrapString.js.map b/tools/eslint/node_modules/table/dist/wrapString.js.map deleted file mode 100644 index 0ba89f7ddd6406..00000000000000 --- a/tools/eslint/node_modules/table/dist/wrapString.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["wrapString.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;;;;;;;kBAae,UAAC,OAAD,EAAU,IAAV,EAAmB;AAC9B,QAAI,eAAJ;QACI,qBADJ;;AAGA,mBAAe,OAAf;;AAEA,aAAS,EAAT;;AAEA,OAAG;AACC,eAAO,IAAP,CAAY,yBAAM,YAAN,EAAoB,CAApB,EAAuB,IAAvB,CAAZ;;AAEA,uBAAe,oBAAO,yBAAM,YAAN,EAAoB,IAApB,CAAP,CAAf;AACH,KAJD,QAIS,2BAAY,YAAZ,CAJT;;AAMA,WAAO,MAAP;AACH,C","file":"wrapString.js","sourcesContent":["import _ from 'lodash';\nimport slice from 'slice-ansi';\nimport stringWidth from 'string-width';\n\n/**\n * Creates an array of strings split into groups the length of size.\n * This function works with strings that contain ASCII characters.\n *\n * wrapText is different from would-be \"chunk\" implementation\n * in that whitespace characters that occur on a chunk size limit are trimmed.\n *\n * @param {string} subject\n * @param {number} size\n * @returns {Array}\n */\nexport default (subject, size) => {\n let chunks,\n subjectSlice;\n\n subjectSlice = subject;\n\n chunks = [];\n\n do {\n chunks.push(slice(subjectSlice, 0, size));\n\n subjectSlice = _.trim(slice(subjectSlice, size));\n } while (stringWidth(subjectSlice));\n\n return chunks;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/wrapWord.js.map b/tools/eslint/node_modules/table/dist/wrapWord.js.map deleted file mode 100644 index 92e36ba776c864..00000000000000 --- a/tools/eslint/node_modules/table/dist/wrapWord.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["wrapWord.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;kBAOe,UAAC,KAAD,EAAQ,IAAR,EAAiB;AAC5B,QAAI,cAAJ;QACI,eADJ;QAEI,WAFJ;QAGI,gBAHJ;;AAKA,cAAU,KAAV;;AAEA,aAAS,EAAT;;;AAGA,SAAK,IAAI,MAAJ,CAAW,WAAW,IAAX,GAAkB,mBAAlB,IAAyC,OAAO,CAAhD,IAAqD,yBAAhE,CAAL;;AAEA,OAAG;AACC,gBAAQ,QAAQ,KAAR,CAAc,EAAd,CAAR;;;;AAIA,YAAI,KAAJ,EAAW;AACP,oBAAQ,MAAM,CAAN,CAAR;;AAEA,sBAAU,yBAAM,OAAN,EAAe,2BAAY,KAAZ,CAAf,CAAV;;AAEA,oBAAQ,oBAAO,KAAP,CAAR;AACH,SAND,MAMO;AACH,oBAAQ,yBAAM,OAAN,EAAe,CAAf,EAAkB,IAAlB,CAAR;AACA,sBAAU,yBAAM,OAAN,EAAe,IAAf,CAAV;AACH;;AAED,eAAO,IAAP,CAAY,KAAZ;AACH,KAjBD,QAiBS,2BAAY,OAAZ,CAjBT;;AAmBA,WAAO,MAAP;AACH,C","file":"wrapWord.js","sourcesContent":["import _ from 'lodash';\nimport slice from 'slice-ansi';\nimport stringWidth from 'string-width';\n\n/**\n * @param {string} input\n * @param {number} size\n * @returns {Array}\n */\nexport default (input, size) => {\n let chunk,\n chunks,\n re,\n subject;\n\n subject = input;\n\n chunks = [];\n\n // https://regex101.com/r/gY5kZ1/1\n re = new RegExp('(^.{1,' + size + '}(\\\\s+|$))|(^.{1,' + (size - 1) + '}(\\\\\\\\|/|_|\\\\.|,|;|\\-))');\n\n do {\n chunk = subject.match(re);\n\n // console.log('chunk', chunk, re);\n\n if (chunk) {\n chunk = chunk[0];\n\n subject = slice(subject, stringWidth(chunk));\n\n chunk = _.trim(chunk);\n } else {\n chunk = slice(subject, 0, size);\n subject = slice(subject, size);\n }\n\n chunks.push(chunk);\n } while (stringWidth(subject));\n\n return chunks;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/index.js b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/index.js new file mode 100644 index 00000000000000..d506327c3e5576 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/index.js @@ -0,0 +1,46 @@ +'use strict'; +/* eslint-disable yoda */ +module.exports = x => { + if (Number.isNaN(x)) { + return false; + } + + // code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + x >= 0x1100 && ( + x <= 0x115f || // Hangul Jamo + x === 0x2329 || // LEFT-POINTING ANGLE BRACKET + x === 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= x && x <= 0x4dbf) || + // CJK Unified Ideographs .. Yi Radicals + (0x4e00 <= x && x <= 0xa4c6) || + // Hangul Jamo Extended-A + (0xa960 <= x && x <= 0xa97c) || + // Hangul Syllables + (0xac00 <= x && x <= 0xd7a3) || + // CJK Compatibility Ideographs + (0xf900 <= x && x <= 0xfaff) || + // Vertical Forms + (0xfe10 <= x && x <= 0xfe19) || + // CJK Compatibility Forms .. Small Form Variants + (0xfe30 <= x && x <= 0xfe6b) || + // Halfwidth and Fullwidth Forms + (0xff01 <= x && x <= 0xff60) || + (0xffe0 <= x && x <= 0xffe6) || + // Kana Supplement + (0x1b000 <= x && x <= 0x1b001) || + // Enclosed Ideographic Supplement + (0x1f200 <= x && x <= 0x1f251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= x && x <= 0x3fffd) + ) + ) { + return true; + } + + return false; +}; diff --git a/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/license b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/eslint/node_modules/table/node_modules/is-fullwidth-code-point/package.json b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/package.json new file mode 100644 index 00000000000000..4f2674f067ec32 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/package.json @@ -0,0 +1,113 @@ +{ + "_args": [ + [ + { + "raw": "is-fullwidth-code-point@^2.0.0", + "scope": null, + "escapedName": "is-fullwidth-code-point", + "name": "is-fullwidth-code-point", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "/Users/trott/io.js/tools/node_modules/table/node_modules/string-width" + ] + ], + "_from": "is-fullwidth-code-point@>=2.0.0 <3.0.0", + "_id": "is-fullwidth-code-point@2.0.0", + "_inCache": true, + "_location": "/table/is-fullwidth-code-point", + "_nodeVersion": "4.5.0", + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/is-fullwidth-code-point-2.0.0.tgz_1474526567505_0.299921662081033" + }, + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "_npmVersion": "3.10.7", + "_phantomChildren": {}, + "_requested": { + "raw": "is-fullwidth-code-point@^2.0.0", + "scope": null, + "escapedName": "is-fullwidth-code-point", + "name": "is-fullwidth-code-point", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/table/string-width" + ], + "_resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "_shasum": "a3b30a5c4f199183167aaab93beefae3ddfb654f", + "_shrinkwrap": null, + "_spec": "is-fullwidth-code-point@^2.0.0", + "_where": "/Users/trott/io.js/tools/node_modules/table/node_modules/string-width", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/is-fullwidth-code-point/issues" + }, + "dependencies": {}, + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "directories": {}, + "dist": { + "shasum": "a3b30a5c4f199183167aaab93beefae3ddfb654f", + "tarball": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "gitHead": "e94a78056056c5546f2bf4c4cf812a2163a46dae", + "homepage": "https://github.com/sindresorhus/is-fullwidth-code-point#readme", + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "char", + "string", + "str", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "license": "MIT", + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "name": "is-fullwidth-code-point", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/is-fullwidth-code-point.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0", + "xo": { + "esnext": true + } +} diff --git a/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/readme.md b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/readme.md new file mode 100644 index 00000000000000..093b0281b2c46b --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/readme.md @@ -0,0 +1,39 @@ +# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) + +> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) + + +## Install + +``` +$ npm install --save is-fullwidth-code-point +``` + + +## Usage + +```js +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +isFullwidthCodePoint('谢'.codePointAt()); +//=> true + +isFullwidthCodePoint('a'.codePointAt()); +//=> false +``` + + +## API + +### isFullwidthCodePoint(input) + +#### input + +Type: `number` + +[Code point](https://en.wikipedia.org/wiki/Code_point) of a character. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/tools/eslint/node_modules/table/node_modules/string-width/index.js b/tools/eslint/node_modules/table/node_modules/string-width/index.js new file mode 100644 index 00000000000000..25a8943c1dcad6 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/index.js @@ -0,0 +1,35 @@ +'use strict'; +const stripAnsi = require('strip-ansi'); +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +module.exports = str => { + if (typeof str !== 'string' || str.length === 0) { + return 0; + } + + let width = 0; + + str = stripAnsi(str); + + for (let i = 0; i < str.length; i++) { + const code = str.codePointAt(i); + + // ignore control characters + if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) { + continue; + } + + // surrogates + if (code >= 0x10000) { + i++; + } + + if (isFullwidthCodePoint(code)) { + width += 2; + } else { + width++; + } + } + + return width; +}; diff --git a/tools/eslint/node_modules/table/node_modules/string-width/license b/tools/eslint/node_modules/table/node_modules/string-width/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/eslint/node_modules/table/node_modules/string-width/package.json b/tools/eslint/node_modules/table/node_modules/string-width/package.json new file mode 100644 index 00000000000000..2fd6a297eb8855 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/package.json @@ -0,0 +1,125 @@ +{ + "_args": [ + [ + { + "raw": "string-width@^2.0.0", + "scope": null, + "escapedName": "string-width", + "name": "string-width", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "/Users/trott/io.js/tools/node_modules/table" + ] + ], + "_from": "string-width@>=2.0.0 <3.0.0", + "_id": "string-width@2.0.0", + "_inCache": true, + "_location": "/table/string-width", + "_nodeVersion": "4.5.0", + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/string-width-2.0.0.tgz_1474527284011_0.7386264291126281" + }, + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "_npmVersion": "3.10.7", + "_phantomChildren": {}, + "_requested": { + "raw": "string-width@^2.0.0", + "scope": null, + "escapedName": "string-width", + "name": "string-width", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/table" + ], + "_resolved": "https://registry.npmjs.org/string-width/-/string-width-2.0.0.tgz", + "_shasum": "635c5436cc72a6e0c387ceca278d4e2eec52687e", + "_shrinkwrap": null, + "_spec": "string-width@^2.0.0", + "_where": "/Users/trott/io.js/tools/node_modules/table", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/string-width/issues" + }, + "dependencies": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^3.0.0" + }, + "description": "Get the visual width of a string - the number of columns required to display it", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "directories": {}, + "dist": { + "shasum": "635c5436cc72a6e0c387ceca278d4e2eec52687e", + "tarball": "https://registry.npmjs.org/string-width/-/string-width-2.0.0.tgz" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "gitHead": "523d7ba4dbb24d40cde88d2c36bb1c7124ab6f82", + "homepage": "https://github.com/sindresorhus/string-width#readme", + "keywords": [ + "string", + "str", + "character", + "char", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "license": "MIT", + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "name": "string-width", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/string-width.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0", + "xo": { + "esnext": true + } +} diff --git a/tools/eslint/node_modules/table/node_modules/string-width/readme.md b/tools/eslint/node_modules/table/node_modules/string-width/readme.md new file mode 100644 index 00000000000000..1ab42c93580ecb --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/readme.md @@ -0,0 +1,42 @@ +# string-width [![Build Status](https://travis-ci.org/sindresorhus/string-width.svg?branch=master)](https://travis-ci.org/sindresorhus/string-width) + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + + +## Install + +``` +$ npm install --save string-width +``` + + +## Usage + +```js +const stringWidth = require('string-width'); + +stringWidth('古'); +//=> 2 + +stringWidth('\u001b[1m古\u001b[22m'); +//=> 2 + +stringWidth('a'); +//=> 1 +``` + + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/tools/eslint/node_modules/table/package.json b/tools/eslint/node_modules/table/package.json index fb2f250fa08068..33c29ec498b7ce 100644 --- a/tools/eslint/node_modules/table/package.json +++ b/tools/eslint/node_modules/table/package.json @@ -14,20 +14,22 @@ ] ], "_from": "table@>=3.7.8 <4.0.0", - "_id": "table@3.8.0", + "_id": "table@3.8.3", "_inCache": true, "_location": "/table", - "_nodeVersion": "6.4.0", + "_nodeVersion": "6.8.1", "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", - "tmp": "tmp/table-3.8.0.tgz_1474139512457_0.8613335366826504" + "tmp": "tmp/table-3.8.3.tgz_1476810452789_0.6529890382662416" }, "_npmUser": { "name": "gajus", "email": "gajus@gajus.com" }, - "_npmVersion": "3.10.3", - "_phantomChildren": {}, + "_npmVersion": "3.10.8", + "_phantomChildren": { + "strip-ansi": "3.0.1" + }, "_requested": { "raw": "table@^3.7.8", "scope": null, @@ -40,8 +42,8 @@ "_requiredBy": [ "/eslint" ], - "_resolved": "https://registry.npmjs.org/table/-/table-3.8.0.tgz", - "_shasum": "252166c7f3286684a9d561b0f3a8929caf3a997b", + "_resolved": "https://registry.npmjs.org/table/-/table-3.8.3.tgz", + "_shasum": "2bbc542f0fda9861a755d3947fefd8b3f513855f", "_shrinkwrap": null, "_spec": "table@^3.7.8", "_where": "/Users/trott/io.js/tools/node_modules/eslint", @@ -59,28 +61,33 @@ "chalk": "^1.1.1", "lodash": "^4.0.0", "slice-ansi": "0.0.4", - "string-width": "^1.0.1" + "string-width": "^2.0.0" }, "description": "Formats data into a string table.", "devDependencies": { + "ajv-cli": "^1.1.0", "babel": "^6.5.2", "babel-cli": "^6.14.0", + "babel-core": "^6.14.0", "babel-plugin-add-module-exports": "^0.2.1", + "babel-plugin-istanbul": "^2.0.3", "babel-preset-es2015-node4": "^2.1.0", "babel-register": "^6.14.0", "chai": "^3.4.1", "eslint": "^3.5.0", "eslint-config-canonical": "^1.8.6", "gitdown": "^2.4.0", + "husky": "^0.11.7", "mocha": "^3.0.2", + "nyc": "^8.3.1", "sinon": "^1.17.2" }, "directories": {}, "dist": { - "shasum": "252166c7f3286684a9d561b0f3a8929caf3a997b", - "tarball": "https://registry.npmjs.org/table/-/table-3.8.0.tgz" + "shasum": "2bbc542f0fda9861a755d3947fefd8b3f513855f", + "tarball": "https://registry.npmjs.org/table/-/table-3.8.3.tgz" }, - "gitHead": "076dd77627213007a989b2c845fa2f3a38896eeb", + "gitHead": "2d1c0d9ebad31f9c76e784e6a88f701de8705005", "homepage": "https://github.com/gajus/table#readme", "keywords": [ "ascii", @@ -98,6 +105,17 @@ } ], "name": "table", + "nyc": { + "include": [ + "src/*.js" + ], + "instrument": false, + "lines": 70, + "require": [ + "babel-register" + ], + "sourceMap": false + }, "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { @@ -105,10 +123,13 @@ "url": "git+https://github.com/gajus/table.git" }, "scripts": { - "build": "babel --copy-files ./src --out-dir ./dist", - "lint": "eslint ./src ./tests", - "readme": "gitdown ./.README/README.md --output-file ./README.md", - "test": "mocha --compilers js:babel-register" + "build": "rm -fr ./dist && babel --copy-files ./src --out-dir ./dist && npm run make-validators", + "lint": "npm run build && eslint ./src ./tests", + "make-readme": "gitdown ./.README/README.md --output-file ./README.md", + "make-validators": "ajv compile --all-errors --inline-refs=false -s src/schemas/config -c ajv-keywords/keywords/typeof -o dist/validateConfig.js && ajv compile --all-errors --inline-refs=false -s src/schemas/streamConfig -c ajv-keywords/keywords/typeof -o dist/validateStreamConfig.js", + "precommit": "npm run lint && npm run test", + "prepublish": "NODE_ENV=production npm run build", + "test": "npm run build && nyc --check-coverage mocha" }, - "version": "3.8.0" + "version": "3.8.3" } diff --git a/tools/eslint/node_modules/tryit/package.json b/tools/eslint/node_modules/tryit/package.json index 7a7a28b076f45c..e0b4e1b8dac03e 100644 --- a/tools/eslint/node_modules/tryit/package.json +++ b/tools/eslint/node_modules/tryit/package.json @@ -14,15 +14,19 @@ ] ], "_from": "tryit@>=1.0.1 <2.0.0", - "_id": "tryit@1.0.2", + "_id": "tryit@1.0.3", "_inCache": true, "_location": "/tryit", - "_nodeVersion": "4.1.0", + "_nodeVersion": "6.8.1", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/tryit-1.0.3.tgz_1477606530482_0.8131801665294915" + }, "_npmUser": { "name": "henrikjoreteg", "email": "henrik@joreteg.com" }, - "_npmVersion": "3.3.8", + "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { "raw": "tryit@^1.0.1", @@ -36,8 +40,8 @@ "_requiredBy": [ "/is-resolvable" ], - "_resolved": "https://registry.npmjs.org/tryit/-/tryit-1.0.2.tgz", - "_shasum": "c196b0073e6b1c595d93c9c830855b7acc32a453", + "_resolved": "https://registry.npmjs.org/tryit/-/tryit-1.0.3.tgz", + "_shasum": "393be730a9446fd1ead6da59a014308f36c289cb", "_shrinkwrap": null, "_spec": "tryit@^1.0.1", "_where": "/Users/trott/io.js/tools/node_modules/is-resolvable", @@ -56,10 +60,13 @@ }, "directories": {}, "dist": { - "shasum": "c196b0073e6b1c595d93c9c830855b7acc32a453", - "tarball": "https://registry.npmjs.org/tryit/-/tryit-1.0.2.tgz" + "shasum": "393be730a9446fd1ead6da59a014308f36c289cb", + "tarball": "https://registry.npmjs.org/tryit/-/tryit-1.0.3.tgz" }, - "gitHead": "b567b4feb491e2ee89addd3d06f66d6ec2217cf5", + "files": [ + "tryit.js" + ], + "gitHead": "706147151922a456988a641b08984b2d1fcf2a86", "homepage": "https://github.com/HenrikJoreteg/tryit#readme", "keywords": [ "errors", @@ -84,5 +91,5 @@ "scripts": { "test": "node test/test.js | tap-spec" }, - "version": "1.0.2" + "version": "1.0.3" } diff --git a/tools/eslint/node_modules/typedarray/package.json b/tools/eslint/node_modules/typedarray/package.json index ab02da539baf7a..19821370412450 100644 --- a/tools/eslint/node_modules/typedarray/package.json +++ b/tools/eslint/node_modules/typedarray/package.json @@ -2,18 +2,18 @@ "_args": [ [ { - "raw": "typedarray@~0.0.5", + "raw": "typedarray@^0.0.6", "scope": null, "escapedName": "typedarray", "name": "typedarray", - "rawSpec": "~0.0.5", - "spec": ">=0.0.5 <0.1.0", + "rawSpec": "^0.0.6", + "spec": ">=0.0.6 <0.0.7", "type": "range" }, "/Users/trott/io.js/tools/node_modules/concat-stream" ] ], - "_from": "typedarray@>=0.0.5 <0.1.0", + "_from": "typedarray@>=0.0.6 <0.0.7", "_id": "typedarray@0.0.6", "_inCache": true, "_location": "/typedarray", @@ -24,12 +24,12 @@ "_npmVersion": "1.4.3", "_phantomChildren": {}, "_requested": { - "raw": "typedarray@~0.0.5", + "raw": "typedarray@^0.0.6", "scope": null, "escapedName": "typedarray", "name": "typedarray", - "rawSpec": "~0.0.5", - "spec": ">=0.0.5 <0.1.0", + "rawSpec": "^0.0.6", + "spec": ">=0.0.6 <0.0.7", "type": "range" }, "_requiredBy": [ @@ -38,7 +38,7 @@ "_resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", "_shasum": "867ac74e3864187b1d3d47d996a78ec5c8830777", "_shrinkwrap": null, - "_spec": "typedarray@~0.0.5", + "_spec": "typedarray@^0.0.6", "_where": "/Users/trott/io.js/tools/node_modules/concat-stream", "author": { "name": "James Halliday", diff --git a/tools/eslint/package.json b/tools/eslint/package.json index f0155d89330b9c..d6c8d488cb5dfa 100644 --- a/tools/eslint/package.json +++ b/tools/eslint/package.json @@ -2,25 +2,25 @@ "_args": [ [ { - "raw": "eslint", + "raw": "eslint@3.13.0", "scope": null, "escapedName": "eslint", "name": "eslint", - "rawSpec": "", - "spec": "latest", - "type": "tag" + "rawSpec": "3.13.0", + "spec": "3.13.0", + "type": "version" }, "/Users/trott/io.js/tools" ] ], - "_from": "eslint@latest", - "_id": "eslint@3.8.0", + "_from": "eslint@3.13.0", + "_id": "eslint@3.13.0", "_inCache": true, "_location": "/eslint", "_nodeVersion": "4.4.7", "_npmOperationalInternal": { "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/eslint-3.8.0.tgz_1476481030547_0.1366094599943608" + "tmp": "tmp/eslint-3.13.0.tgz_1483735229408_0.023912116652354598" }, "_npmUser": { "name": "eslint", @@ -29,21 +29,21 @@ "_npmVersion": "2.15.8", "_phantomChildren": {}, "_requested": { - "raw": "eslint", + "raw": "eslint@3.13.0", "scope": null, "escapedName": "eslint", "name": "eslint", - "rawSpec": "", - "spec": "latest", - "type": "tag" + "rawSpec": "3.13.0", + "spec": "3.13.0", + "type": "version" }, "_requiredBy": [ "#USER" ], - "_resolved": "https://registry.npmjs.org/eslint/-/eslint-3.8.0.tgz", - "_shasum": "4fbbf6833d66654860c23a099c47a0f086de34b7", + "_resolved": "https://registry.npmjs.org/eslint/-/eslint-3.13.0.tgz", + "_shasum": "636925fd163c9babe2e8be7ae43caf518d469577", "_shrinkwrap": null, - "_spec": "eslint", + "_spec": "eslint@3.13.0", "_where": "/Users/trott/io.js/tools", "author": { "name": "Nicholas C. Zakas", @@ -56,6 +56,7 @@ "url": "https://github.com/eslint/eslint/issues/" }, "dependencies": { + "babel-code-frame": "^6.16.0", "chalk": "^1.1.3", "concat-stream": "^1.4.6", "debug": "^2.1.1", @@ -66,8 +67,8 @@ "esutils": "^2.0.2", "file-entry-cache": "^2.0.0", "glob": "^7.0.3", - "globals": "^9.2.0", - "ignore": "^3.1.5", + "globals": "^9.14.0", + "ignore": "^3.2.0", "imurmurhash": "^0.1.4", "inquirer": "^0.12.0", "is-my-json-valid": "^2.10.0", @@ -83,9 +84,9 @@ "pluralize": "^1.2.1", "progress": "^1.1.8", "require-uncached": "^1.0.2", - "shelljs": "^0.6.0", + "shelljs": "^0.7.5", "strip-bom": "^3.0.0", - "strip-json-comments": "~1.0.1", + "strip-json-comments": "~2.0.1", "table": "^3.7.8", "text-table": "~0.2.0", "user-home": "^2.0.0" @@ -118,9 +119,9 @@ "leche": "^2.1.1", "linefix": "^0.1.1", "load-perf": "^0.2.0", - "markdownlint": "^0.2.0", + "markdownlint": "^0.3.1", "mocha": "^2.4.5", - "mock-fs": "^3.10.0", + "mock-fs": "^3.12.1", "npm-license": "^0.3.2", "phantomjs-prebuilt": "^2.1.7", "proxyquire": "^1.7.10", @@ -132,8 +133,8 @@ }, "directories": {}, "dist": { - "shasum": "4fbbf6833d66654860c23a099c47a0f086de34b7", - "tarball": "https://registry.npmjs.org/eslint/-/eslint-3.8.0.tgz" + "shasum": "636925fd163c9babe2e8be7ae43caf518d469577", + "tarball": "https://registry.npmjs.org/eslint/-/eslint-3.13.0.tgz" }, "engines": { "node": ">=4" @@ -146,7 +147,7 @@ "lib", "messages" ], - "gitHead": "82220042725dd0e86b5ddbeac4166e1eb147aa04", + "gitHead": "8571ab82af1d86bf4aa6a9be79ece42493607c69", "homepage": "http://eslint.org", "keywords": [ "ast", @@ -193,5 +194,5 @@ "release": "node Makefile.js release", "test": "node Makefile.js test" }, - "version": "3.8.0" + "version": "3.13.0" } diff --git a/tools/test.py b/tools/test.py index c8edca2b991ad2..b6db2cd68e3f7e 100755 --- a/tools/test.py +++ b/tools/test.py @@ -1628,9 +1628,9 @@ def Main(): tempdir = os.environ.get('NODE_TEST_DIR') or options.temp_dir if tempdir: + os.environ['NODE_TEST_DIR'] = tempdir try: os.makedirs(tempdir) - os.environ['NODE_TEST_DIR'] = tempdir except OSError as exception: if exception.errno != errno.EEXIST: print "Could not create the temporary directory", options.temp_dir