diff --git a/.editorconfig b/.editorconfig index 1c1b4418547481..9eda3f95b66ab0 100644 --- a/.editorconfig +++ b/.editorconfig @@ -36,5 +36,5 @@ end_of_line = ignore trim_trailing_whitespace = ignore charset = ignore -[{test/fixtures,deps,tools/eslint,tools/gyp,tools/icu,tools/msvs}/**] +[{test/fixtures,deps,tools/node_modules,tools/gyp,tools/icu,tools/msvs}/**] insert_final_newline = false diff --git a/.eslintignore b/.eslintignore index b9b743fb536cf5..27d1707084861f 100644 --- a/.eslintignore +++ b/.eslintignore @@ -3,7 +3,7 @@ lib/punycode.js test/addons/??_* test/fixtures test/message/esm_display_syntax_error.mjs -tools/eslint +tools/node_modules tools/icu tools/remark-* node_modules diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 4735778b7bbff8..0839e352cd399d 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -7,8 +7,10 @@ env: node: true es6: true +parser: babel-eslint + parserOptions: - ecmaVersion: 2017 + sourceType: script overrides: - files: ["doc/api/esm.md", "*.mjs", "test/es-module/test-esm-example-loader.js"] diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index c0ac8800df2431..63e76a27fab182 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -13,7 +13,7 @@ Contributors guide: https://github.com/nodejs/node/blob/master/CONTRIBUTING.md - [ ] `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes - [ ] tests and/or benchmarks are included - [ ] documentation is changed or added -- [ ] commit message follows [commit guidelines](https://github.com/nodejs/node/blob/master/CONTRIBUTING.md#commit-message-guidelines) +- [ ] commit message follows [commit guidelines](https://github.com/nodejs/node/blob/master/doc/guides/contributing/pull-requests.md#commit-message-guidelines) ##### Affected core subsystem(s) diff --git a/.gitignore b/.gitignore index 40838bcc7fa8d7..0ff301ace3824d 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ .* !deps/**/.* !test/fixtures/**/.* -!tools/eslint/**/.* +!tools/node_modules/**/.* !tools/doc/node_modules/**/.* !.editorconfig !.eslintignore diff --git a/BUILDING.md b/BUILDING.md index c459a867ba6096..74b5903ed22cd0 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -10,7 +10,7 @@ file a new issue. ## Supported platforms -This list of supported platforms is current as of the branch / release to +This list of supported platforms is current as of the branch/release to which it is attached. ### Input @@ -33,15 +33,15 @@ Support is divided into three tiers: ### Supported platforms -The community does not build or test against end of life distributions (EoL). -Thus we do not recommend that you use Node on end of life or unsupported platforms +The community does not build or test against end-of-life distributions (EoL). +Thus we do not recommend that you use Node on end-of-life or unsupported platforms in production. | System | Support type | Version | Architectures | Notes | |--------------|--------------|----------------------------------|----------------------|------------------| | GNU/Linux | Tier 1 | kernel >= 2.6.32, glibc >= 2.12 | x64, arm, arm64 | | | macOS | Tier 1 | >= 10.10 | x64 | | -| Windows | Tier 1 | >= Windows 7 / 2008 R2 | x86, x64 | vs2017 | +| Windows | Tier 1 | >= Windows 7/2008 R2 | x86, x64 | vs2017 | | SmartOS | Tier 2 | >= 15 < 16.4 | x86, x64 | see note1 | | FreeBSD | Tier 2 | >= 10 | x64 | | | GNU/Linux | Tier 2 | kernel >= 3.13.0, glibc >= 2.19 | ppc64le >=power8 | | @@ -92,16 +92,16 @@ Depending on host platform, the selection of toolchains may vary. *Note:* All prerequisites can be easily installed by following [this bootstrapping guide](https://github.com/nodejs/node/blob/master/tools/bootstrap/README.md). -### Unix / macOS +### Unix/macOS -Prerequisites: +#### Prerequisites * `gcc` and `g++` 4.9.4 or newer, or * `clang` and `clang++` 3.4.2 or newer (macOS: latest Xcode Command Line Tools) * Python 2.6 or 2.7 * GNU Make 3.81 or newer -On macOS you will need to install the `Xcode Command Line Tools` by running +On macOS, you will need to install the `Xcode Command Line Tools` by running `xcode-select --install`. Alternatively, if you already have the full Xcode installed, you can find them under the menu `Xcode -> Open Developer Tool -> More Developer Tools...`. This step will install `clang`, `clang++`, and @@ -114,12 +114,14 @@ If the path to your build directory contains a space, the build will likely fail ```console $ sudo ./tools/macosx-firewall.sh ``` -Running this script will add rules for the executable `node` in the out +Running this script will add rules for the executable `node` in the `out` directory and the symbolic `node` link in the project's root directory. On FreeBSD and OpenBSD, you may also need: * libexecinfo +#### Building Node.js + To build Node.js: ```console @@ -138,13 +140,26 @@ for more information. Note that the above requires that `python` resolve to Python 2.6 or 2.7 and not a newer version. -To run the tests: +#### Running Tests + +To verify the build: + +```console +$ make test-only +``` + +At this point, you are ready to make code changes and re-run the tests. + +If you are running tests prior to submitting a Pull Request, the recommended +command is: ```console $ make test ``` -At this point you are ready to make code changes and re-run the tests! +`make test` does a full check on the codebase, including running linters and +documentation tests. + Optionally, continue below. To run the tests and generate code coverage reports: @@ -166,6 +181,8 @@ reports: $ make coverage-clean ``` +#### Building the documentation + To build the documentation: This will build Node.js first (if necessary) and then use it to build the docs: @@ -215,7 +232,8 @@ Prerequisites: * **Optional** (to build the MSI): the [WiX Toolset v3.11](http://wixtoolset.org/releases/) and the [Wix Toolset Visual Studio 2017 Extension](https://marketplace.visualstudio.com/items?itemName=RobMensching.WixToolsetVisualStudio2017Extension). -If the path to your build directory contains a space, the build will likely fail. +If the path to your build directory contains a space or a non-ASCII character, the +build will likely fail. ```console > .\vcbuild @@ -233,7 +251,7 @@ To test if Node.js was built correctly: > Release\node -e "console.log('Hello from Node.js', process.version)" ``` -### Android / Android-based devices (e.g. Firefox OS) +### Android/Android-based devices (e.g. Firefox OS) Although these instructions for building on Android are provided, please note that Android is not an officially supported platform at this time. Patches to @@ -273,7 +291,7 @@ With the `--download=all`, this may download ICU if you don't have an ICU in `deps/icu`. (The embedded `small-icu` included in the default Node.js source does not include all locales.) -##### Unix / macOS: +##### Unix/macOS: ```console $ ./configure --with-intl=full-icu --download=all @@ -290,7 +308,7 @@ $ ./configure --with-intl=full-icu --download=all The `Intl` object will not be available, nor some other APIs such as `String.normalize`. -##### Unix / macOS: +##### Unix/macOS: ```console $ ./configure --without-intl @@ -302,7 +320,7 @@ $ ./configure --without-intl > .\vcbuild without-intl ``` -#### Use existing installed ICU (Unix / macOS only): +#### Use existing installed ICU (Unix/macOS only): ```console $ pkg-config --modversion icu-i18n && ./configure --with-intl=system-icu @@ -318,7 +336,7 @@ You can find other ICU releases at Download the file named something like `icu4c-**##.#**-src.tgz` (or `.zip`). -##### Unix / macOS +##### Unix/macOS From an already-unpacked ICU: ```console @@ -366,7 +384,7 @@ and [user guide](https://openssl.org/docs/fips/UserGuide-2.0.pdf). through which you get the file complies with the requirements for a "secure installation" as described in section 6.6 in the [user guide](https://openssl.org/docs/fips/UserGuide-2.0.pdf). - For evaluation/experimentation you can simply download and verify + For evaluation/experimentation, you can simply download and verify `openssl-fips-x.x.x.tar.gz` from https://www.openssl.org/source/ 2. Extract source to `openssl-fips` folder and `cd openssl-fips` 3. `./config` @@ -385,3 +403,26 @@ and [user guide](https://openssl.org/docs/fips/UserGuide-2.0.pdf). `/usr/local/ssl/fips-2.0` 8. Build Node.js with `make -j` 9. Verify with `node -p "process.versions.openssl"` (for example `1.0.2a-fips`) + +## Building Node.js with external core modules + +It is possible to specify one or more JavaScript text files to be bundled in +the binary as builtin modules when building Node.js. + +### Unix / macOS + +This command will make `/root/myModule.js` available via +`require('/root/myModule')` and `./myModule2.js` available via +`require('myModule2')`. + +```console +$ ./configure --link-module '/root/myModule.js' --link-module './myModule2.js' +``` + +### Windows + +To make `./myCustomModule.js` available via `require('myCustomModule')`. + +```console +> .\vcbuild link-module './myCustomModule.js' +``` diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ba104e7f77801..c6c8277ec86836 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,8 @@ release. -9.4.0
+9.5.0
+9.4.0
9.3.0
9.2.1
9.2.0
diff --git a/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index 2569570b8d03bd..5a1d51dafe375c 100644 --- a/COLLABORATOR_GUIDE.md +++ b/COLLABORATOR_GUIDE.md @@ -127,12 +127,14 @@ Before landing pull requests, sufficient time should be left for input from other Collaborators. In general, leave at least 48 hours during the week and 72 hours over weekends to account for international time differences and work schedules. However, certain types of pull requests -can be fast-tracked and may be landed after a shorter delay: +can be fast-tracked and may be landed after a shorter delay. For example: -* Focused changes that affect only documentation and/or the test suite. - `code-and-learn` and `good-first-issue` pull requests typically fall - into this category. -* Changes that fix regressions. +* Focused changes that affect only documentation and/or the test suite: + * `code-and-learn` tasks typically fall into this category. + * `good-first-issue` pull requests may also be suitable. +* Changes that fix regressions: + * Regressions that break the workflow (red CI or broken compilation). + * Regressions that happen right before a release, or reported soon after. When a pull request is deemed suitable to be fast-tracked, label it with `fast-track`. The pull request can be landed once 2 or more Collaborators @@ -435,7 +437,7 @@ The TSC should serve as the final arbiter where required. author when squashing. Review the commit message to ensure that it adheres to the guidelines outlined -in the [contributing](./CONTRIBUTING.md#commit-message-guidelines) guide. +in the [contributing](./doc/guides/contributing/pull-requests.md#commit-message-guidelines) guide. Add all necessary [metadata](#metadata) to commit messages before landing. @@ -465,7 +467,7 @@ $ git checkout master ``` Update the tree (assumes your repo is set up as detailed in -[CONTRIBUTING.md](CONTRIBUTING.md#step-1-fork)): +[CONTRIBUTING.md](./doc/guides/contributing/pull-requests.md#step-1-fork)): ```text $ git fetch upstream @@ -560,7 +562,7 @@ commit logs, ensure that they are properly formatted, and add `Reviewed-By` lines. * The commit message text must conform to the -[commit message guidelines](./CONTRIBUTING.md#commit-message-guidelines). +[commit message guidelines](./doc/guides/contributing/pull-requests.md#commit-message-guidelines). * Modify the original commit message to include additional metadata regarding @@ -621,7 +623,7 @@ error: failed to push some refs to 'https://github.com/nodejs/node' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes -hint: (e.g., 'git pull ...') before pushing again. +hint: (e.g. 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b1cc67ada553ff..cb8d20e90d005b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,821 +11,37 @@ small and all contributions are valued. This guide explains the process for contributing to the Node.js project's core `nodejs/node` GitHub Repository and describes what to expect at each step. -* [Code of Conduct](#code-of-conduct) - * [Bad Actors](#bad-actors) -* [Issues](#issues) - * [Asking for General Help](#asking-for-general-help) - * [Discussing non-technical topics](#discussing-non-technical-topics) - * [Submitting a Bug Report](#submitting-a-bug-report) - * [Triaging a Bug Report](#triaging-a-bug-report) - * [Resolving a Bug Report](#resolving-a-bug-report) -* [Pull Requests](#pull-requests) - * [Dependencies](#dependencies) - * [Setting up your local environment](#setting-up-your-local-environment) - * [Step 1: Fork](#step-1-fork) - * [Step 2: Branch](#step-2-branch) - * [The Process of Making Changes](#the-process-of-making-changes) - * [Step 3: Code](#step-3-code) - * [Step 4: Commit](#step-4-commit) - * [Commit message guidelines](#commit-message-guidelines) - * [Step 5: Rebase](#step-5-rebase) - * [Step 6: Test](#step-6-test) - * [Test Coverage](#test-coverage) - * [Step 7: Push](#step-7-push) - * [Step 8: Opening the Pull Request](#step-8-opening-the-pull-request) - * [Step 9: Discuss and Update](#step-9-discuss-and-update) - * [Approval and Request Changes Workflow](#approval-and-request-changes-workflow) - * [Step 10: Landing](#step-10-landing) - * [Reviewing Pull Requests](#reviewing-pull-requests) - * [Review a bit at a time](#review-a-bit-at-a-time) - * [Be aware of the person behind the code](#be-aware-of-the-person-behind-the-code) - * [Respect the minimum wait time for comments](#respect-the-minimum-wait-time-for-comments) - * [Abandoned or Stalled Pull Requests](#abandoned-or-stalled-pull-requests) - * [Approving a change](#approving-a-change) - * [Accept that there are different opinions about what belongs in Node.js](#accept-that-there-are-different-opinions-about-what-belongs-in-nodejs) - * [Performance is not everything](#performance-is-not-everything) - * [Continuous Integration Testing](#continuous-integration-testing) -* [Additional Notes](#additional-notes) - * [Commit Squashing](#commit-squashing) - * [Getting Approvals for your Pull Request](#getting-approvals-for-your-pull-request) - * [CI Testing](#ci-testing) - * [Waiting Until the Pull Request Gets Landed](#waiting-until-the-pull-request-gets-landed) - * [Check Out the Collaborator's Guide](#check-out-the-collaborators-guide) - * [Helpful Resources](#helpful-resources) -* [Developer's Certificate of Origin 1.1](#developers-certificate-of-origin-11) +## [Code of Conduct](./doc/guides/contributing/coc.md) -## Code of Conduct +The Node.js project has a +[Code of Conduct](https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md) +that *all* contributors are expected to follow. This code describes the +*minimum* behavior expectations for all contributors. -The Node.js project has a [Code of Conduct][] that *all* contributors are -expected to follow. This code describes the *minimum* behavior expectations -for all contributors. +See [details on our policy on Code of Conduct](./doc/guides/contributing/coc.md). -As a contributor to Node.js, how you choose to act and interact towards your -fellow contributors, as well as to the community, will reflect back not only -on yourself but on the project as a whole. The Code of Conduct is designed and -intended, above all else, to help establish a culture within the project that -allows anyone and everyone who wants to contribute to feel safe doing so. - -Should any individual act in any way that is considered in violation of the -[Code of Conduct][], corrective actions will be taken. It is possible, however, -for any individual to *act* in such a manner that is not in violation of the -strict letter of the Code of Conduct guidelines while still going completely -against the spirit of what that Code is intended to accomplish. - -Open, diverse, and inclusive communities live and die on the basis of trust. -Contributors can disagree with one another so long as they trust that those -disagreements are in good faith and everyone is working towards a common goal. - -### Bad actors - -All contributors to Node.js tacitly agree to abide by both the letter and -spirit of the [Code of Conduct][]. Failure, or unwillingness, to do so will -result in contributions being respectfully declined. - -A *bad actor* is someone who repeatedly violates the *spirit* of the Code of -Conduct through consistent failure to self-regulate the way in which they -interact with other contributors in the project. In doing so, bad actors -alienate other contributors, discourage collaboration, and generally reflect -poorly on the project as a whole. - -Being a bad actor may be intentional or unintentional. Typically, unintentional -bad behavior can be easily corrected by being quick to apologize and correct -course *even if you are not entirely convinced you need to*. Giving other -contributors the benefit of the doubt and having a sincere willingness to admit -that you *might* be wrong is critical for any successful open collaboration. - -Don't be a bad actor. - -## Issues +## [Issues](./doc/guides/contributing/issues.md) Issues in `nodejs/node` are the primary means by which bug reports and -general discussions are made. For any issue, there are fundamentally three -ways an individual can contribute: - -1. By opening the issue for discussion: For instance, if you believe that you - have uncovered a bug in Node.js, creating a new issue in the `nodejs/node` - issue tracker is the way to report it. -2. By helping to triage the issue: This can be done either by providing - supporting details (a test case that demonstrates a bug), or providing - suggestions on how to address the issue. -3. By helping to resolve the issue: Typically this is done either in the form - of demonstrating that the issue reported is not a problem after all, or more - often, by opening a Pull Request that changes some bit of something in - `nodejs/node` in a concrete and reviewable manner. - -### Asking for General Help - -Because the level of activity in the `nodejs/node` repository is so high, -questions or requests for general help using Node.js should be directed at -the [Node.js help repository][]. - -### Discussing non-technical topics - -Discussion of non-technical topics (such as intellectual property and trademark) -should be directed to the [Technical Steering Committee (TSC) repository][]. - -### Submitting a Bug Report - -When opening a new issue in the `nodejs/node` issue tracker, users will be -presented with a basic template that should be filled in. - -```markdown - - -* **Version**: -* **Platform**: -* **Subsystem**: - - -``` - -If you believe that you have uncovered a bug in Node.js, please fill out this -form, following the template to the best of your ability. Do not worry if you -cannot answer every detail, just fill in what you can. - -The two most important pieces of information we need in order to properly -evaluate the report is a description of the behavior you are seeing and a simple -test case we can use to recreate the problem on our own. If we cannot recreate -the issue, it becomes impossible for us to fix. +general discussions are made. -In order to rule out the possibility of bugs introduced by userland code, test -cases should be limited, as much as possible, to using *only* Node.js APIs. -If the bug occurs only when you're using a specific userland module, there is -a very good chance that either (a) the module has a bug or (b) something in -Node.js changed that broke the module. +* [How to Contribute in Issues](./doc/guides/contributing/issues.md#how-to-contribute-in-issues) +* [Asking for General Help](./doc/guides/contributing/issues.md#asking-for-general-help) +* [Discussing non-technical topics](./doc/guides/contributing/issues.md#discussing-non-technical-topics) +* [Submitting a Bug Report](./doc/guides/contributing/issues.md#submitting-a-bug-report) +* [Triaging a Bug Report](./doc/guides/contributing/issues.md#triaging-a-bug-report) +* [Resolving a Bug Report](./doc/guides/contributing/issues.md#resolving-a-bug-report) -### Triaging a Bug Report - -Once an issue has been opened, it is not uncommon for there to be discussion -around it. Some contributors may have differing opinions about the issue, -including whether the behavior being seen is a bug or a feature. This discussion -is part of the process and should be kept focused, helpful, and professional. - -Short, clipped responses—that provide neither additional context nor supporting -detail—are not helpful or professional. To many, such responses are simply -annoying and unfriendly. - -Contributors are encouraged to help one another make forward progress as much -as possible, empowering one another to solve issues collaboratively. If you -choose to comment on an issue that you feel either is not a problem that needs -to be fixed, or if you encounter information in an issue that you feel is -incorrect, explain *why* you feel that way with additional supporting context, -and be willing to be convinced that you may be wrong. By doing so, we can often -reach the correct outcome much faster. - -### Resolving a Bug Report - -In the vast majority of cases, issues are resolved by opening a Pull Request. -The process for opening and reviewing a Pull Request is similar to that of -opening and triaging issues, but carries with it a necessary review and approval -workflow that ensures that the proposed changes meet the minimal quality and -functional guidelines of the Node.js project. - -## Pull Requests +## [Pull Requests](./doc/guides/contributing/pull-requests.md) Pull Requests are the way concrete changes are made to the code, documentation, dependencies, and tools contained in the `nodejs/node` repository. -There are two fundamental components of the Pull Request process: one concrete -and technical, and one more process oriented. The concrete and technical -component involves the specific details of setting up your local environment -so that you can make the actual changes. This is where we will start. - -### Dependencies - -Node.js has several bundled dependencies in the *deps/* and the *tools/* -directories that are not part of the project proper. Changes to files in those -directories should be sent to their respective projects. Do not send a patch to -Node.js. We cannot accept such patches. - -In case of doubt, open an issue in the -[issue tracker](https://github.com/nodejs/node/issues/) or contact one of the -[project Collaborators](https://github.com/nodejs/node/#current-project-team-members). -Node.js has two IRC channels: -[#Node.js](https://webchat.freenode.net/?channels=node.js) for general help and -questions, and -[#Node-dev](https://webchat.freenode.net/?channels=node-dev) for development of -Node.js core specifically. - -### Setting up your local environment - -To get started, you will need to have `git` installed locally. Depending on -your operating system, there are also a number of other dependencies required. -These are detailed in the [Building guide][]. - -Once you have `git` and are sure you have all of the necessary dependencies, -it's time to create a fork. - -Before getting started, it is recommended to configure `git` so that it knows -who you are: - -```text -$ git config --global user.name "J. Random User" -$ git config --global user.email "j.random.user@example.com" -``` -Please make sure this local email is also added to your -[GitHub email list](https://github.com/settings/emails) so that your commits -will be properly associated with your account and you will be promoted -to Contributor once your first commit is landed. - -#### Step 1: Fork - -Fork the project [on GitHub](https://github.com/nodejs/node) and clone your fork -locally. - -```text -$ git clone git@github.com:username/node.git -$ cd node -$ git remote add upstream https://github.com/nodejs/node.git -$ git fetch upstream -``` - -#### Step 2: Branch - -As a best practice to keep your development environment as organized as -possible, create local branches to work within. These should also be created -directly off of the `master` branch. - -```text -$ git checkout -b my-branch -t upstream/master -``` - -### The Process of Making Changes - -#### Step 3: Code - -The vast majority of Pull Requests opened against the `nodejs/node` -repository includes changes to either the C/C++ code contained in the `src` -directory, the JavaScript code contained in the `lib` directory, the -documentation in `docs/api` or tests within the `test` directory. - -If you are modifying code, please be sure to run `make lint` from time to -time to ensure that the changes follow the Node.js code style guide. - -Any documentation you write (including code comments and API documentation) -should follow the [Style Guide](doc/STYLE_GUIDE.md). Code samples included -in the API docs will also be checked when running `make lint` (or -`vcbuild.bat lint` on Windows). - -For contributing C++ code, you may want to look at the -[C++ Style Guide](CPP_STYLE_GUIDE.md). - -#### Step 4: Commit - -It is a recommended best practice to keep your changes as logically grouped -as possible within individual commits. There is no limit to the number of -commits any single Pull Request may have, and many contributors find it easier -to review changes that are split across multiple commits. - -```text -$ git add my/changed/files -$ git commit -``` - -Note that multiple commits often get squashed when they are landed (see the -notes about [commit squashing](#commit-squashing)). - -##### Commit message guidelines - -A good commit message should describe what changed and why. - -1. The first line should: - - contain a short description of the change (preferably 50 characters or less, - and no more than 72 characters) - - be entirely in lowercase with the exception of proper nouns, acronyms, and - the words that refer to code, like function/variable names - - be prefixed with the name of the changed subsystem and start with an - imperative verb. Check the output of `git log --oneline files/you/changed` to - find out what subsystems your changes touch. - - Examples: - - `net: add localAddress and localPort to Socket` - - `src: fix typos in node_lttng_provider.h` - - -2. Keep the second line blank. -3. Wrap all other lines at 72 columns. - -4. 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 other references -use `Refs:`. - - Examples: - - `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` - -5. If your commit introduces a breaking change (`semver-major`), it should -contain an explanation about the reason of the breaking change, which -situation would trigger the breaking change and what is the exact change. - -Breaking changes will be listed in the wiki with the aim to make upgrading -easier. Please have a look at [Breaking Changes](https://github.com/nodejs/node/wiki/Breaking-changes-between-v4-LTS-and-v6-LTS) -for the level of detail that's suitable. - -Sample complete commit message: - -```txt -subsystem: explain the commit in one line - -Body of commit message is a few lines of text, explaining things -in more detail, possibly giving some background about the issue -being fixed, etc. - -The body of the commit message can be several paragraphs, and -please do proper word-wrap and keep columns shorter than about -72 characters or so. That way, `git log` will show things -nicely even when it is indented. - -Fixes: https://github.com/nodejs/node/issues/1337 -Refs: http://eslint.org/docs/rules/space-in-parens.html -``` - -If you are new to contributing to Node.js, please try to do your best at -conforming to these guidelines, but do not worry if you get something wrong. -One of the existing contributors will help get things situated and the -contributor landing the Pull Request will ensure that everything follows -the project guidelines. - -#### Step 5: Rebase - -As a best practice, once you have committed your changes, it is a good idea -to use `git rebase` (not `git merge`) to synchronize your work with the main -repository. - -```text -$ git fetch upstream -$ git rebase upstream/master -``` - -This ensures that your working branch has the latest changes from `nodejs/node` -master. - -#### Step 6: Test - -Bug fixes and features should always come with tests. A -[guide for writing tests in Node.js](./doc/guides/writing-tests.md) has been -provided to make the process easier. Looking at other tests to see how they -should be structured can also help. - -The `test` directory within the `nodejs/node` repository is complex and it is -often not clear where a new test file should go. When in doubt, add new tests -to the `test/parallel/` directory and the right location will be sorted out -later. - -Before submitting your changes in a Pull Request, always run the full Node.js -test suite. To run the tests (including code linting) on Unix / macOS: - -```text -$ ./configure && make -j4 test -``` - -And on Windows: - -```text -> vcbuild test -``` - -(See the [BUILDING.md](./BUILDING.md) for more details.) - -Make sure the linter does not report any issues and that all tests pass. Please -do not submit patches that fail either check. - -If you want to run the linter without running tests, use -`make lint`/`vcbuild lint`. It will run both JavaScript linting and -C++ linting. - -If you are updating tests and just want to run a single test to check it: - -```text -$ python tools/test.py -J --mode=release parallel/test-stream2-transform -``` - -You can execute the entire suite of tests for a given subsystem -by providing the name of a subsystem: - -```text -$ python tools/test.py -J --mode=release child-process -``` - -If you want to check the other options, please refer to the help by using -the `--help` option - -```text -$ python tools/test.py --help -``` - -You can usually run tests directly with node: - -```text -$ ./node ./test/parallel/test-stream2-transform.js -``` - -Remember to recompile with `make -j4` in between test runs if you change code in -the `lib` or `src` directories. - -##### Test Coverage - -It's good practice to ensure any code you add or change is covered by tests. -You can do so by running the test suite with coverage enabled: - -```text -$ ./configure --coverage && make coverage -``` - -A detailed coverage report will be written to `coverage/index.html` for -JavaScript coverage and to `coverage/cxxcoverage.html` for C++ coverage. - -_Note that generating a test coverage report can take several minutes._ - -To collect coverage for a subset of tests you can set the `CI_JS_SUITES` and -`CI_NATIVE_SUITES` variables: - -```text -$ CI_JS_SUITES=child-process CI_NATIVE_SUITES= make coverage -``` - -The above command executes tests for the `child-process` subsystem and -outputs the resulting coverage report. - -Running tests with coverage will create and modify several directories -and files. To clean up afterwards, run: - -```text -make coverage-clean -./configure && make -j4. -``` - -#### Step 7: Push - -Once you are sure your commits are ready to go, with passing tests and linting, -begin the process of opening a Pull Request by pushing your working branch to -your fork on GitHub. - -```text -$ git push origin my-branch -``` - -#### Step 8: Opening the Pull Request - -From within GitHub, opening a new Pull Request will present you with a template -that should be filled out: - -```markdown - - -##### Checklist - - -- [ ] `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes -- [ ] tests and/or benchmarks are included -- [ ] documentation is changed or added -- [ ] commit message follows [commit guidelines](https://github.com/nodejs/node/blob/master/CONTRIBUTING.md#commit-message-guidelines) - -##### Affected core subsystem(s) - -``` - -Please try to do your best at filling out the details, but feel free to skip -parts if you're not sure what to put. - -Once opened, Pull Requests are usually reviewed within a few days. - -#### Step 9: Discuss and update - -You will probably get feedback or requests for changes to your Pull Request. -This is a big part of the submission process so don't be discouraged! Some -contributors may sign off on the Pull Request right away, others may have -more detailed comments or feedback. This is a necessary part of the process -in order to evaluate whether the changes are correct and necessary. - -To make changes to an existing Pull Request, make the changes to your local -branch, add a new commit with those changes, and push those to your fork. -GitHub will automatically update the Pull Request. - -```text -$ git add my/changed/files -$ git commit -$ git push origin my-branch -``` - -It is also frequently necessary to synchronize your Pull Request with other -changes that have landed in `master` by using `git rebase`: - -```text -$ git fetch --all -$ git rebase origin/master -$ git push --force-with-lease origin my-branch -``` - -**Important:** The `git push --force-with-lease` command is one of the few ways -to delete history in `git`. Before you use it, make sure you understand the -risks. If in doubt, you can always ask for guidance in the Pull Request or on -[IRC in the #node-dev channel][]. - -If you happen to make a mistake in any of your commits, do not worry. You can -amend the last commit (for example if you want to change the commit log). - -```text -$ git add any/changed/files -$ git commit --amend -$ git push --force-with-lease origin my-branch -``` - -There are a number of more advanced mechanisms for managing commits using -`git rebase` that can be used, but are beyond the scope of this guide. - -Feel free to post a comment in the Pull Request to ping reviewers if you are -awaiting an answer on something. If you encounter words or acronyms that -seem unfamiliar, refer to this -[glossary](https://sites.google.com/a/chromium.org/dev/glossary). - -##### Approval and Request Changes Workflow - -All Pull Requests require "sign off" in order to land. Whenever a contributor -reviews a Pull Request they may find specific details that they would like to -see changed or fixed. These may be as simple as fixing a typo, or may involve -substantive changes to the code you have written. In general, such requests -are intended to be helpful, but at times may come across as abrupt or unhelpful, -especially requests to change things that do not include concrete suggestions -on *how* to change them. - -Try not to be discouraged. If you feel that a particular review is unfair, -say so, or contact one of the other contributors in the project and seek their -input. Often such comments are the result of the reviewer having only taken a -short amount of time to review and are not ill-intended. Such issues can often -be resolved with a bit of patience. That said, reviewers should be expected to -be helpful in their feedback, and feedback that is simply vague, dismissive and -unhelpful is likely safe to ignore. - -#### Step 10: Landing - -In order to land, a Pull Request needs to be reviewed and [approved][] by -at least one Node.js Collaborator and pass a -[CI (Continuous Integration) test run][]. After that, as long as there are no -objections from other contributors, the Pull Request can be merged. If you find -your Pull Request waiting longer than you expect, see the -[notes about the waiting time](#waiting-until-the-pull-request-gets-landed). - -When a collaborator lands your Pull Request, they will post -a comment to the Pull Request page mentioning the commit(s) it -landed as. GitHub often shows the Pull Request as `Closed` at this -point, but don't worry. If you look at the branch you raised your -Pull Request against (probably `master`), you should see a commit with -your name on it. Congratulations and thanks for your contribution! - -### Reviewing Pull Requests - -All Node.js contributors who choose to review and provide feedback on Pull -Requests have a responsibility to both the project and the individual making the -contribution. Reviews and feedback must be helpful, insightful, and geared -towards improving the contribution as opposed to simply blocking it. If there -are reasons why you feel the PR should not land, explain what those are. Do not -expect to be able to block a Pull Request from advancing simply because you say -"No" without giving an explanation. Be open to having your mind changed. Be open -to working with the contributor to make the Pull Request better. - -Reviews that are dismissive or disrespectful of the contributor or any other -reviewers are strictly counter to the [Code of Conduct][]. - -When reviewing a Pull Request, the primary goals are for the codebase to improve -and for the person submitting the request to succeed. Even if a Pull Request -does not land, the submitters should come away from the experience feeling like -their effort was not wasted or unappreciated. Every Pull Request from a new -contributor is an opportunity to grow the community. - -#### Review a bit at a time. - -Do not overwhelm new contributors. - -It is tempting to micro-optimize and make everything about relative performance, -perfect grammar, or exact style matches. Do not succumb to that temptation. - -Focus first on the most significant aspects of the change: - -1. Does this change make sense for Node.js? -2. Does this change make Node.js better, even if only incrementally? -3. Are there clear bugs or larger scale issues that need attending to? -4. Is the commit message readable and correct? If it contains a breaking change is it clear enough? - -When changes are necessary, *request* them, do not *demand* them, and do not -assume that the submitter already knows how to add a test or run a benchmark. - -Specific performance optimization techniques, coding styles and conventions -change over time. The first impression you give to a new contributor never does. - -Nits (requests for small changes that are not essential) are fine, but try to -avoid stalling the Pull Request. Most nits can typically be fixed by the -Node.js Collaborator landing the Pull Request but they can also be an -opportunity for the contributor to learn a bit more about the project. - -It is always good to clearly indicate nits when you comment: e.g. -`Nit: change foo() to bar(). But this is not blocking.` - -#### Be aware of the person behind the code - -Be aware that *how* you communicate requests and reviews in your feedback can -have a significant impact on the success of the Pull Request. Yes, we may land -a particular change that makes Node.js better, but the individual might just -not want to have anything to do with Node.js ever again. The goal is not just -having good code. - -#### Respect the minimum wait time for comments - -There is a minimum waiting time which we try to respect for non-trivial -changes, so that people who may have important input in such a distributed -project are able to respond. - -For non-trivial changes, Pull Requests must be left open for *at least* 48 -hours during the week, and 72 hours on a weekend. In most cases, when the -PR is relatively small and focused on a narrow set of changes, these periods -provide more than enough time to adequately review. Sometimes changes take far -longer to review, or need more specialized review from subject matter experts. -When in doubt, do not rush. - -Trivial changes, typically limited to small formatting changes or fixes to -documentation, may be landed within the minimum 48 hour window. - -#### Abandoned or Stalled Pull Requests - -If a Pull Request appears to be abandoned or stalled, it is polite to first -check with the contributor to see if they intend to continue the work before -checking if they would mind if you took it over (especially if it just has -nits left). When doing so, it is courteous to give the original contributor -credit for the work they started (either by preserving their name and email -address in the commit log, or by using an `Author: ` meta-data tag in the -commit. - -#### Approving a change - -Any Node.js core Collaborator (any GitHub user with commit rights in the -`nodejs/node` repository) is authorized to approve any other contributor's -work. Collaborators are not permitted to approve their own Pull Requests. - -Collaborators indicate that they have reviewed and approve of the changes in -a Pull Request either by using GitHub's Approval Workflow, which is preferred, -or by leaving an `LGTM` ("Looks Good To Me") comment. - -When explicitly using the "Changes requested" component of the GitHub Approval -Workflow, show empathy. That is, do not be rude or abrupt with your feedback -and offer concrete suggestions for improvement, if possible. If you're not -sure *how* a particular change can be improved, say so. - -Most importantly, after leaving such requests, it is courteous to make yourself -available later to check whether your comments have been addressed. - -If you see that requested changes have been made, you can clear another -collaborator's `Changes requested` review. - -Change requests that are vague, dismissive, or unconstructive may also be -dismissed if requests for greater clarification go unanswered within a -reasonable period of time. - -If you do not believe that the Pull Request should land at all, use -`Changes requested` to indicate that you are considering some of your comments -to block the PR from landing. When doing so, explain *why* you believe the -Pull Request should not land along with an explanation of what may be an -acceptable alternative course, if any. - -#### Accept that there are different opinions about what belongs in Node.js - -Opinions on this vary, even among the members of the Technical Steering -Committee. - -One general rule of thumb is that if Node.js itself needs it (due to historic -or functional reasons), then it belongs in Node.js. For instance, `url` -parsing is in Node.js because of HTTP protocol support. - -Also, functionality that either cannot be implemented outside of core in any -reasonable way, or only with significant pain. - -It is not uncommon for contributors to suggest new features they feel would -make Node.js better. These may or may not make sense to add, but as with all -changes, be courteous in how you communicate your stance on these. Comments -that make the contributor feel like they should have "known better" or -ridiculed for even trying run counter to the [Code of Conduct][]. - -#### Performance is not everything - -Node.js has always optimized for speed of execution. If a particular change -can be shown to make some part of Node.js faster, it's quite likely to be -accepted. Claims that a particular Pull Request will make things faster will -almost always be met by requests for performance [benchmark results][] that -demonstrate the improvement. - -That said, performance is not the only factor to consider. Node.js also -optimizes in favor of not breaking existing code in the ecosystem, and not -changing working functional code just for the sake of changing. - -If a particular Pull Request introduces a performance or functional -regression, rather than simply rejecting the Pull Request, take the time to -work *with* the contributor on improving the change. Offer feedback and -advice on what would make the Pull Request acceptable, and do not assume that -the contributor should already know how to do that. Be explicit in your -feedback. - -#### Continuous Integration Testing - -All Pull Requests that contain changes to code must be run through -continuous integration (CI) testing at [https://ci.nodejs.org/][]. - -Only Node.js core Collaborators with commit rights to the `nodejs/node` -repository may start a CI testing run. The specific details of how to do -this are included in the new Collaborator [Onboarding guide][]. - -Ideally, the code change will pass ("be green") on all platform configurations -supported by Node.js (there are over 30 platform configurations currently). -This means that all tests pass and there are no linting errors. In reality, -however, it is not uncommon for the CI infrastructure itself to fail on -specific platforms or for so-called "flaky" tests to fail ("be red"). It is -vital to visually inspect the results of all failed ("red") tests to determine -whether the failure was caused by the changes in the Pull Request. - -## Additional Notes - -### Commit Squashing - -When the commits in your Pull Request land, they may be squashed -into one commit per logical change. Metadata will be added to the commit -message (including links to the Pull Request, links to relevant issues, -and the names of the reviewers). The commit history of your Pull Request, -however, will stay intact on the Pull Request page. - -For the size of "one logical change", -[0b5191f](https://github.com/nodejs/node/commit/0b5191f15d0f311c804d542b67e2e922d98834f8) -can be a good example. It touches the implementation, the documentation, -and the tests, but is still one logical change. In general, the tests should -always pass when each individual commit lands on the master branch. - -### Getting Approvals for Your Pull Request - -A Pull Request is approved either by saying LGTM, which stands for -"Looks Good To Me", or by using GitHub's Approve button. -GitHub's Pull Request review feature can be used during the process. -For more information, check out -[the video tutorial](https://www.youtube.com/watch?v=HW0RPaJqm4g) -or [the official documentation](https://help.github.com/articles/reviewing-changes-in-pull-requests/). - -After you push new changes to your branch, you need to get -approval for these new changes again, even if GitHub shows "Approved" -because the reviewers have hit the buttons before. - -### CI Testing - -Every Pull Request needs to be tested -to make sure that it works on the platforms that Node.js -supports. This is done by running the code through the CI system. - -Only a Collaborator can start a CI run. Usually one of them will do it -for you as approvals for the Pull Request come in. -If not, you can ask a Collaborator to start a CI run. - -### Waiting Until the Pull Request Gets Landed - -A Pull Request needs to stay open for at least 48 hours (72 hours on a -weekend) from when it is submitted, even after it gets approved and -passes the CI. This is to make sure that everyone has a chance to -weigh in. If the changes are trivial, collaborators may decide it -doesn't need to wait. A Pull Request may well take longer to be -merged in. All these precautions are important because Node.js is -widely used, so don't be discouraged! - -### Check Out the Collaborator's Guide - -If you want to know more about the code review and the landing process, -you can take a look at the -[collaborator's guide](https://github.com/nodejs/node/blob/master/COLLABORATOR_GUIDE.md). - -### Helpful Resources - -The following additional resources may be of assistance: - -* [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) -* [core-validate-commit](https://github.com/evanlucas/core-validate-commit) - - A utility that ensures commits follow the commit formatting guidelines. +* [Dependencies](./doc/guides/contributing/pull-requests.md#dependencies) +* [Setting up your local environment](./doc/guides/contributing/pull-requests.md#setting-up-your-local-environment) +* [The Process of Making Changes](./doc/guides/contributing/pull-requests.md#the-process-of-making-changes) +* [Reviewing Pull Requests](./doc/guides/contributing/pull-requests.md#reviewing-pull-requests) +* [Additional Notes](./doc/guides/contributing/pull-requests.md#additional-notes) ## Developer's Certificate of Origin 1.1 @@ -853,14 +69,3 @@ By making a contribution to this project, I certify that: personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. - -[approved]: #getting-approvals-for-your-pull-request -[benchmark results]: ./doc/guides/writing-and-running-benchmarks.md -[Building guide]: ./BUILDING.md -[CI (Continuous Integration) test run]: #ci-testing -[Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md -[https://ci.nodejs.org/]: https://ci.nodejs.org/ -[IRC in the #node-dev channel]: https://webchat.freenode.net?channels=node-dev&uio=d4 -[Node.js help repository]: https://github.com/nodejs/help/issues -[Onboarding guide]: ./doc/onboarding.md -[Technical Steering Committee (TSC) repository]: https://github.com/nodejs/TSC/issues diff --git a/CPP_STYLE_GUIDE.md b/CPP_STYLE_GUIDE.md index 6266ee03b7c538..5a275094ad16fa 100644 --- a/CPP_STYLE_GUIDE.md +++ b/CPP_STYLE_GUIDE.md @@ -20,7 +20,8 @@ * [Others](#others) * [Type casting](#type-casting) * [Do not include `*.h` if `*-inl.h` has already been included](#do-not-include-h-if--inlh-has-already-been-included) - * [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods) + * [Avoid throwing JavaScript errors in C++ methods](#avoid-throwing-javascript-errors-in-c) + * [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods) Unfortunately, the C++ linter (based on [Google’s `cpplint`](https://github.com/google/styleguide)), which can be run @@ -213,12 +214,65 @@ instead of #include "util-inl.h" ``` -## Avoid throwing JavaScript errors in nested C++ methods +## Avoid throwing JavaScript errors in C++ -If you need to throw JavaScript errors from a C++ binding method, try to do it -at the top level and not inside of nested calls. +When there is a need to throw errors from a C++ binding method, try to +return the data necessary for constructing the errors to JavaScript, +then construct and throw the errors [using `lib/internal/errors.js`][errors]. -A lot of code inside Node.js is written so that typechecking etc. is performed -in JavaScript. +Note that in general, type-checks on arguments should be done in JavaScript +before the arguments are passed into C++. Then in the C++ binding, simply using +`CHECK` assertions to guard against invalid arguments should be enough. + +If the return value of the binding cannot be used to signal failures or return +the necessary data for constructing errors in JavaScript, pass a context object +to the binding and put the necessary data inside in C++. For example: + +```cpp +void Foo(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + // Let the JavaScript handle the actual type-checking, + // only assertions are placed in C++ + CHECK_EQ(args.Length(), 2); + CHECK(args[0]->IsString()); + CHECK(args[1]->IsObject()); + + int err = DoSomethingWith(args[0].As()); + if (err) { + // Put the data inside the error context + Local ctx = args[1].As(); + Local key = FIXED_ONE_BYTE_STRING(env->isolate(), "code"); + ctx->Set(env->context(), key, err).FromJust(); + } else { + args.GetReturnValue().Set(something_to_return); + } +} + +// In the initialize function +env->SetMethod(target, "foo", Foo); +``` + +```js +exports.foo = function(str) { + // Prefer doing the type-checks in JavaScript + if (typeof str !== 'string') { + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'str', 'string'); + } + + const ctx = {}; + const result = binding.foo(str, ctx); + if (ctx.code !== undefined) { + throw new errors.Error('ERR_ERROR_NAME', ctx.code); + } + return result; +}; +``` + +### Avoid throwing JavaScript errors in nested C++ methods + +When you have to throw the errors from C++, try to do it at the top level and +not inside of nested calls. Using C++ `throw` is not allowed. + +[errors]: https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 7b8903fa5c8bae..4f1ff30d83411c 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -4,27 +4,30 @@ The Node.js project is governed by its Collaborators, including a Technical Steering Committee (TSC) which is responsible for high-level guidance of the project. + + +- [Collaborators](#collaborators) + - [Collaborator Activities](#collaborator-activities) +- [Technical Steering Committee](#technical-steering-committee) + - [TSC Meetings](#tsc-meetings) +- [Collaborator Nominations](#collaborator-nominations) + - [Onboarding](#onboarding) +- [Consensus Seeking Process](#consensus-seeking-process) + + + ## Collaborators -The [nodejs/node](https://github.com/nodejs/node) GitHub repository is -maintained by Collaborators who are added by the TSC on an ongoing basis. +The [nodejs/node][] GitHub repository is maintained by Node.js Core +Collaborators. Upon becoming Collaborators, they: -Individuals identified by the TSC as making significant and valuable -contributions across any Node.js repository may be made Collaborators and given -commit access to the project. Activities taken into consideration include (but -are not limited to) the quality of: +* Become members of the @nodejs/collaborators team +* Gain individual membership of the Node.js foundation -* code commits and pull requests -* documentation commits and pull requests -* comments on issues and pull requests -* contributions to the Node.js website -* assistance provided to end users and novice contributors -* participation in Working Groups -* other participation in the wider Node.js community +Their privileges include but are not limited to: -If individuals making valuable contributions do not believe they have been -considered for commit access, they may log an issue or contact a TSC member -directly. +* Commit access to the [nodejs/node][] repository +* Access to the Node.js continuous integration (CI) jobs Modifications of the contents of the nodejs/node repository are made on a collaborative basis. Anybody with a GitHub account may propose a @@ -49,6 +52,8 @@ Collaborators may opt to elevate significant or controversial modifications to the TSC by assigning the `tsc-review` label to a pull request or issue. The TSC should serve as the final arbiter where required. +See: + * [Current list of Collaborators](./README.md#current-project-team-members) * [A guide for Collaborators](./COLLABORATOR_GUIDE.md) @@ -56,11 +61,11 @@ TSC should serve as the final arbiter where required. Typical activities of a Collaborator include: -* helping users and novice contributors -* contributing code and documentation changes that improve the project -* reviewing and commenting on issues and pull requests -* participation in working groups -* merging pull requests +* Helping users and novice contributors +* Contributing code and documentation changes that improve the project +* Reviewing and commenting on issues and pull requests +* Participation in working groups +* Merging pull requests The TSC periodically reviews the Collaborator list to identify inactive Collaborators. Past Collaborators are typically given _Emeritus_ status. Emeriti @@ -68,8 +73,8 @@ may request that the TSC restore them to active status. ## Technical Steering Committee -The Technical Steering Committee (TSC) has final authority over this project -including: +A subset of the Collaborators form the Technical Steering Committee (TSC). +The TSC has final authority over this project, including: * Technical direction * Project governance and process (including this policy) @@ -78,7 +83,8 @@ including: * Conduct guidelines * Maintaining the list of additional Collaborators -* [Current list of TSC members](./README.md#current-project-team-members) +The current list of TSC members can be found in +[the project README](./README.md#current-project-team-members). The operations of the TSC are governed by the [TSC Charter][] as approved by the Node.js Foundation Board of Directors. @@ -128,10 +134,70 @@ the issue tracker is: either the proposal is dropped or the objecting members are persuaded. If there is an extended impasse, a motion for a vote may be made. +## Collaborator Nominations + +Any existing Collaborator can nominate an individual making significant +and valuable contributions across the Node.js organization to become a new +Collaborator. + +To nominate a new Collaborator, open an issue in the [nodejs/node][] +repository, with a summary of the nominee's contributions, for example: + +* Commits in the [nodejs/node][] repository. + * Can be shown using the link + `https://github.com/nodejs/node/commits?author=${GITHUB_ID}` + (replace `${GITHUB_ID}` with the nominee's GitHub ID). +* Pull requests and issues opened in the [nodejs/node][] repository. + * Can be shown using the link + `https://github.com/nodejs/node/pulls?q=author%3A${GITHUB_ID}+` +* Comments and reviews on issues and pull requests in the + [nodejs/node][] repository + * Can be shown using the links + `https://github.com/nodejs/node/pulls?q=reviewed-by%3A${GITHUB_ID}+` + and `https://github.com/nodejs/node/pulls?q=commenter%3A${GITHUB_ID}+` +* Assistance provided to end users and novice contributors +* Participation in other projects, teams, and working groups of the + Node.js organization + * Can be shown using the links + `https://github.com/search?q=author%3A${GITHUB_ID}++org%3Anodejs&type=Issues` + and + `https://github.com/search?q=commenter%3A${GITHUB_ID}++org%3Anodejs&type=Issues` +* Other participation in the wider Node.js community + +Mention @nodejs/collaborators in the issue to notify other Collaborators about +the nomination. + +If there are no objections raised by any Collaborators one week after +the issue is opened, the nomination will be considered as accepted. +Should there be any objections against the nomination, the TSC is responsible +for working with the individuals involved and finding a resolution. +The nomination must be approved by the TSC, which is assumed when there are no +objections from any TSC members. + +Prior to the public nomination, the Collaborator initiating it can seek +feedback from other Collaborators in private using +[the GitHub discussion page][collaborators-discussions] of the +Collaborators team, and work with the nominee to improve the nominee's +contribution profile, in order to make the nomination as frictionless +as possible. + +If individuals making valuable contributions do not believe they have been +considered for a nomination, they may log an issue or contact a Collaborator +directly. + +### Onboarding + +When the nomination is accepted, the new Collaborator will be onboarded +by a TSC member. See [the onboarding guide](./doc/onboarding.md) on +details of the onboarding process. In general, the onboarding should be +completed within a month after the nomination is accepted. + ## Consensus Seeking Process The TSC follows a [Consensus Seeking][] decision making model as described by the [TSC Charter][]. -[TSC Charter]: https://github.com/nodejs/TSC/blob/master/TSC-Charter.md +[collaborators-discussions]: https://github.com/orgs/nodejs/teams/collaborators/discussions [Consensus Seeking]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making +[TSC Charter]: https://github.com/nodejs/TSC/blob/master/TSC-Charter.md +[nodejs/node]: https://github.com/nodejs/node diff --git a/LICENSE b/LICENSE index 5cb6d3a6f68d73..4d4fd710946b24 100644 --- a/LICENSE +++ b/LICENSE @@ -1038,7 +1038,7 @@ The externally maintained libraries used by Node.js are: OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -- ESLint, located at tools/eslint, is licensed as follows: +- ESLint, located at tools/node_modules/eslint, is licensed as follows: """ Copyright JS Foundation and other contributors, https://js.foundation @@ -1061,6 +1061,32 @@ The externally maintained libraries used by Node.js are: THE SOFTWARE. """ +- babel-eslint, located at tools/node_modules/babel-eslint, is licensed as follows: + """ + Copyright (c) 2014-2016 Sebastian McKenzie + + MIT License + + 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. + """ + - gtest, located at deps/gtest, is licensed as follows: """ Copyright 2008, Google Inc. diff --git a/Makefile b/Makefile index 213284aa70cd15..eaebe4f2b55a4b 100644 --- a/Makefile +++ b/Makefile @@ -14,6 +14,7 @@ COVTESTS ?= test-cov GTEST_FILTER ?= "*" GNUMAKEFLAGS += --no-print-directory GCOV ?= gcov +PWD = $(CURDIR) ifdef JOBS PARALLEL_ARGS = -j $(JOBS) @@ -144,12 +145,14 @@ check: test coverage-clean: if [ -d lib_ ]; then $(RM) -r lib; mv lib_ lib; fi $(RM) -r node_modules - $(RM) -r gcovr testing + $(RM) -r gcovr build $(RM) -r out/$(BUILDTYPE)/.coverage $(RM) -r .cov_tmp - $(RM) out/$(BUILDTYPE)/obj.target/node/{src,gen}/*.gcda + $(RM) out/$(BUILDTYPE)/obj.target/node/gen/*.gcda + $(RM) out/$(BUILDTYPE)/obj.target/node/src/*.gcda $(RM) out/$(BUILDTYPE)/obj.target/node/src/tracing/*.gcda - $(RM) out/$(BUILDTYPE)/obj.target/node/{src,gen}/*.gcno + $(RM) out/$(BUILDTYPE)/obj.target/node/gen/*.gcno + $(RM) out/$(BUILDTYPE)/obj.target/node/src/*.gcno $(RM) out/$(BUILDTYPE)/obj.target/node/src/tracing/*.gcno $(RM) out/$(BUILDTYPE)/obj.target/cctest/src/*.gcno $(RM) out/$(BUILDTYPE)/obj.target/cctest/test/cctest/*.gcno @@ -171,7 +174,7 @@ coverage-build: all $(NODE) ./deps/npm install nyc --no-save --no-package-lock; fi if [ ! -d gcovr ]; then git clone --depth=1 \ --single-branch git://github.com/gcovr/gcovr.git; fi - if [ ! -d testing ]; then git clone --depth=1 \ + if [ ! -d build ]; then git clone --depth=1 \ --single-branch https://github.com/nodejs/build.git; fi if [ ! -f gcovr/scripts/gcovr.orig ]; then \ (cd gcovr && patch -N -p1 < \ @@ -185,7 +188,8 @@ coverage-build: all coverage-test: coverage-build $(RM) -r out/$(BUILDTYPE)/.coverage $(RM) -r .cov_tmp - $(RM) out/$(BUILDTYPE)/obj.target/node/{src,gen}/*.gcda + $(RM) out/$(BUILDTYPE)/obj.target/node/gen/*.gcda + $(RM) out/$(BUILDTYPE)/obj.target/node/src/*.gcda $(RM) out/$(BUILDTYPE)/obj.target/node/src/tracing/*.gcda -$(MAKE) $(COVTESTS) mv lib lib__ @@ -640,7 +644,7 @@ out/doc/api/assets/%: doc/api_assets/% out/doc/api/assets available-node = \ if [ -x $(PWD)/$(NODE) ] && [ -e $(PWD)/$(NODE) ]; then \ $(PWD)/$(NODE) $(1); \ - elif [ -x `which node` ] && [ -e `which node` ]; then \ + elif [ -x `which node` ] && [ -e `which node` ] && [ `which node` ]; then \ `which node` $(1); \ else \ echo "No available node, cannot run \"node $(1)\""; \ @@ -907,15 +911,31 @@ $(TARBALL): release-only $(NODE_EXE) doc mkdir -p $(TARNAME)/doc/api cp doc/node.1 $(TARNAME)/doc/node.1 cp -r out/doc/api/* $(TARNAME)/doc/api/ - $(RM) -r $(TARNAME)/deps/v8/{test,samples,tools/profviz,tools/run-tests.py} - $(RM) -r $(TARNAME)/doc/images # too big - $(RM) -r $(TARNAME)/deps/uv/{docs,samples,test} - $(RM) -r $(TARNAME)/deps/openssl/openssl/{doc,demos,test} + $(RM) -r $(TARNAME)/.editorconfig + $(RM) -r $(TARNAME)/.git* + $(RM) -r $(TARNAME)/.mailmap + $(RM) -r $(TARNAME)/deps/openssl/openssl/demos + $(RM) -r $(TARNAME)/deps/openssl/openssl/doc + $(RM) -r $(TARNAME)/deps/openssl/openssl/test + $(RM) -r $(TARNAME)/deps/uv/docs + $(RM) -r $(TARNAME)/deps/uv/samples + $(RM) -r $(TARNAME)/deps/uv/test + $(RM) -r $(TARNAME)/deps/v8/samples + $(RM) -r $(TARNAME)/deps/v8/test + $(RM) -r $(TARNAME)/deps/v8/tools/profviz + $(RM) -r $(TARNAME)/deps/v8/tools/run-tests.py $(RM) -r $(TARNAME)/deps/zlib/contrib # too big, unused - $(RM) -r $(TARNAME)/.{editorconfig,git*,mailmap} - $(RM) -r $(TARNAME)/tools/{eslint,eslint-rules,osx-pkg.pmdoc,pkgsrc,remark-cli,remark-preset-lint-node} - $(RM) -r $(TARNAME)/tools/{osx-*,license-builder.sh,cpplint.py} + $(RM) -r $(TARNAME)/doc/images # too big $(RM) -r $(TARNAME)/test*.tap + $(RM) -r $(TARNAME)/tools/cpplint.py + $(RM) -r $(TARNAME)/tools/eslint-rules + $(RM) -r $(TARNAME)/tools/license-builder.sh + $(RM) -r $(TARNAME)/tools/node_modules + $(RM) -r $(TARNAME)/tools/osx-* + $(RM) -r $(TARNAME)/tools/osx-pkg.pmdoc + $(RM) -r $(TARNAME)/tools/pkgsrc + $(RM) -r $(TARNAME)/tools/remark-cli + $(RM) -r $(TARNAME)/tools/remark-preset-lint-node find $(TARNAME)/ -name ".eslint*" -maxdepth 2 | xargs $(RM) find $(TARNAME)/ -type l | xargs $(RM) # annoying on windows tar -cf $(TARNAME).tar $(TARNAME) @@ -1019,57 +1039,13 @@ ifeq ($(XZ), 0) ssh $(STAGINGSERVER) "touch nodejs/$(DISTTYPEDIR)/$(FULLVERSION)/$(TARNAME)-$(OSTYPE)-$(ARCH).tar.xz.done" endif -.PHONY: bench-net -bench-net: all - @$(NODE) benchmark/run.js net - -bench-crypto: all - @$(NODE) benchmark/run.js crypto - -.PHONY: bench-tls -bench-tls: all - @$(NODE) benchmark/run.js tls - -.PHONY: bench-http -bench-http: all - @$(NODE) benchmark/run.js http - -.PHONY: bench-fs -bench-fs: all - @$(NODE) benchmark/run.js fs - -.PHONY: bench-misc -bench-misc: benchmark/misc/function_call/build/Release/binding.node - @$(NODE) benchmark/run.js misc - -.PHONY: bench-array -bench-array: all - @$(NODE) benchmark/run.js arrays - -.PHONY: bench-buffer -bench-buffer: all - @$(NODE) benchmark/run.js buffers - -bench-url: all - @$(NODE) benchmark/run.js url - -bench-events: all - @$(NODE) benchmark/run.js events - -bench-util: all - @$(NODE) benchmark/run.js util - -bench-dgram: all - @$(NODE) benchmark/run.js dgram - .PHONY: bench-all -bench-all: bench bench-misc bench-array bench-buffer bench-url bench-events bench-dgram bench-util +bench-all: + @echo "Please use benchmark/run.js or benchmark/compare.js to run the benchmarks." .PHONY: bench -bench: bench-net bench-http bench-fs bench-tls - -.PHONY: bench-ci -bench-ci: bench +bench: + @echo "Please use benchmark/run.js or benchmark/compare.js to run the benchmarks." .PHONY: lint-md-clean lint-md-clean: @@ -1081,27 +1057,32 @@ lint-md-clean: lint-md-build: @if [ ! -d tools/remark-cli/node_modules ]; then \ echo "Markdown linter: installing remark-cli into tools/"; \ - cd tools/remark-cli && ../../$(NODE) ../../$(NPM) install; fi + cd tools/remark-cli && $(call available-node,$(run-npm-install)) fi @if [ ! -d tools/remark-preset-lint-node/node_modules ]; then \ echo "Markdown linter: installing remark-preset-lint-node into tools/"; \ - cd tools/remark-preset-lint-node && ../../$(NODE) ../../$(NPM) install; fi + cd tools/remark-preset-lint-node && $(call available-node,$(run-npm-install)) fi + .PHONY: lint-md ifneq ("","$(wildcard tools/remark-cli/node_modules/)") -LINT_MD_TARGETS = src lib benchmark tools/doc tools/icu -LINT_MD_ROOT_DOCS := $(wildcard *.md) -LINT_MD_FILES := $(shell find $(LINT_MD_TARGETS) -type f \ - -not -path '*node_modules*' -name '*.md') $(LINT_MD_ROOT_DOCS) -LINT_DOC_MD_FILES = $(shell ls doc/**/*.md) -tools/.docmdlintstamp: $(LINT_DOC_MD_FILES) +LINT_MD_DOC_FILES = $(shell ls doc/**/*.md) +run-lint-doc-md = tools/remark-cli/cli.js -q -f $(LINT_MD_DOC_FILES) +# Lint all changed markdown files under doc/ +tools/.docmdlintstamp: $(LINT_MD_DOC_FILES) @echo "Running Markdown linter on docs..." - @$(NODE) tools/remark-cli/cli.js -q -f $(LINT_DOC_MD_FILES) + @$(call available-node,$(run-lint-doc-md)) @touch $@ -tools/.miscmdlintstamp: $(LINT_MD_FILES) +LINT_MD_TARGETS = src lib benchmark tools/doc tools/icu +LINT_MD_ROOT_DOCS := $(wildcard *.md) +LINT_MD_MISC_FILES := $(shell find $(LINT_MD_TARGETS) -type f \ + -not -path '*node_modules*' -name '*.md') $(LINT_MD_ROOT_DOCS) +run-lint-misc-md = tools/remark-cli/cli.js -q -f $(LINT_MD_MISC_FILES) +# Lint other changed markdown files maintained by us +tools/.miscmdlintstamp: $(LINT_MD_MISC_FILES) @echo "Running Markdown linter on misc docs..." - @$(NODE) tools/remark-cli/cli.js -q -f $(LINT_MD_FILES) + @$(call available-node,$(run-lint-misc-md)) @touch $@ tools/.mdlintstamp: tools/.miscmdlintstamp tools/.docmdlintstamp @@ -1115,43 +1096,33 @@ lint-md: endif LINT_JS_TARGETS = benchmark doc lib test tools -LINT_JS_CMD = tools/eslint/bin/eslint.js --cache \ - --rulesdir=tools/eslint-rules --ext=.js,.mjs,.md \ - $(LINT_JS_TARGETS) + +run-lint-js = tools/node_modules/eslint/bin/eslint.js --cache \ + --rulesdir=tools/eslint-rules --ext=.js,.mjs,.md $(LINT_JS_TARGETS) +run-lint-js-fix = $(run-lint-js) --fix .PHONY: lint-js-fix lint-js-fix: - @if [ -x $(NODE) ]; then \ - $(NODE) $(LINT_JS_CMD) --fix; \ - else \ - node $(LINT_JS_CMD) --fix; \ - fi + @$(call available-node,$(run-lint-js-fix)) .PHONY: lint-js # Note that on the CI `lint-js-ci` is run instead. # Lints the JavaScript code with eslint. lint-js: @echo "Running JS linter..." - @if [ -x $(NODE) ]; then \ - $(NODE) $(LINT_JS_CMD); \ - else \ - node $(LINT_JS_CMD); \ - fi + @$(call available-node,$(run-lint-js)) jslint: lint-js @echo "Please use lint-js instead of jslint" +run-lint-js-ci = tools/lint-js.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \ + $(LINT_JS_TARGETS) + .PHONY: lint-js-ci # On the CI the output is emitted in the TAP format. lint-js-ci: @echo "Running JS linter..." - @if [ -x $(NODE) ]; then \ - $(NODE) tools/lint-js.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \ - $(LINT_JS_TARGETS); \ - else \ - node tools/lint-js.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \ - $(LINT_JS_TARGETS); \ - fi + @$(call available-node,$(run-lint-js-ci)) jslint-ci: lint-js-ci @echo "Please use lint-js-ci instead of jslint-ci" @@ -1206,7 +1177,7 @@ cpplint: lint-cpp .PHONY: lint .PHONY: lint-ci -ifneq ("","$(wildcard tools/eslint/)") +ifneq ("","$(wildcard tools/node_modules/eslint/)") lint: ## Run JS, C++, MD and doc linters. @EXIT_STATUS=0 ; \ $(MAKE) lint-js || EXIT_STATUS=$$? ; \ diff --git a/README.md b/README.md index 85a27f549a5150..47b8694797637b 100644 --- a/README.md +++ b/README.md @@ -405,6 +405,8 @@ For more information about the governance of the Node.js project, see **Kunal Pathak** <kunal.pathak@microsoft.com> * [lance](https://github.com/lance) - **Lance Ball** <lball@redhat.com> +* [Leko](https://github.com/Leko) - +**Shingo Inoue** <leko.noor@gmail.com> (he/him) * [lpinca](https://github.com/lpinca) - **Luigi Pinca** <luigipinca@gmail.com> (he/him) * [lucamaraschi](https://github.com/lucamaraschi) - @@ -495,6 +497,8 @@ For more information about the governance of the Node.js project, see **Rich Trott** <rtrott@gmail.com> (he/him) * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com> +* [vdeturckheim](https://github.com/vdeturckheim) - +**Vladimir de Turckheim** <vlad2t@hotmail.com> (he/him) * [vkurchatkin](https://github.com/vkurchatkin) - **Vladimir Kurchatkin** <vladimir.kurchatkin@gmail.com> * [vsemozhetbyt](https://github.com/vsemozhetbyt) - diff --git a/benchmark/_http-benchmarkers.js b/benchmark/_http-benchmarkers.js index 54b7481afaa817..55ebcc96ba21ed 100644 --- a/benchmark/_http-benchmarkers.js +++ b/benchmark/_http-benchmarkers.js @@ -89,11 +89,14 @@ class TestDoubleBenchmarker { } create(options) { + const env = Object.assign({ + duration: options.duration, + test_url: `http://127.0.0.1:${options.port}${options.path}`, + }, process.env); + const child = child_process.fork(this.executable, { silent: true, - env: Object.assign({}, process.env, { - test_url: `http://127.0.0.1:${options.port}${options.path}` - }) + env }); return child; } diff --git a/benchmark/_test-double-benchmarker.js b/benchmark/_test-double-benchmarker.js index 8c2f744fbf6e9f..e2a0eb13126ed5 100644 --- a/benchmark/_test-double-benchmarker.js +++ b/benchmark/_test-double-benchmarker.js @@ -2,6 +2,28 @@ const http = require('http'); -http.get(process.env.test_url, function() { - console.log(JSON.stringify({ throughput: 1 })); -}); +const duration = process.env.duration || 0; +const url = process.env.test_url; + +const start = process.hrtime(); +let throughput = 0; + +function request(res) { + res.on('data', () => {}); + res.on('error', () => {}); + res.on('end', () => { + throughput++; + const diff = process.hrtime(start); + if (duration > 0 && diff[0] < duration) { + run(); + } else { + console.log(JSON.stringify({ throughput })); + } + }); +} + +function run() { + http.get(url, request); +} + +run(); diff --git a/benchmark/arrays/var-int.js b/benchmark/arrays/var-int.js index a8acbf5ccbbcb1..e36a909a3b9e76 100644 --- a/benchmark/arrays/var-int.js +++ b/benchmark/arrays/var-int.js @@ -17,10 +17,8 @@ const bench = common.createBenchmark(main, { n: [25] }); -function main(conf) { - const type = conf.type; +function main({ type, n }) { const clazz = global[type]; - const n = +conf.n; bench.start(); const arr = new clazz(n * 1e6); diff --git a/benchmark/arrays/zero-float.js b/benchmark/arrays/zero-float.js index c8d7dbf7ed57d2..073460e0efb8fc 100644 --- a/benchmark/arrays/zero-float.js +++ b/benchmark/arrays/zero-float.js @@ -17,10 +17,8 @@ const bench = common.createBenchmark(main, { n: [25] }); -function main(conf) { - const type = conf.type; +function main({ type, n }) { const clazz = global[type]; - const n = +conf.n; bench.start(); const arr = new clazz(n * 1e6); diff --git a/benchmark/arrays/zero-int.js b/benchmark/arrays/zero-int.js index b16a6b6b72064e..78fd34ae6c0bf4 100644 --- a/benchmark/arrays/zero-int.js +++ b/benchmark/arrays/zero-int.js @@ -17,10 +17,8 @@ const bench = common.createBenchmark(main, { n: [25] }); -function main(conf) { - const type = conf.type; +function main({ type, n }) { const clazz = global[type]; - const n = +conf.n; bench.start(); const arr = new clazz(n * 1e6); diff --git a/benchmark/assert/deepequal-buffer.js b/benchmark/assert/deepequal-buffer.js index d4495af69b48ef..0e7494544d3387 100644 --- a/benchmark/assert/deepequal-buffer.js +++ b/benchmark/assert/deepequal-buffer.js @@ -13,9 +13,7 @@ const bench = common.createBenchmark(main, { ] }); -function main(conf) { - const n = +conf.n; - const len = +conf.len; +function main({ len, n, method }) { var i; const data = Buffer.allocUnsafe(len + 1); @@ -26,7 +24,7 @@ function main(conf) { data.copy(expected); data.copy(expectedWrong); - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'deepEqual': diff --git a/benchmark/assert/deepequal-map.js b/benchmark/assert/deepequal-map.js index 4976f2619834bf..085274e8bfb943 100644 --- a/benchmark/assert/deepequal-map.js +++ b/benchmark/assert/deepequal-map.js @@ -38,14 +38,11 @@ function benchmark(method, n, values, values2) { bench.end(n); } -function main(conf) { - const n = +conf.n; - const len = +conf.len; - +function main({ n, len, method }) { const array = Array(len).fill(1); var values, values2; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'deepEqual_primitiveOnly': diff --git a/benchmark/assert/deepequal-object.js b/benchmark/assert/deepequal-object.js index 2efa9452af88e1..2c2549d58485fc 100644 --- a/benchmark/assert/deepequal-object.js +++ b/benchmark/assert/deepequal-object.js @@ -25,10 +25,9 @@ function createObj(source, add = '') { })); } -function main(conf) { - const size = +conf.size; - // TODO: Fix this "hack" - const n = (+conf.n) / size; +function main({ size, n, method }) { + // TODO: Fix this "hack". `n` should not be manipulated. + n = n / size; var i; const source = Array.apply(null, Array(size)); @@ -36,7 +35,7 @@ function main(conf) { const expected = createObj(source); const expectedWrong = createObj(source, '4'); - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'deepEqual': diff --git a/benchmark/assert/deepequal-prims-and-objs-big-array-set.js b/benchmark/assert/deepequal-prims-and-objs-big-array-set.js index 19337d7828236d..04802a76928cb2 100644 --- a/benchmark/assert/deepequal-prims-and-objs-big-array-set.js +++ b/benchmark/assert/deepequal-prims-and-objs-big-array-set.js @@ -15,7 +15,7 @@ const primValues = { }; const bench = common.createBenchmark(main, { - prim: Object.keys(primValues), + primitive: Object.keys(primValues), n: [25], len: [1e5], method: [ @@ -30,10 +30,8 @@ const bench = common.createBenchmark(main, { ] }); -function main(conf) { - const prim = primValues[conf.prim]; - const n = +conf.n; - const len = +conf.len; +function main({ n, len, primitive, method }) { + const prim = primValues[primitive]; const actual = []; const expected = []; const expectedWrong = []; @@ -52,7 +50,7 @@ function main(conf) { const expectedSet = new Set(expected); const expectedWrongSet = new Set(expectedWrong); - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'deepEqual_Array': diff --git a/benchmark/assert/deepequal-prims-and-objs-big-loop.js b/benchmark/assert/deepequal-prims-and-objs-big-loop.js index 4a345f27c20f0e..09797dfaf2df21 100644 --- a/benchmark/assert/deepequal-prims-and-objs-big-loop.js +++ b/benchmark/assert/deepequal-prims-and-objs-big-loop.js @@ -14,7 +14,7 @@ const primValues = { }; const bench = common.createBenchmark(main, { - prim: Object.keys(primValues), + primitive: Object.keys(primValues), n: [1e6], method: [ 'deepEqual', @@ -24,16 +24,15 @@ const bench = common.createBenchmark(main, { ] }); -function main(conf) { - const prim = primValues[conf.prim]; - const n = +conf.n; +function main({ n, primitive, method }) { + const prim = primValues[primitive]; const actual = prim; const expected = prim; const expectedWrong = 'b'; var i; // Creates new array to avoid loop invariant code motion - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'deepEqual': diff --git a/benchmark/assert/deepequal-set.js b/benchmark/assert/deepequal-set.js index aa0ebc064886a2..ebcf33cc6d5254 100644 --- a/benchmark/assert/deepequal-set.js +++ b/benchmark/assert/deepequal-set.js @@ -38,15 +38,12 @@ function benchmark(method, n, values, values2) { bench.end(n); } -function main(conf) { - const n = +conf.n; - const len = +conf.len; - +function main({ n, len, method }) { const array = Array(len).fill(1); var values, values2; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'deepEqual_primitiveOnly': diff --git a/benchmark/assert/deepequal-typedarrays.js b/benchmark/assert/deepequal-typedarrays.js index 8e8cc4b083a73e..01546801ff3004 100644 --- a/benchmark/assert/deepequal-typedarrays.js +++ b/benchmark/assert/deepequal-typedarrays.js @@ -24,12 +24,8 @@ const bench = common.createBenchmark(main, { len: [1e6] }); -function main(conf) { - const type = conf.type; +function main({ type, n, len, method }) { const clazz = global[type]; - const n = +conf.n; - const len = +conf.len; - const actual = new clazz(len); const expected = new clazz(len); const expectedWrong = Buffer.alloc(len); @@ -37,7 +33,7 @@ function main(conf) { expectedWrong[wrongIndex] = 123; var i; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'deepEqual': diff --git a/benchmark/assert/throws.js b/benchmark/assert/throws.js index 075e227f886acc..bffde7cbc1fd94 100644 --- a/benchmark/assert/throws.js +++ b/benchmark/assert/throws.js @@ -13,15 +13,14 @@ const bench = common.createBenchmark(main, { ] }); -function main(conf) { - const n = +conf.n; +function main({ n, method }) { const throws = () => { throw new TypeError('foobar'); }; const doesNotThrow = () => { return 'foobar'; }; const regExp = /foobar/; const message = 'failure'; var i; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'doesNotThrow': @@ -54,6 +53,6 @@ function main(conf) { bench.end(n); break; default: - throw new Error(`Unsupported method ${conf.method}`); + throw new Error(`Unsupported method ${method}`); } } diff --git a/benchmark/async_hooks/gc-tracking.js b/benchmark/async_hooks/gc-tracking.js index c71c1b07aa5431..a569fb8fa92485 100644 --- a/benchmark/async_hooks/gc-tracking.js +++ b/benchmark/async_hooks/gc-tracking.js @@ -21,10 +21,8 @@ function endAfterGC(n) { }); } -function main(conf) { - const n = +conf.n; - - switch (conf.method) { +function main({ n, method }) { + switch (method) { case 'trackingEnabled': bench.start(); for (let i = 0; i < n; i++) { diff --git a/benchmark/buffers/buffer-base64-decode-wrapped.js b/benchmark/buffers/buffer-base64-decode-wrapped.js index 3140cd5525ad07..61e3bb654ee7c0 100644 --- a/benchmark/buffers/buffer-base64-decode-wrapped.js +++ b/benchmark/buffers/buffer-base64-decode-wrapped.js @@ -6,8 +6,7 @@ const bench = common.createBenchmark(main, { n: [32], }); -function main(conf) { - const n = +conf.n; +function main({ n }) { const charsPerLine = 76; const linesCount = 8 << 16; const bytesCount = charsPerLine * linesCount / 4 * 3; diff --git a/benchmark/buffers/buffer-base64-decode.js b/benchmark/buffers/buffer-base64-decode.js index 6a9002df383a8f..492922fb2b6eac 100644 --- a/benchmark/buffers/buffer-base64-decode.js +++ b/benchmark/buffers/buffer-base64-decode.js @@ -6,8 +6,7 @@ const bench = common.createBenchmark(main, { n: [32], }); -function main(conf) { - const n = +conf.n; +function main({ n }) { const s = 'abcd'.repeat(8 << 20); // eslint-disable-next-line no-unescaped-regexp-dot s.match(/./); // Flatten string. diff --git a/benchmark/buffers/buffer-base64-encode.js b/benchmark/buffers/buffer-base64-encode.js index 509fcd9a33c9d4..d8b601bbd181f4 100644 --- a/benchmark/buffers/buffer-base64-encode.js +++ b/benchmark/buffers/buffer-base64-encode.js @@ -27,9 +27,7 @@ const bench = common.createBenchmark(main, { n: [32] }); -function main(conf) { - const n = +conf.n; - const len = +conf.len; +function main({ n, len }) { const b = Buffer.allocUnsafe(len); let s = ''; let i; diff --git a/benchmark/buffers/buffer-bytelength.js b/benchmark/buffers/buffer-bytelength.js index fc6dfcf2301eaf..0617b4feb3f140 100644 --- a/benchmark/buffers/buffer-bytelength.js +++ b/benchmark/buffers/buffer-bytelength.js @@ -15,11 +15,7 @@ const chars = [ '𠜎𠜱𠝹𠱓𠱸𠲖𠳏𠳕𠴕𠵼𠵿𠸎𠸏𠹷𠺝𠺢' // 4 bytes ]; -function main(conf) { - const n = conf.n | 0; - const len = conf.len | 0; - const encoding = conf.encoding; - +function main({ n, len, encoding }) { var strings = []; var results; if (encoding === 'buffer') { diff --git a/benchmark/buffers/buffer-compare-instance-method.js b/benchmark/buffers/buffer-compare-instance-method.js index ff3bc4c1abda98..a3433803b79537 100644 --- a/benchmark/buffers/buffer-compare-instance-method.js +++ b/benchmark/buffers/buffer-compare-instance-method.js @@ -7,10 +7,8 @@ const bench = common.createBenchmark(main, { millions: [1] }); -function main(conf) { - const iter = (conf.millions >>> 0) * 1e6; - const size = (conf.size >>> 0); - const args = (conf.args >>> 0); +function main({ millions, size, args }) { + const iter = millions * 1e6; const b0 = Buffer.alloc(size, 'a'); const b1 = Buffer.alloc(size, 'a'); const b0Len = b0.length; diff --git a/benchmark/buffers/buffer-compare-offset.js b/benchmark/buffers/buffer-compare-offset.js index 96719abfbe5618..850fe11d3f429e 100644 --- a/benchmark/buffers/buffer-compare-offset.js +++ b/benchmark/buffers/buffer-compare-offset.js @@ -23,13 +23,11 @@ function compareUsingOffset(b0, b1, len, iter) { bench.end(iter / 1e6); } -function main(conf) { - const iter = (conf.millions >>> 0) * 1e6; - const size = (conf.size >>> 0); - const method = - conf.method === 'slice' ? compareUsingSlice : compareUsingOffset; - method(Buffer.alloc(size, 'a'), - Buffer.alloc(size, 'b'), - size >> 1, - iter); +function main({ millions, size, method }) { + const iter = millions * 1e6; + const fn = method === 'slice' ? compareUsingSlice : compareUsingOffset; + fn(Buffer.alloc(size, 'a'), + Buffer.alloc(size, 'b'), + size >> 1, + iter); } diff --git a/benchmark/buffers/buffer-compare.js b/benchmark/buffers/buffer-compare.js index ad6519cd102340..f7abb4b3d94ffa 100644 --- a/benchmark/buffers/buffer-compare.js +++ b/benchmark/buffers/buffer-compare.js @@ -27,9 +27,8 @@ const bench = common.createBenchmark(main, { millions: [1] }); -function main(conf) { - const iter = (conf.millions >>> 0) * 1e6; - const size = (conf.size >>> 0); +function main({ millions, size }) { + const iter = millions * 1e6; const b0 = Buffer.alloc(size, 'a'); const b1 = Buffer.alloc(size, 'a'); diff --git a/benchmark/buffers/buffer-concat.js b/benchmark/buffers/buffer-concat.js index a27e132193ef41..3f9cffc06a6a7e 100644 --- a/benchmark/buffers/buffer-concat.js +++ b/benchmark/buffers/buffer-concat.js @@ -8,15 +8,11 @@ const bench = common.createBenchmark(main, { n: [1024] }); -function main(conf) { - const n = +conf.n; - const size = +conf.pieceSize; - const pieces = +conf.pieces; - +function main({ n, pieces, pieceSize, withTotalLength }) { const list = new Array(pieces); - list.fill(Buffer.allocUnsafe(size)); + list.fill(Buffer.allocUnsafe(pieceSize)); - const totalLength = conf.withTotalLength ? pieces * size : undefined; + const totalLength = withTotalLength ? pieces * pieceSize : undefined; bench.start(); for (var i = 0; i < n * 1024; i++) { diff --git a/benchmark/buffers/buffer-creation.js b/benchmark/buffers/buffer-creation.js index 4ca0a049228f6c..73e620955e91db 100644 --- a/benchmark/buffers/buffer-creation.js +++ b/benchmark/buffers/buffer-creation.js @@ -15,10 +15,8 @@ const bench = common.createBenchmark(main, { n: [1024] }); -function main(conf) { - const len = +conf.len; - const n = +conf.n; - switch (conf.type) { +function main({ len, n, type }) { + switch (type) { case '': case 'fast-alloc': bench.start(); diff --git a/benchmark/buffers/buffer-from.js b/benchmark/buffers/buffer-from.js index 50cfbc887aa0b9..6f2358bcf296ab 100644 --- a/benchmark/buffers/buffer-from.js +++ b/benchmark/buffers/buffer-from.js @@ -18,10 +18,7 @@ const bench = common.createBenchmark(main, { n: [2048] }); -function main(conf) { - const len = +conf.len; - const n = +conf.n; - +function main({ len, n, source }) { const array = new Array(len).fill(42); const arrayBuf = new ArrayBuffer(len); const str = 'a'.repeat(len); @@ -31,7 +28,7 @@ function main(conf) { var i; - switch (conf.source) { + switch (source) { case 'array': bench.start(); for (i = 0; i < n * 1024; i++) { diff --git a/benchmark/buffers/buffer-hex.js b/benchmark/buffers/buffer-hex.js index d05bb832b3068c..1bdef81139ffe7 100644 --- a/benchmark/buffers/buffer-hex.js +++ b/benchmark/buffers/buffer-hex.js @@ -7,9 +7,7 @@ const bench = common.createBenchmark(main, { n: [1e7] }); -function main(conf) { - const len = conf.len | 0; - const n = conf.n | 0; +function main({ len, n }) { const buf = Buffer.alloc(len); for (let i = 0; i < buf.length; i++) diff --git a/benchmark/buffers/buffer-indexof-number.js b/benchmark/buffers/buffer-indexof-number.js index 2e6e10b9f33d40..91bff0d54bb7eb 100644 --- a/benchmark/buffers/buffer-indexof-number.js +++ b/benchmark/buffers/buffer-indexof-number.js @@ -8,16 +8,14 @@ const bench = common.createBenchmark(main, { n: [1e7] }); -function main(conf) { - const n = +conf.n; - const search = +conf.value; +function main({ n, value }) { const aliceBuffer = fs.readFileSync( path.resolve(__dirname, '../fixtures/alice.html') ); bench.start(); for (var i = 0; i < n; i++) { - aliceBuffer.indexOf(search, 0, undefined); + aliceBuffer.indexOf(value, 0, undefined); } bench.end(n); } diff --git a/benchmark/buffers/buffer-indexof.js b/benchmark/buffers/buffer-indexof.js index 1545475269a025..c98d15320aaaae 100644 --- a/benchmark/buffers/buffer-indexof.js +++ b/benchmark/buffers/buffer-indexof.js @@ -25,16 +25,13 @@ const bench = common.createBenchmark(main, { search: searchStrings, encoding: ['undefined', 'utf8', 'ucs2', 'binary'], type: ['buffer', 'string'], - iter: [1] + iter: [100000] }); -function main(conf) { - const iter = (conf.iter) * 100000; +function main({ iter, search, encoding, type }) { var aliceBuffer = fs.readFileSync( path.resolve(__dirname, '../fixtures/alice.html') ); - var search = conf.search; - var encoding = conf.encoding; if (encoding === 'undefined') { encoding = undefined; @@ -44,7 +41,7 @@ function main(conf) { aliceBuffer = Buffer.from(aliceBuffer.toString(), encoding); } - if (conf.type === 'buffer') { + if (type === 'buffer') { search = Buffer.from(Buffer.from(search).toString(), encoding); } diff --git a/benchmark/buffers/buffer-iterate.js b/benchmark/buffers/buffer-iterate.js index 4e911caa72ce14..8531e1cae82115 100644 --- a/benchmark/buffers/buffer-iterate.js +++ b/benchmark/buffers/buffer-iterate.js @@ -16,14 +16,11 @@ const methods = { 'iterator': benchIterator }; -function main(conf) { - const len = +conf.size; - const clazz = conf.type === 'fast' ? Buffer : SlowBuffer; - const buffer = new clazz(len); +function main({ size, type, method, n }) { + const clazz = type === 'fast' ? Buffer : SlowBuffer; + const buffer = new clazz(size); buffer.fill(0); - - const method = conf.method || 'for'; - methods[method](buffer, conf.n); + methods[method || 'for'](buffer, n); } diff --git a/benchmark/buffers/buffer-read.js b/benchmark/buffers/buffer-read.js index 339da75befce4d..41e842f3123623 100644 --- a/benchmark/buffers/buffer-read.js +++ b/benchmark/buffers/buffer-read.js @@ -25,13 +25,12 @@ const bench = common.createBenchmark(main, { millions: [1] }); -function main(conf) { - const noAssert = conf.noAssert === 'true'; - const len = +conf.millions * 1e6; - const clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer; +function main({ noAssert, millions, buf, type }) { + noAssert = noAssert === 'true'; + const len = millions * 1e6; + const clazz = buf === 'fast' ? Buffer : require('buffer').SlowBuffer; const buff = new clazz(8); - const type = conf.type || 'UInt8'; - const fn = `read${type}`; + const fn = `read${type || 'UInt8'}`; buff.writeDoubleLE(0, 0, noAssert); const testFunction = new Function('buff', ` diff --git a/benchmark/buffers/buffer-slice.js b/benchmark/buffers/buffer-slice.js index 0067d02d8c7931..2e52475da91866 100644 --- a/benchmark/buffers/buffer-slice.js +++ b/benchmark/buffers/buffer-slice.js @@ -10,9 +10,8 @@ const bench = common.createBenchmark(main, { const buf = Buffer.allocUnsafe(1024); const slowBuf = new SlowBuffer(1024); -function main(conf) { - const n = +conf.n; - const b = conf.type === 'fast' ? buf : slowBuf; +function main({ n, type }) { + const b = type === 'fast' ? buf : slowBuf; bench.start(); for (var i = 0; i < n * 1024; i++) { b.slice(10, 256); diff --git a/benchmark/buffers/buffer-swap.js b/benchmark/buffers/buffer-swap.js index 05cde002943f4a..8f6e1f51d3a0f2 100644 --- a/benchmark/buffers/buffer-swap.js +++ b/benchmark/buffers/buffer-swap.js @@ -72,13 +72,9 @@ function genMethod(method) { return (new Function(fnString))(); } -function main(conf) { - const method = conf.method || 'swap16'; - const len = conf.len | 0; - const n = conf.n | 0; - const aligned = conf.aligned || 'true'; +function main({ method, len, n, aligned = 'true' }) { const buf = createBuffer(len, aligned === 'true'); - const bufferSwap = genMethod(method); + const bufferSwap = genMethod(method || 'swap16'); bufferSwap(n, buf); bench.start(); diff --git a/benchmark/buffers/buffer-tojson.js b/benchmark/buffers/buffer-tojson.js index 19a6fe89474838..71936fb622eae6 100644 --- a/benchmark/buffers/buffer-tojson.js +++ b/benchmark/buffers/buffer-tojson.js @@ -7,9 +7,8 @@ const bench = common.createBenchmark(main, { len: [0, 10, 256, 4 * 1024] }); -function main(conf) { - const n = +conf.n; - const buf = Buffer.allocUnsafe(+conf.len); +function main({ n, len }) { + const buf = Buffer.allocUnsafe(len); bench.start(); for (var i = 0; i < n; ++i) diff --git a/benchmark/buffers/buffer-tostring.js b/benchmark/buffers/buffer-tostring.js index 49916fca4023ca..b2a14d8aec55ce 100644 --- a/benchmark/buffers/buffer-tostring.js +++ b/benchmark/buffers/buffer-tostring.js @@ -9,11 +9,7 @@ const bench = common.createBenchmark(main, { n: [1e7] }); -function main(conf) { - var encoding = conf.encoding; - const args = conf.args | 0; - const len = conf.len | 0; - const n = conf.n | 0; +function main({ encoding, args, len, n }) { const buf = Buffer.alloc(len, 42); if (encoding.length === 0) diff --git a/benchmark/buffers/buffer-write-string.js b/benchmark/buffers/buffer-write-string.js index 927aa0b68466ef..37d4fda52c04e3 100644 --- a/benchmark/buffers/buffer-write-string.js +++ b/benchmark/buffers/buffer-write-string.js @@ -10,12 +10,7 @@ const bench = common.createBenchmark(main, { n: [1e7] }); -function main(conf) { - const len = +conf.len; - const n = +conf.n; - const encoding = conf.encoding; - const args = conf.args; - +function main({ len, n, encoding, args }) { const string = 'a'.repeat(len); const buf = Buffer.allocUnsafe(len); diff --git a/benchmark/buffers/buffer-write.js b/benchmark/buffers/buffer-write.js index b500a13dedcccd..ce2fbe3103cb83 100644 --- a/benchmark/buffers/buffer-write.js +++ b/benchmark/buffers/buffer-write.js @@ -45,13 +45,11 @@ const mod = { writeUInt32LE: UINT32 }; -function main(conf) { - const noAssert = conf.noAssert === 'true'; - const len = +conf.millions * 1e6; - const clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer; +function main({ noAssert, millions, buf, type }) { + const len = millions * 1e6; + const clazz = buf === 'fast' ? Buffer : require('buffer').SlowBuffer; const buff = new clazz(8); - const type = conf.type || 'UInt8'; - const fn = `write${type}`; + const fn = `write${type || 'UInt8'}`; if (/Int/.test(fn)) benchInt(buff, fn, len, noAssert); @@ -63,7 +61,7 @@ function benchInt(buff, fn, len, noAssert) { const m = mod[fn]; const testFunction = new Function('buff', ` for (var i = 0; i !== ${len}; i++) { - buff.${fn}(i & ${m}, 0, ${JSON.stringify(noAssert)}); + buff.${fn}(i & ${m}, 0, ${noAssert}); } `); bench.start(); @@ -74,7 +72,7 @@ function benchInt(buff, fn, len, noAssert) { function benchFloat(buff, fn, len, noAssert) { const testFunction = new Function('buff', ` for (var i = 0; i !== ${len}; i++) { - buff.${fn}(i, 0, ${JSON.stringify(noAssert)}); + buff.${fn}(i, 0, ${noAssert}); } `); bench.start(); diff --git a/benchmark/buffers/buffer_zero.js b/benchmark/buffers/buffer_zero.js index 06ca50bbb99ee7..06b68c313f1241 100644 --- a/benchmark/buffers/buffer_zero.js +++ b/benchmark/buffers/buffer_zero.js @@ -10,13 +10,12 @@ const bench = common.createBenchmark(main, { const zeroBuffer = Buffer.alloc(0); const zeroString = ''; -function main(conf) { - const n = +conf.n; +function main({ n, type }) { bench.start(); - if (conf.type === 'buffer') + if (type === 'buffer') for (let i = 0; i < n * 1024; i++) Buffer.from(zeroBuffer); - else if (conf.type === 'string') + else if (type === 'string') for (let i = 0; i < n * 1024; i++) Buffer.from(zeroString); bench.end(n); diff --git a/benchmark/buffers/dataview-set.js b/benchmark/buffers/dataview-set.js index 0dd4598ab7f1c5..ee5acfb1c1f72c 100644 --- a/benchmark/buffers/dataview-set.js +++ b/benchmark/buffers/dataview-set.js @@ -39,11 +39,11 @@ const mod = { setUint32: UINT32 }; -function main(conf) { - const len = +conf.millions * 1e6; +function main({ millions, type }) { + type = type || 'Uint8'; + const len = millions * 1e6; const ab = new ArrayBuffer(8); const dv = new DataView(ab, 0, 8); - const type = conf.type || 'Uint8'; const le = /LE$/.test(type); const fn = `set${type.replace(/[LB]E$/, '')}`; diff --git a/benchmark/child_process/child-process-exec-stdout.js b/benchmark/child_process/child-process-exec-stdout.js index 1e78d445f8376d..a891026b86971f 100644 --- a/benchmark/child_process/child-process-exec-stdout.js +++ b/benchmark/child_process/child-process-exec-stdout.js @@ -12,12 +12,10 @@ const bench = common.createBenchmark(childProcessExecStdout, { dur: [5] }); -function childProcessExecStdout(conf) { +function childProcessExecStdout({ dur, len }) { bench.start(); - const maxDuration = conf.dur * 1000; - const len = +conf.len; - + const maxDuration = dur * 1000; const cmd = `yes "${'.'.repeat(len)}"`; const child = exec(cmd, { 'stdio': ['ignore', 'pipe', 'ignore'] }); diff --git a/benchmark/child_process/child-process-params.js b/benchmark/child_process/child-process-params.js index 644b2136a0f03f..df930395b2a015 100644 --- a/benchmark/child_process/child-process-params.js +++ b/benchmark/child_process/child-process-params.js @@ -20,11 +20,7 @@ const configs = { const bench = common.createBenchmark(main, configs); -function main(conf) { - const n = +conf.n; - const methodName = conf.methodName; - const params = +conf.params; - +function main({ n, methodName, params }) { const method = cp[methodName]; switch (methodName) { diff --git a/benchmark/child_process/child-process-read-ipc.js b/benchmark/child_process/child-process-read-ipc.js index e6fb9b19c202dc..3971eb8b39663e 100644 --- a/benchmark/child_process/child-process-read-ipc.js +++ b/benchmark/child_process/child-process-read-ipc.js @@ -18,11 +18,9 @@ if (process.argv[2] === 'child') { dur: [5] }); const spawn = require('child_process').spawn; - function main(conf) { - bench.start(); - const dur = +conf.dur; - const len = +conf.len; + function main({ dur, len }) { + bench.start(); const options = { 'stdio': ['ignore', 1, 2, 'ipc'] }; const child = spawn(process.argv[0], diff --git a/benchmark/child_process/child-process-read.js b/benchmark/child_process/child-process-read.js index 91c9964e8d1414..0ff08af79483b8 100644 --- a/benchmark/child_process/child-process-read.js +++ b/benchmark/child_process/child-process-read.js @@ -17,12 +17,9 @@ const bench = common.createBenchmark(main, { dur: [5] }); -function main(conf) { +function main({ dur, len }) { bench.start(); - const dur = +conf.dur; - const len = +conf.len; - const msg = `"${'.'.repeat(len)}"`; const options = { 'stdio': ['ignore', 'pipe', 'ignore'] }; const child = child_process.spawn('yes', [msg], options); diff --git a/benchmark/child_process/spawn-echo.js b/benchmark/child_process/spawn-echo.js index 1ce40c3abf4541..62f46fb4c0e8b4 100644 --- a/benchmark/child_process/spawn-echo.js +++ b/benchmark/child_process/spawn-echo.js @@ -5,9 +5,7 @@ const bench = common.createBenchmark(main, { }); const spawn = require('child_process').spawn; -function main(conf) { - const n = +conf.n; - +function main({ n }) { bench.start(); go(n, n); } diff --git a/benchmark/cluster/echo.js b/benchmark/cluster/echo.js index 07096d251db489..90ae7f9fb0b677 100644 --- a/benchmark/cluster/echo.js +++ b/benchmark/cluster/echo.js @@ -10,22 +10,19 @@ if (cluster.isMaster) { n: [1e5] }); - function main(conf) { - const n = +conf.n; - const workers = +conf.workers; - const sends = +conf.sendsPerBroadcast; - const expectedPerBroadcast = sends * workers; - var payload; + function main({ n, workers, sendsPerBroadcast, payload }) { + const expectedPerBroadcast = sendsPerBroadcast * workers; var readies = 0; var broadcasts = 0; var msgCount = 0; + var data; - switch (conf.payload) { + switch (payload) { case 'string': - payload = 'hello world!'; + data = 'hello world!'; break; case 'object': - payload = { action: 'pewpewpew', powerLevel: 9001 }; + data = { action: 'pewpewpew', powerLevel: 9001 }; break; default: throw new Error('Unsupported payload type'); @@ -51,8 +48,8 @@ if (cluster.isMaster) { } for (id in cluster.workers) { const worker = cluster.workers[id]; - for (var i = 0; i < sends; ++i) - worker.send(payload); + for (var i = 0; i < sendsPerBroadcast; ++i) + worker.send(data); } } diff --git a/benchmark/compare.R b/benchmark/compare.R index 5085f4ea73b71a..1527d680c38182 100644 --- a/benchmark/compare.R +++ b/benchmark/compare.R @@ -35,6 +35,21 @@ if (!is.null(plot.filename)) { ggsave(plot.filename, p); } +# computes the shared standard error, as used in the welch t-test +welch.sd = function (old.rate, new.rate) { + old.se.squared = var(old.rate) / length(old.rate) + new.se.squared = var(new.rate) / length(new.rate) + return(sqrt(old.se.squared + new.se.squared)) +} + +# calculate the improvement confidence interval. The improvement is calculated +# by dividing by old.mu and not new.mu, because old.mu is what the mean +# improvement is calculated relative to. +confidence.interval = function (shared.se, old.mu, w, risk) { + interval = qt(1 - (risk / 2), w$parameter) * shared.se; + return(sprintf("±%.2f%%", (interval / old.mu) * 100)) +} + # Print a table with results statistics = ddply(dat, "name", function(subdat) { old.rate = subset(subdat, binary == "old")$rate; @@ -45,33 +60,42 @@ statistics = ddply(dat, "name", function(subdat) { new.mu = mean(new.rate); improvement = sprintf("%.2f %%", ((new.mu - old.mu) / old.mu * 100)); - p.value = NA; - confidence = 'NA'; + r = list( + confidence = "NA", + improvement = improvement, + "accuracy (*)" = "NA", + "(**)" = "NA", + "(***)" = "NA" + ); + # Check if there is enough data to calculate 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 # performance. w = t.test(rate ~ binary, data=subdat); - p.value = w$p.value; + shared.se = welch.sd(old.rate, new.rate) # Add user friendly stars to the table. There should be at least one star # before you can say that there is an improvement. confidence = ''; - if (p.value < 0.001) { + if (w$p.value < 0.001) { confidence = '***'; - } else if (p.value < 0.01) { + } else if (w$p.value < 0.01) { confidence = '**'; - } else if (p.value < 0.05) { + } else if (w$p.value < 0.05) { confidence = '*'; } + + r = list( + confidence = confidence, + improvement = improvement, + "accuracy (*)" = confidence.interval(shared.se, old.mu, w, 0.05), + "(**)" = confidence.interval(shared.se, old.mu, w, 0.01), + "(***)" = confidence.interval(shared.se, old.mu, w, 0.001) + ); } - r = list( - improvement = improvement, - confidence = confidence, - p.value = p.value - ); - return(data.frame(r)); + return(data.frame(r, check.names=FALSE)); }); @@ -81,3 +105,16 @@ statistics$name = NULL; options(width = 200); print(statistics); +cat("\n") +cat(sprintf( +"Be aware that when doing many comparisions the risk of a false-positive +result increases. In this case there are %d comparisions, you can thus +expect the following amount of false-positive results: + %.2f false positives, when considering a 5%% risk acceptance (*, **, ***), + %.2f false positives, when considering a 1%% risk acceptance (**, ***), + %.2f false positives, when considering a 0.1%% risk acceptance (***) +", +nrow(statistics), +nrow(statistics) * 0.05, +nrow(statistics) * 0.01, +nrow(statistics) * 0.001)) diff --git a/benchmark/dgram/array-vs-concat.js b/benchmark/dgram/array-vs-concat.js index 7ee4e2d3acb6e1..a7843a9c7f7c28 100644 --- a/benchmark/dgram/array-vs-concat.js +++ b/benchmark/dgram/array-vs-concat.js @@ -2,6 +2,7 @@ 'use strict'; const common = require('../common.js'); +const dgram = require('dgram'); const PORT = common.PORT; // `num` is the number of send requests to queue up each time. @@ -15,34 +16,15 @@ const bench = common.createBenchmark(main, { dur: [5] }); -var dur; -var len; -var num; -var type; -var chunk; -var chunks; - -function main(conf) { - dur = +conf.dur; - len = +conf.len; - num = +conf.num; - type = conf.type; - chunks = +conf.chunks; - - chunk = []; +function main({ dur, len, num, type, chunks }) { + const chunk = []; for (var i = 0; i < chunks; i++) { chunk.push(Buffer.allocUnsafe(Math.round(len / chunks))); } - server(); -} - -const dgram = require('dgram'); - -function server() { + // Server var sent = 0; const socket = dgram.createSocket('udp4'); - const onsend = type === 'concat' ? onsendConcat : onsendMulti; function onsendConcat() { diff --git a/benchmark/dgram/bind-params.js b/benchmark/dgram/bind-params.js index 411bef98adcf7c..5f7999f7a39241 100644 --- a/benchmark/dgram/bind-params.js +++ b/benchmark/dgram/bind-params.js @@ -12,10 +12,9 @@ const configs = { const bench = common.createBenchmark(main, configs); const noop = () => {}; -function main(conf) { - const n = +conf.n; - const port = conf.port === 'true' ? 0 : undefined; - const address = conf.address === 'true' ? '0.0.0.0' : undefined; +function main({ n, port, address }) { + port = port === 'true' ? 0 : undefined; + address = address === 'true' ? '0.0.0.0' : undefined; if (port !== undefined && address !== undefined) { bench.start(); diff --git a/benchmark/dgram/multi-buffer.js b/benchmark/dgram/multi-buffer.js index 15f70760abfd9e..ee74c584e45278 100644 --- a/benchmark/dgram/multi-buffer.js +++ b/benchmark/dgram/multi-buffer.js @@ -2,6 +2,7 @@ 'use strict'; const common = require('../common.js'); +const dgram = require('dgram'); const PORT = common.PORT; // `num` is the number of send requests to queue up each time. @@ -15,31 +16,11 @@ const bench = common.createBenchmark(main, { dur: [5] }); -var dur; -var len; -var num; -var type; -var chunk; -var chunks; - -function main(conf) { - dur = +conf.dur; - len = +conf.len; - num = +conf.num; - type = conf.type; - chunks = +conf.chunks; - - chunk = []; +function main({ dur, len, num, type, chunks }) { + const chunk = []; for (var i = 0; i < chunks; i++) { chunk.push(Buffer.allocUnsafe(Math.round(len / chunks))); } - - server(); -} - -const dgram = require('dgram'); - -function server() { var sent = 0; var received = 0; const socket = dgram.createSocket('udp4'); diff --git a/benchmark/dgram/offset-length.js b/benchmark/dgram/offset-length.js index 7f5a02afe58107..8a2df9ac67c1b6 100644 --- a/benchmark/dgram/offset-length.js +++ b/benchmark/dgram/offset-length.js @@ -2,6 +2,7 @@ 'use strict'; const common = require('../common.js'); +const dgram = require('dgram'); const PORT = common.PORT; // `num` is the number of send requests to queue up each time. @@ -14,24 +15,8 @@ const bench = common.createBenchmark(main, { dur: [5] }); -var dur; -var len; -var num; -var type; -var chunk; - -function main(conf) { - dur = +conf.dur; - len = +conf.len; - num = +conf.num; - type = conf.type; - chunk = Buffer.allocUnsafe(len); - server(); -} - -const dgram = require('dgram'); - -function server() { +function main({ dur, len, num, type }) { + const chunk = Buffer.allocUnsafe(len); var sent = 0; var received = 0; const socket = dgram.createSocket('udp4'); diff --git a/benchmark/dgram/single-buffer.js b/benchmark/dgram/single-buffer.js index 454662b5425df7..0bf650d265c177 100644 --- a/benchmark/dgram/single-buffer.js +++ b/benchmark/dgram/single-buffer.js @@ -2,6 +2,7 @@ 'use strict'; const common = require('../common.js'); +const dgram = require('dgram'); const PORT = common.PORT; // `num` is the number of send requests to queue up each time. @@ -14,24 +15,8 @@ const bench = common.createBenchmark(main, { dur: [5] }); -var dur; -var len; -var num; -var type; -var chunk; - -function main(conf) { - dur = +conf.dur; - len = +conf.len; - num = +conf.num; - type = conf.type; - chunk = Buffer.allocUnsafe(len); - server(); -} - -const dgram = require('dgram'); - -function server() { +function main({ dur, len, num, type }) { + const chunk = Buffer.allocUnsafe(len); var sent = 0; var received = 0; const socket = dgram.createSocket('udp4'); diff --git a/benchmark/dns/lookup.js b/benchmark/dns/lookup.js index bb562d528c5b37..3cc228c5669265 100644 --- a/benchmark/dns/lookup.js +++ b/benchmark/dns/lookup.js @@ -9,13 +9,10 @@ const bench = common.createBenchmark(main, { n: [5e6] }); -function main(conf) { - const name = conf.name; - const n = +conf.n; - const all = conf.all === 'true' ? true : false; +function main({ name, n, all }) { var i = 0; - if (all) { + if (all === 'true') { const opts = { all: true }; bench.start(); (function cb() { diff --git a/benchmark/domain/domain-fn-args.js b/benchmark/domain/domain-fn-args.js index 0b98d17674064c..fe912e34d206e8 100644 --- a/benchmark/domain/domain-fn-args.js +++ b/benchmark/domain/domain-fn-args.js @@ -3,17 +3,15 @@ const common = require('../common.js'); const domain = require('domain'); const bench = common.createBenchmark(main, { - arguments: [0, 1, 2, 3], + args: [0, 1, 2, 3], n: [10] }); const bdomain = domain.create(); const gargs = [1, 2, 3]; -function main(conf) { - - const n = +conf.n; - const myArguments = gargs.slice(0, conf.arguments); +function main({ n, args }) { + const myArguments = gargs.slice(0, args); bench.start(); bdomain.enter(); diff --git a/benchmark/es/defaultparams-bench.js b/benchmark/es/defaultparams-bench.js index 1393abbe54395c..ce2132718ca369 100644 --- a/benchmark/es/defaultparams-bench.js +++ b/benchmark/es/defaultparams-bench.js @@ -38,10 +38,10 @@ function runDefaultParams(n) { bench.end(n / 1e6); } -function main(conf) { - const n = +conf.millions * 1e6; +function main({ millions, method }) { + const n = millions * 1e6; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'withoutdefaults': diff --git a/benchmark/es/destructuring-bench.js b/benchmark/es/destructuring-bench.js index a6c9a81ae02895..f244506860d248 100644 --- a/benchmark/es/destructuring-bench.js +++ b/benchmark/es/destructuring-bench.js @@ -34,10 +34,10 @@ function runSwapDestructured(n) { bench.end(n / 1e6); } -function main(conf) { - const n = +conf.millions * 1e6; +function main({ millions, method }) { + const n = millions * 1e6; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'swap': diff --git a/benchmark/es/destructuring-object-bench.js b/benchmark/es/destructuring-object-bench.js index 63e085a2424430..73687f018de9dd 100644 --- a/benchmark/es/destructuring-object-bench.js +++ b/benchmark/es/destructuring-object-bench.js @@ -33,10 +33,10 @@ function runDestructured(n) { bench.end(n / 1e6); } -function main(conf) { - const n = +conf.millions * 1e6; +function main({ millions, method }) { + const n = millions * 1e6; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'normal': diff --git a/benchmark/es/foreach-bench.js b/benchmark/es/foreach-bench.js index 62aa02236fc7ae..c7caa7cee6f461 100644 --- a/benchmark/es/foreach-bench.js +++ b/benchmark/es/foreach-bench.js @@ -52,17 +52,15 @@ function useForEach(n, items) { bench.end(n / 1e6); } -function main(conf) { - const n = +conf.millions * 1e6; - const count = +conf.count; - +function main({ millions, count, method }) { + const n = millions * 1e6; const items = new Array(count); var i; var fn; for (i = 0; i < count; i++) items[i] = i; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'for': diff --git a/benchmark/es/map-bench.js b/benchmark/es/map-bench.js index 035ed1a22aaf91..ba8e35c2eb934f 100644 --- a/benchmark/es/map-bench.js +++ b/benchmark/es/map-bench.js @@ -108,10 +108,10 @@ function runMap(n) { bench.end(n / 1e6); } -function main(conf) { - const n = +conf.millions * 1e6; +function main({ millions, method }) { + const n = millions * 1e6; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'object': diff --git a/benchmark/es/restparams-bench.js b/benchmark/es/restparams-bench.js index 32fa985dedb806..78299d292ce6f6 100644 --- a/benchmark/es/restparams-bench.js +++ b/benchmark/es/restparams-bench.js @@ -60,10 +60,10 @@ function runUseArguments(n) { bench.end(n / 1e6); } -function main(conf) { - const n = +conf.millions * 1e6; +function main({ millions, method }) { + const n = millions * 1e6; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'copy': diff --git a/benchmark/es/spread-bench.js b/benchmark/es/spread-bench.js index b6dfb5963e7acc..3c6cc93ea4f817 100644 --- a/benchmark/es/spread-bench.js +++ b/benchmark/es/spread-bench.js @@ -23,16 +23,16 @@ function makeTest(count, rest) { } } -function main(conf) { - const n = +conf.millions * 1e6; - const ctx = conf.context === 'context' ? {} : null; - var fn = makeTest(conf.count, conf.rest); - const args = new Array(conf.count); +function main({ millions, context, count, rest, method }) { + const n = millions * 1e6; + const ctx = context === 'context' ? {} : null; + var fn = makeTest(count, rest); + const args = new Array(count); var i; - for (i = 0; i < conf.count; i++) + for (i = 0; i < count; i++) args[i] = i; - switch (conf.method) { + switch (method) { case '': // Empty string falls through to next line as default, mostly for tests. case 'apply': diff --git a/benchmark/es/string-concatenations.js b/benchmark/es/string-concatenations.js index b7f5c319361c6c..a40b7fa8c3b9f9 100644 --- a/benchmark/es/string-concatenations.js +++ b/benchmark/es/string-concatenations.js @@ -17,15 +17,13 @@ const configs = { const bench = common.createBenchmark(main, configs); -function main(conf) { - const n = +conf.n; - +function main({ n, mode }) { const str = 'abc'; const num = 123; let string; - switch (conf.mode) { + switch (mode) { case '': // Empty string falls through to next line as default, mostly for tests. case 'multi-concat': diff --git a/benchmark/es/string-repeat.js b/benchmark/es/string-repeat.js index 1ddc7db78c7f86..e5bdbb5cc193c1 100644 --- a/benchmark/es/string-repeat.js +++ b/benchmark/es/string-repeat.js @@ -12,14 +12,12 @@ const configs = { const bench = common.createBenchmark(main, configs); -function main(conf) { - const n = +conf.n; - const size = +conf.size; - const character = conf.encoding === 'ascii' ? 'a' : '\ud83d\udc0e'; // '🐎' +function main({ n, size, encoding, mode }) { + const character = encoding === 'ascii' ? 'a' : '\ud83d\udc0e'; // '🐎' let str; - switch (conf.mode) { + switch (mode) { case '': // Empty string falls through to next line as default, mostly for tests. case 'Array': diff --git a/benchmark/events/ee-add-remove.js b/benchmark/events/ee-add-remove.js index 7b6ec35f29b636..eee8ff4524ed1a 100644 --- a/benchmark/events/ee-add-remove.js +++ b/benchmark/events/ee-add-remove.js @@ -4,9 +4,7 @@ const events = require('events'); const bench = common.createBenchmark(main, { n: [25e4] }); -function main(conf) { - const n = conf.n | 0; - +function main({ n }) { const ee = new events.EventEmitter(); const listeners = []; diff --git a/benchmark/events/ee-emit.js b/benchmark/events/ee-emit.js index 3d7eb43b228b71..686ed10d3ecbfd 100644 --- a/benchmark/events/ee-emit.js +++ b/benchmark/events/ee-emit.js @@ -8,11 +8,7 @@ const bench = common.createBenchmark(main, { listeners: [1, 5, 10], }); -function main(conf) { - const n = conf.n | 0; - const argc = conf.argc | 0; - const listeners = Math.max(conf.listeners | 0, 1); - +function main({ n, argc, listeners }) { const ee = new EventEmitter(); for (var k = 0; k < listeners; k += 1) diff --git a/benchmark/events/ee-listener-count-on-prototype.js b/benchmark/events/ee-listener-count-on-prototype.js index 708f62f06687fe..cf6a33f44af9d1 100644 --- a/benchmark/events/ee-listener-count-on-prototype.js +++ b/benchmark/events/ee-listener-count-on-prototype.js @@ -4,9 +4,7 @@ const EventEmitter = require('events').EventEmitter; const bench = common.createBenchmark(main, { n: [5e7] }); -function main(conf) { - const n = conf.n | 0; - +function main({ n }) { const ee = new EventEmitter(); for (var k = 0; k < 5; k += 1) { diff --git a/benchmark/events/ee-listeners-many.js b/benchmark/events/ee-listeners-many.js index 6cb0682b1ca9c3..9a1562eb2c005c 100644 --- a/benchmark/events/ee-listeners-many.js +++ b/benchmark/events/ee-listeners-many.js @@ -4,9 +4,7 @@ const EventEmitter = require('events').EventEmitter; const bench = common.createBenchmark(main, { n: [5e6] }); -function main(conf) { - const n = conf.n | 0; - +function main({ n }) { const ee = new EventEmitter(); ee.setMaxListeners(101); diff --git a/benchmark/events/ee-listeners.js b/benchmark/events/ee-listeners.js index dff73de0b17fc4..d076dc646c93a7 100644 --- a/benchmark/events/ee-listeners.js +++ b/benchmark/events/ee-listeners.js @@ -4,9 +4,7 @@ const EventEmitter = require('events').EventEmitter; const bench = common.createBenchmark(main, { n: [5e6] }); -function main(conf) { - const n = conf.n | 0; - +function main({ n }) { const ee = new EventEmitter(); for (var k = 0; k < 5; k += 1) { diff --git a/benchmark/events/ee-once.js b/benchmark/events/ee-once.js index d9e87a2b0843af..e1a09fb4b71167 100644 --- a/benchmark/events/ee-once.js +++ b/benchmark/events/ee-once.js @@ -4,9 +4,7 @@ const EventEmitter = require('events').EventEmitter; const bench = common.createBenchmark(main, { n: [2e7] }); -function main(conf) { - const n = conf.n | 0; - +function main({ n }) { const ee = new EventEmitter(); function listener() {} diff --git a/benchmark/fs/bench-readdir.js b/benchmark/fs/bench-readdir.js index eb15e72724d8cb..a3e19e242dadbe 100644 --- a/benchmark/fs/bench-readdir.js +++ b/benchmark/fs/bench-readdir.js @@ -9,9 +9,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const n = conf.n >>> 0; - +function main({ n }) { bench.start(); (function r(cntr) { if (cntr-- <= 0) diff --git a/benchmark/fs/bench-readdirSync.js b/benchmark/fs/bench-readdirSync.js index 8ba2a6ec4976c1..ef3327163e8c22 100644 --- a/benchmark/fs/bench-readdirSync.js +++ b/benchmark/fs/bench-readdirSync.js @@ -9,9 +9,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const n = conf.n >>> 0; - +function main({ n }) { bench.start(); for (var i = 0; i < n; i++) { fs.readdirSync(path.resolve(__dirname, '../../lib/')); diff --git a/benchmark/fs/bench-realpath.js b/benchmark/fs/bench-realpath.js index 881bd0031f0024..6690d7e87b091f 100644 --- a/benchmark/fs/bench-realpath.js +++ b/benchmark/fs/bench-realpath.js @@ -12,10 +12,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const n = conf.n >>> 0; - const pathType = conf.pathType; - +function main({ n, pathType }) { bench.start(); if (pathType === 'relative') relativePath(n); diff --git a/benchmark/fs/bench-realpathSync.js b/benchmark/fs/bench-realpathSync.js index 2239d9748af6af..1c751156f73d53 100644 --- a/benchmark/fs/bench-realpathSync.js +++ b/benchmark/fs/bench-realpathSync.js @@ -14,10 +14,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const n = conf.n >>> 0; - const pathType = conf.pathType; - +function main({ n, pathType }) { bench.start(); if (pathType === 'relative') relativePath(n); diff --git a/benchmark/fs/bench-stat.js b/benchmark/fs/bench-stat.js index 05910d3fc3f83f..8a401ae0b9d857 100644 --- a/benchmark/fs/bench-stat.js +++ b/benchmark/fs/bench-stat.js @@ -9,9 +9,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const n = conf.n >>> 0; - const statType = conf.statType; +function main({ n, statType }) { var arg; if (statType === 'fstat') arg = fs.openSync(__filename, 'r'); diff --git a/benchmark/fs/bench-statSync.js b/benchmark/fs/bench-statSync.js index 901f3f1beeaa11..bd8754a6c3d0e3 100644 --- a/benchmark/fs/bench-statSync.js +++ b/benchmark/fs/bench-statSync.js @@ -9,9 +9,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const n = conf.n >>> 0; - const statSyncType = conf.statSyncType; +function main({ n, statSyncType }) { const arg = (statSyncType === 'fstatSync' ? fs.openSync(__filename, 'r') : __dirname); diff --git a/benchmark/fs/read-stream-throughput.js b/benchmark/fs/read-stream-throughput.js index e0dc7edc05ea3e..3af80132725ec0 100644 --- a/benchmark/fs/read-stream-throughput.js +++ b/benchmark/fs/read-stream-throughput.js @@ -18,7 +18,7 @@ const bench = common.createBenchmark(main, { function main(conf) { encodingType = conf.encodingType; - size = +conf.size; + size = conf.size; filesize = conf.filesize; switch (encodingType) { diff --git a/benchmark/fs/readFileSync.js b/benchmark/fs/readFileSync.js index 8fd0b50421e761..c28adeb229b358 100644 --- a/benchmark/fs/readFileSync.js +++ b/benchmark/fs/readFileSync.js @@ -7,9 +7,7 @@ const bench = common.createBenchmark(main, { n: [60e4] }); -function main(conf) { - const n = +conf.n; - +function main({ n }) { bench.start(); for (var i = 0; i < n; ++i) fs.readFileSync(__filename); diff --git a/benchmark/fs/readfile.js b/benchmark/fs/readfile.js index 7c55073fe0f017..7da7758ed06638 100644 --- a/benchmark/fs/readfile.js +++ b/benchmark/fs/readfile.js @@ -15,8 +15,7 @@ const bench = common.createBenchmark(main, { concurrent: [1, 10] }); -function main(conf) { - const len = +conf.len; +function main({ len, dur, concurrent }) { try { fs.unlinkSync(filename); } catch (e) {} var data = Buffer.alloc(len, 'x'); fs.writeFileSync(filename, data); @@ -30,7 +29,7 @@ function main(conf) { bench.end(reads); try { fs.unlinkSync(filename); } catch (e) {} process.exit(0); - }, +conf.dur * 1000); + }, dur * 1000); function read() { fs.readFile(filename, afterRead); @@ -48,6 +47,5 @@ function main(conf) { read(); } - var cur = +conf.concurrent; - while (cur--) read(); + while (concurrent--) read(); } diff --git a/benchmark/fs/write-stream-throughput.js b/benchmark/fs/write-stream-throughput.js index 08f059156f2cd9..6fe00cde48cabb 100644 --- a/benchmark/fs/write-stream-throughput.js +++ b/benchmark/fs/write-stream-throughput.js @@ -13,10 +13,7 @@ const bench = common.createBenchmark(main, { size: [2, 1024, 65535, 1024 * 1024] }); -function main(conf) { - const dur = +conf.dur; - const encodingType = conf.encodingType; - const size = +conf.size; +function main({ dur, encodingType, size }) { var encoding; var chunk; diff --git a/benchmark/http/_chunky_http_client.js b/benchmark/http/_chunky_http_client.js index ee1f4f8caa2510..a90535e489f4c9 100644 --- a/benchmark/http/_chunky_http_client.js +++ b/benchmark/http/_chunky_http_client.js @@ -11,9 +11,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const len = +conf.len; - const num = +conf.n; +function main({ len, n }) { var todo = []; const headers = []; // Chose 7 because 9 showed "Connection error" / "Connection closed" @@ -78,7 +76,7 @@ function main(conf) { size = (size * mult + add) % mod; if (did) { count += 1; - if (count === num) { + if (count === n) { bench.end(count); process.exit(0); } else { diff --git a/benchmark/http/bench-parser.js b/benchmark/http/bench-parser.js index 1bc661e7289168..4c691d71345da3 100644 --- a/benchmark/http/bench-parser.js +++ b/benchmark/http/bench-parser.js @@ -15,9 +15,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const len = conf.len >>> 0; - const n = conf.n >>> 0; +function main({ len, n }) { var header = `GET /hello HTTP/1.1${CRLF}Content-Type: text/plain${CRLF}`; for (var i = 0; i < len; i++) { diff --git a/benchmark/http/check_invalid_header_char.js b/benchmark/http/check_invalid_header_char.js index d71bc6fc607ef5..b9933d690e25cc 100644 --- a/benchmark/http/check_invalid_header_char.js +++ b/benchmark/http/check_invalid_header_char.js @@ -30,10 +30,7 @@ const bench = common.createBenchmark(main, { n: [1e6], }); -function main(conf) { - const n = +conf.n; - const key = conf.key; - +function main({ n, key }) { bench.start(); for (var i = 0; i < n; i++) { _checkInvalidHeaderChar(key); diff --git a/benchmark/http/check_is_http_token.js b/benchmark/http/check_is_http_token.js index 92df3445b45c45..c16993819be93b 100644 --- a/benchmark/http/check_is_http_token.js +++ b/benchmark/http/check_is_http_token.js @@ -40,10 +40,7 @@ const bench = common.createBenchmark(main, { n: [1e6], }); -function main(conf) { - const n = +conf.n; - const key = conf.key; - +function main({ n, key }) { bench.start(); for (var i = 0; i < n; i++) { _checkIsHttpToken(key); diff --git a/benchmark/http/chunked.js b/benchmark/http/chunked.js index 1056f456ef827d..5615395ee0b175 100644 --- a/benchmark/http/chunked.js +++ b/benchmark/http/chunked.js @@ -16,9 +16,9 @@ const bench = common.createBenchmark(main, { c: [100] }); -function main(conf) { +function main({ len, n, c }) { const http = require('http'); - const chunk = Buffer.alloc(conf.len, '8'); + const chunk = Buffer.alloc(len, '8'); const server = http.createServer(function(req, res) { function send(left) { @@ -28,12 +28,12 @@ function main(conf) { send(left - 1); }, 0); } - send(conf.n); + send(n); }); server.listen(common.PORT, function() { bench.http({ - connections: conf.c + connections: c }, function() { server.close(); }); diff --git a/benchmark/http/client-request-body.js b/benchmark/http/client-request-body.js index a6849580cfb44d..49bb9130ae3a8a 100644 --- a/benchmark/http/client-request-body.js +++ b/benchmark/http/client-request-body.js @@ -11,13 +11,10 @@ const bench = common.createBenchmark(main, { method: ['write', 'end'] }); -function main(conf) { - const dur = +conf.dur; - const len = +conf.len; - +function main({ dur, len, type, method }) { var encoding; var chunk; - switch (conf.type) { + switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); break; @@ -55,7 +52,7 @@ function main(conf) { pummel(); // Line up next request. res.resume(); }); - if (conf.method === 'write') { + if (method === 'write') { req.write(chunk, encoding); req.end(); } else { diff --git a/benchmark/http/cluster.js b/benchmark/http/cluster.js index 352b1d2645008f..56393fa1ab0518 100644 --- a/benchmark/http/cluster.js +++ b/benchmark/http/cluster.js @@ -15,7 +15,7 @@ if (cluster.isMaster) { require('../fixtures/simple-http-server.js').listen(port); } -function main(conf) { +function main({ type, len, c }) { process.env.PORT = PORT; var workers = 0; const w1 = cluster.fork(); @@ -27,11 +27,11 @@ function main(conf) { return; setTimeout(function() { - const path = `/${conf.type}/${conf.len}`; + const path = `/${type}/${len}`; bench.http({ path: path, - connections: conf.c + connections: c }, function() { w1.destroy(); w2.destroy(); diff --git a/benchmark/http/create-clientrequest.js b/benchmark/http/create-clientrequest.js index d19a6fb43441ce..97316a7e800419 100644 --- a/benchmark/http/create-clientrequest.js +++ b/benchmark/http/create-clientrequest.js @@ -8,10 +8,7 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const len = +conf.len; - const n = +conf.n; - +function main({ len, n }) { const path = '/'.repeat(len); const opts = { path: path, createConnection: function() {} }; diff --git a/benchmark/http/end-vs-write-end.js b/benchmark/http/end-vs-write-end.js index b7db1eaa7839e2..f839e5c3cd9ed9 100644 --- a/benchmark/http/end-vs-write-end.js +++ b/benchmark/http/end-vs-write-end.js @@ -17,11 +17,10 @@ const bench = common.createBenchmark(main, { method: ['write', 'end'] }); -function main(conf) { +function main({ len, type, method, c }) { const http = require('http'); var chunk; - const len = conf.len; - switch (conf.type) { + switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); break; @@ -42,15 +41,15 @@ function main(conf) { res.end(chunk); } - const method = conf.method === 'write' ? write : end; + const fn = method === 'write' ? write : end; const server = http.createServer(function(req, res) { - method(res); + fn(res); }); server.listen(common.PORT, function() { bench.http({ - connections: conf.c + connections: c }, function() { server.close(); }); diff --git a/benchmark/http/simple.js b/benchmark/http/simple.js index 544aad49688386..d5351815fc1b7e 100644 --- a/benchmark/http/simple.js +++ b/benchmark/http/simple.js @@ -12,17 +12,16 @@ const bench = common.createBenchmark(main, { res: ['normal', 'setHeader', 'setHeaderWH'] }); -function main(conf) { +function main({ type, len, chunks, c, chunkedEnc, res }) { process.env.PORT = PORT; var server = require('../fixtures/simple-http-server.js') .listen(PORT) .on('listening', function() { - const path = - `/${conf.type}/${conf.len}/${conf.chunks}/${conf.res}/${conf.chunkedEnc}`; + const path = `/${type}/${len}/${chunks}/${res}/${chunkedEnc}`; bench.http({ path: path, - connections: conf.c + connections: c }, function() { server.close(); }); diff --git a/benchmark/http2/headers.js b/benchmark/http2/headers.js index 3c8d0465acb0d0..ad1eb50007a92d 100644 --- a/benchmark/http2/headers.js +++ b/benchmark/http2/headers.js @@ -9,9 +9,7 @@ const bench = common.createBenchmark(main, { benchmarker: ['h2load'] }, { flags: ['--no-warnings', '--expose-http2'] }); -function main(conf) { - const n = +conf.n; - const nheaders = +conf.nheaders; +function main({ n, nheaders }) { const http2 = require('http2'); const server = http2.createServer({ maxHeaderListPairs: 20000 diff --git a/benchmark/http2/respond-with-fd.js b/benchmark/http2/respond-with-fd.js index 791e5f3d1e7da6..6076cf91be9d84 100644 --- a/benchmark/http2/respond-with-fd.js +++ b/benchmark/http2/respond-with-fd.js @@ -14,15 +14,11 @@ const bench = common.createBenchmark(main, { benchmarker: ['h2load'] }, { flags: ['--no-warnings', '--expose-http2'] }); -function main(conf) { - +function main({ requests, streams, clients }) { fs.open(file, 'r', (err, fd) => { if (err) throw err; - const n = +conf.requests; - const m = +conf.streams; - const c = +conf.clients; const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { @@ -32,10 +28,10 @@ function main(conf) { server.listen(PORT, () => { bench.http({ path: '/', - requests: n, - maxConcurrentStreams: m, - clients: c, - threads: c + requests, + maxConcurrentStreams: streams, + clients, + threads: clients }, () => server.close()); }); diff --git a/benchmark/http2/simple.js b/benchmark/http2/simple.js index e8cb3ddee2dff8..37c78d340181a8 100644 --- a/benchmark/http2/simple.js +++ b/benchmark/http2/simple.js @@ -15,10 +15,7 @@ const bench = common.createBenchmark(main, { benchmarker: ['h2load'] }, { flags: ['--no-warnings', '--expose-http2'] }); -function main(conf) { - const n = +conf.requests; - const m = +conf.streams; - const c = +conf.clients; +function main({ requests, streams, clients }) { const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { @@ -30,10 +27,10 @@ function main(conf) { server.listen(PORT, () => { bench.http({ path: '/', - requests: n, - maxConcurrentStreams: m, - clients: c, - threads: c + requests, + maxConcurrentStreams: streams, + clients, + threads: clients }, () => { server.close(); }); }); } diff --git a/benchmark/http2/write.js b/benchmark/http2/write.js index 91b9c8f0c5c073..7a802ef84fd9ed 100644 --- a/benchmark/http2/write.js +++ b/benchmark/http2/write.js @@ -10,19 +10,16 @@ const bench = common.createBenchmark(main, { benchmarker: ['h2load'] }, { flags: ['--no-warnings', '--expose-http2'] }); -function main(conf) { - const m = +conf.streams; - const l = +conf.length; - const s = +conf.size; +function main({ streams, length, size }) { const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond(); let written = 0; function write() { - stream.write('ü'.repeat(s)); - written += s; - if (written < l) + stream.write('ü'.repeat(size)); + written += size; + if (written < length) setImmediate(write); else stream.end(); @@ -33,7 +30,7 @@ function main(conf) { bench.http({ path: '/', requests: 10000, - maxConcurrentStreams: m, + maxConcurrentStreams: streams, }, () => { server.close(); }); }); } diff --git a/benchmark/misc/freelist.js b/benchmark/misc/freelist.js index 461f4b3e4c8960..0530255728ffeb 100644 --- a/benchmark/misc/freelist.js +++ b/benchmark/misc/freelist.js @@ -8,9 +8,8 @@ const bench = common.createBenchmark(main, { flags: ['--expose-internals'] }); -function main(conf) { +function main({ n }) { const FreeList = require('internal/freelist'); - const n = conf.n; const poolSize = 1000; const list = new FreeList('test', poolSize, Object); var i; diff --git a/benchmark/misc/function_call/index.js b/benchmark/misc/function_call/index.js index 6a2595d2ae188d..91efa573597cc7 100644 --- a/benchmark/misc/function_call/index.js +++ b/benchmark/misc/function_call/index.js @@ -31,13 +31,13 @@ const bench = common.createBenchmark(main, { millions: [1, 10, 50] }); -function main(conf) { - const n = +conf.millions * 1e6; +function main({ millions, type }) { + const n = millions * 1e6; - const fn = conf.type === 'cxx' ? cxx : js; + const fn = type === 'cxx' ? cxx : js; bench.start(); for (var i = 0; i < n; i++) { fn(); } - bench.end(+conf.millions); + bench.end(millions); } diff --git a/benchmark/misc/object-property-bench.js b/benchmark/misc/object-property-bench.js index d6afd4e9c0bcbb..37da82d88758fd 100644 --- a/benchmark/misc/object-property-bench.js +++ b/benchmark/misc/object-property-bench.js @@ -59,10 +59,10 @@ function runSymbol(n) { bench.end(n / 1e6); } -function main(conf) { - const n = +conf.millions * 1e6; +function main({ millions, method }) { + const n = millions * 1e6; - switch (conf.method) { + switch (method) { // '' is a default case for tests case '': case 'property': diff --git a/benchmark/misc/punycode.js b/benchmark/misc/punycode.js index 40bcd70302003c..7016fa11712bbc 100644 --- a/benchmark/misc/punycode.js +++ b/benchmark/misc/punycode.js @@ -62,10 +62,8 @@ function runICU(n, val) { bench.end(n); } -function main(conf) { - const n = +conf.n; - const val = conf.val; - switch (conf.method) { +function main({ n, val, method }) { + switch (method) { // '' is a default case for tests case '': case 'punycode': diff --git a/benchmark/misc/startup.js b/benchmark/misc/startup.js index b010f9fa469070..703146f081b3c6 100644 --- a/benchmark/misc/startup.js +++ b/benchmark/misc/startup.js @@ -8,8 +8,7 @@ const bench = common.createBenchmark(startNode, { dur: [1] }); -function startNode(conf) { - const dur = +conf.dur; +function startNode({ dur }) { var go = true; var starts = 0; diff --git a/benchmark/misc/util-extend-vs-object-assign.js b/benchmark/misc/util-extend-vs-object-assign.js index f2a039bc5d71fc..149619f6e1dea3 100644 --- a/benchmark/misc/util-extend-vs-object-assign.js +++ b/benchmark/misc/util-extend-vs-object-assign.js @@ -8,19 +8,17 @@ const bench = common.createBenchmark(main, { n: [10e4] }); -function main(conf) { +function main({ n, type }) { let fn; - const n = conf.n | 0; - - if (conf.type === 'extend') { + if (type === 'extend') { fn = util._extend; - } else if (conf.type === 'assign') { + } else if (type === 'assign') { fn = Object.assign; } // Force-optimize the method to test so that the benchmark doesn't // get disrupted by the optimizer kicking in halfway through. - for (var i = 0; i < conf.type.length * 10; i += 1) + for (var i = 0; i < type.length * 10; i += 1) fn({}, process.env); const obj = new Proxy({}, { set: function(a, b, c) { return true; } }); diff --git a/benchmark/module/module-loader.js b/benchmark/module/module-loader.js index cca5fc2c229038..8393d1f92e0e6c 100644 --- a/benchmark/module/module-loader.js +++ b/benchmark/module/module-loader.js @@ -12,8 +12,8 @@ const bench = common.createBenchmark(main, { useCache: ['true', 'false'] }); -function main(conf) { - const n = +conf.thousands * 1e3; +function main({ thousands, fullPath, useCache }) { + const n = thousands * 1e3; refreshTmpDir(); try { fs.mkdirSync(benchmarkDirectory); } catch (e) {} @@ -30,10 +30,10 @@ function main(conf) { ); } - if (conf.fullPath === 'true') - measureFull(n, conf.useCache === 'true'); + if (fullPath === 'true') + measureFull(n, useCache === 'true'); else - measureDir(n, conf.useCache === 'true'); + measureDir(n, useCache === 'true'); refreshTmpDir(); } diff --git a/benchmark/net/net-c2s-cork.js b/benchmark/net/net-c2s-cork.js index a6582caa16be56..55bb99f6f73d2b 100644 --- a/benchmark/net/net-c2s-cork.js +++ b/benchmark/net/net-c2s-cork.js @@ -2,6 +2,7 @@ 'use strict'; const common = require('../common.js'); +const net = require('net'); const PORT = common.PORT; const bench = common.createBenchmark(main, { @@ -10,17 +11,10 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var dur; -var len; -var type; var chunk; var encoding; -function main(conf) { - dur = +conf.dur; - len = +conf.len; - type = conf.type; - +function main({ dur, len, type }) { switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -37,34 +31,6 @@ function main(conf) { throw new Error(`invalid type: ${type}`); } - server(); -} - -const net = require('net'); - -function Writer() { - this.received = 0; - this.writable = true; -} - -Writer.prototype.write = function(chunk, encoding, cb) { - this.received += chunk.length; - - if (typeof encoding === 'function') - encoding(); - else if (typeof cb === 'function') - cb(); - - return true; -}; - -// doesn't matter, never emits anything. -Writer.prototype.on = function() {}; -Writer.prototype.once = function() {}; -Writer.prototype.emit = function() {}; -Writer.prototype.prependListener = function() {}; - -function server() { const writer = new Writer(); // the actual benchmark. @@ -95,3 +61,25 @@ function server() { }); }); } + +function Writer() { + this.received = 0; + this.writable = true; +} + +Writer.prototype.write = function(chunk, encoding, cb) { + this.received += chunk.length; + + if (typeof encoding === 'function') + encoding(); + else if (typeof cb === 'function') + cb(); + + return true; +}; + +// doesn't matter, never emits anything. +Writer.prototype.on = function() {}; +Writer.prototype.once = function() {}; +Writer.prototype.emit = function() {}; +Writer.prototype.prependListener = function() {}; diff --git a/benchmark/net/net-c2s.js b/benchmark/net/net-c2s.js index 140f9612ab1ed9..4add79a1664d4a 100644 --- a/benchmark/net/net-c2s.js +++ b/benchmark/net/net-c2s.js @@ -2,6 +2,7 @@ 'use strict'; const common = require('../common.js'); +const net = require('net'); const PORT = common.PORT; const bench = common.createBenchmark(main, { @@ -10,17 +11,10 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var dur; -var len; -var type; var chunk; var encoding; -function main(conf) { - dur = +conf.dur; - len = +conf.len; - type = conf.type; - +function main({ dur, len, type }) { switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -37,10 +31,30 @@ function main(conf) { throw new Error(`invalid type: ${type}`); } - server(); -} + const reader = new Reader(); + const writer = new Writer(); -const net = require('net'); + // the actual benchmark. + const server = net.createServer(function(socket) { + socket.pipe(writer); + }); + + server.listen(PORT, function() { + const socket = net.connect(PORT); + socket.on('connect', function() { + bench.start(); + + reader.pipe(socket); + + setTimeout(function() { + const bytes = writer.received; + const gbits = (bytes * 8) / (1024 * 1024 * 1024); + bench.end(gbits); + process.exit(0); + }, dur * 1000); + }); + }); +} function Writer() { this.received = 0; @@ -84,30 +98,3 @@ Reader.prototype.pipe = function(dest) { this.flow(); return dest; }; - - -function server() { - const reader = new Reader(); - const writer = new Writer(); - - // the actual benchmark. - const server = net.createServer(function(socket) { - socket.pipe(writer); - }); - - server.listen(PORT, function() { - const socket = net.connect(PORT); - socket.on('connect', function() { - bench.start(); - - reader.pipe(socket); - - setTimeout(function() { - const bytes = writer.received; - const gbits = (bytes * 8) / (1024 * 1024 * 1024); - bench.end(gbits); - process.exit(0); - }, dur * 1000); - }); - }); -} diff --git a/benchmark/net/net-pipe.js b/benchmark/net/net-pipe.js index a8ae50edfbfde0..3dd3bb78ccf9ac 100644 --- a/benchmark/net/net-pipe.js +++ b/benchmark/net/net-pipe.js @@ -2,6 +2,7 @@ 'use strict'; const common = require('../common.js'); +const net = require('net'); const PORT = common.PORT; const bench = common.createBenchmark(main, { @@ -10,17 +11,10 @@ const bench = common.createBenchmark(main, { dur: [5], }); -var dur; -var len; -var type; var chunk; var encoding; -function main(conf) { - dur = +conf.dur; - len = +conf.len; - type = conf.type; - +function main({ dur, len, type }) { switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -37,10 +31,33 @@ function main(conf) { throw new Error(`invalid type: ${type}`); } - server(); -} + const reader = new Reader(); + const writer = new Writer(); -const net = require('net'); + // the actual benchmark. + const server = net.createServer(function(socket) { + socket.pipe(socket); + }); + + server.listen(PORT, function() { + const socket = net.connect(PORT); + socket.on('connect', function() { + bench.start(); + + reader.pipe(socket); + socket.pipe(writer); + + setTimeout(function() { + // multiply by 2 since we're sending it first one way + // then then back again. + const bytes = writer.received * 2; + const gbits = (bytes * 8) / (1024 * 1024 * 1024); + bench.end(gbits); + process.exit(0); + }, dur * 1000); + }); + }); +} function Writer() { this.received = 0; @@ -84,33 +101,3 @@ Reader.prototype.pipe = function(dest) { this.flow(); return dest; }; - - -function server() { - const reader = new Reader(); - const writer = new Writer(); - - // the actual benchmark. - const server = net.createServer(function(socket) { - socket.pipe(socket); - }); - - server.listen(PORT, function() { - const socket = net.connect(PORT); - socket.on('connect', function() { - bench.start(); - - reader.pipe(socket); - socket.pipe(writer); - - setTimeout(function() { - // multiply by 2 since we're sending it first one way - // then then back again. - const bytes = writer.received * 2; - const gbits = (bytes * 8) / (1024 * 1024 * 1024); - bench.end(gbits); - process.exit(0); - }, dur * 1000); - }); - }); -} diff --git a/benchmark/net/net-s2c.js b/benchmark/net/net-s2c.js index 9fec2d8577c098..2ddf8fd6c5ff67 100644 --- a/benchmark/net/net-s2c.js +++ b/benchmark/net/net-s2c.js @@ -10,17 +10,10 @@ const bench = common.createBenchmark(main, { dur: [5] }); -var dur; -var len; -var type; var chunk; var encoding; -function main(conf) { - dur = +conf.dur; - len = +conf.len; - type = conf.type; - +function main({ dur, len, type }) { switch (type) { case 'buf': chunk = Buffer.alloc(len, 'x'); @@ -37,7 +30,29 @@ function main(conf) { throw new Error(`invalid type: ${type}`); } - server(); + const reader = new Reader(); + const writer = new Writer(); + + // the actual benchmark. + const server = net.createServer(function(socket) { + reader.pipe(socket); + }); + + server.listen(PORT, function() { + const socket = net.connect(PORT); + socket.on('connect', function() { + bench.start(); + + socket.pipe(writer); + + setTimeout(function() { + const bytes = writer.received; + const gbits = (bytes * 8) / (1024 * 1024 * 1024); + bench.end(gbits); + process.exit(0); + }, dur * 1000); + }); + }); } const net = require('net'); @@ -84,30 +99,3 @@ Reader.prototype.pipe = function(dest) { this.flow(); return dest; }; - - -function server() { - const reader = new Reader(); - const writer = new Writer(); - - // the actual benchmark. - const server = net.createServer(function(socket) { - reader.pipe(socket); - }); - - server.listen(PORT, function() { - const socket = net.connect(PORT); - socket.on('connect', function() { - bench.start(); - - socket.pipe(writer); - - setTimeout(function() { - const bytes = writer.received; - const gbits = (bytes * 8) / (1024 * 1024 * 1024); - bench.end(gbits); - process.exit(0); - }, dur * 1000); - }); - }); -} diff --git a/benchmark/net/net-wrap-js-stream-passthrough.js b/benchmark/net/net-wrap-js-stream-passthrough.js new file mode 100644 index 00000000000000..05a66f4e7ab783 --- /dev/null +++ b/benchmark/net/net-wrap-js-stream-passthrough.js @@ -0,0 +1,96 @@ +// test the speed of .pipe() with JSStream wrapping for PassThrough streams +'use strict'; + +const common = require('../common.js'); +const { PassThrough } = require('stream'); + +const bench = common.createBenchmark(main, { + len: [102400, 1024 * 1024 * 16], + type: ['utf', 'asc', 'buf'], + dur: [5], +}, { + flags: ['--expose-internals'] +}); + +var chunk; +var encoding; + +function main({ dur, len, type }) { + // Can only require internals inside main(). + const JSStreamWrap = require('internal/wrap_js_stream'); + + switch (type) { + case 'buf': + chunk = Buffer.alloc(len, 'x'); + break; + case 'utf': + encoding = 'utf8'; + chunk = 'ü'.repeat(len / 2); + break; + case 'asc': + encoding = 'ascii'; + chunk = 'x'.repeat(len); + break; + default: + throw new Error(`invalid type: ${type}`); + } + + const reader = new Reader(); + const writer = new Writer(); + + // the actual benchmark. + const fakeSocket = new JSStreamWrap(new PassThrough()); + bench.start(); + reader.pipe(fakeSocket); + fakeSocket.pipe(writer); + + setTimeout(function() { + const bytes = writer.received; + const gbits = (bytes * 8) / (1024 * 1024 * 1024); + bench.end(gbits); + process.exit(0); + }, dur * 1000); +} + +function Writer() { + this.received = 0; + this.writable = true; +} + +Writer.prototype.write = function(chunk, encoding, cb) { + this.received += chunk.length; + + if (typeof encoding === 'function') + encoding(); + else if (typeof cb === 'function') + cb(); + + return true; +}; + +// doesn't matter, never emits anything. +Writer.prototype.on = function() {}; +Writer.prototype.once = function() {}; +Writer.prototype.emit = function() {}; +Writer.prototype.prependListener = function() {}; + + +function flow() { + const dest = this.dest; + const res = dest.write(chunk, encoding); + if (!res) + dest.once('drain', this.flow); + else + process.nextTick(this.flow); +} + +function Reader() { + this.flow = flow.bind(this); + this.readable = true; +} + +Reader.prototype.pipe = function(dest) { + this.dest = dest; + this.flow(); + return dest; +}; diff --git a/benchmark/net/tcp-raw-c2s.js b/benchmark/net/tcp-raw-c2s.js index bd41be87728308..2be3bb3b538ffd 100644 --- a/benchmark/net/tcp-raw-c2s.js +++ b/benchmark/net/tcp-raw-c2s.js @@ -19,23 +19,7 @@ const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; const WriteWrap = process.binding('stream_wrap').WriteWrap; const PORT = common.PORT; -var dur; -var len; -var type; - -function main(conf) { - dur = +conf.dur; - len = +conf.len; - type = conf.type; - server(); -} - - -function fail(err, syscall) { - throw util._errnoException(err, syscall); -} - -function server() { +function main({ dur, len, type }) { const serverHandle = new TCP(TCPConstants.SERVER); var err = serverHandle.bind('127.0.0.1', PORT); if (err) @@ -73,10 +57,15 @@ function server() { clientHandle.readStart(); }; - client(); + client(type, len); +} + + +function fail(err, syscall) { + throw util._errnoException(err, syscall); } -function client() { +function client(type, len) { var chunk; switch (type) { case 'buf': diff --git a/benchmark/net/tcp-raw-pipe.js b/benchmark/net/tcp-raw-pipe.js index 4dd06ed446d6c1..2fc03f08cd4a90 100644 --- a/benchmark/net/tcp-raw-pipe.js +++ b/benchmark/net/tcp-raw-pipe.js @@ -14,27 +14,17 @@ const bench = common.createBenchmark(main, { dur: [5] }); +function fail(err, syscall) { + throw util._errnoException(err, syscall); +} + const { TCP, constants: TCPConstants } = process.binding('tcp_wrap'); const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; const WriteWrap = process.binding('stream_wrap').WriteWrap; const PORT = common.PORT; -var dur; -var len; -var type; - -function main(conf) { - dur = +conf.dur; - len = +conf.len; - type = conf.type; - server(); -} - -function fail(err, syscall) { - throw util._errnoException(err, syscall); -} - -function server() { +function main({ dur, len, type }) { + // Server const serverHandle = new TCP(TCPConstants.SERVER); var err = serverHandle.bind('127.0.0.1', PORT); if (err) @@ -70,10 +60,7 @@ function server() { clientHandle.readStart(); }; - client(); -} - -function client() { + // Client var chunk; switch (type) { case 'buf': @@ -91,9 +78,9 @@ function client() { const clientHandle = new TCP(TCPConstants.SOCKET); const connectReq = new TCPConnectWrap(); - const err = clientHandle.connect(connectReq, '127.0.0.1', PORT); var bytes = 0; + err = clientHandle.connect(connectReq, '127.0.0.1', PORT); if (err) fail(err, 'connect'); diff --git a/benchmark/net/tcp-raw-s2c.js b/benchmark/net/tcp-raw-s2c.js index 2ca6016ce017a1..339f5e393d9254 100644 --- a/benchmark/net/tcp-raw-s2c.js +++ b/benchmark/net/tcp-raw-s2c.js @@ -19,22 +19,7 @@ const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; const WriteWrap = process.binding('stream_wrap').WriteWrap; const PORT = common.PORT; -var dur; -var len; -var type; - -function main(conf) { - dur = +conf.dur; - len = +conf.len; - type = conf.type; - server(); -} - -function fail(err, syscall) { - throw util._errnoException(err, syscall); -} - -function server() { +function main({ dur, len, type }) { const serverHandle = new TCP(TCPConstants.SERVER); var err = serverHandle.bind('127.0.0.1', PORT); if (err) @@ -103,10 +88,14 @@ function server() { } }; - client(); + client(dur); +} + +function fail(err, syscall) { + throw util._errnoException(err, syscall); } -function client() { +function client(dur) { const clientHandle = new TCP(TCPConstants.SOCKET); const connectReq = new TCPConnectWrap(); const err = clientHandle.connect(connectReq, '127.0.0.1', PORT); diff --git a/benchmark/os/cpus.js b/benchmark/os/cpus.js index 2a8535113c207a..da158a1b061c7f 100644 --- a/benchmark/os/cpus.js +++ b/benchmark/os/cpus.js @@ -7,9 +7,7 @@ const bench = common.createBenchmark(main, { n: [3e4] }); -function main(conf) { - const n = +conf.n; - +function main({ n }) { bench.start(); for (var i = 0; i < n; ++i) cpus(); diff --git a/benchmark/os/loadavg.js b/benchmark/os/loadavg.js index 6e3c57ed44b777..2cd38316b24bdd 100644 --- a/benchmark/os/loadavg.js +++ b/benchmark/os/loadavg.js @@ -7,9 +7,7 @@ const bench = common.createBenchmark(main, { n: [5e6] }); -function main(conf) { - const n = +conf.n; - +function main({ n }) { bench.start(); for (var i = 0; i < n; ++i) loadavg(); diff --git a/benchmark/path/basename-posix.js b/benchmark/path/basename-posix.js index 42e98c5932b028..20b734703f0746 100644 --- a/benchmark/path/basename-posix.js +++ b/benchmark/path/basename-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { pathext: [ @@ -18,20 +18,17 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - var input = String(conf.pathext); +function main({ n, pathext }) { var ext; - const extIdx = input.indexOf('|'); + const extIdx = pathext.indexOf('|'); if (extIdx !== -1) { - ext = input.slice(extIdx + 1); - input = input.slice(0, extIdx); + ext = pathext.slice(extIdx + 1); + pathext = pathext.slice(0, extIdx); } bench.start(); for (var i = 0; i < n; i++) { - p.basename(input, ext); + posix.basename(pathext, ext); } bench.end(n); } diff --git a/benchmark/path/basename-win32.js b/benchmark/path/basename-win32.js index 6966e4fe81e1ac..8a66f56d6e3295 100644 --- a/benchmark/path/basename-win32.js +++ b/benchmark/path/basename-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { pathext: [ @@ -18,20 +18,17 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - var input = String(conf.pathext); +function main({ n, pathext }) { var ext; - const extIdx = input.indexOf('|'); + const extIdx = pathext.indexOf('|'); if (extIdx !== -1) { - ext = input.slice(extIdx + 1); - input = input.slice(0, extIdx); + ext = pathext.slice(extIdx + 1); + pathext = pathext.slice(0, extIdx); } bench.start(); for (var i = 0; i < n; i++) { - p.basename(input, ext); + posix.basename(pathext, ext); } bench.end(n); } diff --git a/benchmark/path/dirname-posix.js b/benchmark/path/dirname-posix.js index 98ad67056bffe4..a045125f43c730 100644 --- a/benchmark/path/dirname-posix.js +++ b/benchmark/path/dirname-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -15,14 +15,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.dirname(input); + posix.dirname(path); } bench.end(n); } diff --git a/benchmark/path/dirname-win32.js b/benchmark/path/dirname-win32.js index c09a3aff98de97..f47abdd37910e2 100644 --- a/benchmark/path/dirname-win32.js +++ b/benchmark/path/dirname-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -15,14 +15,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.dirname(input); + win32.dirname(path); } bench.end(n); } diff --git a/benchmark/path/extname-posix.js b/benchmark/path/extname-posix.js index 4b6e056094267b..3dde5e99005d72 100644 --- a/benchmark/path/extname-posix.js +++ b/benchmark/path/extname-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -18,14 +18,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.extname(input); + posix.extname(path); } bench.end(n); } diff --git a/benchmark/path/extname-win32.js b/benchmark/path/extname-win32.js index fd54d485a9c025..55602df34b4a24 100644 --- a/benchmark/path/extname-win32.js +++ b/benchmark/path/extname-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -18,14 +18,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.extname(input); + win32.extname(path); } bench.end(n); } diff --git a/benchmark/path/format-posix.js b/benchmark/path/format-posix.js index fe20cc3c4fda9c..aa92c06a4d5b2f 100644 --- a/benchmark/path/format-posix.js +++ b/benchmark/path/format-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { props: [ @@ -9,10 +9,8 @@ const bench = common.createBenchmark(main, { n: [1e7] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const props = String(conf.props).split('|'); +function main({ n, props }) { + props = props.split('|'); const obj = { root: props[0] || '', dir: props[1] || '', @@ -23,7 +21,7 @@ function main(conf) { bench.start(); for (var i = 0; i < n; i++) { - p.format(obj); + posix.format(obj); } bench.end(n); } diff --git a/benchmark/path/format-win32.js b/benchmark/path/format-win32.js index e59bee8669043e..5921f95cf12064 100644 --- a/benchmark/path/format-win32.js +++ b/benchmark/path/format-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { props: [ @@ -9,10 +9,8 @@ const bench = common.createBenchmark(main, { n: [1e7] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const props = String(conf.props).split('|'); +function main({ n, props }) { + props = props.split('|'); const obj = { root: props[0] || '', dir: props[1] || '', @@ -23,7 +21,7 @@ function main(conf) { bench.start(); for (var i = 0; i < n; i++) { - p.format(obj); + win32.format(obj); } bench.end(n); } diff --git a/benchmark/path/isAbsolute-posix.js b/benchmark/path/isAbsolute-posix.js index 956c8e0d1301e0..42994840487c68 100644 --- a/benchmark/path/isAbsolute-posix.js +++ b/benchmark/path/isAbsolute-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -13,14 +13,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.isAbsolute(input); + posix.isAbsolute(path); } bench.end(n); } diff --git a/benchmark/path/isAbsolute-win32.js b/benchmark/path/isAbsolute-win32.js index 3c93b24220fe45..350e99d48b74a5 100644 --- a/benchmark/path/isAbsolute-win32.js +++ b/benchmark/path/isAbsolute-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -14,14 +14,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.isAbsolute(input); + win32.isAbsolute(path); } bench.end(n); } diff --git a/benchmark/path/join-posix.js b/benchmark/path/join-posix.js index 02b348cdff42d5..f06f74ad37fc46 100644 --- a/benchmark/path/join-posix.js +++ b/benchmark/path/join-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { paths: [ @@ -9,14 +9,12 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const args = String(conf.paths).split('|'); +function main({ n, paths }) { + const args = paths.split('|'); bench.start(); for (var i = 0; i < n; i++) { - p.join.apply(null, args); + posix.join.apply(null, args); } bench.end(n); } diff --git a/benchmark/path/join-win32.js b/benchmark/path/join-win32.js index 96e4aeaa0ca2a9..2fa29f8ebfd356 100644 --- a/benchmark/path/join-win32.js +++ b/benchmark/path/join-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { paths: [ @@ -9,14 +9,12 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const args = String(conf.paths).split('|'); +function main({ n, paths }) { + const args = paths.split('|'); bench.start(); for (var i = 0; i < n; i++) { - p.join.apply(null, args); + win32.join.apply(null, args); } bench.end(n); } diff --git a/benchmark/path/makeLong-win32.js b/benchmark/path/makeLong-win32.js index 0c1ba38aedba6b..4314692eefab5e 100644 --- a/benchmark/path/makeLong-win32.js +++ b/benchmark/path/makeLong-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -12,14 +12,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p._makeLong(input); + win32._makeLong(path); } bench.end(n); } diff --git a/benchmark/path/normalize-posix.js b/benchmark/path/normalize-posix.js index 454a5ba9aebf05..84ac8d2c7c89d2 100644 --- a/benchmark/path/normalize-posix.js +++ b/benchmark/path/normalize-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -14,14 +14,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.normalize(input); + posix.normalize(path); } bench.end(n); } diff --git a/benchmark/path/normalize-win32.js b/benchmark/path/normalize-win32.js index 480856228aae6a..9b983eb9686580 100644 --- a/benchmark/path/normalize-win32.js +++ b/benchmark/path/normalize-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -14,14 +14,10 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const input = String(conf.path); - +function main({ n, path }) { bench.start(); for (var i = 0; i < n; i++) { - p.normalize(input); + win32.normalize(path); } bench.end(n); } diff --git a/benchmark/path/parse-posix.js b/benchmark/path/parse-posix.js index 4f1fb898b86af2..dd1153d3c68b7e 100644 --- a/benchmark/path/parse-posix.js +++ b/benchmark/path/parse-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -15,17 +15,13 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const input = String(conf.path); - +function main({ n, path }) { for (var i = 0; i < n; i++) { - p.parse(input); + posix.parse(path); } bench.start(); for (i = 0; i < n; i++) { - p.parse(input); + posix.parse(path); } bench.end(n); } diff --git a/benchmark/path/parse-win32.js b/benchmark/path/parse-win32.js index da48f78dd57b90..8c4f06272f4b05 100644 --- a/benchmark/path/parse-win32.js +++ b/benchmark/path/parse-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { path: [ @@ -16,17 +16,13 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const input = String(conf.path); - +function main({ n, path }) { for (var i = 0; i < n; i++) { - p.parse(input); + win32.parse(path); } bench.start(); for (i = 0; i < n; i++) { - p.parse(input); + win32.parse(path); } bench.end(n); } diff --git a/benchmark/path/relative-posix.js b/benchmark/path/relative-posix.js index 1280b686bc55ae..70a0e434d98313 100644 --- a/benchmark/path/relative-posix.js +++ b/benchmark/path/relative-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { paths: [ @@ -15,23 +15,20 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - var from = String(conf.paths); +function main({ n, paths }) { var to = ''; - const delimIdx = from.indexOf('|'); + const delimIdx = paths.indexOf('|'); if (delimIdx > -1) { - to = from.slice(delimIdx + 1); - from = from.slice(0, delimIdx); + to = paths.slice(delimIdx + 1); + paths = paths.slice(0, delimIdx); } for (var i = 0; i < n; i++) { - p.relative(from, to); + posix.relative(paths, to); } bench.start(); for (i = 0; i < n; i++) { - p.relative(from, to); + posix.relative(paths, to); } bench.end(n); } diff --git a/benchmark/path/relative-win32.js b/benchmark/path/relative-win32.js index f109cd9d96d15b..4a97e82e028a0c 100644 --- a/benchmark/path/relative-win32.js +++ b/benchmark/path/relative-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { paths: [ @@ -13,25 +13,22 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - var from = String(conf.paths); +function main({ n, paths }) { var to = ''; - const delimIdx = from.indexOf('|'); + const delimIdx = paths.indexOf('|'); if (delimIdx > -1) { - to = from.slice(delimIdx + 1); - from = from.slice(0, delimIdx); + to = paths.slice(delimIdx + 1); + paths = paths.slice(0, delimIdx); } // Warmup for (var i = 0; i < n; i++) { - p.relative(from, to); + win32.relative(paths, to); } bench.start(); for (i = 0; i < n; i++) { - p.relative(from, to); + win32.relative(paths, to); } bench.end(n); } diff --git a/benchmark/path/resolve-posix.js b/benchmark/path/resolve-posix.js index 4ef0d46e284e32..91f4c1da102a5c 100644 --- a/benchmark/path/resolve-posix.js +++ b/benchmark/path/resolve-posix.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { posix } = require('path'); const bench = common.createBenchmark(main, { paths: [ @@ -12,14 +12,12 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.posix; - const args = String(conf.paths).split('|'); +function main({ n, paths }) { + const args = paths.split('|'); bench.start(); for (var i = 0; i < n; i++) { - p.resolve.apply(null, args); + posix.resolve.apply(null, args); } bench.end(n); } diff --git a/benchmark/path/resolve-win32.js b/benchmark/path/resolve-win32.js index c7d8b4cbb75df0..1047da5184b528 100644 --- a/benchmark/path/resolve-win32.js +++ b/benchmark/path/resolve-win32.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common.js'); -const path = require('path'); +const { win32 } = require('path'); const bench = common.createBenchmark(main, { paths: [ @@ -12,14 +12,12 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const p = path.win32; - const args = String(conf.paths).split('|'); +function main({ n, paths }) { + const args = paths.split('|'); bench.start(); for (var i = 0; i < n; i++) { - p.resolve.apply(null, args); + win32.resolve.apply(null, args); } bench.end(n); } diff --git a/benchmark/process/bench-env.js b/benchmark/process/bench-env.js index 66f966f587bb7f..a332d3cbd61895 100644 --- a/benchmark/process/bench-env.js +++ b/benchmark/process/bench-env.js @@ -7,8 +7,7 @@ const bench = common.createBenchmark(main, { }); -function main(conf) { - const n = conf.n >>> 0; +function main({ n }) { bench.start(); for (var i = 0; i < n; i++) { // Access every item in object to process values. diff --git a/benchmark/process/bench-hrtime.js b/benchmark/process/bench-hrtime.js index 8a2920a238d042..9152a32b22d213 100644 --- a/benchmark/process/bench-hrtime.js +++ b/benchmark/process/bench-hrtime.js @@ -8,13 +8,12 @@ const bench = common.createBenchmark(main, { type: ['raw', 'diff'] }); -function main(conf) { - const n = conf.n | 0; +function main({ n, type }) { const hrtime = process.hrtime; var noDead = hrtime(); var i; - if (conf.type === 'raw') { + if (type === 'raw') { bench.start(); for (i = 0; i < n; i++) { noDead = hrtime(); diff --git a/benchmark/process/memoryUsage.js b/benchmark/process/memoryUsage.js index 8b5aea871819ef..f9b969ab885d8b 100644 --- a/benchmark/process/memoryUsage.js +++ b/benchmark/process/memoryUsage.js @@ -5,9 +5,7 @@ const bench = common.createBenchmark(main, { n: [1e5] }); -function main(conf) { - const n = +conf.n; - +function main({ n }) { bench.start(); for (var i = 0; i < n; i++) { process.memoryUsage(); diff --git a/benchmark/process/next-tick-breadth-args.js b/benchmark/process/next-tick-breadth-args.js index ca608f15daa743..d759b955c429fe 100644 --- a/benchmark/process/next-tick-breadth-args.js +++ b/benchmark/process/next-tick-breadth-args.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { millions: [4] }); -function main(conf) { - const N = +conf.millions * 1e6; +function main({ millions }) { + const N = millions * 1e6; var n = 0; function cb1(arg1) { diff --git a/benchmark/process/next-tick-breadth.js b/benchmark/process/next-tick-breadth.js index 51951ce0afd645..aebd623869b577 100644 --- a/benchmark/process/next-tick-breadth.js +++ b/benchmark/process/next-tick-breadth.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { millions: [4] }); -function main(conf) { - const N = +conf.millions * 1e6; +function main({ millions }) { + const N = millions * 1e6; var n = 0; function cb() { diff --git a/benchmark/process/next-tick-depth-args.js b/benchmark/process/next-tick-depth-args.js index de792b303cca23..1c1b95bdc84bd1 100644 --- a/benchmark/process/next-tick-depth-args.js +++ b/benchmark/process/next-tick-depth-args.js @@ -7,8 +7,8 @@ const bench = common.createBenchmark(main, { process.maxTickDepth = Infinity; -function main(conf) { - var n = +conf.millions * 1e6; +function main({ millions }) { + var n = millions * 1e6; function cb4(arg1, arg2, arg3, arg4) { if (--n) { @@ -21,7 +21,7 @@ function main(conf) { else process.nextTick(cb1, 0); } else - bench.end(+conf.millions); + bench.end(millions); } function cb3(arg1, arg2, arg3) { if (--n) { @@ -34,7 +34,7 @@ function main(conf) { else process.nextTick(cb1, 0); } else - bench.end(+conf.millions); + bench.end(millions); } function cb2(arg1, arg2) { if (--n) { @@ -47,7 +47,7 @@ function main(conf) { else process.nextTick(cb1, 0); } else - bench.end(+conf.millions); + bench.end(millions); } function cb1(arg1) { if (--n) { @@ -60,7 +60,7 @@ function main(conf) { else process.nextTick(cb1, 0); } else - bench.end(+conf.millions); + bench.end(millions); } bench.start(); process.nextTick(cb1, true); diff --git a/benchmark/process/next-tick-depth.js b/benchmark/process/next-tick-depth.js index e11beb4d0b1f31..99fc83c3772276 100644 --- a/benchmark/process/next-tick-depth.js +++ b/benchmark/process/next-tick-depth.js @@ -6,8 +6,8 @@ const bench = common.createBenchmark(main, { process.maxTickDepth = Infinity; -function main(conf) { - var n = +conf.millions * 1e6; +function main({ millions }) { + var n = millions * 1e6; bench.start(); process.nextTick(onNextTick); @@ -15,6 +15,6 @@ function main(conf) { if (--n) process.nextTick(onNextTick); else - bench.end(+conf.millions); + bench.end(millions); } } diff --git a/benchmark/process/next-tick-exec-args.js b/benchmark/process/next-tick-exec-args.js index 5ff017bb29cd5b..9e8ff73838460a 100644 --- a/benchmark/process/next-tick-exec-args.js +++ b/benchmark/process/next-tick-exec-args.js @@ -4,8 +4,8 @@ const bench = common.createBenchmark(main, { millions: [5] }); -function main(conf) { - var n = +conf.millions * 1e6; +function main({ millions }) { + var n = millions * 1e6; bench.start(); for (var i = 0; i < n; i++) { @@ -20,6 +20,6 @@ function main(conf) { } function onNextTick(i) { if (i + 1 === n) - bench.end(+conf.millions); + bench.end(millions); } } diff --git a/benchmark/process/next-tick-exec.js b/benchmark/process/next-tick-exec.js index 12c9d4624a903c..a8897cd7456476 100644 --- a/benchmark/process/next-tick-exec.js +++ b/benchmark/process/next-tick-exec.js @@ -4,8 +4,8 @@ const bench = common.createBenchmark(main, { millions: [5] }); -function main(conf) { - var n = +conf.millions * 1e6; +function main({ millions }) { + var n = millions * 1e6; bench.start(); for (var i = 0; i < n; i++) { @@ -13,6 +13,6 @@ function main(conf) { } function onNextTick(i) { if (i + 1 === n) - bench.end(+conf.millions); + bench.end(millions); } } diff --git a/benchmark/querystring/querystring-parse.js b/benchmark/querystring/querystring-parse.js index 740dfc9d21b173..db650165eb9cda 100644 --- a/benchmark/querystring/querystring-parse.js +++ b/benchmark/querystring/querystring-parse.js @@ -8,9 +8,7 @@ const bench = common.createBenchmark(main, { n: [1e6], }); -function main(conf) { - const type = conf.type; - const n = conf.n | 0; +function main({ type, n }) { const input = inputs[type]; var i; // Execute the function a "sufficient" number of times before the timed diff --git a/benchmark/querystring/querystring-stringify.js b/benchmark/querystring/querystring-stringify.js index 97b8f1fc703ba2..cd1debd4df622d 100644 --- a/benchmark/querystring/querystring-stringify.js +++ b/benchmark/querystring/querystring-stringify.js @@ -7,10 +7,7 @@ const bench = common.createBenchmark(main, { n: [1e7], }); -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - +function main({ type, n }) { const inputs = { noencode: { foo: 'bar', diff --git a/benchmark/querystring/querystring-unescapebuffer.js b/benchmark/querystring/querystring-unescapebuffer.js index e37af180eef0ea..4f73ed024b11b1 100644 --- a/benchmark/querystring/querystring-unescapebuffer.js +++ b/benchmark/querystring/querystring-unescapebuffer.js @@ -12,10 +12,7 @@ const bench = common.createBenchmark(main, { n: [10e6], }); -function main(conf) { - const input = conf.input; - const n = conf.n | 0; - +function main({ input, n }) { bench.start(); for (var i = 0; i < n; i += 1) querystring.unescapeBuffer(input); diff --git a/benchmark/streams/readable-bigread.js b/benchmark/streams/readable-bigread.js index 34d478fb478478..99213afaeb8f28 100644 --- a/benchmark/streams/readable-bigread.js +++ b/benchmark/streams/readable-bigread.js @@ -7,8 +7,7 @@ const bench = common.createBenchmark(main, { n: [100e1] }); -function main(conf) { - const n = +conf.n; +function main({ n }) { const b = new Buffer(32); const s = new Readable(); function noop() {} diff --git a/benchmark/streams/readable-bigunevenread.js b/benchmark/streams/readable-bigunevenread.js index d176166ae4f432..e2f2c1406a1da0 100644 --- a/benchmark/streams/readable-bigunevenread.js +++ b/benchmark/streams/readable-bigunevenread.js @@ -7,8 +7,7 @@ const bench = common.createBenchmark(main, { n: [100e1] }); -function main(conf) { - const n = +conf.n; +function main({ n }) { const b = new Buffer(32); const s = new Readable(); function noop() {} diff --git a/benchmark/streams/readable-boundaryread.js b/benchmark/streams/readable-boundaryread.js index 4834da0a2c5bf8..835c7d18b51285 100644 --- a/benchmark/streams/readable-boundaryread.js +++ b/benchmark/streams/readable-boundaryread.js @@ -8,11 +8,10 @@ const bench = common.createBenchmark(main, { type: ['string', 'buffer'] }); -function main(conf) { - const n = +conf.n; +function main({ n, type }) { const s = new Readable(); var data = 'a'.repeat(32); - if (conf.type === 'buffer') + if (type === 'buffer') data = Buffer.from(data); s._read = function() {}; diff --git a/benchmark/streams/readable-readall.js b/benchmark/streams/readable-readall.js index be34afbeabc090..5715e42017c795 100644 --- a/benchmark/streams/readable-readall.js +++ b/benchmark/streams/readable-readall.js @@ -7,8 +7,7 @@ const bench = common.createBenchmark(main, { n: [50e2] }); -function main(conf) { - const n = +conf.n; +function main({ n }) { const b = new Buffer(32); const s = new Readable(); function noop() {} diff --git a/benchmark/streams/readable-unevenread.js b/benchmark/streams/readable-unevenread.js index ebbc727ad23ec3..d7a408b1c56a31 100644 --- a/benchmark/streams/readable-unevenread.js +++ b/benchmark/streams/readable-unevenread.js @@ -7,8 +7,7 @@ const bench = common.createBenchmark(main, { n: [100e1] }); -function main(conf) { - const n = +conf.n; +function main({ n }) { const b = new Buffer(32); const s = new Readable(); function noop() {} diff --git a/benchmark/streams/transform-creation.js b/benchmark/streams/transform-creation.js index bd5ac96fa71e32..abfab0c8e25321 100644 --- a/benchmark/streams/transform-creation.js +++ b/benchmark/streams/transform-creation.js @@ -13,9 +13,7 @@ function MyTransform() { inherits(MyTransform, Transform); MyTransform.prototype._transform = function() {}; -function main(conf) { - const n = +conf.n; - +function main({ n }) { bench.start(); for (var i = 0; i < n; ++i) new MyTransform(); diff --git a/benchmark/streams/writable-manywrites.js b/benchmark/streams/writable-manywrites.js index fadafe86e4cf70..6fcb07e849d615 100644 --- a/benchmark/streams/writable-manywrites.js +++ b/benchmark/streams/writable-manywrites.js @@ -7,8 +7,7 @@ const bench = common.createBenchmark(main, { n: [2e6] }); -function main(conf) { - const n = +conf.n; +function main({ n }) { const b = Buffer.allocUnsafe(1024); const s = new Writable(); s._write = function(chunk, encoding, cb) { diff --git a/benchmark/string_decoder/string-decoder-create.js b/benchmark/string_decoder/string-decoder-create.js index 17c0f6750d0721..386f99e7c0ee6f 100644 --- a/benchmark/string_decoder/string-decoder-create.js +++ b/benchmark/string_decoder/string-decoder-create.js @@ -9,10 +9,7 @@ const bench = common.createBenchmark(main, { n: [25e6] }); -function main(conf) { - const encoding = conf.encoding; - const n = conf.n | 0; - +function main({ encoding, n }) { bench.start(); for (var i = 0; i < n; ++i) { const sd = new StringDecoder(encoding); diff --git a/benchmark/string_decoder/string-decoder.js b/benchmark/string_decoder/string-decoder.js index 31cf7bf2f0a8a5..95baa893bbbf94 100644 --- a/benchmark/string_decoder/string-decoder.js +++ b/benchmark/string_decoder/string-decoder.js @@ -4,8 +4,8 @@ const StringDecoder = require('string_decoder').StringDecoder; const bench = common.createBenchmark(main, { encoding: ['ascii', 'utf8', 'base64-utf8', 'base64-ascii', 'utf16le'], - inlen: [32, 128, 1024, 4096], - chunk: [16, 64, 256, 1024], + inLen: [32, 128, 1024, 4096], + chunkLen: [16, 64, 256, 1024], n: [25e5] }); @@ -13,12 +13,7 @@ const UTF8_ALPHA = 'Blåbærsyltetøy'; const ASC_ALPHA = 'Blueberry jam'; const UTF16_BUF = Buffer.from('Blåbærsyltetøy', 'utf16le'); -function main(conf) { - const encoding = conf.encoding; - const inLen = conf.inlen | 0; - const chunkLen = conf.chunk | 0; - const n = conf.n | 0; - +function main({ encoding, inLen, chunkLen, n }) { var alpha; var buf; const chunks = []; diff --git a/benchmark/timers/immediate.js b/benchmark/timers/immediate.js index bbe81555cacc97..7ddb5cb05af40d 100644 --- a/benchmark/timers/immediate.js +++ b/benchmark/timers/immediate.js @@ -6,9 +6,9 @@ const bench = common.createBenchmark(main, { type: ['depth', 'depth1', 'breadth', 'breadth1', 'breadth4', 'clear'] }); -function main(conf) { - const N = +conf.thousands * 1e3; - switch (conf.type) { +function main({ thousands, type }) { + const N = thousands * 1e3; + switch (type) { case 'depth': depth(N); break; diff --git a/benchmark/timers/set-immediate-breadth-args.js b/benchmark/timers/set-immediate-breadth-args.js index 348cb62fb2cc1a..d5b5a9878066db 100644 --- a/benchmark/timers/set-immediate-breadth-args.js +++ b/benchmark/timers/set-immediate-breadth-args.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { millions: [5] }); -function main(conf) { - const N = +conf.millions * 1e6; +function main({ millions }) { + const N = millions * 1e6; process.on('exit', function() { bench.end(N / 1e6); diff --git a/benchmark/timers/set-immediate-breadth.js b/benchmark/timers/set-immediate-breadth.js index 3d8b038342634d..a4b217b5bff8d6 100644 --- a/benchmark/timers/set-immediate-breadth.js +++ b/benchmark/timers/set-immediate-breadth.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { millions: [10] }); -function main(conf) { - const N = +conf.millions * 1e6; +function main({ millions }) { + const N = millions * 1e6; process.on('exit', function() { bench.end(N / 1e6); diff --git a/benchmark/timers/set-immediate-depth-args.js b/benchmark/timers/set-immediate-depth-args.js index 704b1814514a93..fe1340c4bd55f2 100644 --- a/benchmark/timers/set-immediate-depth-args.js +++ b/benchmark/timers/set-immediate-depth-args.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { millions: [5] }); -function main(conf) { - const N = +conf.millions * 1e6; +function main({ millions }) { + const N = millions * 1e6; process.on('exit', function() { bench.end(N / 1e6); diff --git a/benchmark/timers/timers-breadth.js b/benchmark/timers/timers-breadth.js index 02ebd5bb0d082b..b05b3f91b1859d 100644 --- a/benchmark/timers/timers-breadth.js +++ b/benchmark/timers/timers-breadth.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { thousands: [5000], }); -function main(conf) { - const N = +conf.thousands * 1e3; +function main({ thousands }) { + const N = thousands * 1e3; var n = 0; bench.start(); function cb() { diff --git a/benchmark/timers/timers-cancel-pooled.js b/benchmark/timers/timers-cancel-pooled.js index 23cef153876f20..33897507c83937 100644 --- a/benchmark/timers/timers-cancel-pooled.js +++ b/benchmark/timers/timers-cancel-pooled.js @@ -6,8 +6,8 @@ const bench = common.createBenchmark(main, { millions: [5], }); -function main(conf) { - const iterations = +conf.millions * 1e6; +function main({ millions }) { + const iterations = millions * 1e6; var timer = setTimeout(() => {}, 1); for (var i = 0; i < iterations; i++) { diff --git a/benchmark/timers/timers-cancel-unpooled.js b/benchmark/timers/timers-cancel-unpooled.js index 50931e35124724..57e0139dfe1a4a 100644 --- a/benchmark/timers/timers-cancel-unpooled.js +++ b/benchmark/timers/timers-cancel-unpooled.js @@ -6,8 +6,8 @@ const bench = common.createBenchmark(main, { millions: [1], }); -function main(conf) { - const iterations = +conf.millions * 1e6; +function main({ millions }) { + const iterations = millions * 1e6; const timersList = []; for (var i = 0; i < iterations; i++) { diff --git a/benchmark/timers/timers-depth.js b/benchmark/timers/timers-depth.js index 42dc652b277781..ca74eee393fd45 100644 --- a/benchmark/timers/timers-depth.js +++ b/benchmark/timers/timers-depth.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { thousands: [1], }); -function main(conf) { - const N = +conf.thousands * 1e3; +function main({ thousands }) { + const N = thousands * 1e3; var n = 0; bench.start(); setTimeout(cb, 1); diff --git a/benchmark/timers/timers-insert-pooled.js b/benchmark/timers/timers-insert-pooled.js index 8bbc84290ad9b7..59d2c490c3a9b2 100644 --- a/benchmark/timers/timers-insert-pooled.js +++ b/benchmark/timers/timers-insert-pooled.js @@ -5,8 +5,8 @@ const bench = common.createBenchmark(main, { millions: [5], }); -function main(conf) { - const iterations = +conf.millions * 1e6; +function main({ millions }) { + const iterations = millions * 1e6; bench.start(); diff --git a/benchmark/timers/timers-insert-unpooled.js b/benchmark/timers/timers-insert-unpooled.js index efe8e9aaa579c2..56526633358e42 100644 --- a/benchmark/timers/timers-insert-unpooled.js +++ b/benchmark/timers/timers-insert-unpooled.js @@ -6,8 +6,8 @@ const bench = common.createBenchmark(main, { millions: [1], }); -function main(conf) { - const iterations = +conf.millions * 1e6; +function main({ millions }) { + const iterations = millions * 1e6; const timersList = []; diff --git a/benchmark/timers/timers-timeout-pooled.js b/benchmark/timers/timers-timeout-pooled.js index d39c8cf969a49b..df88e2784f8f91 100644 --- a/benchmark/timers/timers-timeout-pooled.js +++ b/benchmark/timers/timers-timeout-pooled.js @@ -8,8 +8,8 @@ const bench = common.createBenchmark(main, { millions: [10], }); -function main(conf) { - const iterations = +conf.millions * 1e6; +function main({ millions }) { + const iterations = millions * 1e6; let count = 0; // Function tracking on the hidden class in V8 can cause misleading diff --git a/benchmark/tls/convertprotocols.js b/benchmark/tls/convertprotocols.js index 5d561455051a0c..1ee2672bee7bd7 100644 --- a/benchmark/tls/convertprotocols.js +++ b/benchmark/tls/convertprotocols.js @@ -7,9 +7,7 @@ const bench = common.createBenchmark(main, { n: [1, 50000] }); -function main(conf) { - const n = +conf.n; - +function main({ n }) { var i = 0; var m = {}; // First call dominates results diff --git a/benchmark/tls/throughput.js b/benchmark/tls/throughput.js index 51feb85cbaccc1..f63257c49693d6 100644 --- a/benchmark/tls/throughput.js +++ b/benchmark/tls/throughput.js @@ -6,20 +6,15 @@ const bench = common.createBenchmark(main, { size: [2, 1024, 1024 * 1024] }); -var dur, type, encoding, size; -var server; - const path = require('path'); const fs = require('fs'); const cert_dir = path.resolve(__dirname, '../../test/fixtures'); var options; const tls = require('tls'); -function main(conf) { - dur = +conf.dur; - type = conf.type; - size = +conf.size; - +function main({ dur, type, size }) { + var encoding; + var server; var chunk; switch (type) { case 'buf': diff --git a/benchmark/tls/tls-connect.js b/benchmark/tls/tls-connect.js index 628b040ee88c9b..67f2d5f8a932e0 100644 --- a/benchmark/tls/tls-connect.js +++ b/benchmark/tls/tls-connect.js @@ -16,10 +16,7 @@ var dur; var concurrency; var running = true; -function main(conf) { - dur = +conf.dur; - concurrency = +conf.concurrency; - +function main({ dur, concurrency }) { const cert_dir = path.resolve(__dirname, '../../test/fixtures'); const options = { key: fs.readFileSync(`${cert_dir}/test_key.pem`), diff --git a/benchmark/url/legacy-vs-whatwg-url-get-prop.js b/benchmark/url/legacy-vs-whatwg-url-get-prop.js index 229a4e60652b64..93603c258cf1f2 100644 --- a/benchmark/url/legacy-vs-whatwg-url-get-prop.js +++ b/benchmark/url/legacy-vs-whatwg-url-get-prop.js @@ -71,11 +71,7 @@ function useWHATWG(n, input) { return noDead; } -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - const method = conf.method; - +function main({ type, n, method }) { const input = inputs[type]; if (!input) { throw new Error('Unknown input type'); diff --git a/benchmark/url/legacy-vs-whatwg-url-parse.js b/benchmark/url/legacy-vs-whatwg-url-parse.js index ec386b7b85597d..da42d5a189af47 100644 --- a/benchmark/url/legacy-vs-whatwg-url-parse.js +++ b/benchmark/url/legacy-vs-whatwg-url-parse.js @@ -31,11 +31,7 @@ function useWHATWG(n, input) { return noDead; } -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - const method = conf.method; - +function main({ type, n, method }) { const input = inputs[type]; if (!input) { throw new Error('Unknown input type'); diff --git a/benchmark/url/legacy-vs-whatwg-url-searchparams-parse.js b/benchmark/url/legacy-vs-whatwg-url-searchparams-parse.js index b4a80af4e5eabd..51953ec8707374 100644 --- a/benchmark/url/legacy-vs-whatwg-url-searchparams-parse.js +++ b/benchmark/url/legacy-vs-whatwg-url-searchparams-parse.js @@ -28,11 +28,7 @@ function useWHATWG(n, input) { bench.end(n); } -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - const method = conf.method; - +function main({ type, n, method }) { const input = inputs[type]; if (!input) { throw new Error('Unknown input type'); diff --git a/benchmark/url/legacy-vs-whatwg-url-searchparams-serialize.js b/benchmark/url/legacy-vs-whatwg-url-searchparams-serialize.js index 2b8d2c36a810b3..3490782a1bf421 100644 --- a/benchmark/url/legacy-vs-whatwg-url-searchparams-serialize.js +++ b/benchmark/url/legacy-vs-whatwg-url-searchparams-serialize.js @@ -30,11 +30,7 @@ function useWHATWG(n, input, prop) { bench.end(n); } -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - const method = conf.method; - +function main({ type, n, method }) { const input = inputs[type]; if (!input) { throw new Error('Unknown input type'); diff --git a/benchmark/url/legacy-vs-whatwg-url-serialize.js b/benchmark/url/legacy-vs-whatwg-url-serialize.js index 35b459a10c0e0b..e92b941b5d57e5 100644 --- a/benchmark/url/legacy-vs-whatwg-url-serialize.js +++ b/benchmark/url/legacy-vs-whatwg-url-serialize.js @@ -33,11 +33,7 @@ function useWHATWG(n, input, prop) { return noDead; } -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - const method = conf.method; - +function main({ type, n, method }) { const input = inputs[type]; if (!input) { throw new Error('Unknown input type'); diff --git a/benchmark/url/url-format.js b/benchmark/url/url-format.js index dc8e020879e400..14696af8e31c3f 100644 --- a/benchmark/url/url-format.js +++ b/benchmark/url/url-format.js @@ -12,10 +12,7 @@ const bench = common.createBenchmark(main, { n: [25e6] }); -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - +function main({ type, n }) { const input = inputs[type] || ''; // Force-optimize url.format() so that the benchmark doesn't get diff --git a/benchmark/url/url-resolve.js b/benchmark/url/url-resolve.js index 421a70ef6d59f1..48978574ea24ec 100644 --- a/benchmark/url/url-resolve.js +++ b/benchmark/url/url-resolve.js @@ -18,13 +18,12 @@ const bench = common.createBenchmark(main, { n: [1e5] }); -function main(conf) { - const n = conf.n | 0; - const href = hrefs[conf.href]; - const path = paths[conf.path]; +function main({ n, href, path }) { + const h = hrefs[href]; + const p = paths[path]; bench.start(); for (var i = 0; i < n; i += 1) - url.resolve(href, path); + url.resolve(h, p); bench.end(n); } diff --git a/benchmark/url/url-searchparams-iteration.js b/benchmark/url/url-searchparams-iteration.js index 0f4b71a0a183dd..2b13992bdfcfc0 100644 --- a/benchmark/url/url-searchparams-iteration.js +++ b/benchmark/url/url-searchparams-iteration.js @@ -44,10 +44,7 @@ function iterator(n) { assert.strictEqual(noDead[1], '3rd'); } -function main(conf) { - const method = conf.method; - const n = conf.n | 0; - +function main({ method, n }) { switch (method) { case 'forEach': forEach(n); diff --git a/benchmark/url/url-searchparams-read.js b/benchmark/url/url-searchparams-read.js index 762ffcca03d69d..29235ee81e0e14 100644 --- a/benchmark/url/url-searchparams-read.js +++ b/benchmark/url/url-searchparams-read.js @@ -37,11 +37,7 @@ function has(n, param) { bench.end(n); } -function main(conf) { - const method = conf.method; - const param = conf.param; - const n = conf.n | 0; - +function main({ method, param, n }) { switch (method) { case 'get': get(n, param); diff --git a/benchmark/url/url-searchparams-sort.js b/benchmark/url/url-searchparams-sort.js index 677ce511cf3ea2..524dacb6d52dc4 100644 --- a/benchmark/url/url-searchparams-sort.js +++ b/benchmark/url/url-searchparams-sort.js @@ -31,10 +31,9 @@ const bench = common.createBenchmark(main, { flags: ['--expose-internals'] }); -function main(conf) { +function main({ type, n }) { const searchParams = require('internal/url').searchParamsSymbol; - const input = inputs[conf.type]; - const n = conf.n | 0; + const input = inputs[type]; const params = new URLSearchParams(); const array = getParams(input); diff --git a/benchmark/url/usvstring.js b/benchmark/url/usvstring.js index 40a945037385cf..91abe8d67351c7 100644 --- a/benchmark/url/usvstring.js +++ b/benchmark/url/usvstring.js @@ -16,10 +16,9 @@ const bench = common.createBenchmark(main, { flags: ['--expose-internals'] }); -function main(conf) { +function main({ input, n }) { const { toUSVString } = require('internal/url'); - const str = inputs[conf.input]; - const n = conf.n | 0; + const str = inputs[input]; bench.start(); for (var i = 0; i < n; i++) diff --git a/benchmark/url/whatwg-url-idna.js b/benchmark/url/whatwg-url-idna.js index 3d0ea3dc8fe516..c1e3d4a0b85cec 100644 --- a/benchmark/url/whatwg-url-idna.js +++ b/benchmark/url/whatwg-url-idna.js @@ -31,15 +31,13 @@ const bench = common.createBenchmark(main, { n: [5e6] }); -function main(conf) { - const n = conf.n | 0; - const to = conf.to; - const input = inputs[conf.input][to]; +function main({ n, to, input }) { + const value = inputs[input][to]; const method = to === 'ascii' ? domainToASCII : domainToUnicode; bench.start(); for (var i = 0; i < n; i++) { - method(input); + method(value); } bench.end(n); } diff --git a/benchmark/url/whatwg-url-properties.js b/benchmark/url/whatwg-url-properties.js index 3a865d2335ab3c..f526c07f139be9 100644 --- a/benchmark/url/whatwg-url-properties.js +++ b/benchmark/url/whatwg-url-properties.js @@ -46,11 +46,9 @@ function getAlternative(prop) { return alternatives[prop]; } -function main(conf) { - const n = conf.n | 0; - const input = inputs[conf.input]; - const url = new URL(input); - const prop = conf.prop; +function main({ n, input, prop }) { + const value = inputs[input]; + const url = new URL(value); switch (prop) { case 'protocol': diff --git a/benchmark/util/normalize-encoding.js b/benchmark/util/normalize-encoding.js index 2cdfd54442114d..96eab1912d0761 100644 --- a/benchmark/util/normalize-encoding.js +++ b/benchmark/util/normalize-encoding.js @@ -47,11 +47,9 @@ function getInput(input) { } } -function main(conf) { - const normalizeEncoding = require('internal/util').normalizeEncoding; - - const n = conf.n | 0; - const inputs = getInput(conf.input); +function main({ input, n }) { + const { normalizeEncoding } = require('internal/util'); + const inputs = getInput(input); var noDead = ''; bench.start(); diff --git a/benchmark/util/type-check.js b/benchmark/util/type-check.js index ee8dd7e4ece188..e1d1ac553fedcf 100644 --- a/benchmark/util/type-check.js +++ b/benchmark/util/type-check.js @@ -34,16 +34,15 @@ const bench = common.createBenchmark(main, { flags: ['--expose-internals'] }); -function main(conf) { +function main({ type, argument, version, n }) { // For testing, if supplied with an empty type, default to ArrayBufferView. - conf.type = conf.type || 'ArrayBufferView'; + type = type || 'ArrayBufferView'; const util = process.binding('util'); const types = require('internal/util/types'); - const n = (+conf.n) | 0; - const func = { native: util, js: types }[conf.version][`is${conf.type}`]; - const arg = args[conf.type][conf.argument]; + const func = { native: util, js: types }[version][`is${type}`]; + const arg = args[type][argument]; bench.start(); for (var i = 0; i < n; i++) { diff --git a/benchmark/v8/get-stats.js b/benchmark/v8/get-stats.js index 96de7572397161..6ee742858629c2 100644 --- a/benchmark/v8/get-stats.js +++ b/benchmark/v8/get-stats.js @@ -11,9 +11,7 @@ const bench = common.createBenchmark(main, { n: [1e6] }); -function main(conf) { - const n = +conf.n; - const method = conf.method; +function main({ method, n }) { var i = 0; bench.start(); for (; i < n; i++) diff --git a/benchmark/vm/run-in-context.js b/benchmark/vm/run-in-context.js index 6e26a6d0ebeb38..da8f56a6e0153b 100644 --- a/benchmark/vm/run-in-context.js +++ b/benchmark/vm/run-in-context.js @@ -10,10 +10,8 @@ const bench = common.createBenchmark(main, { const vm = require('vm'); -function main(conf) { - const n = +conf.n; - const options = conf.breakOnSigint ? { breakOnSigint: true } : {}; - const withSigintListener = !!conf.withSigintListener; +function main({ n, breakOnSigint, withSigintListener }) { + const options = breakOnSigint ? { breakOnSigint: true } : {}; process.removeAllListeners('SIGINT'); if (withSigintListener) diff --git a/benchmark/vm/run-in-this-context.js b/benchmark/vm/run-in-this-context.js index a0c737f46954f1..33fd3a34d81f8f 100644 --- a/benchmark/vm/run-in-this-context.js +++ b/benchmark/vm/run-in-this-context.js @@ -10,10 +10,8 @@ const bench = common.createBenchmark(main, { const vm = require('vm'); -function main(conf) { - const n = +conf.n; - const options = conf.breakOnSigint ? { breakOnSigint: true } : {}; - const withSigintListener = !!conf.withSigintListener; +function main({ n, breakOnSigint, withSigintListener }) { + const options = breakOnSigint ? { breakOnSigint: true } : {}; process.removeAllListeners('SIGINT'); if (withSigintListener) diff --git a/benchmark/zlib/creation.js b/benchmark/zlib/creation.js index 5046ef50ecff06..4984bf1a86b755 100644 --- a/benchmark/zlib/creation.js +++ b/benchmark/zlib/creation.js @@ -10,14 +10,13 @@ const bench = common.createBenchmark(main, { n: [5e5] }); -function main(conf) { - const n = +conf.n; - const fn = zlib[`create${conf.type}`]; +function main({ n, type, options }) { + const fn = zlib[`create${type}`]; if (typeof fn !== 'function') throw new Error('Invalid zlib type'); var i = 0; - if (conf.options === 'true') { + if (options === 'true') { const opts = {}; bench.start(); for (; i < n; ++i) diff --git a/benchmark/zlib/deflate.js b/benchmark/zlib/deflate.js index 00993b64462539..5e86d659803747 100644 --- a/benchmark/zlib/deflate.js +++ b/benchmark/zlib/deflate.js @@ -8,10 +8,8 @@ const bench = common.createBenchmark(main, { n: [4e5] }); -function main(conf) { - const n = +conf.n; - const method = conf.method; - const chunk = Buffer.alloc(+conf.inputLen, 'a'); +function main({ n, method, inputLen }) { + const chunk = Buffer.alloc(inputLen, 'a'); var i = 0; switch (method) { diff --git a/common.gypi b/common.gypi index b5e1bc0628d22c..0ee48812415799 100644 --- a/common.gypi +++ b/common.gypi @@ -27,7 +27,7 @@ # Reset this number to 0 on major V8 upgrades. # Increment by one for each non-official patch applied to deps/v8. - 'v8_embedder_string': '-node.17', + 'v8_embedder_string': '-node.18', # Enable disassembler for `--print-code` v8 options 'v8_enable_disassembler': 1, diff --git a/configure b/configure index e434059d6f520b..fc1be60c97496c 100755 --- a/configure +++ b/configure @@ -878,7 +878,6 @@ def configure_node(o): configure_mips(o) if flavor == 'aix': - o['variables']['node_core_target_name'] = 'node_base' o['variables']['node_target_type'] = 'static_library' if target_arch in ('x86', 'x64', 'ia32', 'x32'): @@ -900,8 +899,6 @@ def configure_node(o): if options.systemtap_includes: o['include_dirs'] += [options.systemtap_includes] o['variables']['node_use_dtrace'] = b(use_dtrace) - o['variables']['uv_use_dtrace'] = b(use_dtrace) - o['variables']['uv_parent_path'] = '/deps/uv/' elif options.with_dtrace: raise Exception( 'DTrace is currently only supported on SunOS, MacOS or Linux systems.') @@ -978,7 +975,6 @@ def configure_node(o): o['variables']['library_files'] = options.linked_module o['variables']['asan'] = int(options.enable_asan or 0) - o['variables']['debug_devtools'] = 'node' if options.use_xcode and options.use_ninja: raise Exception('--xcode and --ninja cannot be used together.') @@ -988,6 +984,13 @@ def configure_node(o): else: o['variables']['coverage'] = 'false' + if options.shared: + o['variables']['node_target_type'] = 'shared_library' + elif options.enable_static: + o['variables']['node_target_type'] = 'static_library' + else: + o['variables']['node_target_type'] = 'executable' + def configure_library(lib, output): shared_lib = 'shared_' + lib output['variables']['node_' + shared_lib] = b(getattr(options, shared_lib)) @@ -1346,8 +1349,6 @@ def configure_intl(o): # this is the input '.dat' file to use .. icudt*.dat # may be little-endian if from a icu-project.org tarball o['variables']['icu_data_in'] = icu_data_in - # this is the icudt*.dat file which node will be using (platform endianness) - o['variables']['icu_data_file'] = icu_data_file if not os.path.isfile(icu_data_path): print('Error: ICU prebuilt data file %s does not exist.' % icu_data_path) print('See the README.md.') @@ -1484,6 +1485,7 @@ config = { 'BUILDTYPE': 'Debug' if options.debug else 'Release', 'USE_XCODE': str(int(options.use_xcode or 0)), 'PYTHON': sys.executable, + 'NODE_TARGET_TYPE': variables['node_target_type'], } if options.prefix: diff --git a/deps/uv/AUTHORS b/deps/uv/AUTHORS index b227123e4ac35c..c826c8e13306a7 100644 --- a/deps/uv/AUTHORS +++ b/deps/uv/AUTHORS @@ -321,3 +321,7 @@ Pekka Nikander Ed Schouten Xu Meng Matt Harrison +Anna Henningsen +Jérémy Lal +Ben Wijen +elephantp diff --git a/deps/uv/ChangeLog b/deps/uv/ChangeLog index 113c28aed136a7..163500245bf560 100644 --- a/deps/uv/ChangeLog +++ b/deps/uv/ChangeLog @@ -1,3 +1,66 @@ +2018.01.20, Version 1.19.1 (Stable), 8202d1751196c2374ad370f7f3779daef89befae + +Changes since version 1.19.0: + +* Revert "unix,tcp: avoid marking server sockets connected" (Ben Noordhuis) + +* Revert "unix,fs: fix for potential partial reads/writes" (Ben Noordhuis) + +* Revert "win: use RemoveDirectoryW() instead of _wmrmdir()" (Ben Noordhuis) + +* cygwin: fix compilation of ifaddrs impl (Brad King) + + +2018.01.18, Version 1.19.0 (Stable), effbb7c9d29090b2e085a40867f8cdfa916a66df + +Changes since version 1.18.0: + +* core: add getter/setter functions for easier ABI compat (Anna Henningsen) + +* unix: make get(set)_process_title MT-safe (Matt Harrison) + +* unix,win: wait for threads to start (Ben Noordhuis) + +* test: add threadpool init/teardown test (Bartosz Sosnowski) + +* win, process: uv_kill improvements (Bartosz Sosnowski) + +* win: set _WIN32_WINNT to 0x0600 (cjihrig) + +* zos: implement uv_fs_event* functions (jBarz) + +* unix,tcp: avoid marking server sockets connected (Jameson Nash) + +* doc: mark Windows 7 as Tier 1 support (Bartosz Sosnowski) + +* win: map 0.0.0.0 and :: addresses to localhost (Bartosz Sosnowski) + +* build: install libuv.pc unconditionally (Ben Noordhuis) + +* test: remove custom timeout for thread test on ppc (Ben Noordhuis) + +* test: allow multicast not permitted status (Jérémy Lal) + +* test: allow net unreachable status in udp test (Ben Noordhuis) + +* unix: use SA_RESTART when setting our sighandler (Brad King) + +* unix,fs: fix for potential partial reads/writes (Ben Wijen) + +* win,build: do not build executable installer for dll (Bert Belder) + +* win: allow directory symlinks to be created in a non-elevated context (Bert + Belder) + +* zos,test: accept SIGKILL for flaky test (jBarz) + +* win: use RemoveDirectoryW() instead of _wmrmdir() (Ben Noordhuis) + +* unix: fix uv_cpu_info() error on FreeBSD (elephantp) + +* zos,test: decrease pings to avoid timeout (jBarz) + + 2017.12.02, Version 1.18.0 (Stable), 1489c98b7fc17f1702821a269eb0c5e730c5c813 Changes since version 1.17.0: diff --git a/deps/uv/Makefile.am b/deps/uv/Makefile.am index e01cf416638bfe..ae9d96bcf61ef9 100644 --- a/deps/uv/Makefile.am +++ b/deps/uv/Makefile.am @@ -29,6 +29,7 @@ libuv_la_SOURCES = src/fs-poll.c \ src/inet.c \ src/queue.h \ src/threadpool.c \ + src/uv-data-getter-setters.c \ src/uv-common.c \ src/uv-common.h \ src/version.c @@ -158,6 +159,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \ test/test-close-fd.c \ test/test-close-order.c \ test/test-condvar.c \ + test/test-connect-unspecified.c \ test/test-connection-fail.c \ test/test-cwd-and-chdir.c \ test/test-default-loop-close.c \ @@ -174,6 +176,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \ test/test-fs-poll.c \ test/test-fs.c \ test/test-fork.c \ + test/test-getters-setters.c \ test/test-get-currentexe.c \ test/test-get-loadavg.c \ test/test-get-memory.c \ @@ -220,6 +223,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \ test/test-poll-closesocket.c \ test/test-poll-oob.c \ test/test-process-title.c \ + test/test-process-title-threadsafe.c \ test/test-queue-foreach-delete.c \ test/test-ref.c \ test/test-run-nowait.c \ @@ -455,13 +459,10 @@ libuv_la_CFLAGS += -D_UNIX03_THREADS \ -qFLOAT=IEEE libuv_la_LDFLAGS += -qXPLINK libuv_la_SOURCES += src/unix/pthread-fixes.c \ - src/unix/no-fsevents.c \ src/unix/os390.c \ src/unix/os390-syscalls.c \ src/unix/proctitle.c endif -if HAVE_PKG_CONFIG pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = @PACKAGE_NAME@.pc -endif diff --git a/deps/uv/SUPPORTED_PLATFORMS.md b/deps/uv/SUPPORTED_PLATFORMS.md index 08fd5f4a9a1100..c56913bbc2fff1 100644 --- a/deps/uv/SUPPORTED_PLATFORMS.md +++ b/deps/uv/SUPPORTED_PLATFORMS.md @@ -4,7 +4,7 @@ |---|---|---|---| | GNU/Linux | Tier 1 | Linux >= 2.6.32 with glibc >= 2.12 | | | macOS | Tier 1 | macOS >= 10.7 | | -| Windows | Tier 1 | Windows >= 8.1 | MSVC 2008 and later are supported | +| Windows | Tier 1 | >= Windows 7 | MSVC 2008 and later are supported | | FreeBSD | Tier 1 | >= 9 (see note) | | | AIX | Tier 2 | >= 6 | Maintainers: @libuv/aix | | z/OS | Tier 2 | >= V2R2 | Maintainers: @libuv/zos | diff --git a/deps/uv/appveyor.yml b/deps/uv/appveyor.yml index f77e640eb10f09..1b018a59cad86c 100644 --- a/deps/uv/appveyor.yml +++ b/deps/uv/appveyor.yml @@ -28,12 +28,5 @@ build_script: - cmd: set ARCH=%platform% - cmd: vcbuild.bat release %ARCH% shared -after_build: - - '"%PROGRAMFILES(x86)%\NSIS\makensis" /DVERSION=%APPVEYOR_BUILD_VERSION% /DARCH=%ARCH% libuv.nsi' - -artifacts: - - name: Installer - path: 'libuv-*.exe' - cache: - C:\projects\libuv\build\gyp diff --git a/deps/uv/checksparse.sh b/deps/uv/checksparse.sh index d4a983d02618b5..27eb529bcae13c 100755 --- a/deps/uv/checksparse.sh +++ b/deps/uv/checksparse.sh @@ -53,6 +53,7 @@ src/unix/tty.c src/unix/udp.c src/uv-common.c src/uv-common.h +src/uv-data-getter-setters.c " TESTS=" @@ -100,6 +101,7 @@ test/test-fs-copyfile.c test/test-fs-event.c test/test-fs-poll.c test/test-fs.c +test/test-getters-setters.c test/test-get-currentexe.c test/test-get-loadavg.c test/test-get-memory.c @@ -126,6 +128,7 @@ test/test-platform-output.c test/test-poll-close.c test/test-poll.c test/test-process-title.c +test/test-process-title-threadsafe.c test/test-ref.c test/test-run-nowait.c test/test-run-once.c diff --git a/deps/uv/configure.ac b/deps/uv/configure.ac index 7eb1674dbaa7fb..75fb13c8ce7b23 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.18.0], [https://github.com/libuv/libuv/issues]) +AC_INIT([libuv], [1.19.1], [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]) @@ -68,10 +68,5 @@ AS_CASE([$host_os],[mingw*], [ ]) AS_CASE([$host_os], [netbsd*], [AC_CHECK_LIB([kvm], [kvm_open])]) AC_CHECK_HEADERS([sys/ahafs_evProds.h]) -AC_CHECK_PROG(PKG_CONFIG, pkg-config, yes) -AM_CONDITIONAL([HAVE_PKG_CONFIG], [test "x$PKG_CONFIG" != "x"]) -AS_IF([test "x$PKG_CONFIG" != "x"], [ - AC_CONFIG_FILES([libuv.pc]) -]) -AC_CONFIG_FILES([Makefile]) +AC_CONFIG_FILES([Makefile libuv.pc]) AC_OUTPUT diff --git a/deps/uv/docs/src/fs.rst b/deps/uv/docs/src/fs.rst index 16d5e05c7834cf..87af828a28a7fa 100644 --- a/deps/uv/docs/src/fs.rst +++ b/deps/uv/docs/src/fs.rst @@ -340,6 +340,36 @@ API .. note:: These functions are not implemented on Windows. +.. c:function:: uv_fs_type uv_fs_get_type(const uv_fs_t* req) + + Returns `req->fs_type`. + + .. versionadded:: 1.19.0 + +.. c:function:: ssize_t uv_fs_get_result(const uv_fs_t* req) + + Returns `req->result`. + + .. versionadded:: 1.19.0 + +.. c:function:: void* uv_fs_get_ptr(const uv_fs_t* req) + + Returns `req->ptr`. + + .. versionadded:: 1.19.0 + +.. c:function:: const char* uv_fs_get_path(const uv_fs_t* req) + + Returns `req->path`. + + .. versionadded:: 1.19.0 + +.. c:function:: uv_stat_t* uv_fs_get_statbuf(uv_fs_t* req) + + Returns `&req->statbuf`. + + .. versionadded:: 1.19.0 + .. seealso:: The :c:type:`uv_req_t` API functions also apply. Helper functions diff --git a/deps/uv/docs/src/fs_event.rst b/deps/uv/docs/src/fs_event.rst index 2af3e9802bd0a1..bd076aaeb40494 100644 --- a/deps/uv/docs/src/fs_event.rst +++ b/deps/uv/docs/src/fs_event.rst @@ -19,7 +19,13 @@ the best backend for the job on each platform. See documentation_ for more details. + The z/OS file system events monitoring infrastructure does not notify of file + creation/deletion within a directory that is being monitored. + See the `IBM Knowledge centre`_ for more details. + .. _documentation: http://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/ + .. _`IBM Knowledge centre`: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.2.0/com.ibm.zos.v2r1.bpxb100/ioc.htm + diff --git a/deps/uv/docs/src/handle.rst b/deps/uv/docs/src/handle.rst index a0f3d05fdb1b4a..e4cb90b5f7e14b 100644 --- a/deps/uv/docs/src/handle.rst +++ b/deps/uv/docs/src/handle.rst @@ -211,6 +211,38 @@ just for some handle types. Be very careful when using this function. libuv assumes it's in control of the file descriptor so any change to it may lead to malfunction. +.. c:function:: uv_loop_t* uv_handle_get_loop(const uv_handle_t* handle) + + Returns `handle->loop`. + + .. versionadded:: 1.19.0 + +.. c:function:: void* uv_handle_get_data(const uv_handle_t* handle) + + Returns `handle->data`. + + .. versionadded:: 1.19.0 + +.. c:function:: void* uv_handle_set_data(uv_handle_t* handle, void* data) + + Sets `handle->data` to `data`. + + .. versionadded:: 1.19.0 + +.. c:function:: uv_handle_type uv_handle_get_type(const uv_handle_t* handle) + + Returns `handle->type`. + + .. versionadded:: 1.19.0 + +.. c:function:: const char* uv_handle_type_name(uv_handle_type type) + + Returns the name for the equivalent struct for a given handle type, + e.g. `"pipe"` (as in :c:type:`uv_pipe_t`) for `UV_NAMED_PIPE`. + + If no such handle type exists, this returns `NULL`. + + .. versionadded:: 1.19.0 .. _refcount: diff --git a/deps/uv/docs/src/loop.rst b/deps/uv/docs/src/loop.rst index 18dd135cd63834..dcde5049ac2baa 100644 --- a/deps/uv/docs/src/loop.rst +++ b/deps/uv/docs/src/loop.rst @@ -222,3 +222,15 @@ API Any previous value returned from :c:func`uv_backend_fd` is now invalid. That function must be called again to determine the correct backend file descriptor. + +.. c:function:: void* uv_loop_get_data(const uv_loop_t* loop) + + Returns `loop->data`. + + .. versionadded:: 1.19.0 + +.. c:function:: void* uv_loop_set_data(uv_loop_t* loop, void* data) + + Sets `loop->data` to `data`. + + .. versionadded:: 1.19.0 diff --git a/deps/uv/docs/src/misc.rst b/deps/uv/docs/src/misc.rst index a653413e0927bd..07908c98ff8e9c 100644 --- a/deps/uv/docs/src/misc.rst +++ b/deps/uv/docs/src/misc.rst @@ -197,8 +197,7 @@ API `UV_EINVAL` is returned. If `size` cannot accommodate the process title and terminating `NULL` character, the function returns `UV_ENOBUFS`. - .. warning:: - `uv_get_process_title` is not thread safe on any platform except Windows. + .. versionchanged:: 1.18.1 now thread-safe on all supported platforms. .. c:function:: int uv_set_process_title(const char* title) @@ -208,8 +207,7 @@ API larger than the available space. Other platforms will return `UV_ENOMEM` if they cannot allocate enough space to duplicate the contents of `title`. - .. warning:: - `uv_set_process_title` is not thread safe on any platform except Windows. + .. versionchanged:: 1.18.1 now thread-safe on all supported platforms. .. c:function:: int uv_resident_set_memory(size_t* rss) diff --git a/deps/uv/docs/src/process.rst b/deps/uv/docs/src/process.rst index b0380ddfb72e5e..ecc3cbf34814eb 100644 --- a/deps/uv/docs/src/process.rst +++ b/deps/uv/docs/src/process.rst @@ -222,4 +222,10 @@ API Sends the specified signal to the given PID. Check the documentation on :c:ref:`signal` for signal support, specially on Windows. +.. c:function:: uv_pid_t uv_process_get_pid(const uv_process_t* handle) + + Returns `handle->pid`. + + .. versionadded:: 1.19.0 + .. seealso:: The :c:type:`uv_handle_t` API functions also apply. diff --git a/deps/uv/docs/src/request.rst b/deps/uv/docs/src/request.rst index 660b80ae9573b3..54d9a2f30939da 100644 --- a/deps/uv/docs/src/request.rst +++ b/deps/uv/docs/src/request.rst @@ -80,3 +80,30 @@ API Returns the size of the given request type. Useful for FFI binding writers who don't want to know the structure layout. + +.. c:function:: void* uv_req_get_data(const uv_req_t* req) + + Returns `req->data`. + + .. versionadded:: 1.19.0 + +.. c:function:: void* uv_req_set_data(uv_req_t* req, void* data) + + Sets `req->data` to `data`. + + .. versionadded:: 1.19.0 + +.. c:function:: uv_req_type uv_req_get_type(const uv_req_t* req) + + Returns `req->type`. + + .. versionadded:: 1.19.0 + +.. c:function:: const char* uv_req_type_name(uv_req_type type) + + Returns the name for the equivalent struct for a given request type, + e.g. `"connect"` (as in :c:type:`uv_connect_t`) for `UV_CONNECT`. + + If no such request type exists, this returns `NULL`. + + .. versionadded:: 1.19.0 diff --git a/deps/uv/docs/src/stream.rst b/deps/uv/docs/src/stream.rst index 1f4e87e63a9db3..9ec23622512519 100644 --- a/deps/uv/docs/src/stream.rst +++ b/deps/uv/docs/src/stream.rst @@ -228,4 +228,10 @@ API .. versionchanged:: 1.4.0 UNIX implementation added. +.. c:function:: size_t uv_stream_get_write_queue_size(const uv_stream_t* stream) + + Returns `stream->write_queue_size`. + + .. versionadded:: 1.19.0 + .. seealso:: The :c:type:`uv_handle_t` API functions also apply. diff --git a/deps/uv/docs/src/tcp.rst b/deps/uv/docs/src/tcp.rst index a1a5824561add9..e761b460d0e636 100644 --- a/deps/uv/docs/src/tcp.rst +++ b/deps/uv/docs/src/tcp.rst @@ -102,7 +102,14 @@ API and an uninitialized :c:type:`uv_connect_t`. `addr` should point to an initialized ``struct sockaddr_in`` or ``struct sockaddr_in6``. + On Windows if the `addr` is initialized to point to an unspecified address + (``0.0.0.0`` or ``::``) it will be changed to point to ``localhost``. + This is done to match the behavior of Linux systems. + The callback is made when the connection has been established or when a connection error happened. + .. versionchanged:: 1.19.0 added ``0.0.0.0`` and ``::`` to ``localhost`` + mapping + .. seealso:: The :c:type:`uv_stream_t` API functions also apply. diff --git a/deps/uv/docs/src/udp.rst b/deps/uv/docs/src/udp.rst index dd46603394ee7a..8148828522ee2e 100644 --- a/deps/uv/docs/src/udp.rst +++ b/deps/uv/docs/src/udp.rst @@ -243,6 +243,10 @@ API with :c:func:`uv_udp_bind` it will be bound to 0.0.0.0 (the "all interfaces" IPv4 address) and a random port number. + On Windows if the `addr` is initialized to point to an unspecified address + (``0.0.0.0`` or ``::``) it will be changed to point to ``localhost``. + This is done to match the behavior of Linux systems. + :param req: UDP request handle. Need not be initialized. :param handle: UDP handle. Should have been initialized with @@ -259,6 +263,9 @@ API :returns: 0 on success, or an error code < 0 on failure. + .. versionchanged:: 1.19.0 added ``0.0.0.0`` and ``::`` to ``localhost`` + mapping + .. c:function:: int uv_udp_try_send(uv_udp_t* handle, const uv_buf_t bufs[], unsigned int nbufs, const struct sockaddr* addr) Same as :c:func:`uv_udp_send`, but won't queue a send request if it can't @@ -292,4 +299,16 @@ API :returns: 0 on success, or an error code < 0 on failure. +.. c:function:: size_t uv_udp_get_send_queue_size(const uv_udp_t* handle) + + Returns `handle->send_queue_size`. + + .. versionadded:: 1.19.0 + +.. c:function:: size_t uv_udp_get_send_queue_count(const uv_udp_t* handle) + + Returns `handle->send_queue_count`. + + .. versionadded:: 1.19.0 + .. seealso:: The :c:type:`uv_handle_t` API functions also apply. diff --git a/deps/uv/include/uv-os390.h b/deps/uv/include/uv-os390.h index 58f926111aa6af..39e7384db31a5b 100644 --- a/deps/uv/include/uv-os390.h +++ b/deps/uv/include/uv-os390.h @@ -27,4 +27,7 @@ #define UV_PLATFORM_LOOP_FIELDS \ void* ep; \ +#define UV_PLATFORM_FS_EVENT_FIELDS \ + char rfis_rftok[8]; \ + #endif /* UV_MVS_H */ diff --git a/deps/uv/include/uv-version.h b/deps/uv/include/uv-version.h index 831ee54de4486e..581d761df98139 100644 --- a/deps/uv/include/uv-version.h +++ b/deps/uv/include/uv-version.h @@ -31,8 +31,8 @@ */ #define UV_VERSION_MAJOR 1 -#define UV_VERSION_MINOR 18 -#define UV_VERSION_PATCH 0 +#define UV_VERSION_MINOR 19 +#define UV_VERSION_PATCH 1 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/deps/uv/include/uv-win.h b/deps/uv/include/uv-win.h index b96bed22ace759..4c6c50a29c357e 100644 --- a/deps/uv/include/uv-win.h +++ b/deps/uv/include/uv-win.h @@ -20,7 +20,7 @@ */ #ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0502 +# define _WIN32_WINNT 0x0600 #endif #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h index b11666e2e65806..3a061132cce528 100644 --- a/deps/uv/include/uv.h +++ b/deps/uv/include/uv.h @@ -425,7 +425,17 @@ struct uv_handle_s { }; UV_EXTERN size_t uv_handle_size(uv_handle_type type); +UV_EXTERN uv_handle_type uv_handle_get_type(const uv_handle_t* handle); +UV_EXTERN const char* uv_handle_type_name(uv_handle_type type); +UV_EXTERN void* uv_handle_get_data(const uv_handle_t* handle); +UV_EXTERN uv_loop_t* uv_handle_get_loop(const uv_handle_t* handle); +UV_EXTERN void uv_handle_set_data(uv_handle_t* handle, void* data); + UV_EXTERN size_t uv_req_size(uv_req_type type); +UV_EXTERN void* uv_req_get_data(const uv_req_t* req); +UV_EXTERN void uv_req_set_data(uv_req_t* req, void* data); +UV_EXTERN uv_req_type uv_req_get_type(const uv_req_t* req); +UV_EXTERN const char* uv_req_type_name(uv_req_type type); UV_EXTERN int uv_is_active(const uv_handle_t* handle); @@ -465,6 +475,8 @@ struct uv_stream_s { UV_STREAM_FIELDS }; +UV_EXTERN size_t uv_stream_get_write_queue_size(const uv_stream_t* stream); + UV_EXTERN int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb); UV_EXTERN int uv_accept(uv_stream_t* server, uv_stream_t* client); @@ -642,6 +654,8 @@ UV_EXTERN int uv_udp_recv_start(uv_udp_t* handle, uv_alloc_cb alloc_cb, uv_udp_recv_cb recv_cb); UV_EXTERN int uv_udp_recv_stop(uv_udp_t* handle); +UV_EXTERN size_t uv_udp_get_send_queue_size(const uv_udp_t* handle); +UV_EXTERN size_t uv_udp_get_send_queue_count(const uv_udp_t* handle); /* @@ -962,6 +976,7 @@ UV_EXTERN int uv_spawn(uv_loop_t* loop, const uv_process_options_t* options); UV_EXTERN int uv_process_kill(uv_process_t*, int signum); UV_EXTERN int uv_kill(int pid, int signum); +UV_EXTERN uv_pid_t uv_process_get_pid(const uv_process_t*); /* @@ -1135,6 +1150,12 @@ struct uv_fs_s { UV_FS_PRIVATE_FIELDS }; +UV_EXTERN uv_fs_type uv_fs_get_type(const uv_fs_t*); +UV_EXTERN ssize_t uv_fs_get_result(const uv_fs_t*); +UV_EXTERN void* uv_fs_get_ptr(const uv_fs_t*); +UV_EXTERN const char* uv_fs_get_path(const uv_fs_t*); +UV_EXTERN uv_stat_t* uv_fs_get_statbuf(uv_fs_t*); + UV_EXTERN void uv_fs_req_cleanup(uv_fs_t* req); UV_EXTERN int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, @@ -1516,6 +1537,8 @@ struct uv_loop_s { UV_LOOP_PRIVATE_FIELDS }; +UV_EXTERN void* uv_loop_get_data(const uv_loop_t*); +UV_EXTERN void uv_loop_set_data(uv_loop_t*, void* data); /* Don't export the private CPP symbols. */ #undef UV_HANDLE_TYPE_PRIVATE diff --git a/deps/uv/libuv.nsi b/deps/uv/libuv.nsi deleted file mode 100644 index 159756e196ce47..00000000000000 --- a/deps/uv/libuv.nsi +++ /dev/null @@ -1,86 +0,0 @@ -; NSIS installer script for libuv - -!include "MUI2.nsh" - -Name "libuv" -OutFile "libuv-${ARCH}-${VERSION}.exe" - -!include "x64.nsh" -# Default install location, for 32-bit files -InstallDir "$PROGRAMFILES\libuv" - -# Override install and registry locations if this is a 64-bit install. -function .onInit - ${If} ${ARCH} == "x64" - SetRegView 64 - StrCpy $INSTDIR "$PROGRAMFILES64\libuv" - ${EndIf} -functionEnd - -;-------------------------------- -; Installer pages -!insertmacro MUI_PAGE_WELCOME -!insertmacro MUI_PAGE_DIRECTORY -!insertmacro MUI_PAGE_INSTFILES -!insertmacro MUI_PAGE_FINISH - - -;-------------------------------- -; Uninstaller pages -!insertmacro MUI_UNPAGE_WELCOME -!insertmacro MUI_UNPAGE_CONFIRM -!insertmacro MUI_UNPAGE_INSTFILES -!insertmacro MUI_UNPAGE_FINISH - -;-------------------------------- -; Languages -!insertmacro MUI_LANGUAGE "English" - -;-------------------------------- -; Installer sections - -Section "Files" SecInstall - SectionIn RO - SetOutPath "$INSTDIR" - File "Release\*.dll" - File "Release\*.lib" - File "LICENSE" - File "README.md" - - SetOutPath "$INSTDIR\include" - File "include\uv.h" - File "include\uv-errno.h" - File "include\uv-threadpool.h" - File "include\uv-version.h" - File "include\uv-win.h" - File "include\tree.h" - - WriteUninstaller "$INSTDIR\Uninstall.exe" - WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "DisplayName" "libuv-${ARCH}-${VERSION}" - WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "UninstallString" "$\"$INSTDIR\Uninstall.exe$\"" - WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "QuietUninstallString" "$\"$INSTDIR\Uninstall.exe$\" /S" - WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "HelpLink" "http://libuv.org/" - WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "URLInfoAbout" "http://libuv.org/" - WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "DisplayVersion" "${VERSION}" - WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "NoModify" "1" - WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" "NoRepair" "1" -SectionEnd - -Section "Uninstall" - Delete "$INSTDIR\libuv.dll" - Delete "$INSTDIR\libuv.lib" - Delete "$INSTDIR\LICENSE" - Delete "$INSTDIR\README.md" - - Delete "$INSTDIR\include\uv.h" - Delete "$INSTDIR\include\uv-errno.h" - Delete "$INSTDIR\include\uv-threadpool.h" - Delete "$INSTDIR\include\uv-version.h" - Delete "$INSTDIR\include\uv-win.h" - Delete "$INSTDIR\include\tree.h" - - Delete "$INSTDIR\Uninstall.exe" - RMDir "$INSTDIR" - DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\libuv-${ARCH}-${VERSION}" -SectionEnd - diff --git a/deps/uv/src/threadpool.c b/deps/uv/src/threadpool.c index 108934112c582a..413d1c204c2660 100644 --- a/deps/uv/src/threadpool.c +++ b/deps/uv/src/threadpool.c @@ -38,7 +38,6 @@ static uv_thread_t* threads; static uv_thread_t default_threads[4]; static QUEUE exit_message; static QUEUE wq; -static volatile int initialized; static void uv__cancelled(struct uv__work* w) { @@ -53,7 +52,8 @@ static void worker(void* arg) { struct uv__work* w; QUEUE* q; - (void) arg; + uv_sem_post((uv_sem_t*) arg); + arg = NULL; for (;;) { uv_mutex_lock(&mutex); @@ -105,7 +105,7 @@ static void post(QUEUE* q) { UV_DESTRUCTOR(static void cleanup(void)) { unsigned int i; - if (initialized == 0) + if (nthreads == 0) return; post(&exit_message); @@ -122,7 +122,6 @@ UV_DESTRUCTOR(static void cleanup(void)) { threads = NULL; nthreads = 0; - initialized = 0; } #endif @@ -130,6 +129,7 @@ UV_DESTRUCTOR(static void cleanup(void)) { static void init_threads(void) { unsigned int i; const char* val; + uv_sem_t sem; nthreads = ARRAY_SIZE(default_threads); val = getenv("UV_THREADPOOL_SIZE"); @@ -157,11 +157,17 @@ static void init_threads(void) { QUEUE_INIT(&wq); + if (uv_sem_init(&sem, 0)) + abort(); + for (i = 0; i < nthreads; i++) - if (uv_thread_create(threads + i, worker, NULL)) + if (uv_thread_create(threads + i, worker, &sem)) abort(); - initialized = 1; + for (i = 0; i < nthreads; i++) + uv_sem_wait(&sem); + + uv_sem_destroy(&sem); } diff --git a/deps/uv/src/unix/aix.c b/deps/uv/src/unix/aix.c index 06f19a4fc9fc54..fd413090feddf0 100644 --- a/deps/uv/src/unix/aix.c +++ b/deps/uv/src/unix/aix.c @@ -65,11 +65,18 @@ #define RDWR_BUF_SIZE 4096 #define EQ(a,b) (strcmp(a,b) == 0) +static uv_mutex_t process_title_mutex; +static uv_once_t process_title_mutex_once = UV_ONCE_INIT; static void* args_mem = NULL; static char** process_argv = NULL; static int process_argc = 0; static char* process_title_ptr = NULL; +static void init_process_title_mutex_once(void) { + uv_mutex_init(&process_title_mutex); +} + + int uv__platform_loop_init(uv_loop_t* loop) { loop->fs_fd = -1; @@ -856,6 +863,9 @@ int uv_set_process_title(const char* title) { if (new_title == NULL) return -ENOMEM; + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + /* If this is the first time this is set, * don't free and set argv[1] to NULL. */ @@ -868,6 +878,8 @@ int uv_set_process_title(const char* title) { if (process_argc > 1) process_argv[1] = NULL; + uv_mutex_unlock(&process_title_mutex); + return 0; } @@ -880,8 +892,13 @@ int uv_get_process_title(char* buffer, size_t size) { else if (size <= len) return -ENOBUFS; + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + memcpy(buffer, process_argv[0], len + 1); + uv_mutex_unlock(&process_title_mutex); + return 0; } diff --git a/deps/uv/src/unix/bsd-ifaddrs.c b/deps/uv/src/unix/bsd-ifaddrs.c index 2593b9ff330e84..ea3166c5e977c7 100644 --- a/deps/uv/src/unix/bsd-ifaddrs.c +++ b/deps/uv/src/unix/bsd-ifaddrs.c @@ -36,6 +36,7 @@ static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) { return 1; if (ent->ifa_addr == NULL) return 1; +#if !defined(__CYGWIN__) && !defined(__MSYS__) /* * If `exclude_type` is `UV__EXCLUDE_IFPHYS`, just see whether `sa_family` * equals to `AF_LINK` or not. Otherwise, the result depends on the operation @@ -43,6 +44,7 @@ static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) { */ if (exclude_type == UV__EXCLUDE_IFPHYS) return (ent->ifa_addr->sa_family != AF_LINK); +#endif #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) /* * On BSD getifaddrs returns information related to the raw underlying diff --git a/deps/uv/src/unix/freebsd.c b/deps/uv/src/unix/freebsd.c index dba94298d1c06d..f2b3f247a05e3a 100644 --- a/deps/uv/src/unix/freebsd.c +++ b/deps/uv/src/unix/freebsd.c @@ -47,9 +47,16 @@ # define CP_INTR 4 #endif +static uv_mutex_t process_title_mutex; +static uv_once_t process_title_mutex_once = UV_ONCE_INIT; static char *process_title; +static void init_process_title_mutex_once(void) { + uv_mutex_init(&process_title_mutex); +} + + int uv__platform_loop_init(uv_loop_t* loop) { return uv__kqueue_init(loop); } @@ -163,8 +170,15 @@ int uv_set_process_title(const char* title) { char* new_title; new_title = uv__strdup(title); - if (process_title == NULL) + + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + + if (process_title == NULL) { + uv_mutex_unlock(&process_title_mutex); return -ENOMEM; + } + uv__free(process_title); process_title = new_title; @@ -180,6 +194,8 @@ int uv_set_process_title(const char* title) { process_title, strlen(process_title) + 1); + uv_mutex_unlock(&process_title_mutex); + return 0; } @@ -190,17 +206,24 @@ int uv_get_process_title(char* buffer, size_t size) { if (buffer == NULL || size == 0) return -EINVAL; + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + if (process_title) { len = strlen(process_title) + 1; - if (size < len) + if (size < len) { + uv_mutex_unlock(&process_title_mutex); return -ENOBUFS; + } memcpy(buffer, process_title, len); } else { len = 0; } + uv_mutex_unlock(&process_title_mutex); + buffer[len] = '\0'; return 0; @@ -253,6 +276,7 @@ int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) { uv_cpu_info_t* cpu_info; const char* maxcpus_key; const char* cptimes_key; + const char* model_key; char model[512]; long* cp_times; int numcpus; @@ -271,8 +295,20 @@ int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) { cptimes_key = "kern.cp_times"; #endif +#if defined(__arm__) || defined(__aarch64__) + /* The key hw.model and hw.clockrate are not available on FreeBSD ARM. */ + model_key = "hw.machine"; + cpuspeed = 0; +#else + model_key = "hw.model"; + + size = sizeof(cpuspeed); + if (sysctlbyname("hw.clockrate", &cpuspeed, &size, NULL, 0)) + return -errno; +#endif + size = sizeof(model); - if (sysctlbyname("hw.model", &model, &size, NULL, 0)) + if (sysctlbyname(model_key, &model, &size, NULL, 0)) return -errno; size = sizeof(numcpus); @@ -285,12 +321,6 @@ int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) { *count = numcpus; - size = sizeof(cpuspeed); - if (sysctlbyname("hw.clockrate", &cpuspeed, &size, NULL, 0)) { - uv__free(*cpu_infos); - return -errno; - } - /* kern.cp_times on FreeBSD i386 gives an array up to maxcpus instead of * ncpu. */ diff --git a/deps/uv/src/unix/netbsd.c b/deps/uv/src/unix/netbsd.c index d9066349c1d623..742507233144a1 100644 --- a/deps/uv/src/unix/netbsd.c +++ b/deps/uv/src/unix/netbsd.c @@ -40,9 +40,16 @@ #include #include +static uv_mutex_t process_title_mutex; +static uv_once_t process_title_mutex_once = UV_ONCE_INIT; static char *process_title; +static void init_process_title_mutex_once(void) { + uv_mutex_init(&process_title_mutex); +} + + int uv__platform_loop_init(uv_loop_t* loop) { return uv__kqueue_init(loop); } @@ -137,12 +144,21 @@ int uv_set_process_title(const char* title) { char* new_title; new_title = uv__strdup(title); - if (process_title == NULL) + + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + + if (process_title == NULL) { + uv_mutex_unlock(&process_title_mutex); return -ENOMEM; + } + uv__free(process_title); process_title = new_title; setproctitle("%s", title); + uv_mutex_unlock(&process_title_mutex); + return 0; } @@ -153,17 +169,24 @@ int uv_get_process_title(char* buffer, size_t size) { if (buffer == NULL || size == 0) return -EINVAL; + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + if (process_title) { len = strlen(process_title) + 1; - if (size < len) + if (size < len) { + uv_mutex_unlock(&process_title_mutex); return -ENOBUFS; + } memcpy(buffer, process_title, len); } else { len = 0; } + uv_mutex_unlock(&process_title_mutex); + buffer[len] = '\0'; return 0; diff --git a/deps/uv/src/unix/openbsd.c b/deps/uv/src/unix/openbsd.c index d1c90289e5691e..c0ffa564b4c2e9 100644 --- a/deps/uv/src/unix/openbsd.c +++ b/deps/uv/src/unix/openbsd.c @@ -36,9 +36,16 @@ #include +static uv_mutex_t process_title_mutex; +static uv_once_t process_title_mutex_once = UV_ONCE_INIT; static char *process_title; +static void init_process_title_mutex_once(void) { + uv_mutex_init(&process_title_mutex); +} + + int uv__platform_loop_init(uv_loop_t* loop) { return uv__kqueue_init(loop); } @@ -149,11 +156,21 @@ int uv_set_process_title(const char* title) { char* new_title; new_title = uv__strdup(title); - if (process_title == NULL) + + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + + if (process_title == NULL) { + uv_mutex_unlock(&process_title_mutex); return -ENOMEM; + } + uv__free(process_title); process_title = new_title; setproctitle("%s", title); + + uv_mutex_unlock(&process_title_mutex); + return 0; } @@ -164,17 +181,24 @@ int uv_get_process_title(char* buffer, size_t size) { if (buffer == NULL || size == 0) return -EINVAL; + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + if (process_title) { len = strlen(process_title) + 1; - if (size < len) + if (size < len) { + uv_mutex_unlock(&process_title_mutex); return -ENOBUFS; + } memcpy(buffer, process_title, len); } else { len = 0; } + uv_mutex_unlock(&process_title_mutex); + buffer[len] = '\0'; return 0; diff --git a/deps/uv/src/unix/os390-syscalls.c b/deps/uv/src/unix/os390-syscalls.c index 5bc489387ef3c5..21558ea8689a00 100644 --- a/deps/uv/src/unix/os390-syscalls.c +++ b/deps/uv/src/unix/os390-syscalls.c @@ -25,6 +25,8 @@ #include #include #include +#include +#include #define CW_CONDVAR 32 @@ -103,10 +105,19 @@ static void maybe_resize(uv__os390_epoll* lst, unsigned int len) { unsigned int newsize; unsigned int i; struct pollfd* newlst; + struct pollfd event; if (len <= lst->size) return; + if (lst->size == 0) + event.fd = -1; + else { + /* Extract the message queue at the end. */ + event = lst->items[lst->size - 1]; + lst->items[lst->size - 1].fd = -1; + } + newsize = next_power_of_two(len); newlst = uv__realloc(lst->items, newsize * sizeof(lst->items[0])); @@ -115,11 +126,40 @@ static void maybe_resize(uv__os390_epoll* lst, unsigned int len) { for (i = lst->size; i < newsize; ++i) newlst[i].fd = -1; + /* Restore the message queue at the end */ + newlst[newsize - 1] = event; + lst->items = newlst; lst->size = newsize; } +static void init_message_queue(uv__os390_epoll* lst) { + struct { + long int header; + char body; + } msg; + + /* initialize message queue */ + lst->msg_queue = msgget(IPC_PRIVATE, 0622 | IPC_CREAT); + if (lst->msg_queue == -1) + abort(); + + /* + On z/OS, the message queue will be affiliated with the process only + when a send is performed on it. Once this is done, the system + can be queried for all message queues belonging to our process id. + */ + msg.header = 1; + if (msgsnd(lst->msg_queue, &msg, sizeof(msg.body), 0) != 0) + abort(); + + /* Clean up the dummy message sent above */ + if (msgrcv(lst->msg_queue, &msg, sizeof(msg.body), 0, 0) != sizeof(msg.body)) + abort(); +} + + static void before_fork(void) { uv_mutex_lock(&global_epoll_lock); } @@ -139,8 +179,13 @@ static void child_fork(void) { /* reset epoll list */ while (!QUEUE_EMPTY(&global_epoll_queue)) { + uv__os390_epoll* lst; q = QUEUE_HEAD(&global_epoll_queue); QUEUE_REMOVE(q); + lst = QUEUE_DATA(q, uv__os390_epoll, member); + uv__free(lst->items); + lst->items = NULL; + lst->size = 0; } uv_mutex_unlock(&global_epoll_lock); @@ -166,6 +211,10 @@ uv__os390_epoll* epoll_create1(int flags) { /* initialize list */ lst->size = 0; lst->items = NULL; + init_message_queue(lst); + maybe_resize(lst, 1); + lst->items[lst->size - 1].fd = lst->msg_queue; + lst->items[lst->size - 1].events = POLLIN; uv_once(&once, epoll_init); uv_mutex_lock(&global_epoll_lock); QUEUE_INSERT_TAIL(&global_epoll_queue, &lst->member); @@ -182,15 +231,20 @@ int epoll_ctl(uv__os390_epoll* lst, struct epoll_event *event) { uv_mutex_lock(&global_epoll_lock); - if(op == EPOLL_CTL_DEL) { + if (op == EPOLL_CTL_DEL) { if (fd >= lst->size || lst->items[fd].fd == -1) { uv_mutex_unlock(&global_epoll_lock); errno = ENOENT; return -1; } lst->items[fd].fd = -1; - } else if(op == EPOLL_CTL_ADD) { - maybe_resize(lst, fd + 1); + } else if (op == EPOLL_CTL_ADD) { + + /* Resizing to 'fd + 1' would expand the list to contain at least + * 'fd'. But we need to guarantee that the last index on the list + * is reserved for the message queue. So specify 'fd + 2' instead. + */ + maybe_resize(lst, fd + 2); if (lst->items[fd].fd != -1) { uv_mutex_unlock(&global_epoll_lock); errno = EEXIST; @@ -198,7 +252,7 @@ int epoll_ctl(uv__os390_epoll* lst, } lst->items[fd].fd = fd; lst->items[fd].events = event->events; - } else if(op == EPOLL_CTL_MOD) { + } else if (op == EPOLL_CTL_MOD) { if (fd >= lst->size || lst->items[fd].fd == -1) { uv_mutex_unlock(&global_epoll_lock); errno = ENOENT; @@ -215,17 +269,19 @@ int epoll_ctl(uv__os390_epoll* lst, int epoll_wait(uv__os390_epoll* lst, struct epoll_event* events, int maxevents, int timeout) { - size_t size; + nmsgsfds_t size; struct pollfd* pfds; int pollret; int reventcount; - size = lst->size; + size = _SET_FDS_MSGS(size, 1, lst->size - 1); pfds = lst->items; pollret = poll(pfds, size, timeout); if (pollret <= 0) return pollret; + pollret = _NFDS(pollret) + _NMSGS(pollret); + reventcount = 0; for (int i = 0; i < lst->size && i < maxevents && reventcount < pollret; ++i) { @@ -261,9 +317,14 @@ int epoll_file_close(int fd) { } void epoll_queue_close(uv__os390_epoll* lst) { + /* Remove epoll instance from global queue */ uv_mutex_lock(&global_epoll_lock); QUEUE_REMOVE(&lst->member); uv_mutex_unlock(&global_epoll_lock); + + /* Free resources */ + msgctl(lst->msg_queue, IPC_RMID, NULL); + lst->msg_queue = -1; uv__free(lst->items); lst->items = NULL; } diff --git a/deps/uv/src/unix/os390-syscalls.h b/deps/uv/src/unix/os390-syscalls.h index 5ce6a681bf1cb3..6e34a88cb95d1b 100644 --- a/deps/uv/src/unix/os390-syscalls.h +++ b/deps/uv/src/unix/os390-syscalls.h @@ -50,6 +50,7 @@ typedef struct { QUEUE member; struct pollfd* items; unsigned long size; + int msg_queue; } uv__os390_epoll; /* epoll api */ diff --git a/deps/uv/src/unix/os390.c b/deps/uv/src/unix/os390.c index 127656db8789e6..081438e8e73d3c 100644 --- a/deps/uv/src/unix/os390.c +++ b/deps/uv/src/unix/os390.c @@ -26,6 +26,8 @@ #include #include #include +#include +#include #if defined(__clang__) #include "csrsic.h" #else @@ -684,11 +686,124 @@ int uv__io_check_fd(uv_loop_t* loop, int fd) { return 0; } + +void uv__fs_event_close(uv_fs_event_t* handle) { + uv_fs_event_stop(handle); +} + + +int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) { + uv__handle_init(loop, (uv_handle_t*)handle, UV_FS_EVENT); + return 0; +} + + +int uv_fs_event_start(uv_fs_event_t* handle, uv_fs_event_cb cb, + const char* filename, unsigned int flags) { + uv__os390_epoll* ep; + _RFIS reg_struct; + char* path; + int rc; + + if (uv__is_active(handle)) + return -EINVAL; + + ep = handle->loop->ep; + assert(ep->msg_queue != -1); + + reg_struct.__rfis_cmd = _RFIS_REG; + reg_struct.__rfis_qid = ep->msg_queue; + reg_struct.__rfis_type = 1; + memcpy(reg_struct.__rfis_utok, &handle, sizeof(handle)); + + path = uv__strdup(filename); + if (path == NULL) + return -ENOMEM; + + rc = __w_pioctl(path, _IOCC_REGFILEINT, sizeof(reg_struct), ®_struct); + if (rc != 0) + return -errno; + + uv__handle_start(handle); + handle->path = path; + handle->cb = cb; + memcpy(handle->rfis_rftok, reg_struct.__rfis_rftok, + sizeof(handle->rfis_rftok)); + + return 0; +} + + +int uv_fs_event_stop(uv_fs_event_t* handle) { + uv__os390_epoll* ep; + _RFIS reg_struct; + int rc; + + if (!uv__is_active(handle)) + return 0; + + ep = handle->loop->ep; + assert(ep->msg_queue != -1); + + reg_struct.__rfis_cmd = _RFIS_UNREG; + reg_struct.__rfis_qid = ep->msg_queue; + reg_struct.__rfis_type = 1; + memcpy(reg_struct.__rfis_rftok, handle->rfis_rftok, + sizeof(handle->rfis_rftok)); + + /* + * This call will take "/" as the path argument in case we + * don't care to supply the correct path. The system will simply + * ignore it. + */ + rc = __w_pioctl("/", _IOCC_REGFILEINT, sizeof(reg_struct), ®_struct); + if (rc != 0 && errno != EALREADY && errno != ENOENT) + abort(); + + uv__handle_stop(handle); + + return 0; +} + + +static int os390_message_queue_handler(uv__os390_epoll* ep) { + uv_fs_event_t* handle; + int msglen; + int events; + _RFIM msg; + + if (ep->msg_queue == -1) + return 0; + + msglen = msgrcv(ep->msg_queue, &msg, sizeof(msg), 0, IPC_NOWAIT); + + if (msglen == -1 && errno == ENOMSG) + return 0; + + if (msglen == -1) + abort(); + + events = 0; + if (msg.__rfim_event == _RFIM_ATTR || msg.__rfim_event == _RFIM_WRITE) + events = UV_CHANGE; + else if (msg.__rfim_event == _RFIM_RENAME) + events = UV_RENAME; + else + /* Some event that we are not interested in. */ + return 0; + + handle = *(uv_fs_event_t**)(msg.__rfim_utok); + handle->cb(handle, uv__basename_r(handle->path), events, 0); + return 1; +} + + void uv__io_poll(uv_loop_t* loop, int timeout) { static const int max_safe_timeout = 1789569; struct epoll_event events[1024]; struct epoll_event* pe; struct epoll_event e; + uv__os390_epoll* ep; int real_timeout; QUEUE* q; uv__io_t* w; @@ -802,6 +917,12 @@ void uv__io_poll(uv_loop_t* loop, int timeout) { if (fd == -1) continue; + ep = loop->ep; + if (fd == ep->msg_queue) { + os390_message_queue_handler(ep); + continue; + } + assert(fd >= 0); assert((unsigned) fd < loop->nwatchers); @@ -866,7 +987,12 @@ void uv__set_process_title(const char* title) { } int uv__io_fork(uv_loop_t* loop) { - uv__platform_loop_delete(loop); + /* + Nullify the msg queue but don't close it because + it is still being used by the parent. + */ + loop->ep = NULL; + uv__platform_loop_delete(loop); return uv__platform_loop_init(loop); } diff --git a/deps/uv/src/unix/proctitle.c b/deps/uv/src/unix/proctitle.c index 2ed0b21c6625bd..1b3a798820e282 100644 --- a/deps/uv/src/unix/proctitle.c +++ b/deps/uv/src/unix/proctitle.c @@ -26,6 +26,8 @@ extern void uv__set_process_title(const char* title); +static uv_mutex_t process_title_mutex; +static uv_once_t process_title_mutex_once = UV_ONCE_INIT; static void* args_mem; static struct { @@ -34,6 +36,11 @@ static struct { } process_title; +static void init_process_title_mutex_once(void) { + uv_mutex_init(&process_title_mutex); +} + + char** uv_setup_args(int argc, char** argv) { char** new_argv; size_t size; @@ -81,12 +88,16 @@ char** uv_setup_args(int argc, char** argv) { int uv_set_process_title(const char* title) { - if (process_title.len == 0) - return 0; + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + + if (process_title.len != 0) { + /* No need to terminate, byte after is always '\0'. */ + strncpy(process_title.str, title, process_title.len); + uv__set_process_title(title); + } - /* No need to terminate, byte after is always '\0'. */ - strncpy(process_title.str, title, process_title.len); - uv__set_process_title(title); + uv_mutex_unlock(&process_title_mutex); return 0; } @@ -95,14 +106,22 @@ int uv_set_process_title(const char* title) { int uv_get_process_title(char* buffer, size_t size) { if (buffer == NULL || size == 0) return -EINVAL; - else if (size <= process_title.len) + + uv_once(&process_title_mutex_once, init_process_title_mutex_once); + uv_mutex_lock(&process_title_mutex); + + if (size <= process_title.len) { + uv_mutex_unlock(&process_title_mutex); return -ENOBUFS; + } if (process_title.len != 0) memcpy(buffer, process_title.str, process_title.len + 1); buffer[process_title.len] = '\0'; + uv_mutex_unlock(&process_title_mutex); + return 0; } diff --git a/deps/uv/src/unix/signal.c b/deps/uv/src/unix/signal.c index cb09ead50a4c45..3759778011223f 100644 --- a/deps/uv/src/unix/signal.c +++ b/deps/uv/src/unix/signal.c @@ -28,6 +28,9 @@ #include #include +#ifndef SA_RESTART +# define SA_RESTART 0 +#endif typedef struct { uv_signal_t* handle; @@ -216,7 +219,9 @@ static int uv__signal_register_handler(int signum, int oneshot) { if (sigfillset(&sa.sa_mask)) abort(); sa.sa_handler = uv__signal_handler; - sa.sa_flags = oneshot ? SA_RESETHAND : 0; + sa.sa_flags = SA_RESTART; + if (oneshot) + sa.sa_flags |= SA_RESETHAND; /* XXX save old action so we can restore it later on? */ if (sigaction(signum, &sa, NULL)) diff --git a/deps/uv/src/uv-data-getter-setters.c b/deps/uv/src/uv-data-getter-setters.c new file mode 100644 index 00000000000000..533e4a2fe12bb3 --- /dev/null +++ b/deps/uv/src/uv-data-getter-setters.c @@ -0,0 +1,96 @@ +#include "uv.h" + +const char* uv_handle_type_name(uv_handle_type type) { + switch (type) { +#define XX(uc,lc) case UV_##uc: return #lc; + UV_HANDLE_TYPE_MAP(XX) +#undef XX + case UV_FILE: return "file"; + case UV_HANDLE_TYPE_MAX: + case UV_UNKNOWN_HANDLE: return NULL; + } + return NULL; +} + +uv_handle_type uv_handle_get_type(const uv_handle_t* handle) { + return handle->type; +} + +void* uv_handle_get_data(const uv_handle_t* handle) { + return handle->data; +} + +uv_loop_t* uv_handle_get_loop(const uv_handle_t* handle) { + return handle->loop; +} + +void uv_handle_set_data(uv_handle_t* handle, void* data) { + handle->data = data; +} + +const char* uv_req_type_name(uv_req_type type) { + switch (type) { +#define XX(uc,lc) case UV_##uc: return #lc; + UV_REQ_TYPE_MAP(XX) +#undef XX + case UV_REQ_TYPE_MAX: + case UV_UNKNOWN_REQ: return NULL; + } + return NULL; +} + +uv_req_type uv_req_get_type(const uv_req_t* req) { + return req->type; +} + +void* uv_req_get_data(const uv_req_t* req) { + return req->data; +} + +void uv_req_set_data(uv_req_t* req, void* data) { + req->data = data; +} + +size_t uv_stream_get_write_queue_size(const uv_stream_t* stream) { + return stream->write_queue_size; +} + +size_t uv_udp_get_send_queue_size(const uv_udp_t* handle) { + return handle->send_queue_size; +} + +size_t uv_udp_get_send_queue_count(const uv_udp_t* handle) { + return handle->send_queue_count; +} + +uv_pid_t uv_process_get_pid(const uv_process_t* proc) { + return proc->pid; +} + +uv_fs_type uv_fs_get_type(const uv_fs_t* req) { + return req->fs_type; +} + +ssize_t uv_fs_get_result(const uv_fs_t* req) { + return req->result; +} + +void* uv_fs_get_ptr(const uv_fs_t* req) { + return req->ptr; +} + +const char* uv_fs_get_path(const uv_fs_t* req) { + return req->path; +} + +uv_stat_t* uv_fs_get_statbuf(uv_fs_t* req) { + return &req->statbuf; +} + +void* uv_loop_get_data(const uv_loop_t* loop) { + return loop->data; +} + +void uv_loop_set_data(uv_loop_t* loop, void* data) { + loop->data = data; +} diff --git a/deps/uv/src/win/fs.c b/deps/uv/src/win/fs.c index 11c7c13edd04d6..097b00e08d50d5 100644 --- a/deps/uv/src/win/fs.c +++ b/deps/uv/src/win/fs.c @@ -1785,7 +1785,7 @@ static void fs__symlink(uv_fs_t* req) { } if (req->fs.info.file_flags & UV_FS_SYMLINK_DIR) - flags = SYMBOLIC_LINK_FLAG_DIRECTORY; + flags = SYMBOLIC_LINK_FLAG_DIRECTORY | uv__file_symlink_usermode_flag; else flags = uv__file_symlink_usermode_flag; diff --git a/deps/uv/src/win/process.c b/deps/uv/src/win/process.c index 764250e138c48d..cc06d9e22abcb6 100644 --- a/deps/uv/src/win/process.c +++ b/deps/uv/src/win/process.c @@ -1173,6 +1173,10 @@ int uv_spawn(uv_loop_t* loop, static int uv__kill(HANDLE process_handle, int signum) { + if (signum < 0 || signum >= NSIG) { + return UV_EINVAL; + } + switch (signum) { case SIGTERM: case SIGKILL: @@ -1237,8 +1241,15 @@ int uv_process_kill(uv_process_t* process, int signum) { int uv_kill(int pid, int signum) { int err; - HANDLE process_handle = OpenProcess(PROCESS_TERMINATE | - PROCESS_QUERY_INFORMATION, FALSE, pid); + HANDLE process_handle; + + if (pid == 0) { + process_handle = GetCurrentProcess(); + } else { + process_handle = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, + FALSE, + pid); + } if (process_handle == NULL) { err = GetLastError(); diff --git a/deps/uv/src/win/tcp.c b/deps/uv/src/win/tcp.c index e63a63e7712af1..fd6efbaf891d64 100644 --- a/deps/uv/src/win/tcp.c +++ b/deps/uv/src/win/tcp.c @@ -747,10 +747,15 @@ static int uv_tcp_try_connect(uv_connect_t* req, uv_connect_cb cb) { uv_loop_t* loop = handle->loop; const struct sockaddr* bind_addr; + struct sockaddr_storage converted; BOOL success; DWORD bytes; int err; + err = uv__convert_to_localhost_if_unspecified(addr, &converted); + if (err) + return err; + if (handle->delayed_error) { return handle->delayed_error; } @@ -782,12 +787,12 @@ static int uv_tcp_try_connect(uv_connect_t* req, memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); success = handle->tcp.conn.func_connectex(handle->socket, - addr, - addrlen, - NULL, - 0, - &bytes, - &req->u.io.overlapped); + (const struct sockaddr*) &converted, + addrlen, + NULL, + 0, + &bytes, + &req->u.io.overlapped); if (UV_SUCCEEDED_WITHOUT_IOCP(success)) { /* Process the req without IOCP. */ diff --git a/deps/uv/src/win/udp.c b/deps/uv/src/win/udp.c index 21348f3796926a..cd1d0e07b23cb9 100644 --- a/deps/uv/src/win/udp.c +++ b/deps/uv/src/win/udp.c @@ -923,10 +923,15 @@ int uv__udp_try_send(uv_udp_t* handle, unsigned int addrlen) { DWORD bytes; const struct sockaddr* bind_addr; + struct sockaddr_storage converted; int err; assert(nbufs > 0); + err = uv__convert_to_localhost_if_unspecified(addr, &converted); + if (err) + return err; + /* Already sending a message.*/ if (handle->send_queue_count != 0) return UV_EAGAIN; @@ -948,7 +953,7 @@ int uv__udp_try_send(uv_udp_t* handle, nbufs, &bytes, 0, - addr, + (const struct sockaddr*) &converted, addrlen, NULL, NULL); diff --git a/deps/uv/src/win/winsock.c b/deps/uv/src/win/winsock.c index e86d76b131caa4..7cfa90f8af5127 100644 --- a/deps/uv/src/win/winsock.c +++ b/deps/uv/src/win/winsock.c @@ -559,3 +559,31 @@ int WSAAPI uv_msafd_poll(SOCKET socket, AFD_POLL_INFO* info_in, return SOCKET_ERROR; } } + +int uv__convert_to_localhost_if_unspecified(const struct sockaddr* addr, + struct sockaddr_storage* storage) { + struct sockaddr_in* dest4; + struct sockaddr_in6* dest6; + + if (addr == NULL) + return UV_EINVAL; + + switch (addr->sa_family) { + case AF_INET: + dest4 = (struct sockaddr_in*) storage; + memcpy(dest4, addr, sizeof(*dest4)); + if (dest4->sin_addr.s_addr == 0) + dest4->sin_addr.s_addr = htonl(INADDR_LOOPBACK); + return 0; + case AF_INET6: + dest6 = (struct sockaddr_in6*) storage; + memcpy(dest6, addr, sizeof(*dest6)); + if (memcmp(&dest6->sin6_addr, + &uv_addr_ip6_any_.sin6_addr, + sizeof(uv_addr_ip6_any_.sin6_addr)) == 0) + dest6->sin6_addr = (struct in6_addr) IN6ADDR_LOOPBACK_INIT; + return 0; + default: + return UV_EINVAL; + } +} diff --git a/deps/uv/src/win/winsock.h b/deps/uv/src/win/winsock.h index 7c007ab4934608..7ecb755bfb061b 100644 --- a/deps/uv/src/win/winsock.h +++ b/deps/uv/src/win/winsock.h @@ -187,4 +187,7 @@ typedef struct _IP_ADAPTER_UNICAST_ADDRESS_LH { #endif +int uv__convert_to_localhost_if_unspecified(const struct sockaddr* addr, + struct sockaddr_storage* storage); + #endif /* UV_WIN_WINSOCK_H_ */ diff --git a/deps/uv/test/task.h b/deps/uv/test/task.h index 67eb9804926824..af99d92fb45414 100644 --- a/deps/uv/test/task.h +++ b/deps/uv/test/task.h @@ -209,7 +209,7 @@ UNUSED static int can_ipv6(void) { return supported; } -#if defined(__MVS__) || defined(__CYGWIN__) || defined(__MSYS__) +#if defined(__CYGWIN__) || defined(__MSYS__) # define NO_FS_EVENTS "Filesystem watching not supported on this platform." #endif diff --git a/deps/uv/test/test-connect-unspecified.c b/deps/uv/test/test-connect-unspecified.c new file mode 100644 index 00000000000000..04e1c8a5f7c682 --- /dev/null +++ b/deps/uv/test/test-connect-unspecified.c @@ -0,0 +1,61 @@ +/* Copyright libuv project contributors. All rights reserved. +* +* 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. +*/ + +#include "uv.h" +#include "task.h" + +static void connect_4(uv_connect_t* req, int status) { + ASSERT(status != UV_EADDRNOTAVAIL); +} + +static void connect_6(uv_connect_t* req, int status) { + ASSERT(status != UV_EADDRNOTAVAIL); +} + +TEST_IMPL(connect_unspecified) { + uv_loop_t* loop; + uv_tcp_t socket4; + struct sockaddr_in addr4; + uv_connect_t connect4; + uv_tcp_t socket6; + struct sockaddr_in6 addr6; + uv_connect_t connect6; + + loop = uv_default_loop(); + + ASSERT(uv_tcp_init(loop, &socket4) == 0); + ASSERT(uv_ip4_addr("0.0.0.0", TEST_PORT, &addr4) == 0); + ASSERT(uv_tcp_connect(&connect4, + &socket4, + (const struct sockaddr*) &addr4, + connect_4) == 0); + + ASSERT(uv_tcp_init(loop, &socket6) == 0); + ASSERT(uv_ip6_addr("::", TEST_PORT, &addr6) == 0); + ASSERT(uv_tcp_connect(&connect6, + &socket6, + (const struct sockaddr*) &addr6, + connect_6) == 0); + + ASSERT(uv_run(loop, UV_RUN_DEFAULT) == 0); + + return 0; +} diff --git a/deps/uv/test/test-fork.c b/deps/uv/test/test-fork.c index ba85b531064ae5..924c65b2141134 100644 --- a/deps/uv/test/test-fork.c +++ b/deps/uv/test/test-fork.c @@ -533,10 +533,12 @@ TEST_IMPL(fork_fs_events_file_parent_child) { #if defined(NO_FS_EVENTS) RETURN_SKIP(NO_FS_EVENTS); #endif -#if defined(__sun) || defined(_AIX) +#if defined(__sun) || defined(_AIX) || defined(__MVS__) /* It's not possible to implement this without additional * bookkeeping on SunOS. For AIX it is possible, but has to be * written. See https://github.com/libuv/libuv/pull/846#issuecomment-287170420 + * TODO: On z/OS, we need to open another message queue and subscribe to the + * same events as the parent. */ return 0; #else diff --git a/deps/uv/test/test-fs-event.c b/deps/uv/test/test-fs-event.c index fba6b5440b0fc3..dc47b3a62d2399 100644 --- a/deps/uv/test/test-fs-event.c +++ b/deps/uv/test/test-fs-event.c @@ -396,6 +396,8 @@ static void timer_cb_watch_twice(uv_timer_t* handle) { TEST_IMPL(fs_event_watch_dir) { #if defined(NO_FS_EVENTS) RETURN_SKIP(NO_FS_EVENTS); +#elif defined(__MVS__) + RETURN_SKIP("Directory watching not supported on this platform."); #endif uv_loop_t* loop = uv_default_loop(); @@ -820,6 +822,8 @@ static void fs_event_cb_close(uv_fs_event_t* handle, const char* filename, TEST_IMPL(fs_event_close_in_callback) { #if defined(NO_FS_EVENTS) RETURN_SKIP(NO_FS_EVENTS); +#elif defined(__MVS__) + RETURN_SKIP("Directory watching not supported on this platform."); #endif uv_loop_t* loop; int r; diff --git a/deps/uv/test/test-fs.c b/deps/uv/test/test-fs.c index cae02dd1fddec8..7c481f0711978f 100644 --- a/deps/uv/test/test-fs.c +++ b/deps/uv/test/test-fs.c @@ -1861,7 +1861,7 @@ TEST_IMPL(fs_symlink) { } -TEST_IMPL(fs_symlink_dir) { +int test_symlink_dir_impl(int type) { uv_fs_t req; int r; char* test_dir; @@ -1895,8 +1895,12 @@ TEST_IMPL(fs_symlink_dir) { test_dir = "test_dir"; #endif - r = uv_fs_symlink(NULL, &req, test_dir, "test_dir_symlink", - UV_FS_SYMLINK_JUNCTION, NULL); + r = uv_fs_symlink(NULL, &req, test_dir, "test_dir_symlink", type, NULL); + if (type == UV_FS_SYMLINK_DIR && (r == UV_ENOTSUP || r == UV_EPERM)) { + uv_fs_req_cleanup(&req); + RETURN_SKIP("this version of Windows doesn't support unprivileged " + "creation of directory symlinks"); + } fprintf(stderr, "r == %i\n", r); ASSERT(r == 0); ASSERT(req.result == 0); @@ -2005,6 +2009,13 @@ TEST_IMPL(fs_symlink_dir) { return 0; } +TEST_IMPL(fs_symlink_dir) { + return test_symlink_dir_impl(UV_FS_SYMLINK_DIR); +} + +TEST_IMPL(fs_symlink_junction) { + return test_symlink_dir_impl(UV_FS_SYMLINK_JUNCTION); +} #ifdef _WIN32 TEST_IMPL(fs_non_symlink_reparse_point) { diff --git a/deps/uv/test/test-getters-setters.c b/deps/uv/test/test-getters-setters.c new file mode 100644 index 00000000000000..60a1b9264da179 --- /dev/null +++ b/deps/uv/test/test-getters-setters.c @@ -0,0 +1,88 @@ +#include "uv.h" +#include "task.h" +#include +#include + +int cookie1; +int cookie2; +int cookie3; + + +TEST_IMPL(handle_type_name) { + ASSERT(strcmp(uv_handle_type_name(UV_NAMED_PIPE), "pipe") == 0); + ASSERT(strcmp(uv_handle_type_name(UV_UDP), "udp") == 0); + ASSERT(strcmp(uv_handle_type_name(UV_FILE), "file") == 0); + ASSERT(uv_handle_type_name(UV_HANDLE_TYPE_MAX) == NULL); + ASSERT(uv_handle_type_name(UV_HANDLE_TYPE_MAX + 1) == NULL); + ASSERT(uv_handle_type_name(UV_UNKNOWN_HANDLE) == NULL); + return 0; +} + + +TEST_IMPL(req_type_name) { + ASSERT(strcmp(uv_req_type_name(UV_REQ), "req") == 0); + ASSERT(strcmp(uv_req_type_name(UV_UDP_SEND), "udp_send") == 0); + ASSERT(strcmp(uv_req_type_name(UV_WORK), "work") == 0); + ASSERT(uv_req_type_name(UV_REQ_TYPE_MAX) == NULL); + ASSERT(uv_req_type_name(UV_REQ_TYPE_MAX + 1) == NULL); + ASSERT(uv_req_type_name(UV_UNKNOWN_REQ) == NULL); + return 0; +} + + +TEST_IMPL(getters_setters) { + uv_loop_t* loop; + uv_pipe_t* pipe; + uv_fs_t* fs; + int r; + + loop = malloc(uv_loop_size()); + ASSERT(loop != NULL); + r = uv_loop_init(loop); + ASSERT(r == 0); + + uv_loop_set_data(loop, &cookie1); + ASSERT(loop->data == &cookie1); + ASSERT(uv_loop_get_data(loop) == &cookie1); + + pipe = malloc(uv_handle_size(UV_NAMED_PIPE)); + r = uv_pipe_init(loop, pipe, 0); + ASSERT(uv_handle_get_type((uv_handle_t*)pipe) == UV_NAMED_PIPE); + + ASSERT(uv_handle_get_loop((uv_handle_t*)pipe) == loop); + pipe->data = &cookie2; + ASSERT(uv_handle_get_data((uv_handle_t*)pipe) == &cookie2); + uv_handle_set_data((uv_handle_t*)pipe, &cookie1); + ASSERT(uv_handle_get_data((uv_handle_t*)pipe) == &cookie1); + ASSERT(pipe->data == &cookie1); + + ASSERT(uv_stream_get_write_queue_size((uv_stream_t*)pipe) == 0); + pipe->write_queue_size++; + ASSERT(uv_stream_get_write_queue_size((uv_stream_t*)pipe) == 1); + pipe->write_queue_size--; + uv_close((uv_handle_t*)pipe, NULL); + + r = uv_run(loop, UV_RUN_DEFAULT); + ASSERT(r == 0); + + fs = malloc(uv_req_size(UV_FS)); + uv_fs_stat(loop, fs, ".", NULL); + + r = uv_run(loop, UV_RUN_DEFAULT); + ASSERT(r == 0); + + ASSERT(uv_fs_get_type(fs) == UV_FS_STAT); + ASSERT(uv_fs_get_result(fs) == 0); + ASSERT(uv_fs_get_ptr(fs) == uv_fs_get_statbuf(fs)); + ASSERT(uv_fs_get_statbuf(fs)->st_mode & S_IFDIR); + ASSERT(strcmp(uv_fs_get_path(fs), ".") == 0); + uv_fs_req_cleanup(fs); + + r = uv_loop_close(loop); + ASSERT(r == 0); + + free(pipe); + free(fs); + free(loop); + return 0; +} diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index 2adbe6a017cfc3..5a50ec6713f03f 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -28,6 +28,7 @@ TEST_DECLARE (run_once) TEST_DECLARE (run_nowait) TEST_DECLARE (loop_alive) TEST_DECLARE (loop_close) +TEST_DECLARE (loop_instant_close) TEST_DECLARE (loop_stop) TEST_DECLARE (loop_update_time) TEST_DECLARE (loop_backend_timeout) @@ -54,6 +55,7 @@ TEST_DECLARE (tty_file) TEST_DECLARE (tty_pty) TEST_DECLARE (stdio_over_pipes) TEST_DECLARE (ip6_pton) +TEST_DECLARE (connect_unspecified) TEST_DECLARE (ipc_listen_before_write) TEST_DECLARE (ipc_listen_after_write) #ifndef _WIN32 @@ -214,6 +216,7 @@ TEST_DECLARE (async_null_cb) TEST_DECLARE (eintr_handling) TEST_DECLARE (get_currentexe) TEST_DECLARE (process_title) +TEST_DECLARE (process_title_threadsafe) TEST_DECLARE (cwd_and_chdir) TEST_DECLARE (get_memory) TEST_DECLARE (get_passwd) @@ -264,6 +267,7 @@ TEST_DECLARE (spawn_tcp_server) TEST_DECLARE (fs_poll) TEST_DECLARE (fs_poll_getpath) TEST_DECLARE (kill) +TEST_DECLARE (kill_invalid_signum) TEST_DECLARE (fs_file_noent) TEST_DECLARE (fs_file_nametoolong) TEST_DECLARE (fs_file_loop) @@ -285,6 +289,7 @@ TEST_DECLARE (fs_realpath) TEST_DECLARE (fs_symlink) TEST_DECLARE (fs_symlink_dir) #ifdef _WIN32 +TEST_DECLARE (fs_symlink_junction) TEST_DECLARE (fs_non_symlink_reparse_point) #endif TEST_DECLARE (fs_utime) @@ -397,6 +402,10 @@ HELPER_DECLARE (pipe_echo_server) TEST_DECLARE (queue_foreach_delete) +TEST_DECLARE (handle_type_name) +TEST_DECLARE (req_type_name) +TEST_DECLARE (getters_setters) + #ifndef _WIN32 TEST_DECLARE (fork_timer) TEST_DECLARE (fork_socketpair) @@ -422,6 +431,7 @@ TASK_LIST_START TEST_ENTRY (run_nowait) TEST_ENTRY (loop_alive) TEST_ENTRY (loop_close) + TEST_ENTRY (loop_instant_close) TEST_ENTRY (loop_stop) TEST_ENTRY (loop_update_time) TEST_ENTRY (loop_backend_timeout) @@ -459,6 +469,7 @@ TASK_LIST_START TEST_ENTRY (tty_pty) TEST_ENTRY (stdio_over_pipes) TEST_ENTRY (ip6_pton) + TEST_ENTRY (connect_unspecified) TEST_ENTRY (ipc_listen_before_write) TEST_ENTRY (ipc_listen_after_write) #ifndef _WIN32 @@ -668,6 +679,7 @@ TASK_LIST_START TEST_ENTRY (get_currentexe) TEST_ENTRY (process_title) + TEST_ENTRY (process_title_threadsafe) TEST_ENTRY (cwd_and_chdir) @@ -748,6 +760,7 @@ TASK_LIST_START TEST_ENTRY (fs_poll) TEST_ENTRY (fs_poll_getpath) TEST_ENTRY (kill) + TEST_ENTRY (kill_invalid_signum) TEST_ENTRY (poll_close_doesnt_corrupt_stack) TEST_ENTRY (poll_closesocket) @@ -803,6 +816,7 @@ TASK_LIST_START TEST_ENTRY (fs_symlink) TEST_ENTRY (fs_symlink_dir) #ifdef _WIN32 + TEST_ENTRY (fs_symlink_junction) TEST_ENTRY (fs_non_symlink_reparse_point) #endif TEST_ENTRY (fs_stat_missing_path) @@ -843,14 +857,7 @@ TASK_LIST_START TEST_ENTRY (get_osfhandle_valid_handle) TEST_ENTRY (threadpool_queue_work_simple) TEST_ENTRY (threadpool_queue_work_einval) -#if defined(__PPC__) || defined(__PPC64__) /* For linux PPC and AIX */ - /* pthread_join takes a while, especially on AIX. - * Therefore being gratuitous with timeout. - */ - TEST_ENTRY_CUSTOM (threadpool_multiple_event_loops, 0, 0, 120000) -#else TEST_ENTRY (threadpool_multiple_event_loops) -#endif TEST_ENTRY (threadpool_cancel_getaddrinfo) TEST_ENTRY (threadpool_cancel_getnameinfo) TEST_ENTRY (threadpool_cancel_work) @@ -870,6 +877,10 @@ TASK_LIST_START TEST_ENTRY (queue_foreach_delete) + TEST_ENTRY (handle_type_name) + TEST_ENTRY (req_type_name) + TEST_ENTRY (getters_setters) + #ifndef _WIN32 TEST_ENTRY (fork_timer) TEST_ENTRY (fork_socketpair) diff --git a/deps/uv/test/test-loop-close.c b/deps/uv/test/test-loop-close.c index 971c9d725bec02..f0f3e627f971e2 100644 --- a/deps/uv/test/test-loop-close.c +++ b/deps/uv/test/test-loop-close.c @@ -55,3 +55,21 @@ TEST_IMPL(loop_close) { return 0; } + +static void loop_instant_close_work_cb(uv_work_t* req) { +} + +static void loop_instant_close_after_work_cb(uv_work_t* req, int status) { +} + +TEST_IMPL(loop_instant_close) { + static uv_loop_t loop; + static uv_work_t req; + ASSERT(0 == uv_loop_init(&loop)); + ASSERT(0 == uv_queue_work(&loop, + &req, + loop_instant_close_work_cb, + loop_instant_close_after_work_cb)); + MAKE_VALGRIND_HAPPY(); + return 0; +} diff --git a/deps/uv/test/test-ping-pong.c b/deps/uv/test/test-ping-pong.c index bdc967151ed8f2..508f0db67bcf77 100644 --- a/deps/uv/test/test-ping-pong.c +++ b/deps/uv/test/test-ping-pong.c @@ -27,7 +27,7 @@ static int completed_pingers = 0; -#if defined(__CYGWIN__) || defined(__MSYS__) +#if defined(__CYGWIN__) || defined(__MSYS__) || defined(__MVS__) #define NUM_PINGS 100 /* fewer pings to avoid timeout */ #else #define NUM_PINGS 1000 diff --git a/deps/uv/test/test-process-title-threadsafe.c b/deps/uv/test/test-process-title-threadsafe.c new file mode 100644 index 00000000000000..d986576ed93c02 --- /dev/null +++ b/deps/uv/test/test-process-title-threadsafe.c @@ -0,0 +1,90 @@ +/* Copyright libuv project contributors. All rights reserved. +* +* 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. +*/ + + +#include "uv.h" +#include "task.h" + +#include + +#ifdef __APPLE__ +# define NUM_ITERATIONS 20 +#else +# define NUM_ITERATIONS 50 +#endif + +static const char* titles[] = { + "8L2NY0Kdj0XyNFZnmUZigIOfcWjyNr0SkMmUhKw99VLUsZFrvCQQC3XIRfNR8pjyMjXObllled", + "jUAcscJN49oLSN8GdmXj2Wo34XX2T2vp2j5khfajNQarlOulp57cE130yiY53ipJFnPyTn5i82", + "9niCI5icXGFS72XudhXqo5alftmZ1tpE7B3cwUmrq0CCDjC84FzBNB8XAHqvpNQfI2QAQG6ztT", + "n8qXVXuG6IEHDpabJgTEiwtpY6LHMZ8MgznnMpdHARu5EywufA6hcBaQfetb0YhEsK0ykDd7JU" +}; + +static void getter_thread_body(void* arg) { + char buffer[512]; + + for (;;) { + ASSERT(0 == uv_get_process_title(buffer, sizeof(buffer))); + ASSERT( + 0 == strcmp(buffer, titles[0]) || + 0 == strcmp(buffer, titles[1]) || + 0 == strcmp(buffer, titles[2]) || + 0 == strcmp(buffer, titles[3])); + + uv_sleep(0); + } +} + + +static void setter_thread_body(void* arg) { + int i; + + for (i = 0; i < NUM_ITERATIONS; i++) { + ASSERT(0 == uv_set_process_title(titles[0])); + ASSERT(0 == uv_set_process_title(titles[1])); + ASSERT(0 == uv_set_process_title(titles[2])); + ASSERT(0 == uv_set_process_title(titles[3])); + } +} + + +TEST_IMPL(process_title_threadsafe) { + uv_thread_t setter_threads[4]; + uv_thread_t getter_thread; + int i; + +#if defined(__sun) || defined(__CYGWIN__) || defined(__MSYS__) || \ + defined(__MVS__) + RETURN_SKIP("uv_(get|set)_process_title is not implemented."); +#else + + ASSERT(0 == uv_set_process_title(titles[0])); + ASSERT(0 == uv_thread_create(&getter_thread, getter_thread_body, NULL)); + + for (i = 0; i < (int) ARRAY_SIZE(setter_threads); i++) + ASSERT(0 == uv_thread_create(&setter_threads[i], setter_thread_body, NULL)); + + for (i = 0; i < (int) ARRAY_SIZE(setter_threads); i++) + ASSERT(0 == uv_thread_join(&setter_threads[i])); + + return 0; +#endif +} diff --git a/deps/uv/test/test-signal.c b/deps/uv/test/test-signal.c index 9a881510c72151..c2ce5ec0e0a85e 100644 --- a/deps/uv/test/test-signal.c +++ b/deps/uv/test/test-signal.c @@ -22,6 +22,26 @@ #include "uv.h" #include "task.h" +#ifndef _WIN32 +#include +#endif + +TEST_IMPL(kill_invalid_signum) { + uv_pid_t pid; + + pid = uv_os_getpid(); + + ASSERT(uv_kill(pid, -1) == UV_EINVAL); +#ifdef _WIN32 + /* NSIG is not available on all platforms. */ + ASSERT(uv_kill(pid, NSIG) == UV_EINVAL); +#endif + ASSERT(uv_kill(pid, 4096) == UV_EINVAL); + + MAKE_VALGRIND_HAPPY(); + return 0; +} + /* For Windows we test only signum handling */ #ifdef _WIN32 static void signum_test_cb(uv_signal_t* handle, int signum) { diff --git a/deps/uv/test/test-spawn.c b/deps/uv/test/test-spawn.c index 4b138265a5bc51..4a2869a18afa43 100644 --- a/deps/uv/test/test-spawn.c +++ b/deps/uv/test/test-spawn.c @@ -92,7 +92,7 @@ static void kill_cb(uv_process_t* process, #else ASSERT(exit_status == 0); #endif -#if defined(__APPLE__) +#if defined(__APPLE__) || defined(__MVS__) /* * At least starting with Darwin Kernel Version 16.4.0, sending a SIGTERM to a * process that is still starting up kills it with SIGKILL instead of SIGTERM. @@ -805,6 +805,8 @@ TEST_IMPL(spawn_detached) { ASSERT(exit_cb_called == 0); + ASSERT(process.pid == uv_process_get_pid(&process)); + r = uv_kill(process.pid, 0); ASSERT(r == 0); @@ -1560,9 +1562,6 @@ TEST_IMPL(spawn_fs_open) { #ifndef _WIN32 TEST_IMPL(closed_fd_events) { -#if defined(__MVS__) - RETURN_SKIP("Filesystem watching not supported on this platform."); -#endif uv_stdio_container_t stdio[3]; uv_pipe_t pipe_handle; int fd[2]; diff --git a/deps/uv/test/test-udp-multicast-interface.c b/deps/uv/test/test-udp-multicast-interface.c index 71001a77e03e18..0b3c0e62da559f 100644 --- a/deps/uv/test/test-udp-multicast-interface.c +++ b/deps/uv/test/test-udp-multicast-interface.c @@ -44,7 +44,7 @@ static void close_cb(uv_handle_t* handle) { static void sv_send_cb(uv_udp_send_t* req, int status) { ASSERT(req != NULL); - ASSERT(status == 0 || status == UV_ENETUNREACH); + ASSERT(status == 0 || status == UV_ENETUNREACH || status == UV_EPERM); CHECK_HANDLE(req->handle); sv_send_cb_called++; diff --git a/deps/uv/test/test-udp-multicast-ttl.c b/deps/uv/test/test-udp-multicast-ttl.c index 7f1af9b9dd9bd2..e92608be4809bf 100644 --- a/deps/uv/test/test-udp-multicast-ttl.c +++ b/deps/uv/test/test-udp-multicast-ttl.c @@ -44,7 +44,7 @@ static void close_cb(uv_handle_t* handle) { static void sv_send_cb(uv_udp_send_t* req, int status) { ASSERT(req != NULL); - ASSERT(status == 0 || status == UV_ENETUNREACH); + ASSERT(status == 0 || status == UV_ENETUNREACH || status == UV_EPERM); CHECK_HANDLE(req->handle); sv_send_cb_called++; diff --git a/deps/uv/test/test-udp-send-hang-loop.c b/deps/uv/test/test-udp-send-hang-loop.c index 6253ff7a4134c0..bf4dfebfb35098 100644 --- a/deps/uv/test/test-udp-send-hang-loop.c +++ b/deps/uv/test/test-udp-send-hang-loop.c @@ -67,7 +67,7 @@ static void idle_cb(uv_idle_t* handle) { static void send_cb(uv_udp_send_t* req, int status) { ASSERT(req != NULL); - ASSERT(status == 0); + ASSERT(status == 0 || status == UV_ENETUNREACH); CHECK_OBJECT(req->handle, uv_udp_t, client); CHECK_OBJECT(req, uv_udp_send_t, send_req); req->handle = NULL; diff --git a/deps/uv/uv.gyp b/deps/uv/uv.gyp index 96fb801a77b034..46606c5bda868d 100644 --- a/deps/uv/uv.gyp +++ b/deps/uv/uv.gyp @@ -78,6 +78,7 @@ 'src/inet.c', 'src/queue.h', 'src/threadpool.c', + 'src/uv-data-getter-setters.c', 'src/uv-common.c', 'src/uv-common.h', 'src/version.c' @@ -339,7 +340,6 @@ ['OS=="zos"', { 'sources': [ 'src/unix/pthread-fixes.c', - 'src/unix/no-fsevents.c', 'src/unix/os390.c', 'src/unix/os390-syscalls.c' ] @@ -366,6 +366,7 @@ 'test/test-callback-order.c', 'test/test-close-fd.c', 'test/test-close-order.c', + 'test/test-connect-unspecified.c', 'test/test-connection-fail.c', 'test/test-cwd-and-chdir.c', 'test/test-default-loop-close.c', @@ -380,6 +381,7 @@ 'test/test-fs.c', 'test/test-fs-copyfile.c', 'test/test-fs-event.c', + 'test/test-getters-setters.c', 'test/test-get-currentexe.c', 'test/test-get-memory.c', 'test/test-get-passwd.c', @@ -425,6 +427,7 @@ 'test/test-poll-closesocket.c', 'test/test-poll-oob.c', 'test/test-process-title.c', + 'test/test-process-title-threadsafe.c', 'test/test-queue-foreach-delete.c', 'test/test-ref.c', 'test/test-run-nowait.c', diff --git a/deps/v8/src/parsing/parser-base.h b/deps/v8/src/parsing/parser-base.h index f555dbdbe0e5a7..1788eba51c8fe6 100644 --- a/deps/v8/src/parsing/parser-base.h +++ b/deps/v8/src/parsing/parser-base.h @@ -3634,6 +3634,7 @@ void ParserBase::ParseFormalParameter(FormalParametersT* parameters, // BindingElement[?Yield, ?GeneratorParameter] bool is_rest = parameters->has_rest; + FuncNameInferrer::State fni_state(fni_); ExpressionT pattern = ParsePrimaryExpression(CHECK_OK_CUSTOM(Void)); ValidateBindingPattern(CHECK_OK_CUSTOM(Void)); diff --git a/deps/v8/test/message/fail/func-name-inferrer-arg-1.js b/deps/v8/test/message/fail/func-name-inferrer-arg-1.js new file mode 100644 index 00000000000000..6c28367d921433 --- /dev/null +++ b/deps/v8/test/message/fail/func-name-inferrer-arg-1.js @@ -0,0 +1,10 @@ +// Copyright 2017 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(function (param = function() { throw new Error('boom') }) { + (() => { + param(); + })(); + +})(); diff --git a/deps/v8/test/message/fail/func-name-inferrer-arg-1.out b/deps/v8/test/message/fail/func-name-inferrer-arg-1.out new file mode 100644 index 00000000000000..3c19121a0a6efa --- /dev/null +++ b/deps/v8/test/message/fail/func-name-inferrer-arg-1.out @@ -0,0 +1,8 @@ +*%(basename)s:5: Error: boom +(function (param = function() { throw new Error('boom') }) { + ^ +Error: boom + at param (*%(basename)s:5:39) + at *%(basename)s:7:5 + at *%(basename)s:8:5 + at *%(basename)s:10:3 \ No newline at end of file diff --git a/deps/v8/test/message/fail/func-name-inferrer-arg.js b/deps/v8/test/message/fail/func-name-inferrer-arg.js new file mode 100644 index 00000000000000..3fcd044b9b1831 --- /dev/null +++ b/deps/v8/test/message/fail/func-name-inferrer-arg.js @@ -0,0 +1,10 @@ +// Copyright 2017 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(function (param) { + (() => { + throw new Error('boom'); + })(); + +})(); diff --git a/deps/v8/test/message/fail/func-name-inferrer-arg.out b/deps/v8/test/message/fail/func-name-inferrer-arg.out new file mode 100644 index 00000000000000..06e001d1d5e641 --- /dev/null +++ b/deps/v8/test/message/fail/func-name-inferrer-arg.out @@ -0,0 +1,7 @@ +*%(basename)s:7: Error: boom + throw new Error('boom'); + ^ +Error: boom + at *%(basename)s:7:11 + at *%(basename)s:8:5 + at *%(basename)s:10:3 \ No newline at end of file diff --git a/doc/STYLE_GUIDE.md b/doc/STYLE_GUIDE.md index 8ea9c8fe81b732..7fc2d6e0b1bb13 100644 --- a/doc/STYLE_GUIDE.md +++ b/doc/STYLE_GUIDE.md @@ -3,7 +3,7 @@ * Documentation is written in markdown files with names formatted as `lowercase-with-dashes.md`. * Underscores in filenames are allowed only when they are present in the - topic the document will describe (e.g., `child_process`). + topic the document will describe (e.g. `child_process`). * Some files, such as top-level markdown files, are exceptions. * Documents should be word-wrapped at 80 characters. * The formatting described in `.editorconfig` is preferred. diff --git a/doc/api/addons.md b/doc/api/addons.md index e2df5f30e9a32a..c6802530f6dc67 100644 --- a/doc/api/addons.md +++ b/doc/api/addons.md @@ -221,7 +221,7 @@ illustration of how it can be used. > Stability: 1 - Experimental N-API is an API for building native Addons. It is independent from -the underlying JavaScript runtime (e.g., V8) and is maintained as part of +the underlying JavaScript runtime (e.g. V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across version of Node.js. It is intended to insulate Addons from changes in the underlying JavaScript engine and allow modules diff --git a/doc/api/assert.md b/doc/api/assert.md index f4654bf67eae3f..3df420cab64ff1 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -375,6 +375,8 @@ argument in callbacks. ```js const assert = require('assert'); +assert.ifError(null); +// OK assert.ifError(0); // OK assert.ifError(1); diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index e8cb9344c4c123..4fa23f28d116b0 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -244,10 +244,10 @@ RANDOMBYTESREQUEST, TLSWRAP, Timeout, Immediate, TickObject There is also the `PROMISE` resource type, which is used to track `Promise` instances and asynchronous work scheduled by them. -Users are be able to define their own `type` when using the public embedder API. +Users are able to define their own `type` when using the public embedder API. *Note:* It is possible to have type name collisions. Embedders are encouraged -to use a unique prefixes, such as the npm package name, to prevent collisions +to use unique prefixes, such as the npm package name, to prevent collisions when listening to the hooks. ###### `triggerId` @@ -470,6 +470,14 @@ init for PROMISE with id 6, trigger id: 5 # the Promise returned by then() #### `async_hooks.executionAsyncId()` + + * Returns: {number} The `asyncId` of the current execution context. Useful to track when something calls. @@ -484,7 +492,7 @@ fs.open(path, 'r', (err, fd) => { }); ``` -The ID returned fom `executionAsyncId()` is related to execution timing, not +The ID returned from `executionAsyncId()` is related to execution timing, not causality (which is covered by `triggerAsyncId()`). For example: ```js diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 41b4e643055af2..1e5b23cb4b9982 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1583,7 +1583,7 @@ endian format (`readDoubleBE()` returns big endian, `readDoubleLE()` returns little endian). Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Examples: @@ -1619,7 +1619,7 @@ endian format (`readFloatBE()` returns big endian, `readFloatLE()` returns little endian). Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Examples: @@ -1652,7 +1652,7 @@ added: v0.5.0 Reads a signed 8-bit integer from `buf` at the specified `offset`. Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Integers read from a `Buffer` are interpreted as two's complement signed values. @@ -1686,7 +1686,7 @@ the specified endian format (`readInt16BE()` returns big endian, `readInt16LE()` returns little endian). Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Integers read from a `Buffer` are interpreted as two's complement signed values. @@ -1720,7 +1720,7 @@ the specified endian format (`readInt32BE()` returns big endian, `readInt32LE()` returns little endian). Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Integers read from a `Buffer` are interpreted as two's complement signed values. @@ -1755,7 +1755,7 @@ and interprets the result as a two's complement signed value. Supports up to 48 bits of accuracy. Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Examples: @@ -1784,7 +1784,7 @@ added: v0.5.0 Reads an unsigned 8-bit integer from `buf` at the specified `offset`. Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Examples: @@ -1816,7 +1816,7 @@ specified endian format (`readUInt16BE()` returns big endian, `readUInt16LE()` returns little endian). Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Examples: @@ -1854,7 +1854,7 @@ specified endian format (`readUInt32BE()` returns big endian, `readUInt32LE()` returns little endian). Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Examples: @@ -1887,7 +1887,7 @@ and interprets the result as an unsigned integer. Supports up to 48 bits of accuracy. Setting `noAssert` to `true` allows `offset` to be beyond the end of `buf`, but -the result should be considered undefined behavior. +the resulting behavior is undefined. Examples: @@ -2225,7 +2225,7 @@ endian). `value` *should* be a valid 64-bit double. Behavior is undefined when `value` is anything other than a 64-bit double. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. Examples: @@ -2260,7 +2260,7 @@ endian). `value` *should* be a valid 32-bit float. Behavior is undefined when `value` is anything other than a 32-bit float. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. Examples: @@ -2293,7 +2293,7 @@ signed 8-bit integer. Behavior is undefined when `value` is anything other than a signed 8-bit integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. `value` is interpreted and written as a two's complement signed integer. @@ -2326,7 +2326,7 @@ endian). `value` *should* be a valid signed 16-bit integer. Behavior is undefine when `value` is anything other than a signed 16-bit integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. `value` is interpreted and written as a two's complement signed integer. @@ -2359,7 +2359,7 @@ endian). `value` *should* be a valid signed 32-bit integer. Behavior is undefine when `value` is anything other than a signed 32-bit integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. `value` is interpreted and written as a two's complement signed integer. @@ -2393,7 +2393,7 @@ Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than a signed integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. Examples: @@ -2426,7 +2426,7 @@ valid unsigned 8-bit integer. Behavior is undefined when `value` is anything other than an unsigned 8-bit integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. Examples: @@ -2459,7 +2459,7 @@ endian). `value` should be a valid unsigned 16-bit integer. Behavior is undefined when `value` is anything other than an unsigned 16-bit integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. Examples: @@ -2496,7 +2496,7 @@ endian). `value` should be a valid unsigned 32-bit integer. Behavior is undefined when `value` is anything other than an unsigned 32-bit integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. Examples: @@ -2532,7 +2532,7 @@ Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than an unsigned integer. Setting `noAssert` to `true` allows the encoded form of `value` to extend beyond -the end of `buf`, but the result should be considered undefined behavior. +the end of `buf`, but the resulting behavior is undefined. Examples: diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 2f86d5156fc438..fcfd79150abf53 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -25,7 +25,7 @@ ls.on('close', (code) => { }); ``` -By default, pipes for `stdin`, `stdout` and `stderr` are established between +By default, pipes for `stdin`, `stdout`, and `stderr` are established between the parent Node.js process and the spawned child. It is possible to stream data through these pipes in a non-blocking way. *Note, however, that some programs use line-buffered I/O internally. While that does not affect Node.js, it can @@ -170,7 +170,7 @@ exec('echo "The \\$HOME variable is $HOME"'); //The $HOME variable is escaped in the first instance, but not in the second ``` -*Note*: Never pass unsanitised user input to this function. Any input +*Note*: Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution. @@ -418,7 +418,7 @@ The `child_process.spawn()` method spawns a new process using the given `command`, with command line arguments in `args`. If omitted, `args` defaults to an empty array. -*Note*: If the `shell` option is enabled, do not pass unsanitised user input to +*Note*: If the `shell` option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution. @@ -661,7 +661,7 @@ The [`child_process.spawnSync()`][], [`child_process.execSync()`][], and the Node.js event loop, pausing execution of any additional code until the spawned process exits. -Blocking calls like these are mostly useful for simplifying general purpose +Blocking calls like these are mostly useful for simplifying general-purpose scripting tasks and for simplifying the loading/processing of application configuration at startup. @@ -715,7 +715,7 @@ completely exited. does not exit, the parent process will still wait until the child process has exited. -If the process times out, or has a non-zero exit code, this method ***will*** +If the process times out or has a non-zero exit code, this method ***will*** throw an [`Error`][] that will include the full result of the underlying [`child_process.spawnSync()`][]. @@ -767,11 +767,11 @@ exited. *Note that if the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process has exited.* -If the process times out, or has a non-zero exit code, this method ***will*** +If the process times out or has a non-zero exit code, this method ***will*** throw. The [`Error`][] object will contain the entire result from [`child_process.spawnSync()`][] -*Note*: Never pass unsanitised user input to this function. Any input +*Note*: Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution. @@ -839,7 +839,7 @@ completely exited. Note that if the process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process has exited. -*Note*: If the `shell` option is enabled, do not pass unsanitised user input +*Note*: If the `shell` option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution. @@ -1124,10 +1124,10 @@ process.send({ foo: 'bar', baz: NaN }); Child Node.js processes will have a [`process.send()`][] method of their own that allows the child to send messages back to the parent. -There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages -containing a `NODE_` prefix in its `cmd` property are considered to be reserved -for use within Node.js core and will not be emitted in the child's -[`process.on('message')`][] event. Rather, such messages are emitted using the +There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages +containing a `NODE_` prefix in the `cmd` property are reserved for use within +Node.js core and will not be emitted in the child's [`process.on('message')`][] +event. Rather, such messages are emitted using the `process.on('internalMessage')` event and are consumed internally by Node.js. Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. diff --git a/doc/api/cluster.md b/doc/api/cluster.md index 016fdf6c185c68..8e165e2c33d7c8 100644 --- a/doc/api/cluster.md +++ b/doc/api/cluster.md @@ -711,6 +711,8 @@ changes: * `exec` {string} File path to worker file. **Default:** `process.argv[1]` * `args` {Array} String arguments passed to worker. **Default:** `process.argv.slice(2)` + * `cwd` {string} Current working directory of the worker process. **Default:** + `undefined` (inherits from parent process) * `silent` {boolean} Whether or not to send output to parent's stdio. **Default:** `false` * `stdio` {Array} Configures the stdio of forked processes. Because the diff --git a/doc/api/crypto.md b/doc/api/crypto.md index cc9838e9625bb5..f264f4ed20538e 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -1250,7 +1250,7 @@ password always creates the same key. The low iteration count and non-cryptographically secure hash algorithm allow passwords to be tested very rapidly. -In line with OpenSSL's recommendation to use pbkdf2 instead of +In line with OpenSSL's recommendation to use PBKDF2 instead of [`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on their own using [`crypto.pbkdf2()`][] and to use [`crypto.createCipheriv()`][] to create the `Cipher` object. Users should not use ciphers with counter mode @@ -1312,7 +1312,7 @@ password always creates the same key. The low iteration count and non-cryptographically secure hash algorithm allow passwords to be tested very rapidly. -In line with OpenSSL's recommendation to use pbkdf2 instead of +In line with OpenSSL's recommendation to use PBKDF2 instead of [`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on their own using [`crypto.pbkdf2()`][] and to use [`crypto.createDecipheriv()`][] to create the `Decipher` object. diff --git a/doc/api/dgram.md b/doc/api/dgram.md index 0aa6a67668c32b..e44bf3eea5a166 100644 --- a/doc/api/dgram.md +++ b/doc/api/dgram.md @@ -161,7 +161,7 @@ added: v0.11.14 --> * `options` {Object} Required. Supports the following properties: - * `port` {Integer} + * `port` {integer} * `address` {string} * `exclusive` {boolean} * `callback` {Function} @@ -390,7 +390,7 @@ packets may be sent to a local interface's broadcast address. added: v8.6.0 --> -* `multicastInterface` {String} +* `multicastInterface` {string} *Note: All references to scope in this section are referring to [IPv6 Zone Indices][], which are defined by [RFC 4007][]. In string form, an IP diff --git a/doc/api/dns.md b/doc/api/dns.md index 4ae44a211a0e06..c1ec1cfa51c41c 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -483,7 +483,7 @@ added: v0.1.27 Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a -two-dimensional array of the text records available for `hostname` (e.g., +two-dimensional array of the text records available for `hostname` (e.g. `[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of one record. Depending on the use case, these could be either joined together or treated separately. diff --git a/doc/api/errors.md b/doc/api/errors.md index 73fd1d52cbeedc..134f52265e0f6d 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -1265,6 +1265,24 @@ While using `N-API`, a constructor passed was not a function. While using `N-API`, `Constructor.prototype` was not an object. + +### ERR_NAPI_INVALID_DATAVIEW_ARGS + +While calling `napi_create_dataview()`, a given `offset` was outside the bounds +of the dataview or `offset + length` was larger than a length of given `buffer`. + + +### ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT + +While calling `napi_create_typedarray()`, the provided `offset` was not a +multiple of the element size. + + +### ERR_NAPI_INVALID_TYPEDARRAY_LENGTH + +While calling `napi_create_typedarray()`, `(length * size_of_element) + +byte_offset` was larger than the length of given `buffer`. + ### ERR_NO_CRYPTO @@ -1284,11 +1302,6 @@ A Node.js API was called in an unsupported manner. For example: `Buffer.write(string, encoding, offset[, length])` - -### ERR_OUTOFMEMORY - -An operation caused an out-of-memory condition. - ### ERR_OUT_OF_RANGE diff --git a/doc/api/esm.md b/doc/api/esm.md index 08d3ea6b3060b9..b90927c0d57cec 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -33,14 +33,15 @@ node --experimental-modules my-app.mjs ### Supported Only the CLI argument for the main entry point to the program can be an entry -point into an ESM graph. Dynamic import can also be used with the flag -`--harmony-dynamic-import` to create entry points into ESM graphs at run time. +point into an ESM graph. In the future `import()` can be used to create entry +points into ESM graphs at run time. ### Unsupported | Feature | Reason | | --- | --- | -| `require('./foo.mjs')` | ES Modules have differing resolution and timing, use dynamic import | +| `require('./foo.mjs')` | ES Modules have differing resolution and timing, use language standard `import()` | +| `import()` | pending newer V8 release used in Node.js | | `import.meta` | pending V8 implementation | ## Notable differences between `import` and `require` @@ -132,7 +133,7 @@ module. This can be one of the following: | `format` | Description | | --- | --- | | `"esm"` | Load a standard JavaScript module | -| `"cjs"` | Load a node-style CommonJS module | +| `"commonjs"` | Load a node-style CommonJS module | | `"builtin"` | Load a node builtin CommonJS module | | `"json"` | Load a JSON file | | `"addon"` | Load a [C++ Addon][addons] | diff --git a/doc/api/fs.md b/doc/api/fs.md index e1dabde956c9d1..f26dc6efbd204b 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -843,7 +843,7 @@ changes: description: The `file` parameter can be a file descriptor now. --> -* `file` {string|Buffer|number} filename or file descriptor +* `file` {string|Buffer|URL|number} filename or file descriptor * `data` {string|Buffer} * `options` {Object|string} * `encoding` {string|null} **Default:** `'utf8'` @@ -898,7 +898,7 @@ changes: description: The `file` parameter can be a file descriptor now. --> -* `file` {string|Buffer|number} filename or file descriptor +* `file` {string|Buffer|URL|number} filename or file descriptor * `data` {string|Buffer} * `options` {Object|string} * `encoding` {string|null} **Default:** `'utf8'` @@ -1334,7 +1334,7 @@ deprecated: v1.0.0 * `path` {string|Buffer|URL} * `callback` {Function} - * `exists` {Boolean} + * `exists` {boolean} Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false. Example: @@ -1709,7 +1709,7 @@ changes: it will emit a deprecation warning. --> -* `path` {string|Buffer} +* `path` {string|Buffer|URL} * `mode` {integer} * `callback` {Function} * `err` {Error} @@ -1724,7 +1724,7 @@ Only available on macOS. deprecated: v0.4.7 --> -* `path` {string|Buffer} +* `path` {string|Buffer|URL} * `mode` {integer} Synchronous lchmod(2). Returns `undefined`. @@ -1739,7 +1739,7 @@ changes: it will emit a deprecation warning. --> -* `path` {string|Buffer} +* `path` {string|Buffer|URL} * `uid` {integer} * `gid` {integer} * `callback` {Function} @@ -1753,7 +1753,7 @@ to the completion callback. deprecated: v0.4.7 --> -* `path` {string|Buffer} +* `path` {string|Buffer|URL} * `uid` {integer} * `gid` {integer} @@ -2694,7 +2694,7 @@ changes: it will emit a deprecation warning. --> -* `path` {string|Buffer} +* `path` {string|Buffer|URL} * `len` {integer} **Default:** `0` * `callback` {Function} * `err` {Error} @@ -2711,7 +2711,7 @@ being thrown in the future. added: v0.8.6 --> -* `path` {string|Buffer} +* `path` {string|Buffer|URL} * `len` {integer} **Default:** `0` Synchronous truncate(2). Returns `undefined`. A file descriptor can also be @@ -2760,10 +2760,9 @@ Synchronous unlink(2). Returns `undefined`. added: v0.1.31 --> -* `filename` {string|Buffer} -* `listener` {Function|undefined} **Default:** `undefined` - * `eventType` {string} - * `filename` {string|Buffer} +* `filename` {string|Buffer|URL} +* `listener` {Function} Optional, a listener previously attached using + `fs.watchFile()` Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, *all* listeners are removed, @@ -3121,7 +3120,7 @@ changes: description: The `file` parameter can be a file descriptor now. --> -* `file` {string|Buffer|integer} filename or file descriptor +* `file` {string|Buffer|URL|integer} filename or file descriptor * `data` {string|Buffer|Uint8Array} * `options` {Object|string} * `encoding` {string|null} **Default:** `'utf8'` @@ -3172,7 +3171,7 @@ changes: description: The `file` parameter can be a file descriptor now. --> -* `file` {string|Buffer|integer} filename or file descriptor +* `file` {string|Buffer|URL|integer} filename or file descriptor * `data` {string|Buffer|Uint8Array} * `options` {Object|string} * `encoding` {string|null} **Default:** `'utf8'` diff --git a/doc/api/http.md b/doc/api/http.md index 536d247226f3a2..02c78550e0d703 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -622,7 +622,7 @@ Once a socket is assigned to this request and is connected added: v0.5.9 --> -* `timeout` {number} Milliseconds before a request is considered to be timed out. +* `timeout` {number} Milliseconds before a request times out. * `callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. Once a socket is assigned to this request and is connected diff --git a/doc/api/http2.md b/doc/api/http2.md index a67fc387d832a2..4f37400c0cc260 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -229,8 +229,8 @@ added: v8.4.0 The `'stream'` event is emitted when a new `Http2Stream` is created. When invoked, the handler function will receive a reference to the `Http2Stream` -object, a [Headers Object][], and numeric flags associated with the creation -of the stream. +object, a [HTTP2 Headers Object][], and numeric flags associated with the +creation of the stream. ```js const http2 = require('http2'); @@ -382,7 +382,7 @@ Transmits a `GOAWAY` frame to the connected peer *without* shutting down the added: v8.4.0 --> -* Value: {[Settings Object][]} +* Value: {HTTP2 Settings Object} A prototype-less object describing the current local settings of this `Http2Session`. The local settings are local to *this* `Http2Session` instance. @@ -461,7 +461,7 @@ instance's underlying [`net.Socket`]. added: v8.4.0 --> -* Value: {[Settings Object][]} +* Value: {HTTP2 Settings Object} A prototype-less object describing the current remote settings of this `Http2Session`. The remote settings are set by the *connected* HTTP/2 peer. @@ -540,16 +540,28 @@ All other interactions will be routed directly to the socket. added: v8.4.0 --> +Provides miscellaneous information about the current state of the +`Http2Session`. + * Value: {Object} - * `effectiveLocalWindowSize` {number} - * `effectiveRecvDataLength` {number} - * `nextStreamID` {number} - * `localWindowSize` {number} - * `lastProcStreamID` {number} - * `remoteWindowSize` {number} - * `outboundQueueSize` {number} - * `deflateDynamicTableSize` {number} - * `inflateDynamicTableSize` {number} + * `effectiveLocalWindowSize` {number} The current local (receive) + flow control window size for the `Http2Session`. + * `effectiveRecvDataLength` {number} The current number of bytes + that have been received since the last flow control `WINDOW_UPDATE`. + * `nextStreamID` {number} The numeric identifier to be used the + next time a new `Http2Stream` is created by this `Http2Session`. + * `localWindowSize` {number} The number of bytes that the remote peer can + send without receiving a `WINDOW_UPDATE`. + * `lastProcStreamID` {number} The numeric id of the `Http2Stream` + for which a `HEADERS` or `DATA` frame was most recently received. + * `remoteWindowSize` {number} The number of bytes that this `Http2Session` + may send without receiving a `WINDOW_UPDATE`. + * `outboundQueueSize` {number} The number of frames currently within the + outbound queue for this `Http2Session`. + * `deflateDynamicTableSize` {number} The current size in bytes of the + outbound header compression state table. + * `inflateDynamicTableSize` {number} The current size in bytes of the + inbound header compression state table. An object describing the current status of this `Http2Session`. @@ -558,7 +570,7 @@ An object describing the current status of this `Http2Session`. added: v8.4.0 --> -* `settings` {[Settings Object][]} +* `settings` {HTTP2 Settings Object} * Returns {undefined} Updates the current local settings for this `Http2Session` and sends a new @@ -695,7 +707,7 @@ client.on('altsvc', (alt, origin, stream) => { added: v8.4.0 --> -* `headers` {[Headers Object][]} +* `headers` {HTTP2 Headers Object} * `options` {Object} * `endStream` {boolean} `true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not @@ -883,7 +895,7 @@ added: v8.4.0 The `'trailers'` event is emitted when a block of headers associated with trailing header fields is received. The listener callback is passed the -[Headers Object][] and flags associated with the headers. +[HTTP2 Headers Object][] and flags associated with the headers. ```js stream.on('trailers', (headers, flags) => { @@ -907,7 +919,7 @@ added: v8.4.0 --> * code {number} Unsigned 32-bit integer identifying the error code. **Default:** - `http2.constant.NGHTTP2_NO_ERROR` (`0x00`) + `http2.constants.NGHTTP2_NO_ERROR` (`0x00`) * `callback` {Function} An optional function registered to listen for the `'close'` event. * Returns: {undefined} @@ -977,6 +989,34 @@ destroyed after either receiving an `RST_STREAM` frame from the connected peer, calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. +#### http2stream.sentHeaders + + +* Value: {HTTP2 Headers Object} + +An object containing the outbound headers sent for this `Http2Stream`. + +#### http2stream.sentInfoHeaders + + +* Value: {HTTP2 Headers Object[]} + +An array of objects containing the outbound informational (additional) headers +sent for this `Http2Stream`. + +#### http2stream.sentTrailers + + +* Value: {HTTP2 Headers Object} + +An object containing the outbound trailers sent for this this `HttpStream`. + #### http2stream.session +Provides miscellaneous information about the current state of the +`Http2Stream`. * Value: {Object} - * `localWindowSize` {number} - * `state` {number} - * `localClose` {number} - * `remoteClose` {number} - * `sumDependencyWeight` {number} - * `weight` {number} + * `localWindowSize` {number} The number of bytes the connected peer may send + for this `Http2Stream` without receiving a `WINDOW_UPDATE`. + * `state` {number} A flag indicating the low-level current state of the + `Http2Stream` as determined by nghttp2. + * `localClose` {number} `true` if this `Http2Stream` has been closed locally. + * `remoteClose` {number} `true` if this `Http2Stream` has been closed + remotely. + * `sumDependencyWeight` {number} The sum weight of all `Http2Stream` + instances that depend on this `Http2Stream` as specified using + `PRIORITY` frames. + * `weight` {number} The priority weight of this `Http2Stream`. A current state of this `Http2Stream`. @@ -1049,8 +1096,8 @@ added: v8.4.0 The `'headers'` event is emitted when an additional block of headers is received for a stream, such as when a block of `1xx` informational headers is received. -The listener callback is passed the [Headers Object][] and flags associated with -the headers. +The listener callback is passed the [HTTP2 Headers Object][] and flags +associated with the headers. ```js stream.on('headers', (headers, flags) => { @@ -1064,8 +1111,8 @@ added: v8.4.0 --> The `'push'` event is emitted when response headers for a Server Push stream -are received. The listener callback is passed the [Headers Object][] and flags -associated with the headers. +are received. The listener callback is passed the [HTTP2 Headers Object][] and +flags associated with the headers. ```js stream.on('push', (headers, flags) => { @@ -1081,7 +1128,7 @@ added: v8.4.0 The `'response'` event is emitted when a response `HEADERS` frame has been received for this stream from the connected HTTP/2 server. The listener is invoked with two arguments: an Object containing the received -[Headers Object][], and flags associated with the headers. +[HTTP2 Headers Object][], and flags associated with the headers. For example: @@ -1111,7 +1158,7 @@ provide additional methods such as `http2stream.pushStream()` and added: v8.4.0 --> -* `headers` {[Headers Object][]} +* `headers` {HTTP2 Headers Object} * Returns: {undefined} Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. @@ -1142,7 +1189,7 @@ accepts push streams, `false` otherwise. Settings are the same for every added: v8.4.0 --> -* `headers` {[Headers Object][]} +* `headers` {HTTP2 Headers Object} * `options` {Object} * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with @@ -1152,17 +1199,23 @@ added: v8.4.0 created stream is dependent on. * `callback` {Function} Callback that is called once the push stream has been initiated. + * `err` {Error} + * `pushStream` {ServerHttp2Stream} The returned pushStream object. + * `headers` {HTTP2 Headers Object} Headers object the pushStream was + initiated with. * Returns: {undefined} Initiates a push stream. The callback is invoked with the new `Http2Stream` -instance created for the push stream. +instance created for the push stream passed as the second argument, or an +`Error` passed as the first argument. ```js const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }); - stream.pushStream({ ':path': '/' }, (pushStream) => { + stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + if (err) throw err; pushStream.respond({ ':status': 200 }); pushStream.end('some pushed data'); }); @@ -1179,7 +1232,7 @@ a `weight` value to `http2stream.priority` with the `silent` option set to added: v8.4.0 --> -* `headers` {[Headers Object][]} +* `headers` {HTTP2 Headers Object} * `options` {Object} * `endStream` {boolean} Set to `true` to indicate that the response will not include payload data. @@ -1225,7 +1278,7 @@ added: v8.4.0 --> * `fd` {number} A readable file descriptor. -* `headers` {[Headers Object][]} +* `headers` {HTTP2 Headers Object} * `options` {Object} * `statCheck` {Function} * `getTrailers` {Function} Callback function invoked to collect trailer @@ -1309,7 +1362,7 @@ added: v8.4.0 --> * `path` {string|Buffer|URL} -* `headers` {[Headers Object][]} +* `headers` {HTTP2 Headers Object} * `options` {Object} * `statCheck` {Function} * `onError` {Function} Callback function invoked in the case of an @@ -1675,7 +1728,7 @@ changes: * `selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using options.selectPadding][]. - * `settings` {[Settings Object][]} The initial settings to send to the + * `settings` {HTTP2 Settings Object} The initial settings to send to the remote peer upon connection. * `onRequestHandler` {Function} See [Compatibility API][] * Returns: {Http2Server} @@ -1762,7 +1815,7 @@ changes: * `selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using options.selectPadding][]. - * `settings` {[Settings Object][]} The initial settings to send to the + * `settings` {HTTP2 Settings Object} The initial settings to send to the remote peer upon connection. * ...: Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required. @@ -1858,7 +1911,7 @@ changes: * `selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using options.selectPadding][]. - * `settings` {[Settings Object][]} The initial settings to send to the + * `settings` {HTTP2 Settings Object} The initial settings to send to the remote peer upon connection. * `createConnection` {Function} An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any @@ -1911,7 +1964,7 @@ a given number of milliseconds set using `http2server.setTimeout()`. added: v8.4.0 --> -* Returns: {[Settings Object][]} +* Returns: {HTTP2 Settings Object} Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called @@ -1922,7 +1975,7 @@ so instances returned may be safely modified for use. added: v8.4.0 --> -* `settings` {[Settings Object][]} +* `settings` {HTTP2 Settings Object} * Returns: {Buffer} Returns a `Buffer` instance containing serialized representation of the given @@ -1944,10 +1997,10 @@ added: v8.4.0 --> * `buf` {Buffer|Uint8Array} The packed settings. -* Returns: {[Settings Object][]} +* Returns: {HTTP2 Settings Object} -Returns a [Settings Object][] containing the deserialized settings from the -given `Buffer` as generated by `http2.getPackedSettings()`. +Returns a [HTTP2 Settings Object][] containing the deserialized settings from +the given `Buffer` as generated by `http2.getPackedSettings()`. ### Headers Object @@ -2319,7 +2372,7 @@ Example: console.log(request.headers); ``` -See [Headers Object][]. +See [HTTP2 Headers Object][]. *Note*: In HTTP/2, the request path, hostname, protocol, and method are represented as special headers prefixed with the `:` character (e.g. `':path'`). @@ -3041,13 +3094,13 @@ following additional properties: [Compatibility API]: #http2_compatibility_api [HTTP/1]: http.html [HTTP/2]: https://tools.ietf.org/html/rfc7540 +[HTTP2 Headers Object]: #http2_headers_object +[HTTP2 Settings Object]: #http2_settings_object [HTTPS]: https.html -[Headers Object]: #http2_headers_object [Http2Session and Sockets]: #http2_http2session_and_sockets [Performance Observer]: perf_hooks.html [Readable Stream]: stream.html#stream_class_stream_readable [RFC 7838]: https://tools.ietf.org/html/rfc7838 -[Settings Object]: #http2_settings_object [Using options.selectPadding]: #http2_using_options_selectpadding [Writable Stream]: stream.html#stream_writable_streams [`'checkContinue'`]: #http2_event_checkcontinue diff --git a/doc/api/modules.md b/doc/api/modules.md index 458ba73c3df064..157ec3b6f715b9 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -468,7 +468,7 @@ added: v0.1.27 * {string} -The directory name of the current module. This the same as the +The directory name of the current module. This is the same as the [`path.dirname()`][] of the [`__filename`][]. Example: running `node example.js` from `/Users/mjr` @@ -626,9 +626,11 @@ added: v8.9.0 --> * `request` {string} The module path whose lookup paths are being retrieved. -* Returns: {Array} +* Returns: {Array|null} -Returns an array containing the paths searched during resolution of `request`. +Returns an array containing the paths searched during resolution of `request` or +null if the `request` string references a core module, for example `http` or +`fs`. ## The `module` Object @@ -1038,7 +1038,7 @@ JavaScript arrays are described in [Section 22.1](https://tc39.github.io/ecma262/#sec-array-objects) of the ECMAScript Language Specification. -#### *napi_create_array_with_length* +#### napi_create_array_with_length @@ -1067,7 +1067,7 @@ JavaScript arrays are described in [Section 22.1](https://tc39.github.io/ecma262/#sec-array-objects) of the ECMAScript Language Specification. -#### *napi_create_arraybuffer* +#### napi_create_arraybuffer @@ -1099,7 +1099,7 @@ JavaScript ArrayBuffer objects are described in [Section 24.1](https://tc39.github.io/ecma262/#sec-arraybuffer-objects) of the ECMAScript Language Specification. -#### *napi_create_buffer* +#### napi_create_buffer @@ -1120,7 +1120,7 @@ Returns `napi_ok` if the API succeeded. This API allocates a `node::Buffer` object. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice. -#### *napi_create_buffer_copy* +#### napi_create_buffer_copy @@ -1145,7 +1145,7 @@ This API allocates a `node::Buffer` object and initializes it with data copied from the passed-in buffer. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice. -#### *napi_create_external* +#### napi_create_external @@ -1212,7 +1212,7 @@ JavaScript ArrayBuffers are described in [Section 24.1](https://tc39.github.io/ecma262/#sec-arraybuffer-objects) of the ECMAScript Language Specification. -#### *napi_create_external_buffer* +#### napi_create_external_buffer @@ -1243,7 +1243,7 @@ structure, in most cases using a TypedArray will suffice. *Note*: For Node.js >=4 `Buffers` are Uint8Arrays. -#### *napi_create_function* +#### napi_create_function @@ -1276,7 +1276,7 @@ JavaScript Functions are described in [Section 19.2](https://tc39.github.io/ecma262/#sec-function-objects) of the ECMAScript Language Specification. -#### *napi_create_object* +#### napi_create_object @@ -1296,7 +1296,7 @@ The JavaScript Object type is described in [Section 6.1.7](https://tc39.github.io/ecma262/#sec-object-type) of the ECMAScript Language Specification. -#### *napi_create_symbol* +#### napi_create_symbol @@ -1319,7 +1319,7 @@ The JavaScript Symbol type is described in [Section 19.4](https://tc39.github.io/ecma262/#sec-symbol-objects) of the ECMAScript Language Specification. -#### *napi_create_typedarray* +#### napi_create_typedarray @@ -1355,7 +1355,7 @@ JavaScript TypedArray Objects are described in of the ECMAScript Language Specification. -#### *napi_create_dataview* +#### napi_create_dataview @@ -1389,7 +1389,7 @@ JavaScript DataView Objects are described in [Section 24.3][] of the ECMAScript Language Specification. ### Functions to convert from C types to N-API -#### *napi_create_int32* +#### napi_create_int32 @@ -1410,7 +1410,7 @@ The JavaScript Number type is described in [Section 6.1.6](https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type) of the ECMAScript Language Specification. -#### *napi_create_uint32* +#### napi_create_uint32 @@ -1431,7 +1431,7 @@ The JavaScript Number type is described in [Section 6.1.6](https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type) of the ECMAScript Language Specification. -#### *napi_create_int64* +#### napi_create_int64 @@ -1458,7 +1458,7 @@ outside the range of [`Number.MAX_SAFE_INTEGER`](https://tc39.github.io/ecma262/#sec-number.max_safe_integer) (2^53 - 1) will lose precision. -#### *napi_create_double* +#### napi_create_double @@ -1479,7 +1479,7 @@ The JavaScript Number type is described in [Section 6.1.6](https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type) of the ECMAScript Language Specification. -#### *napi_create_string_latin1* +#### napi_create_string_latin1 @@ -1504,7 +1504,7 @@ The JavaScript String type is described in [Section 6.1.4](https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type) of the ECMAScript Language Specification. -#### *napi_create_string_utf16* +#### napi_create_string_utf16 @@ -1529,7 +1529,7 @@ The JavaScript String type is described in [Section 6.1.4](https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type) of the ECMAScript Language Specification. -#### *napi_create_string_utf8* +#### napi_create_string_utf8 @@ -1555,7 +1555,7 @@ The JavaScript String type is described in of the ECMAScript Language Specification. ### Functions to convert from N-API to C types -#### *napi_get_array_length* +#### napi_get_array_length @@ -1578,7 +1578,7 @@ Array length is described in [Section 22.1.4.1](https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length) of the ECMAScript Language Specification. -#### *napi_get_arraybuffer_info* +#### napi_get_arraybuffer_info @@ -1606,7 +1606,7 @@ which can be used to guarantee control over the lifetime of the ArrayBuffer. It's also safe to use the returned data buffer within the same callback as long as there are no calls to other APIs that might trigger a GC. -#### *napi_get_buffer_info* +#### napi_get_buffer_info @@ -1630,7 +1630,7 @@ and it's length. *Warning*: Use caution while using this API since the underlying data buffer's lifetime is not guaranteed if it's managed by the VM. -#### *napi_get_prototype* +#### napi_get_prototype @@ -1648,7 +1648,7 @@ not the same as the function's `prototype` property). Returns `napi_ok` if the API succeeded. -#### *napi_get_typedarray_info* +#### napi_get_typedarray_info @@ -1680,7 +1680,7 @@ is managed by the VM -#### *napi_get_dataview_info* +#### napi_get_dataview_info @@ -1708,7 +1708,7 @@ Returns `napi_ok` if the API succeeded. This API returns various properties of a DataView. -#### *napi_get_value_bool* +#### napi_get_value_bool @@ -1727,7 +1727,7 @@ passed in it returns `napi_boolean_expected`. This API returns the C boolean primitive equivalent of the given JavaScript Boolean. -#### *napi_get_value_double* +#### napi_get_value_double @@ -1749,7 +1749,7 @@ This API returns the C double primitive equivalent of the given JavaScript Number. -#### *napi_get_value_external* +#### napi_get_value_external @@ -1769,7 +1769,7 @@ passed in it returns `napi_invalid_arg`. This API retrieves the external data pointer that was previously passed to `napi_create_external()`. -#### *napi_get_value_int32* +#### napi_get_value_int32 @@ -1792,7 +1792,7 @@ of the given JavaScript Number. If the number exceeds the range of the bottom 32 bits. This can result in a large positive number becoming a negative number if the value is > 2^31 -1. -#### *napi_get_value_int64* +#### napi_get_value_int64 @@ -1812,7 +1812,7 @@ is passed in it returns `napi_number_expected`. This API returns the C int64 primitive equivalent of the given JavaScript Number -#### *napi_get_value_string_latin1* +#### napi_get_value_string_latin1 @@ -1839,7 +1839,7 @@ is passed in it returns `napi_string_expected`. This API returns the ISO-8859-1-encoded string corresponding the value passed in. -#### *napi_get_value_string_utf8* +#### napi_get_value_string_utf8 @@ -1865,7 +1865,7 @@ is passed in it returns `napi_string_expected`. This API returns the UTF8-encoded string corresponding the value passed in. -#### *napi_get_value_string_utf16* +#### napi_get_value_string_utf16 @@ -1891,7 +1891,7 @@ is passed in it returns `napi_string_expected`. This API returns the UTF16-encoded string corresponding the value passed in. -#### *napi_get_value_uint32* +#### napi_get_value_uint32 @@ -1913,7 +1913,7 @@ This API returns the C primitive equivalent of the given `napi_value` as a `uint32_t`. ### Functions to get global instances -#### *napi_get_boolean* +#### napi_get_boolean @@ -1931,7 +1931,7 @@ Returns `napi_ok` if the API succeeded. This API is used to return the JavaScript singleton object that is used to represent the given boolean value -#### *napi_get_global* +#### napi_get_global @@ -1946,7 +1946,7 @@ Returns `napi_ok` if the API succeeded. This API returns the global Object. -#### *napi_get_null* +#### napi_get_null @@ -1961,7 +1961,7 @@ Returns `napi_ok` if the API succeeded. This API returns the null Object. -#### *napi_get_undefined* +#### napi_get_undefined @@ -1989,7 +1989,7 @@ These APIs support doing one of the following: 2. Check the type of a JavaScript value 3. Check for equality between two JavaScript values -### *napi_coerce_to_bool* +### napi_coerce_to_bool @@ -2010,7 +2010,7 @@ This API implements the abstract operation ToBoolean as defined in of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in Object. -### *napi_coerce_to_number* +### napi_coerce_to_number @@ -2031,7 +2031,7 @@ This API implements the abstract operation ToNumber as defined in of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in Object. -### *napi_coerce_to_object* +### napi_coerce_to_object @@ -2052,7 +2052,7 @@ This API implements the abstract operation ToObject as defined in of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in Object. -### *napi_coerce_to_string* +### napi_coerce_to_string @@ -2073,7 +2073,7 @@ This API implements the abstract operation ToString as defined in of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in Object. -### *napi_typeof* +### napi_typeof @@ -2094,7 +2094,7 @@ the object as defined in [Section 12.5.5][] of the ECMAScript Language Specification. However, it has support for detecting an External value. If `value` has a type that is invalid, an error is returned. -### *napi_instanceof* +### napi_instanceof @@ -2119,7 +2119,7 @@ defined in [Section 12.10.4](https://tc39.github.io/ecma262/#sec-instanceofoperator) of the ECMAScript Language Specification. -### *napi_is_array* +### napi_is_array @@ -2137,7 +2137,7 @@ This API represents invoking the `IsArray` operation on the object as defined in [Section 7.2.2](https://tc39.github.io/ecma262/#sec-isarray) of the ECMAScript Language Specification. -### *napi_is_arraybuffer* +### napi_is_arraybuffer @@ -2153,7 +2153,7 @@ Returns `napi_ok` if the API succeeded. This API checks if the Object passsed in is an array buffer. -### *napi_is_buffer* +### napi_is_buffer @@ -2170,7 +2170,7 @@ Returns `napi_ok` if the API succeeded. This API checks if the Object passsed in is a buffer. -### *napi_is_error* +### napi_is_error @@ -2186,7 +2186,7 @@ Returns `napi_ok` if the API succeeded. This API checks if the Object passsed in is an Error. -### *napi_is_typedarray* +### napi_is_typedarray @@ -2204,7 +2204,7 @@ This API checks if the Object passsed in is a typed array. -### *napi_is_dataview* +### napi_is_dataview @@ -2221,7 +2221,7 @@ Returns `napi_ok` if the API succeeded. This API checks if the Object passed in is a DataView. -### *napi_strict_equals* +### napi_strict_equals @@ -2375,7 +2375,7 @@ if (status != napi_ok) return status; ``` ### Structures -#### *napi_property_attributes* +#### napi_property_attributes ```C typedef enum { napi_default = 0, @@ -2409,7 +2409,7 @@ a static property on a class as opposed to an instance property, which is the default. This is used only by [`napi_define_class`][]. It is ignored by `napi_define_properties`. -#### *napi_property_descriptor* +#### napi_property_descriptor ```C typedef struct { // One of utf8name or name should be NULL. @@ -2455,7 +2455,7 @@ this function is invoked. See [`napi_property_attributes`](#n_api_napi_property_attributes). ### Functions -#### *napi_get_property_names* +#### napi_get_property_names @@ -2476,7 +2476,7 @@ Returns `napi_ok` if the API succeeded. This API returns the array of propertys for the Object passed in -#### *napi_set_property* +#### napi_set_property @@ -2496,7 +2496,7 @@ Returns `napi_ok` if the API succeeded. This API set a property on the Object passed in. -#### *napi_get_property* +#### napi_get_property @@ -2517,7 +2517,7 @@ Returns `napi_ok` if the API succeeded. This API gets the requested property from the Object passed in. -#### *napi_has_property* +#### napi_has_property @@ -2538,7 +2538,7 @@ Returns `napi_ok` if the API succeeded. This API checks if the Object passed in has the named property. -#### *napi_delete_property* +#### napi_delete_property @@ -2560,7 +2560,7 @@ Returns `napi_ok` if the API succeeded. This API attempts to delete the `key` own property from `object`. -#### *napi_has_own_property* +#### napi_has_own_property @@ -2583,7 +2583,7 @@ be a string or a Symbol, or an error will be thrown. N-API will not perform any conversion between data types. -#### *napi_set_named_property* +#### napi_set_named_property @@ -2604,7 +2604,7 @@ Returns `napi_ok` if the API succeeded. This method is equivalent to calling [`napi_set_property`][] with a `napi_value` created from the string passed in as `utf8Name` -#### *napi_get_named_property* +#### napi_get_named_property @@ -2625,7 +2625,7 @@ Returns `napi_ok` if the API succeeded. This method is equivalent to calling [`napi_get_property`][] with a `napi_value` created from the string passed in as `utf8Name` -#### *napi_has_named_property* +#### napi_has_named_property @@ -2646,7 +2646,7 @@ Returns `napi_ok` if the API succeeded. This method is equivalent to calling [`napi_has_property`][] with a `napi_value` created from the string passed in as `utf8Name` -#### *napi_set_element* +#### napi_set_element @@ -2666,7 +2666,7 @@ Returns `napi_ok` if the API succeeded. This API sets and element on the Object passed in. -#### *napi_get_element* +#### napi_get_element @@ -2686,7 +2686,7 @@ Returns `napi_ok` if the API succeeded. This API gets the element at the requested index. -#### *napi_has_element* +#### napi_has_element @@ -2707,7 +2707,7 @@ Returns `napi_ok` if the API succeeded. This API returns if the Object passed in has an element at the requested index. -#### *napi_delete_element* +#### napi_delete_element @@ -2728,7 +2728,7 @@ Returns `napi_ok` if the API succeeded. This API attempts to delete the specified `index` from `object`. -#### *napi_define_properties* +#### napi_define_properties @@ -2771,7 +2771,7 @@ like a regular JavaScript function call, or as a constructor function. -### *napi_call_function* +### napi_call_function @@ -2837,7 +2837,7 @@ status = napi_get_value_int32(env, return_val, &result); if (status != napi_ok) return; ``` -### *napi_create_function* +### napi_create_function @@ -2905,7 +2905,7 @@ myaddon.sayHello(); `NAPI_MODULE` in the earlier snippet but the name of the target in `binding.gyp` responsible for creating the `.node` file. -### *napi_get_cb_info* +### napi_get_cb_info @@ -2935,7 +2935,7 @@ Returns `napi_ok` if the API succeeded. This method is used within a callback function to retrieve details about the call like the arguments and the `this` pointer from a given callback info. -### *napi_get_new_target* +### napi_get_new_target @@ -2954,7 +2954,7 @@ Returns `napi_ok` if the API succeeded. This API returns the `new.target` of the constructor call. If the current callback is not a constructor call, the result is `NULL`. -### *napi_new_instance* +### napi_new_instance @@ -3049,7 +3049,7 @@ if (is_instance) { The reference must be freed once it is no longer needed. -### *napi_define_class* +### napi_define_class @@ -3105,7 +3105,7 @@ case, to prevent the function value from being garbage-collected, create a persistent reference to it using [`napi_create_reference`][] and ensure the reference count is kept >= 1. -### *napi_wrap* +### napi_wrap @@ -3167,7 +3167,7 @@ native instance associated with it by virtue of a previous call to another native instance with the given object, call `napi_remove_wrap()` on it first. -### *napi_unwrap* +### napi_unwrap @@ -3192,7 +3192,7 @@ method or accessor, then the `this` argument to the callback is the wrapper object; the wrapped C++ instance that is the target of the call can be obtained then by calling `napi_unwrap()` on the wrapper object. -### *napi_remove_wrap* +### napi_remove_wrap @@ -3283,7 +3283,7 @@ napi_status napi_create_async_work(napi_env env, - `[in] env`: The environment that the API is invoked under. - `[in] async_resource`: An optional object associated with the async work that will be passed to possible async_hooks [`init` hooks][]. -- `[in] async_resource_name`: An identifier for the kind of resource that is +- `[in] async_resource_name`: Identifier for the kind of resource that is being provided for diagnostic information exposed by the `async_hooks` API. - `[in] execute`: The native function which should be called to excute the logic asynchronously. @@ -3368,7 +3368,7 @@ scenario, because with those the async execution still happens on the main event loop. When using any other async mechanism, the following APIs are necessary to ensure an async operation is properly tracked by the runtime. -### *napi_async_init** +### napi_async_init @@ -3382,14 +3382,14 @@ napi_status napi_async_init(napi_env env, - `[in] env`: The environment that the API is invoked under. - `[in] async_resource`: An optional object associated with the async work that will be passed to possible `async_hooks` [`init` hooks][]. -- `[in] async_resource_name`: Required identifier for the kind of resource +- `[in] async_resource_name`: Identifier for the kind of resource that is being provided for diagnostic information exposed by the `async_hooks` API. - `[out] result`: The initialized async context. Returns `napi_ok` if the API succeeded. -### *napi_async_destroy** +### napi_async_destroy @@ -3403,7 +3403,7 @@ napi_status napi_async_destroy(napi_env env, Returns `napi_ok` if the API succeeded. -### *napi_make_callback* +### napi_make_callback -* `path` {String} Path the server should listen to. See +* `path` {string} Path the server should listen to. See [Identifying paths for IPC connections][]. * `backlog` {number} Common parameter of [`server.listen()`][] functions. * `callback` {Function} Common parameter of [`server.listen()`][] functions. diff --git a/doc/api/perf_hooks.md b/doc/api/perf_hooks.md index 5ce94624cb9d22..6d98d25af37cbc 100644 --- a/doc/api/perf_hooks.md +++ b/doc/api/perf_hooks.md @@ -29,6 +29,14 @@ added: v8.5.0 The `Performance` provides access to performance metric data. A single instance of this class is provided via the `performance` property. +### performance.clearEntries(name) + + +Remove all performance entry objects with `entryType` equal to `name` from the +Performance Timeline. + ### performance.clearFunctions([name]) + +Remove all performance entry objects with `entryType` equal to `gc` from the +Performance Timeline. + ### performance.clearMarks([name]) + +* {boolean} + +The `process.noDeprecation` property indicates whether the `--no-deprecation` +flag is set on the current Node.js process. See the documentation for +the [`warning` event][process_warning] and the +[`emitWarning` method][process_emit_warning] for more information about this +flag's behavior. + ## process.pid + +* {boolean} + +The `process.throwDeprecation` property indicates whether the +`--throw-deprecation` flag is set on the current Node.js process. See the +documentation for the [`warning` event][process_warning] and the +[`emitWarning` method][process_emit_warning] for more information about this +flag's behavior. + ## process.title + +* {boolean} + +The `process.traceDeprecation` property indicates whether the +`--trace-deprecation` flag is set on the current Node.js process. See the +documentation for the [`warning` event][process_warning] and the +[`emitWarning` method][process_emit_warning] for more information about this +flag's behavior. + ## process.umask([mask]) ```js -{ - http_parser: '2.3.0', - node: '1.1.1', - v8: '6.1.534.42-node.0', - uv: '1.3.0', - zlib: '1.2.8', - ares: '1.10.0-DEV', - modules: '43', - icu: '55.1', - openssl: '1.0.1k', - unicode: '8.0', - cldr: '29.0', +{ http_parser: '2.7.0', + node: '8.9.0', + v8: '6.3.292.48-node.6', + uv: '1.18.0', + zlib: '1.2.11', + ares: '1.13.0', + modules: '60', + nghttp2: '1.29.0', + napi: '2', + openssl: '1.0.2n', + icu: '60.1', + unicode: '10.0', + cldr: '32.0', tz: '2016b' } ``` @@ -1977,5 +2030,6 @@ cases: [Readable]: stream.html#stream_readable_streams [Signal Events]: #process_signal_events [Stream compatibility]: stream.html#stream_compatibility_with_older_node_js_versions +[Supported platforms]: https://github.com/nodejs/node/blob/master/BUILDING.md#supported-platforms-1 [TTY]: tty.html#tty_tty [Writable]: stream.html#stream_writable_streams diff --git a/doc/api/readline.md b/doc/api/readline.md index 8619d75132836d..7ba1277dce2d9c 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -60,8 +60,8 @@ The `'close'` event is emitted when one of the following occur: The listener function is called without passing any arguments. -The `readline.Interface` instance should be considered to be "finished" once -the `'close'` event is emitted. +The `readline.Interface` instance is finished once the `'close'` event is +emitted. ### Event: 'line' -The `replServer.clearBufferedComand()` method clears any command that has been +The `replServer.clearBufferedCommand()` method clears any command that has been buffered but not yet executed. This method is primarily intended to be called from within the action function for commands registered using the `replServer.defineCommand()` method. diff --git a/doc/api/stream.md b/doc/api/stream.md index 87c43dca8c0913..c0351a3679445e 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -1474,7 +1474,7 @@ added: v8.0.0 argument. The `_destroy()` method is called by [`writable.destroy()`][writable-destroy]. -It can be overriden by child classes but it **must not** be called directly. +It can be overridden by child classes but it **must not** be called directly. #### writable.\_final(callback) + +* **Version**: +* **Platform**: +* **Subsystem**: + + +``` + +If you believe that you have uncovered a bug in Node.js, please fill out this +form, following the template to the best of your ability. Do not worry if you +cannot answer every detail, just fill in what you can. + +The two most important pieces of information we need in order to properly +evaluate the report is a description of the behavior you are seeing and a simple +test case we can use to recreate the problem on our own. If we cannot recreate +the issue, it becomes impossible for us to fix. + +In order to rule out the possibility of bugs introduced by userland code, test +cases should be limited, as much as possible, to using *only* Node.js APIs. +If the bug occurs only when you're using a specific userland module, there is +a very good chance that either (a) the module has a bug or (b) something in +Node.js changed that broke the module. + +See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). + +## Triaging a Bug Report + +Once an issue has been opened, it is not uncommon for there to be discussion +around it. Some contributors may have differing opinions about the issue, +including whether the behavior being seen is a bug or a feature. This discussion +is part of the process and should be kept focused, helpful, and professional. + +Short, clipped responses—that provide neither additional context nor supporting +detail—are not helpful or professional. To many, such responses are simply +annoying and unfriendly. + +Contributors are encouraged to help one another make forward progress as much +as possible, empowering one another to solve issues collaboratively. If you +choose to comment on an issue that you feel either is not a problem that needs +to be fixed, or if you encounter information in an issue that you feel is +incorrect, explain *why* you feel that way with additional supporting context, +and be willing to be convinced that you may be wrong. By doing so, we can often +reach the correct outcome much faster. + +## Resolving a Bug Report + +In the vast majority of cases, issues are resolved by opening a Pull Request. +The process for opening and reviewing a Pull Request is similar to that of +opening and triaging issues, but carries with it a necessary review and approval +workflow that ensures that the proposed changes meet the minimal quality and +functional guidelines of the Node.js project. + +[Node.js help repository]: https://github.com/nodejs/help/issues +[Technical Steering Committee (TSC) repository]: https://github.com/nodejs/TSC/issues diff --git a/doc/guides/contributing/pull-requests.md b/doc/guides/contributing/pull-requests.md new file mode 100644 index 00000000000000..5812c8c54645e2 --- /dev/null +++ b/doc/guides/contributing/pull-requests.md @@ -0,0 +1,663 @@ +# Pull Requests + +There are two fundamental components of the Pull Request process: one concrete +and technical, and one more process oriented. The concrete and technical +component involves the specific details of setting up your local environment +so that you can make the actual changes. This is where we will start. + +* [Dependencies](#dependencies) +* [Setting up your local environment](#setting-up-your-local-environment) + * [Step 1: Fork](#step-1-fork) + * [Step 2: Branch](#step-2-branch) +* [The Process of Making Changes](#the-process-of-making-changes) + * [Step 3: Code](#step-3-code) + * [Step 4: Commit](#step-4-commit) + * [Commit message guidelines](#commit-message-guidelines) + * [Step 5: Rebase](#step-5-rebase) + * [Step 6: Test](#step-6-test) + * [Test Coverage](#test-coverage) + * [Step 7: Push](#step-7-push) + * [Step 8: Opening the Pull Request](#step-8-opening-the-pull-request) + * [Step 9: Discuss and Update](#step-9-discuss-and-update) + * [Approval and Request Changes Workflow](#approval-and-request-changes-workflow) + * [Step 10: Landing](#step-10-landing) +* [Reviewing Pull Requests](#reviewing-pull-requests) + * [Review a bit at a time](#review-a-bit-at-a-time) + * [Be aware of the person behind the code](#be-aware-of-the-person-behind-the-code) + * [Respect the minimum wait time for comments](#respect-the-minimum-wait-time-for-comments) + * [Abandoned or Stalled Pull Requests](#abandoned-or-stalled-pull-requests) + * [Approving a change](#approving-a-change) + * [Accept that there are different opinions about what belongs in Node.js](#accept-that-there-are-different-opinions-about-what-belongs-in-nodejs) + * [Performance is not everything](#performance-is-not-everything) + * [Continuous Integration Testing](#continuous-integration-testing) +* [Additional Notes](#additional-notes) + * [Commit Squashing](#commit-squashing) + * [Getting Approvals for your Pull Request](#getting-approvals-for-your-pull-request) + * [CI Testing](#ci-testing) + * [Waiting Until the Pull Request Gets Landed](#waiting-until-the-pull-request-gets-landed) + * [Check Out the Collaborator's Guide](#check-out-the-collaborators-guide) + +## Dependencies + +Node.js has several bundled dependencies in the *deps/* and the *tools/* +directories that are not part of the project proper. Changes to files in those +directories should be sent to their respective projects. Do not send a patch to +Node.js. We cannot accept such patches. + +In case of doubt, open an issue in the +[issue tracker](https://github.com/nodejs/node/issues/) or contact one of the +[project Collaborators](https://github.com/nodejs/node/#current-project-team-members). +Node.js has two IRC channels: +[#Node.js](https://webchat.freenode.net/?channels=node.js) for general help and +questions, and +[#Node-dev](https://webchat.freenode.net/?channels=node-dev) for development of +Node.js core specifically. + +## Setting up your local environment + +To get started, you will need to have `git` installed locally. Depending on +your operating system, there are also a number of other dependencies required. +These are detailed in the [Building guide][]. + +Once you have `git` and are sure you have all of the necessary dependencies, +it's time to create a fork. + +Before getting started, it is recommended to configure `git` so that it knows +who you are: + +```text +$ git config --global user.name "J. Random User" +$ git config --global user.email "j.random.user@example.com" +``` +Please make sure this local email is also added to your +[GitHub email list](https://github.com/settings/emails) so that your commits +will be properly associated with your account and you will be promoted +to Contributor once your first commit is landed. + +### Step 1: Fork + +Fork the project [on GitHub](https://github.com/nodejs/node) and clone your fork +locally. + +```text +$ git clone git@github.com:username/node.git +$ cd node +$ git remote add upstream https://github.com/nodejs/node.git +$ git fetch upstream +``` + +### Step 2: Branch + +As a best practice to keep your development environment as organized as +possible, create local branches to work within. These should also be created +directly off of the `master` branch. + +```text +$ git checkout -b my-branch -t upstream/master +``` + +## The Process of Making Changes + +### Step 3: Code + +The vast majority of Pull Requests opened against the `nodejs/node` +repository includes changes to either the C/C++ code contained in the `src` +directory, the JavaScript code contained in the `lib` directory, the +documentation in `docs/api` or tests within the `test` directory. + +If you are modifying code, please be sure to run `make lint` from time to +time to ensure that the changes follow the Node.js code style guide. + +Any documentation you write (including code comments and API documentation) +should follow the [Style Guide](doc/STYLE_GUIDE.md). Code samples included +in the API docs will also be checked when running `make lint` (or +`vcbuild.bat lint` on Windows). + +For contributing C++ code, you may want to look at the +[C++ Style Guide](CPP_STYLE_GUIDE.md). + +### Step 4: Commit + +It is a recommended best practice to keep your changes as logically grouped +as possible within individual commits. There is no limit to the number of +commits any single Pull Request may have, and many contributors find it easier +to review changes that are split across multiple commits. + +```text +$ git add my/changed/files +$ git commit +``` + +Note that multiple commits often get squashed when they are landed (see the +notes about [commit squashing](#commit-squashing)). + +#### Commit message guidelines + +A good commit message should describe what changed and why. + +1. The first line should: + - contain a short description of the change (preferably 50 characters or less, + and no more than 72 characters) + - be entirely in lowercase with the exception of proper nouns, acronyms, and + the words that refer to code, like function/variable names + - be prefixed with the name of the changed subsystem and start with an + imperative verb. Check the output of `git log --oneline files/you/changed` to + find out what subsystems your changes touch. + + Examples: + - `net: add localAddress and localPort to Socket` + - `src: fix typos in node_lttng_provider.h` + + +2. Keep the second line blank. +3. Wrap all other lines at 72 columns. + +4. 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 other references +use `Refs:`. + + Examples: + - `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` + +5. If your commit introduces a breaking change (`semver-major`), it should +contain an explanation about the reason of the breaking change, which +situation would trigger the breaking change and what is the exact change. + +Breaking changes will be listed in the wiki with the aim to make upgrading +easier. Please have a look at [Breaking Changes](https://github.com/nodejs/node/wiki/Breaking-changes-between-v4-LTS-and-v6-LTS) +for the level of detail that's suitable. + +Sample complete commit message: + +```txt +subsystem: explain the commit in one line + +Body of commit message is a few lines of text, explaining things +in more detail, possibly giving some background about the issue +being fixed, etc. + +The body of the commit message can be several paragraphs, and +please do proper word-wrap and keep columns shorter than about +72 characters or so. That way, `git log` will show things +nicely even when it is indented. + +Fixes: https://github.com/nodejs/node/issues/1337 +Refs: http://eslint.org/docs/rules/space-in-parens.html +``` + +If you are new to contributing to Node.js, please try to do your best at +conforming to these guidelines, but do not worry if you get something wrong. +One of the existing contributors will help get things situated and the +contributor landing the Pull Request will ensure that everything follows +the project guidelines. + +See [core-validate-commit](https://github.com/evanlucas/core-validate-commit) - +A utility that ensures commits follow the commit formatting guidelines. + +### Step 5: Rebase + +As a best practice, once you have committed your changes, it is a good idea +to use `git rebase` (not `git merge`) to synchronize your work with the main +repository. + +```text +$ git fetch upstream +$ git rebase upstream/master +``` + +This ensures that your working branch has the latest changes from `nodejs/node` +master. + +### Step 6: Test + +Bug fixes and features should always come with tests. A +[guide for writing tests in Node.js][] has been +provided to make the process easier. Looking at other tests to see how they +should be structured can also help. + +The `test` directory within the `nodejs/node` repository is complex and it is +often not clear where a new test file should go. When in doubt, add new tests +to the `test/parallel/` directory and the right location will be sorted out +later. + +Before submitting your changes in a Pull Request, always run the full Node.js +test suite. To run the tests (including code linting) on Unix / macOS: + +```text +$ ./configure && make -j4 test +``` + +And on Windows: + +```text +> vcbuild test +``` + +(See the [Building guide][] for more details.) + +Make sure the linter does not report any issues and that all tests pass. Please +do not submit patches that fail either check. + +If you want to run the linter without running tests, use +`make lint`/`vcbuild lint`. It will run both JavaScript linting and +C++ linting. + +If you are updating tests and just want to run a single test to check it: + +```text +$ python tools/test.py -J --mode=release parallel/test-stream2-transform +``` + +You can execute the entire suite of tests for a given subsystem +by providing the name of a subsystem: + +```text +$ python tools/test.py -J --mode=release child-process +``` + +If you want to check the other options, please refer to the help by using +the `--help` option + +```text +$ python tools/test.py --help +``` + +You can usually run tests directly with node: + +```text +$ ./node ./test/parallel/test-stream2-transform.js +``` + +Remember to recompile with `make -j4` in between test runs if you change code in +the `lib` or `src` directories. + +#### Test Coverage + +It's good practice to ensure any code you add or change is covered by tests. +You can do so by running the test suite with coverage enabled: + +```text +$ ./configure --coverage && make coverage +``` + +A detailed coverage report will be written to `coverage/index.html` for +JavaScript coverage and to `coverage/cxxcoverage.html` for C++ coverage. + +_Note that generating a test coverage report can take several minutes._ + +To collect coverage for a subset of tests you can set the `CI_JS_SUITES` and +`CI_NATIVE_SUITES` variables: + +```text +$ CI_JS_SUITES=child-process CI_NATIVE_SUITES= make coverage +``` + +The above command executes tests for the `child-process` subsystem and +outputs the resulting coverage report. + +Running tests with coverage will create and modify several directories +and files. To clean up afterwards, run: + +```text +make coverage-clean +./configure && make -j4. +``` + +### Step 7: Push + +Once you are sure your commits are ready to go, with passing tests and linting, +begin the process of opening a Pull Request by pushing your working branch to +your fork on GitHub. + +```text +$ git push origin my-branch +``` + +### Step 8: Opening the Pull Request + +From within GitHub, opening a new Pull Request will present you with a template +that should be filled out: + +```markdown + + +#### Checklist + + +- [ ] `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes +- [ ] tests and/or benchmarks are included +- [ ] documentation is changed or added +- [ ] commit message follows [commit guidelines](https://github.com/nodejs/node/blob/master/doc/guides/contributing/pull-requests.md#commit-message-guidelines) + +#### Affected core subsystem(s) + +``` + +Please try to do your best at filling out the details, but feel free to skip +parts if you're not sure what to put. + +Once opened, Pull Requests are usually reviewed within a few days. + +### Step 9: Discuss and update + +You will probably get feedback or requests for changes to your Pull Request. +This is a big part of the submission process so don't be discouraged! Some +contributors may sign off on the Pull Request right away, others may have +more detailed comments or feedback. This is a necessary part of the process +in order to evaluate whether the changes are correct and necessary. + +To make changes to an existing Pull Request, make the changes to your local +branch, add a new commit with those changes, and push those to your fork. +GitHub will automatically update the Pull Request. + +```text +$ git add my/changed/files +$ git commit +$ git push origin my-branch +``` + +It is also frequently necessary to synchronize your Pull Request with other +changes that have landed in `master` by using `git rebase`: + +```text +$ git fetch --all +$ git rebase origin/master +$ git push --force-with-lease origin my-branch +``` + +**Important:** The `git push --force-with-lease` command is one of the few ways +to delete history in `git`. Before you use it, make sure you understand the +risks. If in doubt, you can always ask for guidance in the Pull Request or on +[IRC in the #node-dev channel][]. + +If you happen to make a mistake in any of your commits, do not worry. You can +amend the last commit (for example if you want to change the commit log). + +```text +$ git add any/changed/files +$ git commit --amend +$ git push --force-with-lease origin my-branch +``` + +There are a number of more advanced mechanisms for managing commits using +`git rebase` that can be used, but are beyond the scope of this guide. + +Feel free to post a comment in the Pull Request to ping reviewers if you are +awaiting an answer on something. If you encounter words or acronyms that +seem unfamiliar, refer to this +[glossary](https://sites.google.com/a/chromium.org/dev/glossary). + +#### Approval and Request Changes Workflow + +All Pull Requests require "sign off" in order to land. Whenever a contributor +reviews a Pull Request they may find specific details that they would like to +see changed or fixed. These may be as simple as fixing a typo, or may involve +substantive changes to the code you have written. In general, such requests +are intended to be helpful, but at times may come across as abrupt or unhelpful, +especially requests to change things that do not include concrete suggestions +on *how* to change them. + +Try not to be discouraged. If you feel that a particular review is unfair, +say so, or contact one of the other contributors in the project and seek their +input. Often such comments are the result of the reviewer having only taken a +short amount of time to review and are not ill-intended. Such issues can often +be resolved with a bit of patience. That said, reviewers should be expected to +be helpful in their feedback, and feedback that is simply vague, dismissive and +unhelpful is likely safe to ignore. + +### Step 10: Landing + +In order to land, a Pull Request needs to be reviewed and [approved][] by +at least one Node.js Collaborator and pass a +[CI (Continuous Integration) test run][]. After that, as long as there are no +objections from other contributors, the Pull Request can be merged. If you find +your Pull Request waiting longer than you expect, see the +[notes about the waiting time](#waiting-until-the-pull-request-gets-landed). + +When a collaborator lands your Pull Request, they will post +a comment to the Pull Request page mentioning the commit(s) it +landed as. GitHub often shows the Pull Request as `Closed` at this +point, but don't worry. If you look at the branch you raised your +Pull Request against (probably `master`), you should see a commit with +your name on it. Congratulations and thanks for your contribution! + +## Reviewing Pull Requests + +All Node.js contributors who choose to review and provide feedback on Pull +Requests have a responsibility to both the project and the individual making the +contribution. Reviews and feedback must be helpful, insightful, and geared +towards improving the contribution as opposed to simply blocking it. If there +are reasons why you feel the PR should not land, explain what those are. Do not +expect to be able to block a Pull Request from advancing simply because you say +"No" without giving an explanation. Be open to having your mind changed. Be open +to working with the contributor to make the Pull Request better. + +Reviews that are dismissive or disrespectful of the contributor or any other +reviewers are strictly counter to the [Code of Conduct][]. + +When reviewing a Pull Request, the primary goals are for the codebase to improve +and for the person submitting the request to succeed. Even if a Pull Request +does not land, the submitters should come away from the experience feeling like +their effort was not wasted or unappreciated. Every Pull Request from a new +contributor is an opportunity to grow the community. + +### Review a bit at a time. + +Do not overwhelm new contributors. + +It is tempting to micro-optimize and make everything about relative performance, +perfect grammar, or exact style matches. Do not succumb to that temptation. + +Focus first on the most significant aspects of the change: + +1. Does this change make sense for Node.js? +2. Does this change make Node.js better, even if only incrementally? +3. Are there clear bugs or larger scale issues that need attending to? +4. Is the commit message readable and correct? If it contains a breaking change is it clear enough? + +When changes are necessary, *request* them, do not *demand* them, and do not +assume that the submitter already knows how to add a test or run a benchmark. + +Specific performance optimization techniques, coding styles and conventions +change over time. The first impression you give to a new contributor never does. + +Nits (requests for small changes that are not essential) are fine, but try to +avoid stalling the Pull Request. Most nits can typically be fixed by the +Node.js Collaborator landing the Pull Request but they can also be an +opportunity for the contributor to learn a bit more about the project. + +It is always good to clearly indicate nits when you comment: e.g. +`Nit: change foo() to bar(). But this is not blocking.` + +### Be aware of the person behind the code + +Be aware that *how* you communicate requests and reviews in your feedback can +have a significant impact on the success of the Pull Request. Yes, we may land +a particular change that makes Node.js better, but the individual might just +not want to have anything to do with Node.js ever again. The goal is not just +having good code. + +### Respect the minimum wait time for comments + +There is a minimum waiting time which we try to respect for non-trivial +changes, so that people who may have important input in such a distributed +project are able to respond. + +For non-trivial changes, Pull Requests must be left open for *at least* 48 +hours during the week, and 72 hours on a weekend. In most cases, when the +PR is relatively small and focused on a narrow set of changes, these periods +provide more than enough time to adequately review. Sometimes changes take far +longer to review, or need more specialized review from subject matter experts. +When in doubt, do not rush. + +Trivial changes, typically limited to small formatting changes or fixes to +documentation, may be landed within the minimum 48 hour window. + +### Abandoned or Stalled Pull Requests + +If a Pull Request appears to be abandoned or stalled, it is polite to first +check with the contributor to see if they intend to continue the work before +checking if they would mind if you took it over (especially if it just has +nits left). When doing so, it is courteous to give the original contributor +credit for the work they started (either by preserving their name and email +address in the commit log, or by using an `Author: ` meta-data tag in the +commit. + +### Approving a change + +Any Node.js core Collaborator (any GitHub user with commit rights in the +`nodejs/node` repository) is authorized to approve any other contributor's +work. Collaborators are not permitted to approve their own Pull Requests. + +Collaborators indicate that they have reviewed and approve of the changes in +a Pull Request either by using GitHub's Approval Workflow, which is preferred, +or by leaving an `LGTM` ("Looks Good To Me") comment. + +When explicitly using the "Changes requested" component of the GitHub Approval +Workflow, show empathy. That is, do not be rude or abrupt with your feedback +and offer concrete suggestions for improvement, if possible. If you're not +sure *how* a particular change can be improved, say so. + +Most importantly, after leaving such requests, it is courteous to make yourself +available later to check whether your comments have been addressed. + +If you see that requested changes have been made, you can clear another +collaborator's `Changes requested` review. + +Change requests that are vague, dismissive, or unconstructive may also be +dismissed if requests for greater clarification go unanswered within a +reasonable period of time. + +If you do not believe that the Pull Request should land at all, use +`Changes requested` to indicate that you are considering some of your comments +to block the PR from landing. When doing so, explain *why* you believe the +Pull Request should not land along with an explanation of what may be an +acceptable alternative course, if any. + +### Accept that there are different opinions about what belongs in Node.js + +Opinions on this vary, even among the members of the Technical Steering +Committee. + +One general rule of thumb is that if Node.js itself needs it (due to historic +or functional reasons), then it belongs in Node.js. For instance, `url` +parsing is in Node.js because of HTTP protocol support. + +Also, functionality that either cannot be implemented outside of core in any +reasonable way, or only with significant pain. + +It is not uncommon for contributors to suggest new features they feel would +make Node.js better. These may or may not make sense to add, but as with all +changes, be courteous in how you communicate your stance on these. Comments +that make the contributor feel like they should have "known better" or +ridiculed for even trying run counter to the [Code of Conduct][]. + +### Performance is not everything + +Node.js has always optimized for speed of execution. If a particular change +can be shown to make some part of Node.js faster, it's quite likely to be +accepted. Claims that a particular Pull Request will make things faster will +almost always be met by requests for performance [benchmark results][] that +demonstrate the improvement. + +That said, performance is not the only factor to consider. Node.js also +optimizes in favor of not breaking existing code in the ecosystem, and not +changing working functional code just for the sake of changing. + +If a particular Pull Request introduces a performance or functional +regression, rather than simply rejecting the Pull Request, take the time to +work *with* the contributor on improving the change. Offer feedback and +advice on what would make the Pull Request acceptable, and do not assume that +the contributor should already know how to do that. Be explicit in your +feedback. + +### Continuous Integration Testing + +All Pull Requests that contain changes to code must be run through +continuous integration (CI) testing at [https://ci.nodejs.org/][]. + +Only Node.js core Collaborators with commit rights to the `nodejs/node` +repository may start a CI testing run. The specific details of how to do +this are included in the new Collaborator [Onboarding guide][]. + +Ideally, the code change will pass ("be green") on all platform configurations +supported by Node.js (there are over 30 platform configurations currently). +This means that all tests pass and there are no linting errors. In reality, +however, it is not uncommon for the CI infrastructure itself to fail on +specific platforms or for so-called "flaky" tests to fail ("be red"). It is +vital to visually inspect the results of all failed ("red") tests to determine +whether the failure was caused by the changes in the Pull Request. + +## Additional Notes + +### Commit Squashing + +When the commits in your Pull Request land, they may be squashed +into one commit per logical change. Metadata will be added to the commit +message (including links to the Pull Request, links to relevant issues, +and the names of the reviewers). The commit history of your Pull Request, +however, will stay intact on the Pull Request page. + +For the size of "one logical change", +[0b5191f](https://github.com/nodejs/node/commit/0b5191f15d0f311c804d542b67e2e922d98834f8) +can be a good example. It touches the implementation, the documentation, +and the tests, but is still one logical change. In general, the tests should +always pass when each individual commit lands on the master branch. + +### Getting Approvals for Your Pull Request + +A Pull Request is approved either by saying LGTM, which stands for +"Looks Good To Me", or by using GitHub's Approve button. +GitHub's Pull Request review feature can be used during the process. +For more information, check out +[the video tutorial](https://www.youtube.com/watch?v=HW0RPaJqm4g) +or [the official documentation](https://help.github.com/articles/reviewing-changes-in-pull-requests/). + +After you push new changes to your branch, you need to get +approval for these new changes again, even if GitHub shows "Approved" +because the reviewers have hit the buttons before. + +### CI Testing + +Every Pull Request needs to be tested +to make sure that it works on the platforms that Node.js +supports. This is done by running the code through the CI system. + +Only a Collaborator can start a CI run. Usually one of them will do it +for you as approvals for the Pull Request come in. +If not, you can ask a Collaborator to start a CI run. + +### Waiting Until the Pull Request Gets Landed + +A Pull Request needs to stay open for at least 48 hours (72 hours on a +weekend) from when it is submitted, even after it gets approved and +passes the CI. This is to make sure that everyone has a chance to +weigh in. If the changes are trivial, collaborators may decide it +doesn't need to wait. A Pull Request may well take longer to be +merged in. All these precautions are important because Node.js is +widely used, so don't be discouraged! + +### Check Out the Collaborator's Guide + +If you want to know more about the code review and the landing process, +you can take a look at the +[collaborator's guide](https://github.com/nodejs/node/blob/master/COLLABORATOR_GUIDE.md). + +[approved]: #getting-approvals-for-your-pull-request +[benchmark results]: ../writing-and-running-benchmarks.md +[Building guide]: ../../../BUILDING.md +[CI (Continuous Integration) test run]: #ci-testing +[Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md +[guide for writing tests in Node.js]: ../writing-tests.md +[https://ci.nodejs.org/]: https://ci.nodejs.org/ +[IRC in the #node-dev channel]: https://webchat.freenode.net?channels=node-dev&uio=d4 +[Onboarding guide]: ../onboarding.md diff --git a/doc/guides/maintaining-V8.md b/doc/guides/maintaining-V8.md index d45fa072074aee..04bc155660105b 100644 --- a/doc/guides/maintaining-V8.md +++ b/doc/guides/maintaining-V8.md @@ -29,8 +29,7 @@ For example, at the time of this writing: released as part of the Chromium **canary** builds. This branch will be promoted to beta next when V8 5.5 ships as stable. -All older branches are considered **abandoned**, and are not maintained by the -V8 team. +All older branches are abandoned and are not maintained by the V8 team. ### V8 merge process overview @@ -144,9 +143,10 @@ includes the following branches1: -The versions of V8 used in Node.js v4.x and v6.x have already been abandoned by -upstream V8. However, Node.js needs to continue supporting these branches for -many months (Current branches) or several years (LTS branches). +The versions of V8 used in Node.js v4.x, v6.x, and 8.x have already been +abandoned by upstream V8. However, Node.js needs to continue supporting +these branches for many months (Current branches) or several +years (LTS branches). ## Maintenance Process diff --git a/doc/guides/maintaining-the-build-files.md b/doc/guides/maintaining-the-build-files.md index c9dd155dd80269..ca5ee090a69dcc 100644 --- a/doc/guides/maintaining-the-build-files.md +++ b/doc/guides/maintaining-the-build-files.md @@ -15,7 +15,7 @@ There are three main build files that may be directly run when building Node.js: Makefile mentioned below is maintained separately by humans). For a detailed guide on this script, see [configure](#configure). - `vcbuild.bat`: A Windows Batch Script that locates build tools, provides a - subset of the targets avilable in the [Makefile](#makefile), and a few targets + subset of the targets available in the [Makefile](#makefile), and a few targets of its own. For a detailed guide on this script, see [vcbuild.bat](#vcbuild.bat). - `Makefile`: A Makefile that can be run with GNU Make. It provides a set of diff --git a/doc/guides/using-internal-errors.md b/doc/guides/using-internal-errors.md index 3ae11e901a62ba..90962757bb0bb2 100644 --- a/doc/guides/using-internal-errors.md +++ b/doc/guides/using-internal-errors.md @@ -119,8 +119,8 @@ likely be required. ### Class: errors.Error(key[, args...]) -* `key` {String} The static error identifier -* `args...` {Any} Zero or more optional arguments +* `key` {string} The static error identifier +* `args...` {any} Zero or more optional arguments ```js const errors = require('internal/errors'); @@ -139,8 +139,8 @@ The `myError` object will have a `code` property equal to the `key` and a ### Class: errors.TypeError(key[, args...]) -* `key` {String} The static error identifier -* `args...` {Any} Zero or more optional arguments +* `key` {string} The static error identifier +* `args...` {any} Zero or more optional arguments ```js const errors = require('internal/errors'); @@ -159,8 +159,8 @@ The `myError` object will have a `code` property equal to the `key` and a ### Class: errors.RangeError(key[, args...]) -* `key` {String} The static error identifier -* `args...` {Any} Zero or more optional arguments +* `key` {string} The static error identifier +* `args...` {any} Zero or more optional arguments ```js const errors = require('internal/errors'); @@ -179,8 +179,8 @@ The `myError` object will have a `code` property equal to the `key` and a ### Method: errors.message(key, args) -* `key` {String} The static error identifier +* `key` {string} The static error identifier * `args` {Array} Zero or more optional arguments passed as an Array -* Returns: {String} +* Returns: {string} Returns the formatted error message string for the given `key`. diff --git a/doc/onboarding-extras.md b/doc/onboarding-extras.md index 9b00b2cecfcbb3..4d389376c98d20 100644 --- a/doc/onboarding-extras.md +++ b/doc/onboarding-extras.md @@ -2,45 +2,45 @@ ## Who to CC in issues -| Subsystem | Maintainers | -| --- | --- | -| `benchmark/*` | @nodejs/benchmarking, @mscdex | -| `bootstrap_node.js` | @fishrock123 | -| `doc/*`, `*.md` | @nodejs/documentation | -| `lib/assert` | @nodejs/testing | -| `lib/async_hooks` | @nodejs/async\_hooks for bugs/reviews (+ @nodejs/diagnostics for API) | -| `lib/buffer` | @nodejs/buffer | -| `lib/child_process` | @bnoordhuis, @cjihrig | -| `lib/cluster` | @bnoordhuis, @cjihrig, @mcollina | -| `lib/{crypto,tls,https}` | @nodejs/crypto | -| `lib/dgram` | @cjihrig, @mcollina | -| `lib/domains` | @misterdjules | -| `lib/fs`, `src/{fs,file}` | @nodejs/fs | -| `lib/{_}http{*}` | @nodejs/http | -| `lib/inspector.js`, `src/inspector_*` | @nodejs/v8-inspector | -| `lib/internal/url`, `src/node_url` | @nodejs/url | -| `lib/net` | @bnoordhuis, @indutny, @nodejs/streams | -| `lib/repl` | @addaleax, @fishrock123 | -| `lib/{_}stream{*}` | @nodejs/streams | -| `lib/timers` | @fishrock123, @misterdjules | -| `lib/util` | @bnoordhuis, @cjihrig, @evanlucas | -| `lib/zlib` | @addaleax, @bnoordhuis, @indutny | -| `src/async-wrap.*` | @nodejs/async\_hooks | -| `src/node_api.*` | @nodejs/n-api | -| `src/node_crypto.*` | @nodejs/crypto | -| `test/*` | @nodejs/testing | -| `tools/eslint`, `.eslintrc` | @not-an-aardvark, @silverwind, @trott | -| build | @nodejs/build | -| ES Modules | @bmeck, @Fishrock123, @guybedford, @MylesBorins, @targos | -| GYP | @nodejs/gyp | -| performance | @nodejs/performance | -| platform specific | @nodejs/platform-{aix,arm,freebsd,macos,ppc,smartos,s390,windows} | -| python code | @nodejs/python | -| upgrading c-ares | @jbergstroem | -| upgrading http-parser | @jbergstroem, @nodejs/http | -| upgrading libuv | @saghul | -| upgrading npm | @fishrock123, @MylesBorins | -| upgrading V8 | @nodejs/v8, @nodejs/post-mortem | +| Subsystem | Maintainers | +| --- | --- | +| `benchmark/*` | @nodejs/benchmarking, @mscdex | +| `bootstrap_node.js` | @fishrock123 | +| `doc/*`, `*.md` | @nodejs/documentation | +| `lib/assert` | @nodejs/testing | +| `lib/async_hooks` | @nodejs/async\_hooks for bugs/reviews (+ @nodejs/diagnostics for API) | +| `lib/buffer` | @nodejs/buffer | +| `lib/child_process` | @bnoordhuis, @cjihrig | +| `lib/cluster` | @bnoordhuis, @cjihrig, @mcollina | +| `lib/{crypto,tls,https}` | @nodejs/crypto | +| `lib/dgram` | @cjihrig, @mcollina | +| `lib/domains` | @misterdjules | +| `lib/fs`, `src/{fs,file}` | @nodejs/fs | +| `lib/{_}http{*}` | @nodejs/http | +| `lib/inspector.js`, `src/inspector_*` | @nodejs/v8-inspector | +| `lib/internal/url`, `src/node_url` | @nodejs/url | +| `lib/net` | @bnoordhuis, @indutny, @nodejs/streams | +| `lib/repl` | @addaleax, @fishrock123 | +| `lib/{_}stream{*}` | @nodejs/streams | +| `lib/timers` | @fishrock123, @misterdjules | +| `lib/util` | @bnoordhuis, @cjihrig, @evanlucas | +| `lib/zlib` | @addaleax, @bnoordhuis, @indutny | +| `src/async-wrap.*` | @nodejs/async\_hooks | +| `src/node_api.*` | @nodejs/n-api | +| `src/node_crypto.*` | @nodejs/crypto | +| `test/*` | @nodejs/testing | +| `tools/node_modules/eslint`, `.eslintrc` | @not-an-aardvark, @silverwind, @trott | +| build | @nodejs/build | +| ES Modules | @bmeck, @Fishrock123, @guybedford, @MylesBorins, @targos | +| GYP | @nodejs/gyp | +| performance | @nodejs/performance | +| platform specific | @nodejs/platform-{aix,arm,freebsd,macos,ppc,smartos,s390,windows} | +| python code | @nodejs/python | +| upgrading c-ares | @jbergstroem | +| upgrading http-parser | @jbergstroem, @nodejs/http | +| upgrading libuv | @saghul | +| upgrading npm | @fishrock123, @MylesBorins | +| upgrading V8 | @nodejs/v8, @nodejs/post-mortem | When things need extra attention, are controversial, or `semver-major`: @nodejs/tsc diff --git a/doc/onboarding.md b/doc/onboarding.md index e67f6638d3a0e4..296f9db7d02ef8 100644 --- a/doc/onboarding.md +++ b/doc/onboarding.md @@ -9,6 +9,8 @@ onboarding session. GitHub account. Unless two-factor authentication is enabled, do not give an account elevated privileges such as the ability to land code in the main repository or to start continuous integration (CI) jobs. +* Announce the accepted nomination in a TSC meeting and in the TSC + mailing list. ## Fifteen minutes before the onboarding session @@ -199,12 +201,13 @@ onboarding session. * Optionally, include your personal pronouns. * Label your pull request with the `doc` subsystem label. * Run CI on your PR. -* After one or two approvals, land the PR. +* After one or two approvals, land the PR (PRs of this type do not need to wait + for 48/72 hours to land). * Be sure to add the `PR-URL: ` and appropriate `Reviewed-By:` - metadata! - * [`core-validate-commit`][] helps a lot with this – install and use it if you - can! - * [`node-core-utils`][] fetches the metadata for you. + metadata. + * [`core-validate-commit`][] automates the validation of commit messages. + * [`node-core-utils`][] automates the generation of metadata and the landing + process. See the documentation of [`git-node`][]. ## Final notes @@ -227,6 +230,7 @@ onboarding session. [Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md [`core-validate-commit`]: https://github.com/evanlucas/core-validate-commit +[`git-node`]: https://github.com/nodejs/node-core-utils#git-node [`node-core-utils`]: https://github.com/nodejs/node-core-utils [Landing Pull Requests]: https://github.com/nodejs/node/blob/master/COLLABORATOR_GUIDE.md#landing-pull-requests [https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0]: https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0 diff --git a/lib/_http_client.js b/lib/_http_client.js index 09925b22791972..2287c2751b8ce6 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -70,7 +70,7 @@ function isInvalidPath(s) { } function validateHost(host, name) { - if (host != null && typeof host !== 'string') { + if (host !== null && host !== undefined && typeof host !== 'string') { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', `options.${name}`, ['string', 'undefined', 'null'], host); } @@ -145,7 +145,7 @@ function ClientRequest(options, cb) { var method = options.method; var methodIsString = (typeof method === 'string'); - if (method != null && !methodIsString) { + if (method !== null && method !== undefined && !methodIsString) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'method', 'string', method); } @@ -452,6 +452,7 @@ function socketOnData(d) { socket.removeListener('data', socketOnData); socket.removeListener('end', socketOnEnd); parser.finish(); + freeParser(parser, req, socket); var bodyHead = d.slice(bytesParsed, d.length); @@ -472,7 +473,6 @@ function socketOnData(d) { // Got Upgrade header or CONNECT method, but have no handler. socket.destroy(); } - freeParser(parser, req, socket); } else if (parser.incoming && parser.incoming.complete && // When the status code is 100 (Continue), the server will // send a final response after this client sends a request @@ -490,7 +490,6 @@ function parserOnIncomingClient(res, shouldKeepAlive) { var socket = this.socket; var req = socket._httpMessage; - // propagate "domain" setting... if (req.domain && !res.domain) { debug('setting "res.domain"'); @@ -503,29 +502,22 @@ function parserOnIncomingClient(res, shouldKeepAlive) { // We already have a response object, this means the server // sent a double response. socket.destroy(); - return; + return 0; // No special treatment. } req.res = res; // Responses to CONNECT request is handled as Upgrade. - if (req.method === 'CONNECT') { + const method = req.method; + if (method === 'CONNECT') { res.upgrade = true; - return 2; // skip body, and the rest + return 2; // Skip body and treat as Upgrade. } - // Responses to HEAD requests are crazy. - // HEAD responses aren't allowed to have an entity-body - // but *can* have a content-length which actually corresponds - // to the content-length of the entity-body had the request - // been a GET. - var isHeadResponse = req.method === 'HEAD'; - debug('AGENT isHeadResponse', isHeadResponse); - if (res.statusCode === 100) { // restart the parser, as this is a continue message. req.res = null; // Clear res so that we don't hit double-responses. req.emit('continue'); - return true; + return 1; // Skip body but don't treat as Upgrade. } if (req.shouldKeepAlive && !shouldKeepAlive && !req.upgradeOrConnect) { @@ -535,7 +527,6 @@ function parserOnIncomingClient(res, shouldKeepAlive) { req.shouldKeepAlive = false; } - DTRACE_HTTP_CLIENT_RESPONSE(socket, req); LTTNG_HTTP_CLIENT_RESPONSE(socket, req); COUNTER_HTTP_CLIENT_RESPONSE(); @@ -553,7 +544,10 @@ function parserOnIncomingClient(res, shouldKeepAlive) { if (!handled) res._dump(); - return isHeadResponse; + if (method === 'HEAD') + return 1; // Skip body but don't treat as Upgrade. + + return 0; // No special treatment. } // client @@ -579,7 +573,7 @@ function responseKeepAlive(res, req) { socket.removeListener('error', socketErrorListener); socket.once('error', freeSocketErrorListener); // There are cases where _handle === null. Avoid those. Passing null to - // nextTick() will call initTriggerId() to retrieve the id. + // nextTick() will call getDefaultTriggerAsyncId() to retrieve the id. const asyncId = socket._handle ? socket._handle.getAsyncId() : null; // Mark this socket as available, AFTER user-added end // handlers have a chance to run. diff --git a/lib/_http_common.js b/lib/_http_common.js index cf37bbebe36197..b4caf5939e5afc 100644 --- a/lib/_http_common.js +++ b/lib/_http_common.js @@ -106,19 +106,10 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, parser.incoming.upgrade = upgrade; - var skipBody = 0; // response to HEAD or CONNECT + if (upgrade) + return 2; // Skip body and treat as Upgrade. - if (!upgrade) { - // For upgraded connections and CONNECT method request, we'll emit this - // after parser.execute so that we can capture the first part of the new - // protocol. - skipBody = parser.onIncoming(parser.incoming, shouldKeepAlive); - } - - if (typeof skipBody !== 'number') - return skipBody ? 1 : 0; - else - return skipBody; + return parser.onIncoming(parser.incoming, shouldKeepAlive); } // XXX This is a mess. @@ -190,6 +181,7 @@ var parsers = new FreeList('parsers', 1000, function() { return parser; }); +function closeParserInstance(parser) { parser.close(); } // Free the parser and also break any links that it // might have to any other things. @@ -212,7 +204,9 @@ function freeParser(parser, req, socket) { parser.outgoing = null; parser[kOnExecute] = null; if (parsers.free(parser) === false) { - parser.close(); + // Make sure the parser's stack has unwound before deleting the + // corresponding C++ object through .close(). + setImmediate(closeParserInstance, parser); } else { // Since the Parser destructor isn't going to run the destroy() callbacks // it needs to be triggered manually. diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 628504b4433158..8fecfc8a8db878 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -38,6 +38,8 @@ const errors = require('internal/errors'); const { CRLF, debug } = common; const { utcDate } = internalHttp; +const kIsCorked = Symbol('isCorked'); + var RE_FIELDS = /^(?:Connection|Transfer-Encoding|Content-Length|Date|Expect|Trailer|Upgrade)$/i; var RE_CONN_VALUES = /(?:^|\W)close|upgrade(?:$|\W)/ig; @@ -99,6 +101,7 @@ function OutgoingMessage() { this.finished = false; this._headerSent = false; + this[kIsCorked] = false; this.socket = null; this.connection = null; @@ -657,9 +660,10 @@ function write_(msg, chunk, encoding, callback, fromEnd) { // signal the user to keep writing. if (chunk.length === 0) return true; - if (!fromEnd && msg.connection && !msg.connection.corked) { + if (!fromEnd && msg.connection && !msg[kIsCorked]) { msg.connection.cork(); - process.nextTick(connectionCorkNT, msg.connection); + msg[kIsCorked] = true; + process.nextTick(connectionCorkNT, msg, msg.connection); } var len, ret; @@ -688,7 +692,8 @@ function writeAfterEndNT(err, callback) { } -function connectionCorkNT(conn) { +function connectionCorkNT(msg, conn) { + msg[kIsCorked] = false; conn.uncork(); } diff --git a/lib/_http_server.js b/lib/_http_server.js index 5857e43d79c787..c60119822a98d5 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -37,6 +37,10 @@ const { } = require('_http_common'); const { OutgoingMessage } = require('_http_outgoing'); const { outHeadersKey, ondrain } = require('internal/http'); +const { + defaultTriggerAsyncIdScope, + getOrSetAsyncId +} = require('internal/async_hooks'); const errors = require('internal/errors'); const Buffer = require('buffer').Buffer; @@ -292,6 +296,12 @@ Server.prototype.setTimeout = function setTimeout(msecs, callback) { function connectionListener(socket) { + defaultTriggerAsyncIdScope( + getOrSetAsyncId(socket), connectionListenerInternal, this, socket + ); +} + +function connectionListenerInternal(server, socket) { debug('SERVER new http connection'); httpSocketSetup(socket); @@ -299,13 +309,13 @@ function connectionListener(socket) { // Ensure that the server property of the socket is correctly set. // See https://github.com/nodejs/node/issues/13435 if (socket.server === null) - socket.server = this; + socket.server = server; // If the user has added a listener to the server, // request, or response, then it's their responsibility. // otherwise, destroy on timeout by default - if (this.timeout && typeof socket.setTimeout === 'function') - socket.setTimeout(this.timeout); + if (server.timeout && typeof socket.setTimeout === 'function') + socket.setTimeout(server.timeout); socket.on('timeout', socketOnTimeout); var parser = parsers.alloc(); @@ -315,8 +325,8 @@ function connectionListener(socket) { parser.incoming = null; // Propagate headers limit from server instance to parser - if (typeof this.maxHeadersCount === 'number') { - parser.maxHeaderPairs = this.maxHeadersCount << 1; + if (typeof server.maxHeadersCount === 'number') { + parser.maxHeaderPairs = server.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList parser.maxHeaderPairs = 2000; @@ -336,8 +346,8 @@ function connectionListener(socket) { outgoingData: 0, keepAliveTimeoutSet: false }; - state.onData = socketOnData.bind(undefined, this, socket, parser, state); - state.onEnd = socketOnEnd.bind(undefined, this, socket, parser, state); + state.onData = socketOnData.bind(undefined, server, socket, parser, state); + state.onEnd = socketOnEnd.bind(undefined, server, socket, parser, state); state.onClose = socketOnClose.bind(undefined, socket, state); state.onDrain = socketOnDrain.bind(undefined, socket, state); socket.on('data', state.onData); @@ -345,7 +355,7 @@ function connectionListener(socket) { socket.on('end', state.onEnd); socket.on('close', state.onClose); socket.on('drain', state.onDrain); - parser.onIncoming = parserOnIncoming.bind(undefined, this, socket, state); + parser.onIncoming = parserOnIncoming.bind(undefined, server, socket, state); // We are consuming socket, so it won't get any actual data socket.on('resume', onSocketResume); @@ -364,7 +374,7 @@ function connectionListener(socket) { } } parser[kOnExecute] = - onParserExecute.bind(undefined, this, socket, parser, state); + onParserExecute.bind(undefined, server, socket, parser, state); socket._paused = false; } @@ -617,7 +627,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) { } else { server.emit('request', req, res); } - return false; // Not a HEAD response. (Not even a response!) + return 0; // No special treatment. } function resetSocketTimeout(server, socket, state) { diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 21598efa65f254..500071203b0f3b 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -652,8 +652,8 @@ Readable.prototype.pipe = function(dest, pipeOpts) { if (((state.pipesCount === 1 && state.pipes === dest) || (state.pipesCount > 1 && state.pipes.indexOf(dest) !== -1)) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; increasedAwaitDrain = true; } src.pause(); diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 549bff1599a911..895563bb39de25 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -283,7 +283,7 @@ Writable.prototype.write = function(chunk, encoding, cb) { if (typeof cb !== 'function') cb = nop; - if (state.ended) + if (state.ending) writeAfterEnd(this, cb); else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; diff --git a/lib/async_hooks.js b/lib/async_hooks.js index 78dff7218c13ea..340863a83c432e 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -19,8 +19,7 @@ const { disableHooks, // Sensitive Embedder API newUid, - initTriggerId, - setInitTriggerId, + getDefaultTriggerAsyncId, emitInit, emitBefore, emitAfter, @@ -152,7 +151,7 @@ class AsyncResource { if (typeof opts === 'number') { opts = { triggerAsyncId: opts, requireManualDestroy: false }; } else if (opts.triggerAsyncId === undefined) { - opts.triggerAsyncId = initTriggerId(); + opts.triggerAsyncId = getDefaultTriggerAsyncId(); } // Unlike emitInitScript, AsyncResource doesn't supports null as the @@ -245,18 +244,11 @@ Object.defineProperty(module.exports, 'newUid', { Object.defineProperty(module.exports, 'initTriggerId', { get: internalUtil.deprecate(function() { - return initTriggerId; + return getDefaultTriggerAsyncId; }, 'async_hooks.initTriggerId is deprecated. ' + 'Use the AsyncResource default instead.', 'DEP0085') }); -Object.defineProperty(module.exports, 'setInitTriggerId', { - get: internalUtil.deprecate(function() { - return setInitTriggerId; - }, 'async_hooks.setInitTriggerId is deprecated. ' + - 'Use the triggerAsyncId parameter in AsyncResource instead.', 'DEP0085') -}); - Object.defineProperty(module.exports, 'emitInit', { get: internalUtil.deprecate(function() { return emitInit; diff --git a/lib/buffer.js b/lib/buffer.js index 2cb1785d45bd11..91b30012ef65d5 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -1204,7 +1204,7 @@ Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { // // An all-bits-one exponent is either a positive or negative infinity, if // the fraction is zero, or NaN when it is non-zero. The standard allows -// both quiet and signalling NaNs but since NaN is a canonical value in +// both quiet and signaling NaNs but since NaN is a canonical value in // JavaScript, we cannot (and do not) distinguish between the two. // // Other exponents are regular numbers and are computed by subtracting the bias diff --git a/lib/dgram.js b/lib/dgram.js index bfd024bfee6c48..cd70dc5be91f0d 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -28,7 +28,7 @@ const dns = require('dns'); const util = require('util'); const { isUint8Array } = require('internal/util/types'); const EventEmitter = require('events'); -const { setInitTriggerId } = require('internal/async_hooks'); +const { defaultTriggerAsyncIdScope } = require('internal/async_hooks'); const { UV_UDP_REUSEADDR } = process.binding('constants').os; const { async_id_symbol } = process.binding('async_wrap'); const { nextTick } = require('internal/process/next_tick'); @@ -448,21 +448,24 @@ Socket.prototype.send = function(buffer, } const afterDns = (ex, ip) => { - doSend(ex, this, ip, list, address, port, callback); + defaultTriggerAsyncIdScope( + this[async_id_symbol], + doSend, + ex, this, ip, list, address, port, callback + ); }; this._handle.lookup(address, afterDns); }; - function doSend(ex, self, ip, list, address, port, callback) { if (ex) { if (typeof callback === 'function') { - callback(ex); + process.nextTick(callback, ex); return; } - self.emit('error', ex); + process.nextTick(() => self.emit('error', ex)); return; } else if (!self._handle) { return; @@ -476,20 +479,18 @@ function doSend(ex, self, ip, list, address, port, callback) { req.callback = callback; req.oncomplete = afterSend; } - // node::SendWrap isn't instantiated and attached to the JS instance of - // SendWrap above until send() is called. So don't set the init trigger id - // until now. - setInitTriggerId(self[async_id_symbol]); + var err = self._handle.send(req, list, list.length, port, ip, !!callback); + if (err && callback) { // don't emit as error, dgram_legacy.js compatibility const ex = exceptionWithHostPort(err, 'send', address, port); - nextTick(self[async_id_symbol], callback, ex); + process.nextTick(callback, ex); } } diff --git a/lib/fs.js b/lib/fs.js index d4988eb649f2e1..b2043d45f40afc 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1110,20 +1110,16 @@ if (constants.O_SYMLINK !== undefined) { }; fs.lchmodSync = function(path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); + const fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); // Prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. - var ret; + let ret; try { ret = fs.fchmodSync(fd, mode); - } catch (err) { - try { - fs.closeSync(fd); - } catch (ignore) {} - throw err; + } finally { + fs.closeSync(fd); } - fs.closeSync(fd); return ret; }; } @@ -1155,13 +1151,25 @@ if (constants.O_SYMLINK !== undefined) { callback(err); return; } - fs.fchown(fd, uid, gid, callback); + // Prefer to return the chown error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchown(fd, uid, gid, function(err) { + fs.close(fd, function(err2) { + callback(err || err2); + }); + }); }); }; fs.lchownSync = function(path, uid, gid) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); - return fs.fchownSync(fd, uid, gid); + const fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); + let ret; + try { + ret = fs.fchownSync(fd, uid, gid); + } finally { + fs.closeSync(fd); + } + return ret; }; } @@ -1997,7 +2005,8 @@ function ReadStream(path, options) { this.flags = options.flags === undefined ? 'r' : options.flags; this.mode = options.mode === undefined ? 0o666 : options.mode; - this.start = options.start; + this.start = typeof this.fd !== 'number' && options.start === undefined ? + 0 : options.start; this.end = options.end; this.autoClose = options.autoClose === undefined ? true : options.autoClose; this.pos = undefined; diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index 46cc1806b94a8d..26da41cacf354a 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -14,20 +14,26 @@ const async_wrap = process.binding('async_wrap'); * kTriggerAsyncId: The trigger_async_id of the resource responsible for * the current execution stack. * kAsyncIdCounter: Incremental counter tracking the next assigned async_id. - * kInitTriggerAsyncId: Written immediately before a resource's constructor + * kDefaultTriggerAsyncId: Written immediately before a resource's constructor * that sets the value of the init()'s triggerAsyncId. The order of * retrieving the triggerAsyncId value is passing directly to the - * constructor -> value set in kInitTriggerAsyncId -> executionAsyncId of + * constructor -> value set in kDefaultTriggerAsyncId -> executionAsyncId of * the current resource. + * + * async_ids_fast_stack is a Float64Array that contains part of the async ID + * stack. Each pushAsyncIds() call adds two doubles to it, and each + * popAsyncIds() call removes two doubles from it. + * It has a fixed size, so if that is exceeded, calls to the native + * side are used instead in pushAsyncIds() and popAsyncIds(). */ -const { async_hook_fields, async_id_fields } = async_wrap; +const { async_id_symbol, async_hook_fields, async_id_fields } = async_wrap; // Store the pair executionAsyncId and triggerAsyncId in a std::stack on // Environment::AsyncHooks::ids_stack_ tracks the resource responsible for the // current execution stack. This is unwound as each resource exits. In the case // of a fatal exception this stack is emptied after calling each hook's after() // callback. -const { pushAsyncIds, popAsyncIds } = async_wrap; -// For performance reasons, only track Proimses when a hook is enabled. +const { pushAsyncIds: pushAsyncIds_, popAsyncIds: popAsyncIds_ } = async_wrap; +// For performance reasons, only track Promises when a hook is enabled. const { enablePromiseHook, disablePromiseHook } = async_wrap; // Properties in active_hooks are used to keep track of the set of hooks being // executed in case another hook is enabled/disabled. The new set of hooks is @@ -60,8 +66,8 @@ const active_hooks = { // async execution. These are tracked so if the user didn't include callbacks // for a given step, that step can bail out early. const { kInit, kBefore, kAfter, kDestroy, kPromiseResolve, - kCheck, kExecutionAsyncId, kAsyncIdCounter, - kInitTriggerAsyncId } = async_wrap.constants; + kCheck, kExecutionAsyncId, kAsyncIdCounter, kTriggerAsyncId, + kDefaultTriggerAsyncId, kStackLength } = async_wrap.constants; // Used in AsyncHook and AsyncResource. const init_symbol = Symbol('init'); @@ -242,25 +248,41 @@ function newUid() { return ++async_id_fields[kAsyncIdCounter]; } +function getOrSetAsyncId(object) { + if (object.hasOwnProperty(async_id_symbol)) { + return object[async_id_symbol]; + } + + return object[async_id_symbol] = newUid(); +} + // Return the triggerAsyncId meant for the constructor calling it. It's up to // the user to safeguard this call and make sure it's zero'd out when the // constructor is complete. -function initTriggerId() { - var triggerAsyncId = async_id_fields[kInitTriggerAsyncId]; - // Reset value after it's been called so the next constructor doesn't - // inherit it by accident. - async_id_fields[kInitTriggerAsyncId] = 0; - if (triggerAsyncId <= 0) - triggerAsyncId = async_id_fields[kExecutionAsyncId]; - return triggerAsyncId; +function getDefaultTriggerAsyncId() { + var defaultTriggerAsyncId = async_id_fields[kDefaultTriggerAsyncId]; + // If defaultTriggerAsyncId isn't set, use the executionAsyncId + if (defaultTriggerAsyncId < 0) + defaultTriggerAsyncId = async_id_fields[kExecutionAsyncId]; + return defaultTriggerAsyncId; } -function setInitTriggerId(triggerAsyncId) { +function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) { // CHECK(Number.isSafeInteger(triggerAsyncId)) // CHECK(triggerAsyncId > 0) - async_id_fields[kInitTriggerAsyncId] = triggerAsyncId; + const oldDefaultTriggerAsyncId = async_id_fields[kDefaultTriggerAsyncId]; + async_id_fields[kDefaultTriggerAsyncId] = triggerAsyncId; + + var ret; + try { + ret = Reflect.apply(block, null, args); + } finally { + async_id_fields[kDefaultTriggerAsyncId] = oldDefaultTriggerAsyncId; + } + + return ret; } @@ -279,13 +301,9 @@ function emitInitScript(asyncId, type, triggerAsyncId, resource) { return; // This can run after the early return check b/c running this function - // manually means that the embedder must have used initTriggerId(). + // manually means that the embedder must have used getDefaultTriggerAsyncId(). if (triggerAsyncId === null) { - triggerAsyncId = initTriggerId(); - } else { - // If a triggerAsyncId was passed, any kInitTriggerAsyncId still must be - // null'd. - async_id_fields[kInitTriggerAsyncId] = 0; + triggerAsyncId = getDefaultTriggerAsyncId(); } emitInitNative(asyncId, type, triggerAsyncId, resource); @@ -326,6 +344,38 @@ function emitDestroyScript(asyncId) { } +// This is the equivalent of the native push_async_ids() call. +function pushAsyncIds(asyncId, triggerAsyncId) { + const offset = async_hook_fields[kStackLength]; + if (offset * 2 >= async_wrap.async_ids_stack.length) + return pushAsyncIds_(asyncId, triggerAsyncId); + async_wrap.async_ids_stack[offset * 2] = async_id_fields[kExecutionAsyncId]; + async_wrap.async_ids_stack[offset * 2 + 1] = async_id_fields[kTriggerAsyncId]; + async_hook_fields[kStackLength]++; + async_id_fields[kExecutionAsyncId] = asyncId; + async_id_fields[kTriggerAsyncId] = triggerAsyncId; +} + + +// This is the equivalent of the native pop_async_ids() call. +function popAsyncIds(asyncId) { + if (async_hook_fields[kStackLength] === 0) return false; + const stackLength = async_hook_fields[kStackLength]; + + if (async_hook_fields[kCheck] > 0 && + async_id_fields[kExecutionAsyncId] !== asyncId) { + // Do the same thing as the native code (i.e. crash hard). + return popAsyncIds_(asyncId); + } + + const offset = stackLength - 1; + async_id_fields[kExecutionAsyncId] = async_wrap.async_ids_stack[2 * offset]; + async_id_fields[kTriggerAsyncId] = async_wrap.async_ids_stack[2 * offset + 1]; + async_hook_fields[kStackLength] = offset; + return offset > 0; +} + + module.exports = { // Private API getHookArrays, @@ -337,8 +387,9 @@ module.exports = { disableHooks, // Sensitive Embedder API newUid, - initTriggerId, - setInitTriggerId, + getOrSetAsyncId, + getDefaultTriggerAsyncId, + defaultTriggerAsyncIdScope, emitInit: emitInitScript, emitBefore: emitBeforeScript, emitAfter: emitAfterScript, diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index 72101cb6408cc9..a6ac7b66afbc0b 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -21,9 +21,6 @@ setupProcessObject(); - internalBinding = process._internalBinding; - delete process._internalBinding; - // do this good and early, since it handles errors. setupProcessFatal(); @@ -245,6 +242,54 @@ perf.markMilestone(NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE); } + const moduleLoadList = []; + Object.defineProperty(process, 'moduleLoadList', { + value: moduleLoadList, + configurable: true, + enumerable: true, + writable: false + }); + + { + const bindingObj = Object.create(null); + + const getBinding = process.binding; + process.binding = function binding(module) { + module = String(module); + let mod = bindingObj[module]; + if (typeof mod !== 'object') { + mod = bindingObj[module] = getBinding(module); + moduleLoadList.push(`Binding ${module}`); + } + return mod; + }; + + const getLinkedBinding = process._linkedBinding; + process._linkedBinding = function _linkedBinding(module) { + module = String(module); + let mod = bindingObj[module]; + if (typeof mod !== 'object') + mod = bindingObj[module] = getLinkedBinding(module); + return mod; + }; + } + + { + const bindingObj = Object.create(null); + + const getInternalBinding = process._internalBinding; + delete process._internalBinding; + + internalBinding = function internalBinding(module) { + let mod = bindingObj[module]; + if (typeof mod !== 'object') { + mod = bindingObj[module] = getInternalBinding(module); + moduleLoadList.push(`Internal Binding ${module}`); + } + return mod; + }; + } + function setupProcessObject() { process._setupProcessObject(pushValueToArray); @@ -366,16 +411,16 @@ // Arrays containing hook flags and ids for async_hook calls. const { async_hook_fields, async_id_fields } = async_wrap; // Internal functions needed to manipulate the stack. - const { clearAsyncIdStack, asyncIdStackSize } = async_wrap; + const { clearAsyncIdStack } = async_wrap; const { kAfter, kExecutionAsyncId, - kInitTriggerAsyncId } = async_wrap.constants; + kDefaultTriggerAsyncId, kStackLength } = async_wrap.constants; process._fatalException = function(er) { var caught; - // It's possible that kInitTriggerAsyncId was set for a constructor call - // that threw and was never cleared. So clear it now. - async_id_fields[kInitTriggerAsyncId] = 0; + // It's possible that kDefaultTriggerAsyncId was set for a constructor + // call that threw and was never cleared. So clear it now. + async_id_fields[kDefaultTriggerAsyncId] = -1; if (exceptionHandlerState.captureFn !== null) { exceptionHandlerState.captureFn(er); @@ -406,7 +451,7 @@ do { NativeModule.require('internal/async_hooks').emitAfter( async_id_fields[kExecutionAsyncId]); - } while (asyncIdStackSize() > 0); + } while (async_hook_fields[kStackLength] > 0); // Or completely empty the id stack. } else { clearAsyncIdStack(); @@ -542,7 +587,7 @@ throw err; } - process.moduleLoadList.push(`NativeModule ${id}`); + moduleLoadList.push(`NativeModule ${id}`); const nativeModule = new NativeModule(id); diff --git a/lib/internal/cluster/child.js b/lib/internal/cluster/child.js index 98c5e7b5597f74..40c1a12327558f 100644 --- a/lib/internal/cluster/child.js +++ b/lib/internal/cluster/child.js @@ -1,6 +1,7 @@ 'use strict'; const assert = require('assert'); const util = require('util'); +const path = require('path'); const EventEmitter = require('events'); const Worker = require('internal/cluster/worker'); const { internal, sendHelper } = require('internal/cluster/utils'); @@ -48,7 +49,14 @@ cluster._setupWorker = function() { // obj is a net#Server or a dgram#Socket object. cluster._getServer = function(obj, options, cb) { - const indexesKey = [options.address, + let address = options.address; + + // Resolve unix socket paths to absolute paths + if (options.port < 0 && typeof address === 'string' && + process.platform !== 'win32') + address = path.resolve(address); + + const indexesKey = [address, options.port, options.addressType, options.fd ].join(':'); @@ -64,6 +72,8 @@ cluster._getServer = function(obj, options, cb) { data: null }, options); + message.address = address; + // Set custom data on handle (i.e. tls tickets key) if (obj._getServerData) message.data = obj._getServerData(); diff --git a/lib/internal/cluster/master.js b/lib/internal/cluster/master.js index 408b31c2b77805..570cf7bc6f93d4 100644 --- a/lib/internal/cluster/master.js +++ b/lib/internal/cluster/master.js @@ -2,6 +2,7 @@ const assert = require('assert'); const { fork } = require('child_process'); const util = require('util'); +const path = require('path'); const EventEmitter = require('events'); const RoundRobinHandle = require('internal/cluster/round_robin_handle'); const SharedHandle = require('internal/cluster/shared_handle'); @@ -125,6 +126,7 @@ function createWorkerProcess(id, env) { } return fork(cluster.settings.exec, cluster.settings.args, { + cwd: cluster.settings.cwd, env: workerEnv, silent: cluster.settings.silent, windowsHide: cluster.settings.windowsHide, @@ -276,6 +278,18 @@ function queryServer(worker, message) { var handle = handles[key]; if (handle === undefined) { + let address = message.address; + + // Find shortest path for unix sockets because of the ~100 byte limit + if (message.port < 0 && typeof address === 'string' && + process.platform !== 'win32') { + + address = path.relative(process.cwd(), address); + + if (message.address.length < address.length) + address = message.address; + } + var constructor = RoundRobinHandle; // UDP is exempt from round-robin connection balancing for what should // be obvious reasons: it's connectionless. There is nothing to send to @@ -287,7 +301,7 @@ function queryServer(worker, message) { } handles[key] = handle = new constructor(key, - message.address, + address, message.port, message.addressType, message.fd, diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 807e8e76909b76..70569fd8439611 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -316,10 +316,15 @@ E('ERR_MODULE_RESOLUTION_LEGACY', '%s not found by import in %s.' + E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function'); E('ERR_NAPI_CONS_PROTOTYPE_OBJECT', 'Constructor.prototype must be an object'); +E('ERR_NAPI_INVALID_DATAVIEW_ARGS', + 'byte_offset + byte_length should be less than or eqaul to the size in ' + + 'bytes of the array passed in'); +E('ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT', 'start offset of %s should be a ' + + 'multiple of %s'); +E('ERR_NAPI_INVALID_TYPEDARRAY_LENGTH', 'Invalid typed array length'); E('ERR_NO_CRYPTO', 'Node.js is not compiled with OpenSSL crypto support'); E('ERR_NO_ICU', '%s is not supported on Node.js compiled without ICU'); E('ERR_NO_LONGER_SUPPORTED', '%s is no longer supported'); -E('ERR_OUTOFMEMORY', 'Out of memory'); E('ERR_OUT_OF_RANGE', 'The "%s" argument is out of range'); E('ERR_PARSE_HISTORY_DATA', 'Could not parse history data in %s'); E('ERR_REQUIRE_ESM', 'Must use import to load ES Module: %s'); diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index e818085afb763a..aade7e83be3511 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -74,6 +74,7 @@ const kEncrypted = Symbol('encrypted'); const kHandle = Symbol('handle'); const kID = Symbol('id'); const kInit = Symbol('init'); +const kInfoHeaders = Symbol('sent-info-headers'); const kMaybeDestroy = Symbol('maybe-destroy'); const kLocalSettings = Symbol('local-settings'); const kOptions = Symbol('options'); @@ -82,6 +83,8 @@ const kProceed = Symbol('proceed'); const kProtocol = Symbol('protocol'); const kProxySocket = Symbol('proxy-socket'); const kRemoteSettings = Symbol('remote-settings'); +const kSentHeaders = Symbol('sent-headers'); +const kSentTrailers = Symbol('sent-trailers'); const kServer = Symbol('server'); const kSession = Symbol('session'); const kState = Symbol('state'); @@ -256,6 +259,7 @@ function onStreamTrailers() { stream.destroy(headersList); return []; } + stream[kSentTrailers] = trailers; return headersList; } @@ -273,7 +277,7 @@ function submitRstStream(code) { // point, close them. If there is an open fd for file send, close that also. // At this point the underlying node::http2:Http2Stream handle is no // longer usable so destroy it also. -function onStreamClose(code, hasData) { +function onStreamClose(code) { const stream = this[kOwner]; if (stream.destroyed) return; @@ -281,8 +285,7 @@ function onStreamClose(code, hasData) { const state = stream[kState]; debug(`Http2Stream ${stream[kID]} [Http2Session ` + - `${sessionName(stream[kSession][kType])}]: closed with code ${code}` + - ` [has data? ${hasData}]`); + `${sessionName(stream[kSession][kType])}]: closed with code ${code}`); if (!stream.closed) { // Unenroll from timeouts @@ -300,13 +303,14 @@ function onStreamClose(code, hasData) { if (state.fd !== undefined) tryClose(state.fd); - stream[kMaybeDestroy](null, code, hasData); + stream.push(null); + stream[kMaybeDestroy](null, code); } // Receives a chunk of data for a given stream and forwards it on // to the Http2Stream Duplex for processing. -function onStreamRead(nread, buf, handle) { - const stream = handle[kOwner]; +function onStreamRead(nread, buf) { + const stream = this[kOwner]; if (nread >= 0 && !stream.destroyed) { debug(`Http2Stream ${stream[kID]} [Http2Session ` + `${sessionName(stream[kSession][kType])}]: receiving data chunk ` + @@ -314,7 +318,7 @@ function onStreamRead(nread, buf, handle) { stream[kUpdateTimer](); if (!stream.push(buf)) { if (!stream.destroyed) // we have to check a second time - handle.readStop(); + this.readStop(); } return; } @@ -1344,6 +1348,7 @@ class ClientHttp2Session extends Http2Session { throw headersList; const stream = new ClientHttp2Stream(this, undefined, undefined, {}); + stream[kSentHeaders] = headers; // Close the writable side of the stream if options.endStream is set. if (options.endStream) @@ -1422,13 +1427,8 @@ function streamOnResume() { } function streamOnPause() { - // if (!this.destroyed && !this.pending) - // this[kHandle].readStop(); -} - -function handleFlushData(self) { if (!this.destroyed && !this.pending) - this[kHandle].flushData(); + this[kHandle].readStop(); } // If the writable side of the Http2Stream is still open, emit the @@ -1507,6 +1507,18 @@ class Http2Stream extends Duplex { return `Http2Stream ${util.format(obj)}`; } + get sentHeaders() { + return this[kSentHeaders]; + } + + get sentTrailers() { + return this[kSentTrailers]; + } + + get sentInfoHeaders() { + return this[kInfoHeaders]; + } + get pending() { return this[kID] === undefined; } @@ -1549,7 +1561,7 @@ class Http2Stream extends Duplex { return !!(this[kState].flags & STREAM_FLAGS_HEADERS_SENT); } - // true if the Http2Stream was aborted abornomally. + // true if the Http2Stream was aborted abnormally. get aborted() { return !!(this[kState].flags & STREAM_FLAGS_ABORTED); } @@ -1662,11 +1674,10 @@ class Http2Stream extends Duplex { this.push(null); return; } - const flushfn = handleFlushData.bind(this); if (!this.pending) { - flushfn(); + streamOnResume.call(this); } else { - this.once('ready', flushfn); + this.once('ready', streamOnResume); } } @@ -1805,10 +1816,10 @@ class Http2Stream extends Duplex { // The Http2Stream can be destroyed if it has closed and if the readable // side has received the final chunk. - [kMaybeDestroy](error, code = NGHTTP2_NO_ERROR, hasData = true) { + [kMaybeDestroy](error, code = NGHTTP2_NO_ERROR) { if (error == null) { if (code === NGHTTP2_NO_ERROR && - ((!this._readableState.ended && hasData) || + (!this._readableState.ended || !this._writableState.ended || this._writableState.pendingcb > 0 || !this.closed)) { @@ -1846,6 +1857,7 @@ function processRespondWithFD(self, fd, headers, offset = 0, length = -1, state.flags |= STREAM_FLAGS_HEADERS_SENT; const headersList = mapToHeaders(headers, assertValidPseudoHeaderResponse); + self[kSentHeaders] = headers; if (!Array.isArray(headersList)) { self.destroy(headersList); return; @@ -2076,6 +2088,7 @@ class ServerHttp2Stream extends Http2Stream { const id = ret.id(); const stream = new ServerHttp2Stream(session, ret, id, options, headers); + stream[kSentHeaders] = headers; if (options.endStream) stream.end(); @@ -2135,6 +2148,7 @@ class ServerHttp2Stream extends Http2Stream { const headersList = mapToHeaders(headers, assertValidPseudoHeaderResponse); if (!Array.isArray(headersList)) throw headersList; + this[kSentHeaders] = headers; state.flags |= STREAM_FLAGS_HEADERS_SENT; @@ -2320,6 +2334,10 @@ class ServerHttp2Stream extends Http2Stream { const headersList = mapToHeaders(headers, assertValidPseudoHeaderResponse); if (!Array.isArray(headersList)) throw headersList; + if (!this[kInfoHeaders]) + this[kInfoHeaders] = [headers]; + else + this[kInfoHeaders].push(headers); const ret = this[kHandle].info(headersList); if (ret < 0) @@ -2380,7 +2398,7 @@ Object.defineProperty(Http2Session.prototype, 'setTimeout', setTimeout); // When the socket emits an error, destroy the associated Http2Session and -// foward it the same error. +// forward it the same error. function socketOnError(error) { const session = this[kSession]; if (session !== undefined) { diff --git a/lib/internal/process.js b/lib/internal/process.js index e58b83d21631ff..757c8de8e685f1 100644 --- a/lib/internal/process.js +++ b/lib/internal/process.js @@ -178,24 +178,23 @@ function setupKillAndExit() { function setupSignalHandlers() { - // Load events module in order to access prototype elements on process like - // process.addListener. - const signalWraps = {}; + const signalWraps = Object.create(null); + let Signal; function isSignal(event) { return typeof event === 'string' && constants[event] !== undefined; } // Detect presence of a listener for the special signal types - process.on('newListener', function(type, listener) { - if (isSignal(type) && - !signalWraps.hasOwnProperty(type)) { - const Signal = process.binding('signal_wrap').Signal; + process.on('newListener', function(type) { + if (isSignal(type) && signalWraps[type] === undefined) { + if (Signal === undefined) + Signal = process.binding('signal_wrap').Signal; const wrap = new Signal(); wrap.unref(); - wrap.onsignal = function() { process.emit(type, type); }; + wrap.onsignal = process.emit.bind(process, type, type); const signum = constants[type]; const err = wrap.start(signum); @@ -208,8 +207,8 @@ function setupSignalHandlers() { } }); - process.on('removeListener', function(type, listener) { - if (signalWraps.hasOwnProperty(type) && this.listenerCount(type) === 0) { + process.on('removeListener', function(type) { + if (signalWraps[type] !== undefined && this.listenerCount(type) === 0) { signalWraps[type].close(); delete signalWraps[type]; } @@ -227,14 +226,7 @@ function setupChannel() { // Make sure it's not accidentally inherited by child processes. delete process.env.NODE_CHANNEL_FD; - const cp = require('child_process'); - - // Load tcp_wrap to avoid situation where we might immediately receive - // a message. - // FIXME is this really necessary? - process.binding('tcp_wrap'); - - cp._forkChild(fd); + require('child_process')._forkChild(fd); assert(process.send); } } diff --git a/lib/internal/process/next_tick.js b/lib/internal/process/next_tick.js index 260aa70b431b86..bf7d0bc94dc4ce 100644 --- a/lib/internal/process/next_tick.js +++ b/lib/internal/process/next_tick.js @@ -48,7 +48,7 @@ function setupNextTick() { const promises = require('internal/process/promises'); const errors = require('internal/errors'); const emitPendingUnhandledRejections = promises.setup(scheduleMicrotasks); - const initTriggerId = async_hooks.initTriggerId; + const getDefaultTriggerAsyncId = async_hooks.getDefaultTriggerAsyncId; // Two arrays that share state between C++ and JS. const { async_hook_fields, async_id_fields } = async_wrap; // Used to change the state of the async id stack. @@ -210,7 +210,7 @@ function setupNextTick() { nextTickQueue.push(new TickObject(callback, args, ++async_id_fields[kAsyncIdCounter], - initTriggerId())); + getDefaultTriggerAsyncId())); } // `internalNextTick()` will not enqueue any callback when the process is @@ -237,7 +237,7 @@ function setupNextTick() { } if (triggerAsyncId === null) - triggerAsyncId = initTriggerId(); + triggerAsyncId = getDefaultTriggerAsyncId(); // In V8 6.2, moving tickInfo & async_id_fields[kAsyncIdCounter] into the // TickObject incurs a significant performance penalty in the // next-tick-breadth-args benchmark (revisit later) diff --git a/lib/internal/streams/BufferList.js b/lib/internal/streams/BufferList.js index 23d5a8a2db0eb7..b2daf82e74190b 100644 --- a/lib/internal/streams/BufferList.js +++ b/lib/internal/streams/BufferList.js @@ -61,8 +61,6 @@ module.exports = class BufferList { concat(n) { if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) - return this.head.data; const ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; diff --git a/lib/internal/trace_events_async_hooks.js b/lib/internal/trace_events_async_hooks.js index 6d996b083fb49b..704da98e14412b 100644 --- a/lib/internal/trace_events_async_hooks.js +++ b/lib/internal/trace_events_async_hooks.js @@ -4,7 +4,7 @@ const trace_events = process.binding('trace_events'); const async_wrap = process.binding('async_wrap'); const async_hooks = require('async_hooks'); -// Use small letters such that chrome://traceing groups by the name. +// Use small letters such that chrome://tracing groups by the name. // The behavior is not only useful but the same as the events emitted using // the specific C++ macros. const BEFORE_EVENT = 'b'.charCodeAt(0); diff --git a/lib/internal/url.js b/lib/internal/url.js index caa4c3d0283a3e..b395e77b046f10 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -6,7 +6,7 @@ const { isHexTable } = require('internal/querystring'); -const { getConstructorOf } = require('internal/util'); +const { getConstructorOf, removeColors } = require('internal/util'); const errors = require('internal/errors'); const querystring = require('querystring'); @@ -181,9 +181,8 @@ class URLSearchParams { for (var i = 0; i < list.length; i += 2) output.push(`${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`); - var colorRe = /\u001b\[\d\d?m/g; var length = output.reduce( - (prev, cur) => prev + cur.replace(colorRe, '').length + separator.length, + (prev, cur) => prev + removeColors(cur).length + separator.length, -separator.length ); if (length > ctx.breakLength) { diff --git a/lib/internal/util.js b/lib/internal/util.js index 9f32785fbbfe53..e4d184e117175e 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -12,6 +12,12 @@ const noCrypto = !process.versions.openssl; const experimentalWarnings = new Set(); +const colorRegExp = /\u001b\[\d\d?m/g; + +function removeColors(str) { + return str.replace(colorRegExp, ''); +} + function isError(e) { return objectToString(e) === '[object Error]' || e instanceof Error; } @@ -297,6 +303,7 @@ module.exports = { objectToString, promisify, spliceOne, + removeColors, // Symbol used to customize promisify conversion customPromisifyArgs: kCustomPromisifyArgsSymbol, diff --git a/lib/internal/wrap_js_stream.js b/lib/internal/wrap_js_stream.js index 611095655b5a65..1c494e57e1f9dd 100644 --- a/lib/internal/wrap_js_stream.js +++ b/lib/internal/wrap_js_stream.js @@ -8,6 +8,15 @@ const uv = process.binding('uv'); const debug = util.debuglog('stream_wrap'); const errors = require('internal/errors'); +const kCurrentWriteRequest = Symbol('kCurrentWriteRequest'); +const kCurrentShutdownRequest = Symbol('kCurrentShutdownRequest'); + +function isClosing() { return this.owner.isClosing(); } +function onreadstart() { return this.owner.readStart(); } +function onreadstop() { return this.owner.readStop(); } +function onshutdown(req) { return this.owner.doShutdown(req); } +function onwrite(req, bufs) { return this.owner.doWrite(req, bufs); } + /* This class serves as a wrapper for when the C++ side of Node wants access * to a standard JS stream. For example, TLS or HTTP do not operate on network * resources conceptually, although that is the common case and what we are @@ -27,12 +36,13 @@ class JSStreamWrap extends Socket { debug('close'); this.doClose(cb); }; - handle.isAlive = () => this.isAlive(); - handle.isClosing = () => this.isClosing(); - handle.onreadstart = () => this.readStart(); - handle.onreadstop = () => this.readStop(); - handle.onshutdown = (req) => this.doShutdown(req); - handle.onwrite = (req, bufs) => this.doWrite(req, bufs); + // Inside of the following functions, `this` refers to the handle + // and `this.owner` refers to this JSStreamWrap instance. + handle.isClosing = isClosing; + handle.onreadstart = onreadstart; + handle.onreadstop = onreadstop; + handle.onshutdown = onshutdown; + handle.onwrite = onwrite; stream.pause(); stream.on('error', (err) => this.emit('error', err)); @@ -60,7 +70,10 @@ class JSStreamWrap extends Socket { super({ handle, manualStart: true }); this.stream = stream; - this._list = null; + this[kCurrentWriteRequest] = null; + this[kCurrentShutdownRequest] = null; + + // Start reading. this.read(0); } @@ -69,10 +82,6 @@ class JSStreamWrap extends Socket { return JSStreamWrap; } - isAlive() { - return true; - } - isClosing() { return !this.readable || !this.writable; } @@ -88,33 +97,56 @@ class JSStreamWrap extends Socket { } doShutdown(req) { + assert.strictEqual(this[kCurrentShutdownRequest], null); + this[kCurrentShutdownRequest] = req; + + // TODO(addaleax): It might be nice if we could get into a state where + // DoShutdown() is not called on streams while a write is still pending. + // + // Currently, the only part of the code base where that happens is the + // TLS implementation, which calls both DoWrite() and DoShutdown() on the + // underlying network stream inside of its own DoShutdown() method. + // Working around that on the native side is not quite trivial (yet?), + // so for now that is supported here. + + if (this[kCurrentWriteRequest] !== null) + return this.on('drain', () => this.doShutdown(req)); + assert.strictEqual(this[kCurrentWriteRequest], null); + const handle = this._handle; - const item = this._enqueue('shutdown', req); this.stream.end(() => { // Ensure that write was dispatched setImmediate(() => { - if (!this._dequeue(item)) - return; - - handle.finishShutdown(req, 0); + this.finishShutdown(handle, 0); }); }); return 0; } + // handle === this._handle except when called from doClose(). + finishShutdown(handle, errCode) { + // The shutdown request might already have been cancelled. + if (this[kCurrentShutdownRequest] === null) + return; + const req = this[kCurrentShutdownRequest]; + this[kCurrentShutdownRequest] = null; + handle.finishShutdown(req, errCode); + } + doWrite(req, bufs) { - const self = this; - const handle = this._handle; + assert.strictEqual(this[kCurrentWriteRequest], null); + assert.strictEqual(this[kCurrentShutdownRequest], null); + this[kCurrentWriteRequest] = req; - var pending = bufs.length; + const handle = this._handle; + const self = this; - // Queue the request to be able to cancel it - const item = this._enqueue('write', req); + let pending = bufs.length; this.stream.cork(); - for (var n = 0; n < bufs.length; n++) - this.stream.write(bufs[n], done); + for (var i = 0; i < bufs.length; ++i) + this.stream.write(bufs[i], done); this.stream.uncork(); function done(err) { @@ -126,93 +158,42 @@ class JSStreamWrap extends Socket { let errCode = 0; if (err) { - const code = uv[`UV_${err.code}`]; - errCode = (err.code && code) ? code : uv.UV_EPIPE; + errCode = uv[`UV_${err.code}`] || uv.UV_EPIPE; } // Ensure that write was dispatched - setImmediate(function() { - // Do not invoke callback twice - if (!self._dequeue(item)) - return; - - handle.finishWrite(req, errCode); + setImmediate(() => { + self.finishWrite(handle, errCode); }); } return 0; } - _enqueue(type, req) { - const item = new QueueItem(type, req); - if (this._list === null) { - this._list = item; - return item; - } - - item.next = this._list.next; - item.prev = this._list; - item.next.prev = item; - item.prev.next = item; - - return item; - } - - _dequeue(item) { - assert(item instanceof QueueItem); - - var next = item.next; - var prev = item.prev; - - if (next === null && prev === null) - return false; - - item.next = null; - item.prev = null; - - if (next === item) { - prev = null; - next = null; - } else { - prev.next = next; - next.prev = prev; - } - - if (this._list === item) - this._list = next; + // handle === this._handle except when called from doClose(). + finishWrite(handle, errCode) { + // The write request might already have been cancelled. + if (this[kCurrentWriteRequest] === null) + return; + const req = this[kCurrentWriteRequest]; + this[kCurrentWriteRequest] = null; - return true; + handle.finishWrite(req, errCode); } doClose(cb) { const handle = this._handle; setImmediate(() => { - while (this._list !== null) { - const item = this._list; - const req = item.req; - this._dequeue(item); - - const errCode = uv.UV_ECANCELED; - if (item.type === 'write') { - handle.finishWrite(req, errCode); - } else if (item.type === 'shutdown') { - handle.finishShutdown(req, errCode); - } - } - // Should be already set by net.js assert.strictEqual(this._handle, null); + + this.finishWrite(handle, uv.UV_ECANCELED); + this.finishShutdown(handle, uv.UV_ECANCELED); + cb(); }); } } -function QueueItem(type, req) { - this.type = type; - this.req = req; - this.prev = this; - this.next = this; -} - module.exports = JSStreamWrap; diff --git a/lib/net.js b/lib/net.js index 540de753641e88..886365092c05a6 100644 --- a/lib/net.js +++ b/lib/net.js @@ -43,7 +43,7 @@ const { TCPConnectWrap } = process.binding('tcp_wrap'); const { PipeConnectWrap } = process.binding('pipe_wrap'); const { ShutdownWrap, WriteWrap } = process.binding('stream_wrap'); const { async_id_symbol } = process.binding('async_wrap'); -const { newUid, setInitTriggerId } = require('internal/async_hooks'); +const { newUid, defaultTriggerAsyncIdScope } = require('internal/async_hooks'); const { nextTick } = require('internal/process/next_tick'); const errors = require('internal/errors'); const dns = require('dns'); @@ -274,6 +274,14 @@ Socket.prototype._unrefTimer = function _unrefTimer() { timers._unrefActive(s); }; + +function shutdownSocket(self, callback) { + var req = new ShutdownWrap(); + req.oncomplete = callback; + req.handle = self._handle; + return self._handle.shutdown(req); +} + // the user has called .end(), and all the bytes have been // sent out to the other side. function onSocketFinish() { @@ -295,14 +303,9 @@ function onSocketFinish() { if (!this._handle || !this._handle.shutdown) return this.destroy(); - var req = new ShutdownWrap(); - req.oncomplete = afterShutdown; - req.handle = this._handle; - // node::ShutdownWrap isn't instantiated and attached to the JS instance of - // ShutdownWrap above until shutdown() is called. So don't set the init - // trigger id until now. - setInitTriggerId(this[async_id_symbol]); - var err = this._handle.shutdown(req); + var err = defaultTriggerAsyncIdScope( + this[async_id_symbol], shutdownSocket, this, afterShutdown + ); if (err) return this.destroy(errnoException(err, 'shutdown')); @@ -936,23 +939,15 @@ function internalConnect( req.localAddress = localAddress; req.localPort = localPort; - // node::TCPConnectWrap isn't instantiated and attached to the JS instance - // of TCPConnectWrap above until connect() is called. So don't set the init - // trigger id until now. - setInitTriggerId(self[async_id_symbol]); if (addressType === 4) err = self._handle.connect(req, address, port); else err = self._handle.connect6(req, address, port); - } else { const req = new PipeConnectWrap(); req.address = address; req.oncomplete = afterConnect; - // node::PipeConnectWrap isn't instantiated and attached to the JS instance - // of PipeConnectWrap above until connect() is called. So don't set the - // init trigger id until now. - setInitTriggerId(self[async_id_symbol]); + err = self._handle.connect(req, address, afterConnect); } @@ -1021,7 +1016,9 @@ Socket.prototype.connect = function(...args) { 'string', path); } - internalConnect(this, path); + defaultTriggerAsyncIdScope( + this[async_id_symbol], internalConnect, this, path + ); } else { lookupAndConnect(this, options); } @@ -1064,7 +1061,11 @@ function lookupAndConnect(self, options) { if (addressType) { nextTick(self[async_id_symbol], function() { if (self.connecting) - internalConnect(self, host, port, addressType, localAddress, localPort); + defaultTriggerAsyncIdScope( + self[async_id_symbol], + internalConnect, + self, host, port, addressType, localAddress, localPort + ); }); return; } @@ -1091,33 +1092,33 @@ function lookupAndConnect(self, options) { debug('connect: dns options', dnsopts); self._host = host; var lookup = options.lookup || dns.lookup; - setInitTriggerId(self[async_id_symbol]); - lookup(host, dnsopts, function emitLookup(err, ip, addressType) { - self.emit('lookup', err, ip, addressType, host); + defaultTriggerAsyncIdScope(self[async_id_symbol], function() { + lookup(host, dnsopts, function emitLookup(err, ip, addressType) { + self.emit('lookup', err, ip, addressType, host); - // It's possible we were destroyed while looking this up. - // XXX it would be great if we could cancel the promise returned by - // the look up. - if (!self.connecting) return; + // It's possible we were destroyed while looking this up. + // XXX it would be great if we could cancel the promise returned by + // the look up. + if (!self.connecting) return; - if (err) { - // net.createConnection() creates a net.Socket object and - // immediately calls net.Socket.connect() on it (that's us). - // There are no event listeners registered yet so defer the - // error event to the next tick. - err.host = options.host; - err.port = options.port; - err.message = err.message + ' ' + options.host + ':' + options.port; - process.nextTick(connectErrorNT, self, err); - } else { - self._unrefTimer(); - internalConnect(self, - ip, - port, - addressType, - localAddress, - localPort); - } + if (err) { + // net.createConnection() creates a net.Socket object and + // immediately calls net.Socket.connect() on it (that's us). + // There are no event listeners registered yet so defer the + // error event to the next tick. + err.host = options.host; + err.port = options.port; + err.message = err.message + ' ' + options.host + ':' + options.port; + process.nextTick(connectErrorNT, self, err); + } else { + self._unrefTimer(); + defaultTriggerAsyncIdScope( + self[async_id_symbol], + internalConnect, + self, ip, port, addressType, localAddress, localPort + ); + } + }); }); } diff --git a/lib/path.js b/lib/path.js index e9f76bce9973c5..eca4fcb9d21718 100644 --- a/lib/path.js +++ b/lib/path.js @@ -51,19 +51,14 @@ function normalizeStringWin32(path, allowAboveRoot) { res.charCodeAt(res.length - 1) !== 46/*.*/ || res.charCodeAt(res.length - 2) !== 46/*.*/) { if (res.length > 2) { - const start = res.length - 1; - var j = start; - for (; j >= 0; --j) { - if (res.charCodeAt(j) === 92/*\*/) - break; - } - if (j !== start) { - if (j === -1) { + const lastSlashIndex = res.lastIndexOf('\\'); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { res = ''; lastSegmentLength = 0; } else { - res = res.slice(0, j); - lastSegmentLength = j; + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf('\\'); } lastSlash = i; dots = 0; @@ -124,19 +119,14 @@ function normalizeStringPosix(path, allowAboveRoot) { res.charCodeAt(res.length - 1) !== 46/*.*/ || res.charCodeAt(res.length - 2) !== 46/*.*/) { if (res.length > 2) { - const start = res.length - 1; - var j = start; - for (; j >= 0; --j) { - if (res.charCodeAt(j) === 47/*/*/) - break; - } - if (j !== start) { - if (j === -1) { + const lastSlashIndex = res.lastIndexOf('/'); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { res = ''; lastSegmentLength = 0; } else { - res = res.slice(0, j); - lastSegmentLength = j; + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf('/'); } lastSlash = i; dots = 0; diff --git a/lib/perf_hooks.js b/lib/perf_hooks.js index 4a05f7ccba7bc8..15256a63c0b97c 100644 --- a/lib/perf_hooks.js +++ b/lib/perf_hooks.js @@ -471,6 +471,10 @@ class Performance extends PerformanceObserverEntryList { this[kClearEntry]('function', name); } + clearEntries(name) { + this[kClearEntry](name); + } + timerify(fn) { if (typeof fn !== 'function') { const errors = lazyErrors(); diff --git a/lib/readline.js b/lib/readline.js index 9b9a054fd66fb7..bca9c25ab2348b 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -760,7 +760,8 @@ Interface.prototype._ttyWrite = function(s, key) { key = key || {}; this._previousKey = key; - // Ignore escape key - Fixes #2876 + // Ignore escape key, fixes + // https://github.com/nodejs/node-v0.x-archive/issues/2876. if (key.name === 'escape') return; if (key.ctrl && key.shift) { diff --git a/lib/timers.js b/lib/timers.js index 1560215fe0ad5d..d637ca91ae48e9 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -34,7 +34,7 @@ const kOnTimeout = TimerWrap.kOnTimeout | 0; // Two arrays that share state between C++ and JS. const { async_hook_fields, async_id_fields } = async_wrap; const { - initTriggerId, + getDefaultTriggerAsyncId, // The needed emit*() functions. emitInit, emitBefore, @@ -181,7 +181,7 @@ function insert(item, unrefed) { if (!item[async_id_symbol] || item._destroyed) { item._destroyed = false; item[async_id_symbol] = ++async_id_fields[kAsyncIdCounter]; - item[trigger_async_id_symbol] = initTriggerId(); + item[trigger_async_id_symbol] = getDefaultTriggerAsyncId(); if (async_hook_fields[kInit] > 0) { emitInit(item[async_id_symbol], 'Timeout', @@ -207,11 +207,11 @@ function TimersList(msecs, unrefed) { if (unrefed === true) timer.unref(); timer.start(msecs); - - timer[kOnTimeout] = listOnTimeout; } -function listOnTimeout() { +// adds listOnTimeout to the C++ object prototype, as +// V8 would not inline it otherwise. +TimerWrap.prototype[kOnTimeout] = function listOnTimeout() { var list = this._list; var msecs = list.msecs; @@ -280,7 +280,7 @@ function listOnTimeout() { return; this.close(); -} +}; // An optimization so that the try/finally only de-optimizes (since at least v8 @@ -552,7 +552,7 @@ function Timeout(callback, after, args, isRepeat) { this._destroyed = false; this[async_id_symbol] = ++async_id_fields[kAsyncIdCounter]; - this[trigger_async_id_symbol] = initTriggerId(); + this[trigger_async_id_symbol] = getDefaultTriggerAsyncId(); if (async_hook_fields[kInit] > 0) { emitInit(this[async_id_symbol], 'Timeout', @@ -769,7 +769,7 @@ function Immediate(callback, args) { this._destroyed = false; this[async_id_symbol] = ++async_id_fields[kAsyncIdCounter]; - this[trigger_async_id_symbol] = initTriggerId(); + this[trigger_async_id_symbol] = getDefaultTriggerAsyncId(); if (async_hook_fields[kInit] > 0) { emitInit(this[async_id_symbol], 'Immediate', diff --git a/lib/util.js b/lib/util.js index 27a9d983c6cc47..68ef730759bb06 100644 --- a/lib/util.js +++ b/lib/util.js @@ -58,7 +58,8 @@ const { getConstructorOf, isError, promisify, - join + join, + removeColors } = require('internal/util'); const inspectDefaultOptions = Object.seal({ @@ -84,7 +85,6 @@ const strEscapeSequencesRegExp = /[\x00-\x1f\x27\x5c]/; const strEscapeSequencesReplacer = /[\x00-\x1f\x27\x5c]/g; /* eslint-enable */ const keyStrRegExp = /^[a-zA-Z_][a-zA-Z_0-9]*$/; -const colorRegExp = /\u001b\[\d\d?m/g; const numberRegExp = /^(0|[1-9][0-9]*)$/; // Escaped special characters. Use empty strings to fill up unused entries. @@ -843,7 +843,7 @@ function reduceToSingleString(ctx, output, base, braces, addLn) { var length = 0; for (var i = 0; i < output.length && length <= breakLength; i++) { if (ctx.colors) { - length += output[i].replace(colorRegExp, '').length + 1; + length += removeColors(output[i]).length + 1; } else { length += output[i].length + 1; } diff --git a/node.gyp b/node.gyp index 46796d01fd800f..ca5eb730129224 100644 --- a/node.gyp +++ b/node.gyp @@ -22,6 +22,8 @@ 'node_v8_options%': '', 'node_enable_v8_vtunejit%': 'false', 'node_core_target_name%': 'node', + 'node_lib_target_name%': 'node_lib', + 'node_intermediate_lib_type%': 'static_library', 'library_files': [ 'lib/internal/bootstrap_node.js', 'lib/async_hooks.js', @@ -156,6 +158,17 @@ 'conditions': [ [ 'node_shared=="true"', { 'node_target_type%': 'shared_library', + 'conditions': [ + ['OS=="aix"', { + # For AIX, always generate static library first, + # It needs an extra step to generate exp and + # then use both static lib and exp to create + # shared lib. + 'node_intermediate_lib_type': 'static_library', + }, { + 'node_intermediate_lib_type': 'shared_library', + }], + ], }, { 'node_target_type%': 'executable', }], @@ -172,7 +185,81 @@ 'targets': [ { 'target_name': '<(node_core_target_name)', - 'type': '<(node_target_type)', + 'type': 'executable', + 'sources': [ + 'src/node_main.cc' + ], + 'include_dirs': [ + 'src', + 'deps/v8/include', + ], + 'conditions': [ + [ 'node_intermediate_lib_type=="static_library" and ' + 'node_shared=="true" and OS=="aix"', { + # For AIX, shared lib is linked by static lib and .exp. In the + # case here, the executable needs to link to shared lib. + # Therefore, use 'node_aix_shared' target to generate the + # shared lib and then executable. + 'dependencies': [ 'node_aix_shared' ], + }, { + 'dependencies': [ '<(node_lib_target_name)' ], + }], + [ 'node_intermediate_lib_type=="static_library" and ' + 'node_shared=="false"', { + 'includes': [ + 'node.gypi' + ], + 'xcode_settings': { + 'OTHER_LDFLAGS': [ + '-Wl,-force_load,<(PRODUCT_DIR)/<(STATIC_LIB_PREFIX)' + '<(node_core_target_name)<(STATIC_LIB_SUFFIX)', + ], + }, + 'msvs_settings': { + 'VCLinkerTool': { + 'AdditionalOptions': [ + '/WHOLEARCHIVE:<(PRODUCT_DIR)\\lib\\' + '<(node_core_target_name)<(STATIC_LIB_SUFFIX)', + ], + }, + }, + 'conditions': [ + ['OS in "linux freebsd openbsd solaris android"', { + 'ldflags': [ + '-Wl,--whole-archive,<(OBJ_DIR)/<(STATIC_LIB_PREFIX)' + '<(node_core_target_name)<(STATIC_LIB_SUFFIX)', + '-Wl,--no-whole-archive', + ], + }], + [ 'OS=="win"', { + 'sources': [ 'src/res/node.rc' ], + 'conditions': [ + [ 'node_use_etw=="true"', { + 'sources': [ + 'tools/msvs/genfiles/node_etw_provider.rc' + ], + }], + [ 'node_use_perfctr=="true"', { + 'sources': [ + 'tools/msvs/genfiles/node_perfctr_provider.rc', + ], + }] + ], + }], + ], + }], + [ 'node_intermediate_lib_type=="shared_library" and OS=="win"', { + # On Windows, having the same name for both executable and shared + # lib causes filename collision. Need a different PRODUCT_NAME for + # the executable and rename it back to node.exe later + 'product_name': '<(node_core_target_name)-win', + }], + ], + }, + { + 'target_name': '<(node_lib_target_name)', + 'type': '<(node_intermediate_lib_type)', + 'product_name': '<(node_core_target_name)', 'dependencies': [ 'node_js2c#host', @@ -184,7 +271,6 @@ 'include_dirs': [ 'src', - 'tools/msvs/genfiles', '<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h ], @@ -210,7 +296,6 @@ 'src/node_file.cc', 'src/node_http2.cc', 'src/node_http_parser.cc', - 'src/node_main.cc', 'src/node_os.cc', 'src/node_platform.cc', 'src/node_perf.cc', @@ -314,6 +399,9 @@ [ 'node_shared=="true" and node_module_version!="" and OS!="win"', { 'product_extension': '<(shlib_suffix)', }], + ['node_shared=="true" and OS=="aix"', { + 'product_name': 'node_base', + }], [ 'v8_enable_inspector==1', { 'defines': [ 'HAVE_INSPECTOR=1', @@ -344,7 +432,7 @@ 'src/backtrace_win32.cc', ], 'conditions': [ - [ 'node_target_type!="static_library"', { + [ 'node_intermediate_lib_type!="static_library"', { 'sources': [ 'src/res/node.rc', ], @@ -357,6 +445,10 @@ 'FD_SETSIZE=1024', # we need to use node's preferred "win32" rather than gyp's preferred "win" 'NODE_PLATFORM="win32"', + # Stop from defining macros that conflict with + # std::min() and std::max(). We don't use (much) + # but we still inherit it from uv.h. + 'NOMINMAX', '_UNICODE=1', ], 'libraries': [ '-lpsapi.lib' ] @@ -364,6 +456,64 @@ 'defines': [ '__POSIX__' ], 'sources': [ 'src/backtrace_posix.cc' ], }], + [ 'node_use_etw=="true"', { + 'defines': [ 'HAVE_ETW=1' ], + 'dependencies': [ 'node_etw' ], + 'include_dirs': [ + 'src', + 'tools/msvs/genfiles', + '<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h + ], + 'sources': [ + 'src/node_win32_etw_provider.h', + 'src/node_win32_etw_provider-inl.h', + 'src/node_win32_etw_provider.cc', + 'src/node_dtrace.cc', + 'tools/msvs/genfiles/node_etw_provider.h', + ], + 'conditions': [ + ['node_intermediate_lib_type != "static_library"', { + 'sources': [ + 'tools/msvs/genfiles/node_etw_provider.rc', + ], + }], + ], + }], + [ 'node_use_perfctr=="true"', { + 'defines': [ 'HAVE_PERFCTR=1' ], + 'dependencies': [ 'node_perfctr' ], + 'include_dirs': [ + 'src', + 'tools/msvs/genfiles', + '<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h + ], + 'sources': [ + 'src/node_win32_perfctr_provider.h', + 'src/node_win32_perfctr_provider.cc', + 'src/node_counters.cc', + 'src/node_counters.h', + ], + 'conditions': [ + ['node_intermediate_lib_type != "static_library"', { + 'sources': [ + 'tools/msvs/genfiles/node_perfctr_provider.rc', + ], + }], + ], + }], + [ 'node_use_lttng=="true"', { + 'defines': [ 'HAVE_LTTNG=1' ], + 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ], + 'libraries': [ '-llttng-ust' ], + 'include_dirs': [ + 'src', + 'tools/msvs/genfiles', + '<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h + ], + 'sources': [ + 'src/node_lttng.cc' + ], + }], [ 'node_use_dtrace=="true"', { 'defines': [ 'HAVE_DTRACE=1' ], 'dependencies': [ @@ -404,7 +554,6 @@ ] ] } ], [ 'node_use_openssl=="true"', { - 'defines': [ 'HAVE_OPENSSL=1' ], 'sources': [ 'src/node_crypto.cc', 'src/node_crypto_bio.cc', @@ -415,49 +564,6 @@ 'src/tls_wrap.cc', 'src/tls_wrap.h' ], - 'conditions': [ - ['openssl_fips != ""', { - 'defines': [ 'NODE_FIPS_MODE' ], - }], - [ 'node_shared_openssl=="false"', { - 'dependencies': [ - './deps/openssl/openssl.gyp:openssl', - - # For tests - './deps/openssl/openssl.gyp:openssl-cli', - ], - 'conditions': [ - # -force_load or --whole-archive are not applicable for - # the static library - [ 'node_target_type!="static_library"', { - 'xcode_settings': { - 'OTHER_LDFLAGS': [ - '-Wl,-force_load,<(PRODUCT_DIR)/<(OPENSSL_PRODUCT)', - ], - }, - 'conditions': [ - ['OS in "linux freebsd" and node_shared=="false"', { - 'ldflags': [ - '-Wl,--whole-archive,' - '<(OBJ_DIR)/deps/openssl/' - '<(OPENSSL_PRODUCT)', - '-Wl,--no-whole-archive', - ], - }], - # openssl.def is based on zlib.def, zlib symbols - # are always exported. - ['use_openssl_def==1', { - 'sources': ['<(SHARED_INTERMEDIATE_DIR)/openssl.def'], - }], - ['OS=="win" and use_openssl_def==0', { - 'sources': ['deps/zlib/win32/zlib.def'], - }], - ], - }], - ], - }]] - }, { - 'defines': [ 'HAVE_OPENSSL=0' ] }], ], }, @@ -515,7 +621,7 @@ 'target_name': 'node_etw', 'type': 'none', 'conditions': [ - [ 'node_use_etw=="true" and node_target_type!="static_library"', { + [ 'node_use_etw=="true"', { 'actions': [ { 'action_name': 'node_etw', @@ -536,7 +642,7 @@ 'target_name': 'node_perfctr', 'type': 'none', 'conditions': [ - [ 'node_use_perfctr=="true" and node_target_type!="static_library"', { + [ 'node_use_perfctr=="true"', { 'actions': [ { 'action_name': 'node_perfctr_man', @@ -598,15 +704,13 @@ '<(SHARED_INTERMEDIATE_DIR)/node_javascript.cc', ], 'conditions': [ - [ 'node_use_dtrace=="false" and node_use_etw=="false" or ' - 'node_target_type=="static_library"', { + [ 'node_use_dtrace=="false" and node_use_etw=="false"', { 'inputs': [ 'src/notrace_macros.py' ] }], - ['node_use_lttng=="false" or node_target_type=="static_library"', { + [ 'node_use_lttng=="false"', { 'inputs': [ 'src/nolttng_macros.py' ] }], - [ 'node_use_perfctr=="false" or ' - 'node_target_type=="static_library"', { + [ 'node_use_perfctr=="false"', { 'inputs': [ 'src/noperfctr_macros.py' ] }] ], @@ -656,10 +760,10 @@ { 'action_name': 'node_dtrace_provider_o', 'inputs': [ - '<(OBJ_DIR)/node/src/node_dtrace.o', + '<(OBJ_DIR)/<(node_lib_target_name)/src/node_dtrace.o', ], 'outputs': [ - '<(OBJ_DIR)/node/src/node_dtrace_provider.o' + '<(OBJ_DIR)/<(node_lib_target_name)/src/node_dtrace_provider.o' ], 'action': [ 'dtrace', '-G', '-xnolibs', '-s', 'src/node_provider.d', '<@(_inputs)', '-o', '<@(_outputs)' ] @@ -709,7 +813,7 @@ '<(SHARED_INTERMEDIATE_DIR)/v8constants.h' ], 'outputs': [ - '<(OBJ_DIR)/node/src/node_dtrace_ustack.o' + '<(OBJ_DIR)/<(node_lib_target_name)/src/node_dtrace_ustack.o' ], 'conditions': [ [ 'target_arch=="ia32" or target_arch=="arm"', { @@ -756,12 +860,41 @@ } ], ] }, + { + # When using shared lib to build executable in Windows, in order to avoid + # filename collision, the executable name is node-win.exe. Need to rename + # it back to node.exe + 'target_name': 'rename_node_bin_win', + 'type': 'none', + 'dependencies': [ + '<(node_core_target_name)', + ], + 'conditions': [ + [ 'OS=="win" and node_intermediate_lib_type=="shared_library"', { + 'actions': [ + { + 'action_name': 'rename_node_bin_win', + 'inputs': [ + '<(PRODUCT_DIR)/<(node_core_target_name)-win.exe' + ], + 'outputs': [ + '<(PRODUCT_DIR)/<(node_core_target_name).exe', + ], + 'action': [ + 'mv', '<@(_inputs)', '<@(_outputs)', + ], + }, + ], + } ], + ] + }, { 'target_name': 'cctest', 'type': 'executable', 'dependencies': [ '<(node_core_target_name)', + 'rename_node_bin_win', 'deps/gtest/gtest.gyp:gtest', 'node_js2c#host', 'node_dtrace_header', @@ -770,9 +903,9 @@ ], 'variables': { - 'OBJ_PATH': '<(OBJ_DIR)/node/src', - 'OBJ_GEN_PATH': '<(OBJ_DIR)/node/gen', - 'OBJ_TRACING_PATH': '<(OBJ_DIR)/node/src/tracing', + 'OBJ_PATH': '<(OBJ_DIR)/<(node_lib_target_name)/src', + 'OBJ_GEN_PATH': '<(OBJ_DIR)/<(node_lib_target_name)/gen', + 'OBJ_TRACING_PATH': '<(OBJ_DIR)/<(node_lib_target_name)/src/tracing', 'OBJ_SUFFIX': 'o', 'OBJ_SEPARATOR': '/', 'conditions': [ @@ -783,18 +916,19 @@ 'OBJ_PATH': '<(OBJ_DIR)/src', 'OBJ_GEN_PATH': '<(OBJ_DIR)/gen', 'OBJ_TRACING_PATH': '<(OBJ_DIR)/src/tracing', - 'OBJ_SEPARATOR': '/node.', + 'OBJ_SEPARATOR': '/<(node_lib_target_name).', }, { 'conditions': [ ['OS=="win"', { - 'OBJ_PATH': '<(OBJ_DIR)/node', - 'OBJ_GEN_PATH': '<(OBJ_DIR)/node', - 'OBJ_TRACING_PATH': '<(OBJ_DIR)/node', + 'OBJ_PATH': '<(OBJ_DIR)/<(node_lib_target_name)', + 'OBJ_GEN_PATH': '<(OBJ_DIR)/<(node_lib_target_name)', + 'OBJ_TRACING_PATH': '<(OBJ_DIR)/<(node_lib_target_name)', }], ['OS=="aix"', { - 'OBJ_PATH': '<(OBJ_DIR)/node_base/src', - 'OBJ_GEN_PATH': '<(OBJ_DIR)/node_base/gen', - 'OBJ_TRACING_PATH': '<(OBJ_DIR)/node_base/src/tracing', + 'OBJ_PATH': '<(OBJ_DIR)/<(node_lib_target_name)/src', + 'OBJ_GEN_PATH': '<(OBJ_DIR)/<(node_lib_target_name)/gen', + 'OBJ_TRACING_PATH': + '<(OBJ_DIR)/<(node_lib_target_name)/src/tracing', }], ]} ] @@ -826,62 +960,73 @@ 'test/cctest/test_url.cc' ], - 'sources!': [ - 'src/node_main.cc' + 'libraries': [ + '<(OBJ_PATH)<(OBJ_SEPARATOR)async_wrap.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)env.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_buffer.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_debug_options.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_i18n.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_perf.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_platform.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_url.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)util.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)string_bytes.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)string_search.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)stream_base.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_constants.<(OBJ_SUFFIX)', + '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)agent.<(OBJ_SUFFIX)', + '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)node_trace_buffer.<(OBJ_SUFFIX)', + '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)node_trace_writer.<(OBJ_SUFFIX)', + '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)trace_event.<(OBJ_SUFFIX)', + '<(OBJ_GEN_PATH)<(OBJ_SEPARATOR)node_javascript.<(OBJ_SUFFIX)', ], 'conditions': [ - ['node_target_type!="static_library"', { - 'libraries': [ - '<(OBJ_PATH)<(OBJ_SEPARATOR)async_wrap.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)env.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_buffer.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_debug_options.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_i18n.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_perf.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_platform.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_url.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)util.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)string_bytes.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)string_search.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)stream_base.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_constants.<(OBJ_SUFFIX)', - '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)agent.<(OBJ_SUFFIX)', - '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)node_trace_buffer.<(OBJ_SUFFIX)', - '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)node_trace_writer.<(OBJ_SUFFIX)', - '<(OBJ_TRACING_PATH)<(OBJ_SEPARATOR)trace_event.<(OBJ_SUFFIX)', - '<(OBJ_GEN_PATH)<(OBJ_SEPARATOR)node_javascript.<(OBJ_SUFFIX)', - ], - }], [ 'node_use_openssl=="true"', { - 'libraries': [ - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_crypto.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_crypto_bio.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)node_crypto_clienthello.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)tls_wrap.<(OBJ_SUFFIX)', + 'conditions': [ + ['node_target_type!="static_library"', { + 'libraries': [ + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_crypto.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_crypto_bio.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_crypto_clienthello.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)tls_wrap.<(OBJ_SUFFIX)', + ], + }], ], 'defines': [ 'HAVE_OPENSSL=1', ], }], + [ 'node_use_perfctr=="true"', { + 'defines': [ 'HAVE_PERFCTR=1' ], + 'libraries': [ + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_counters.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)' + 'node_win32_perfctr_provider.<(OBJ_SUFFIX)', + ], + }], ['v8_enable_inspector==1', { 'sources': [ 'test/cctest/test_inspector_socket.cc', 'test/cctest/test_inspector_socket_server.cc' ], - 'libraries': [ - '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_agent.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_io.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_js_api.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_socket.<(OBJ_SUFFIX)', - '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_socket_server.<(OBJ_SUFFIX)', + 'conditions': [ + ['node_target_type!="static_library"', { + 'libraries': [ + '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_agent.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_io.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_js_api.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_socket.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)inspector_socket_server.<(OBJ_SUFFIX)', + ], + }], ], 'defines': [ 'HAVE_INSPECTOR=1', ], }], - [ 'node_use_dtrace=="true"', { + [ 'node_use_dtrace=="true" and node_target_type!="static_library"', { 'libraries': [ '<(OBJ_PATH)<(OBJ_SEPARATOR)node_dtrace.<(OBJ_SUFFIX)', ], @@ -894,143 +1039,56 @@ }], ['OS=="linux"', { 'libraries': [ - '<(SHARED_INTERMEDIATE_DIR)/node_dtrace_provider.o', + '<(SHARED_INTERMEDIATE_DIR)<(OBJ_SEPARATOR)' + 'node_dtrace_provider.<(OBJ_SUFFIX)', ] }], ], - }], - [ 'OS=="win"', { - 'libraries': [ - '<(OBJ_PATH)<(OBJ_SEPARATOR)backtrace_win32.<(OBJ_SUFFIX)', - ], }, { - 'libraries': [ - '<(OBJ_PATH)<(OBJ_SEPARATOR)backtrace_posix.<(OBJ_SUFFIX)', - ], - }], - [ 'node_shared_zlib=="false"', { - 'dependencies': [ - 'deps/zlib/zlib.gyp:zlib', - ] - }], - [ 'node_shared_openssl=="false" and node_shared=="false"', { - 'dependencies': [ - 'deps/openssl/openssl.gyp:openssl' - ] - }], - [ 'node_shared_http_parser=="false"', { - 'dependencies': [ - 'deps/http_parser/http_parser.gyp:http_parser' - ] - }], - [ 'node_shared_libuv=="false"', { - 'dependencies': [ - 'deps/uv/uv.gyp:libuv' + 'conditions': [ + [ 'node_use_etw=="true" and OS=="win"', { + 'libraries': [ + '<(OBJ_PATH)<(OBJ_SEPARATOR)node_dtrace.<(OBJ_SUFFIX)', + '<(OBJ_PATH)<(OBJ_SEPARATOR)' + 'node_win32_etw_provider.<(OBJ_SUFFIX)', + ], + }] ] }], - [ 'node_shared_nghttp2=="false"', { - 'dependencies': [ - 'deps/nghttp2/nghttp2.gyp:nghttp2' + [ 'OS=="win" and node_target_type!="static_library"', { + 'libraries': [ + '<(OBJ_PATH)<(OBJ_SEPARATOR)backtrace_win32.<(OBJ_SUFFIX)', ], - 'include_dirs': [ - 'deps/nghttp2/lib/includes' - ] - }], - [ 'node_use_v8_platform=="true"', { - 'dependencies': [ - 'deps/v8/src/v8.gyp:v8_libplatform', + }, { + 'conditions': [ + ['node_target_type!="static_library"', { + 'libraries': [ + '<(OBJ_PATH)<(OBJ_SEPARATOR)backtrace_posix.<(OBJ_SUFFIX)', + ], + }], ], }], ['OS=="solaris"', { 'ldflags': [ '-I<(SHARED_INTERMEDIATE_DIR)' ] }], - [ 'node_use_openssl=="true"', { - 'conditions': [ - [ 'node_shared_openssl=="false"', { - 'conditions': [ - # -force_load or --whole-archive are not applicable for - # the static library - [ 'node_target_type!="static_library"', { - 'xcode_settings': { - 'OTHER_LDFLAGS': [ - '-Wl,-force_load,<(PRODUCT_DIR)/<(OPENSSL_PRODUCT)', - ], - }, - 'conditions': [ - ['OS in "linux freebsd" and node_shared=="false"', { - 'ldflags': [ - '-Wl,--whole-archive,' - '<(OBJ_DIR)/deps/openssl/' - '<(OPENSSL_PRODUCT)', - '-Wl,--no-whole-archive', - ], - }], - ], - }], - ], - }]] - }], ] } ], # end targets 'conditions': [ - [ 'node_target_type=="static_library"', { + [ 'OS=="aix" and node_shared=="true"', { 'targets': [ { - 'target_name': 'static_node', - 'type': 'executable', + 'target_name': 'node_aix_shared', + 'type': 'shared_library', 'product_name': '<(node_core_target_name)', - 'dependencies': [ - '<(node_core_target_name)', - ], - 'sources+': [ - 'src/node_main.cc', - ], - 'include_dirs': [ - 'deps/v8/include', - ], - 'xcode_settings': { - 'OTHER_LDFLAGS': [ - '-Wl,-force_load,<(PRODUCT_DIR)/<(STATIC_LIB_PREFIX)' - '<(node_core_target_name)<(STATIC_LIB_SUFFIX)', - ], - }, - 'msvs_settings': { - 'VCLinkerTool': { - 'AdditionalOptions': [ - '/WHOLEARCHIVE:<(PRODUCT_DIR)/lib/' - '<(node_core_target_name)<(STATIC_LIB_SUFFIX)', - ], - }, - }, - 'conditions': [ - ['OS in "linux freebsd openbsd solaris android"', { - 'ldflags': [ - '-Wl,--whole-archive,<(OBJ_DIR)/<(STATIC_LIB_PREFIX)' - '<(node_core_target_name)<(STATIC_LIB_SUFFIX)', - '-Wl,--no-whole-archive', - ], - }], - ], - }, - ], - }], - ['OS=="aix"', { - 'targets': [ - { - 'target_name': 'node', + 'ldflags': [ '--shared' ], + 'product_extension': '<(shlib_suffix)', 'conditions': [ - ['node_shared=="true"', { - 'type': 'shared_library', - 'ldflags': ['--shared'], - 'product_extension': '<(shlib_suffix)', - }, { - 'type': 'executable', - }], ['target_arch=="ppc64"', { 'ldflags': [ - '-Wl,-blibpath:/usr/lib:/lib:/opt/freeware/lib/pthread/ppc64' + '-Wl,-blibpath:/usr/lib:/lib:' + '/opt/freeware/lib/pthread/ppc64' ], }], ['target_arch=="ppc"', { @@ -1039,45 +1097,20 @@ ], }] ], - 'dependencies': ['<(node_core_target_name)', 'node_exp'], - + 'includes': [ + 'node.gypi' + ], + 'dependencies': [ '<(node_lib_target_name)' ], 'include_dirs': [ 'src', 'deps/v8/include', ], - 'sources': [ - 'src/node_main.cc', '<@(library_files)', - # node.gyp is added to the project by default. 'common.gypi', ], - - 'ldflags': ['-Wl,-bE:<(PRODUCT_DIR)/node.exp', '-Wl,-brtl'], }, - { - 'target_name': 'node_exp', - 'type': 'none', - 'dependencies': [ - '<(node_core_target_name)', - ], - 'actions': [ - { - 'action_name': 'expfile', - 'inputs': [ - '<(OBJ_DIR)' - ], - 'outputs': [ - '<(PRODUCT_DIR)/node.exp' - ], - 'action': [ - 'sh', 'tools/create_expfile.sh', - '<@(_inputs)', '<@(_outputs)' - ], - } - ] - } - ], # end targets + ] }], # end aix section ], # end conditions block } diff --git a/node.gypi b/node.gypi index 3990c59ef98851..386601906fbe4a 100644 --- a/node.gypi +++ b/node.gypi @@ -1,4 +1,29 @@ { + # 'force_load' means to include the static libs into the shared lib or + # executable. Therefore, it is enabled when building: + # 1. The executable and it uses static lib (cctest and node) + # 2. The shared lib + # Linker optimizes out functions that are not used. When force_load=true, + # --whole-archive,force_load and /WHOLEARCHIVE are used to include + # all obj files in static libs into the executable or shared lib. + 'variables': { + 'variables': { + 'variables': { + 'force_load%': 'true', + 'current_type%': '<(_type)', + }, + 'force_load%': '<(force_load)', + 'conditions': [ + ['current_type=="static_library"', { + 'force_load': 'false', + }], + [ 'current_type=="executable" and node_target_type=="shared_library"', { + 'force_load': 'false', + }] + ], + }, + 'force_load%': '<(force_load)', + }, 'conditions': [ [ 'node_shared=="false"', { 'msvs_settings': { @@ -36,12 +61,6 @@ [ 'node_v8_options!=""', { 'defines': [ 'NODE_V8_OPTIONS="<(node_v8_options)"'], }], - # No node_main.cc for anything except executable - [ 'node_target_type!="executable"', { - 'sources!': [ - 'src/node_main.cc', - ], - }], [ 'node_release_urlbase!=""', { 'defines': [ 'NODE_RELEASE_URLBASE="<(node_release_urlbase)"', @@ -70,37 +89,6 @@ 'deps/v8/src/third_party/vtune/v8vtune.gyp:v8_vtune' ], }], - [ 'node_use_lttng=="true"', { - 'defines': [ 'HAVE_LTTNG=1' ], - 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ], - 'libraries': [ '-llttng-ust' ], - 'sources': [ - 'src/node_lttng.cc' - ], - } ], - [ 'node_use_etw=="true" and node_target_type!="static_library"', { - 'defines': [ 'HAVE_ETW=1' ], - 'dependencies': [ 'node_etw' ], - 'sources': [ - 'src/node_win32_etw_provider.h', - 'src/node_win32_etw_provider-inl.h', - 'src/node_win32_etw_provider.cc', - 'src/node_dtrace.cc', - 'tools/msvs/genfiles/node_etw_provider.h', - 'tools/msvs/genfiles/node_etw_provider.rc', - ] - } ], - [ 'node_use_perfctr=="true" and node_target_type!="static_library"', { - 'defines': [ 'HAVE_PERFCTR=1' ], - 'dependencies': [ 'node_perfctr' ], - 'sources': [ - 'src/node_win32_perfctr_provider.h', - 'src/node_win32_perfctr_provider.cc', - 'src/node_counters.cc', - 'src/node_counters.h', - 'tools/msvs/genfiles/node_perfctr_provider.rc', - ] - } ], [ 'node_no_browser_globals=="true"', { 'defines': [ 'NODE_NO_BROWSER_GLOBALS' ], } ], @@ -108,7 +96,7 @@ 'dependencies': [ 'deps/v8/src/v8.gyp:postmortem-metadata' ], 'conditions': [ # -force_load is not applicable for the static library - [ 'node_target_type!="static_library"', { + [ 'force_load=="true"', { 'xcode_settings': { 'OTHER_LDFLAGS': [ '-Wl,-force_load,<(V8_BASE)', @@ -159,6 +147,27 @@ 'defines': [ '_LINUX_SOURCE_COMPAT', ], + 'conditions': [ + [ 'force_load=="true"', { + + 'actions': [ + { + 'action_name': 'expfile', + 'inputs': [ + '<(OBJ_DIR)' + ], + 'outputs': [ + '<(PRODUCT_DIR)/node.exp' + ], + 'action': [ + 'sh', 'tools/create_expfile.sh', + '<@(_inputs)', '<@(_outputs)' + ], + } + ], + 'ldflags': ['-Wl,-bE:<(PRODUCT_DIR)/node.exp', '-Wl,-brtl'], + }], + ], }], [ 'OS=="solaris"', { 'libraries': [ @@ -174,12 +183,14 @@ 'NODE_PLATFORM="sunos"', ], }], - [ '(OS=="freebsd" or OS=="linux") and node_shared=="false" and coverage=="false"', { + [ '(OS=="freebsd" or OS=="linux") and node_shared=="false"' + ' and coverage=="false" and force_load=="true"', { 'ldflags': [ '-Wl,-z,noexecstack', '-Wl,--whole-archive <(V8_BASE)', '-Wl,--no-whole-archive' ] }], - [ '(OS=="freebsd" or OS=="linux") and node_shared=="false" and coverage=="true"', { + [ '(OS=="freebsd" or OS=="linux") and node_shared=="false"' + ' and coverage=="true" and force_load=="true"', { 'ldflags': [ '-Wl,-z,noexecstack', '-Wl,--whole-archive <(V8_BASE)', '-Wl,--no-whole-archive', @@ -206,5 +217,54 @@ [ 'OS=="sunos"', { 'ldflags': [ '-Wl,-M,/usr/lib/ld/map.noexstk' ], }], + + [ 'node_use_openssl=="true"', { + 'defines': [ 'HAVE_OPENSSL=1' ], + 'conditions': [ + ['openssl_fips != ""', { + 'defines': [ 'NODE_FIPS_MODE' ], + }], + [ 'node_shared_openssl=="false"', { + 'dependencies': [ + './deps/openssl/openssl.gyp:openssl', + + # For tests + './deps/openssl/openssl.gyp:openssl-cli', + ], + 'conditions': [ + # -force_load or --whole-archive are not applicable for + # the static library + [ 'force_load=="true"', { + 'xcode_settings': { + 'OTHER_LDFLAGS': [ + '-Wl,-force_load,<(PRODUCT_DIR)/<(OPENSSL_PRODUCT)', + ], + }, + 'conditions': [ + ['OS in "linux freebsd" and node_shared=="false"', { + 'ldflags': [ + '-Wl,--whole-archive,' + '<(OBJ_DIR)/deps/openssl/' + '<(OPENSSL_PRODUCT)', + '-Wl,--no-whole-archive', + ], + }], + # openssl.def is based on zlib.def, zlib symbols + # are always exported. + ['use_openssl_def==1', { + 'sources': ['<(SHARED_INTERMEDIATE_DIR)/openssl.def'], + }], + ['OS=="win" and use_openssl_def==0', { + 'sources': ['deps/zlib/win32/zlib.def'], + }], + ], + }], + ], + }]] + + }, { + 'defines': [ 'HAVE_OPENSSL=0' ] + }], + ], } diff --git a/src/aliased_buffer.h b/src/aliased_buffer.h index 21aaeb61141c59..b99b01f5d94ca2 100644 --- a/src/aliased_buffer.h +++ b/src/aliased_buffer.h @@ -95,6 +95,21 @@ class AliasedBuffer { js_array_.Reset(); } + AliasedBuffer& operator=(AliasedBuffer&& that) { + this->~AliasedBuffer(); + isolate_ = that.isolate_; + count_ = that.count_; + byte_offset_ = that.byte_offset_; + buffer_ = that.buffer_; + free_buffer_ = that.free_buffer_; + + js_array_.Reset(isolate_, that.js_array_.Get(isolate_)); + + that.buffer_ = nullptr; + that.js_array_.Reset(); + return *this; + } + /** * Helper class that is returned from operator[] to support assignment into * a specified location. @@ -111,11 +126,17 @@ class AliasedBuffer { index_(that.index_) { } - inline Reference& operator=(const NativeT &val) { + template + inline Reference& operator=(const T& val) { aliased_buffer_->SetValue(index_, val); return *this; } + // This is not caught by the template operator= above. + inline Reference& operator=(const Reference& val) { + return *this = static_cast(val); + } + operator NativeT() const { return aliased_buffer_->GetValue(index_); } @@ -186,8 +207,12 @@ class AliasedBuffer { return GetValue(index); } + size_t Length() const { + return count_; + } + private: - v8::Isolate* const isolate_; + v8::Isolate* isolate_; size_t count_; size_t byte_offset_; NativeT* buffer_; diff --git a/src/async_wrap.cc b/src/async_wrap.cc index 236c5670472980..f770348b9c9183 100644 --- a/src/async_wrap.cc +++ b/src/async_wrap.cc @@ -308,12 +308,13 @@ static void PromiseHook(PromiseHookType type, Local promise, if (parent_wrap == nullptr) { parent_wrap = PromiseWrap::New(env, parent_promise, nullptr, true); } - // get id from parentWrap - double trigger_async_id = parent_wrap->get_async_id(); - env->set_init_trigger_async_id(trigger_async_id); - } - wrap = PromiseWrap::New(env, promise, parent_wrap, silent); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope( + env, parent_wrap->get_async_id()); + wrap = PromiseWrap::New(env, promise, parent_wrap, silent); + } else { + wrap = PromiseWrap::New(env, promise, nullptr, silent); + } } CHECK_NE(wrap, nullptr); @@ -466,13 +467,6 @@ void AsyncWrap::PopAsyncIds(const FunctionCallbackInfo& args) { } -void AsyncWrap::AsyncIdStackSize(const FunctionCallbackInfo& args) { - Environment* env = Environment::GetCurrent(args); - args.GetReturnValue().Set( - static_cast(env->async_hooks()->stack_size())); -} - - void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); env->async_hooks()->clear_async_id_stack(); @@ -511,7 +505,6 @@ void AsyncWrap::Initialize(Local target, env->SetMethod(target, "setupHooks", SetupHooks); env->SetMethod(target, "pushAsyncIds", PushAsyncIds); env->SetMethod(target, "popAsyncIds", PopAsyncIds); - env->SetMethod(target, "asyncIdStackSize", AsyncIdStackSize); env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack); env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId); env->SetMethod(target, "enablePromiseHook", EnablePromiseHook); @@ -541,13 +534,18 @@ void AsyncWrap::Initialize(Local target, // // kAsyncUid: Maintains the state of the next unique id to be assigned. // - // kInitTriggerAsyncId: Write the id of the resource responsible for a + // kDefaultTriggerAsyncId: Write the id of the resource responsible for a // handle's creation just before calling the new handle's constructor. - // After the new handle is constructed kInitTriggerAsyncId is set back to 0. + // After the new handle is constructed kDefaultTriggerAsyncId is set back + // to 0. FORCE_SET_TARGET_FIELD(target, "async_id_fields", env->async_hooks()->async_id_fields().GetJSArray()); + target->Set(context, + env->async_ids_stack_string(), + env->async_hooks()->async_ids_stack().GetJSArray()).FromJust(); + Local constants = Object::New(isolate); #define SET_HOOKS_CONSTANT(name) \ FORCE_SET_TARGET_FIELD( \ @@ -563,7 +561,8 @@ void AsyncWrap::Initialize(Local target, SET_HOOKS_CONSTANT(kExecutionAsyncId); SET_HOOKS_CONSTANT(kTriggerAsyncId); SET_HOOKS_CONSTANT(kAsyncIdCounter); - SET_HOOKS_CONSTANT(kInitTriggerAsyncId); + SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId); + SET_HOOKS_CONSTANT(kStackLength); #undef SET_HOOKS_CONSTANT FORCE_SET_TARGET_FIELD(target, "constants", constants); @@ -593,6 +592,7 @@ void AsyncWrap::Initialize(Local target, env->set_async_hooks_after_function(Local()); env->set_async_hooks_destroy_function(Local()); env->set_async_hooks_promise_resolve_function(Local()); + env->set_async_hooks_binding(target); } @@ -676,7 +676,7 @@ void AsyncWrap::EmitDestroy(Environment* env, double async_id) { void AsyncWrap::AsyncReset(double execution_async_id, bool silent) { async_id_ = execution_async_id == -1 ? env()->new_async_id() : execution_async_id; - trigger_async_id_ = env()->get_init_trigger_async_id(); + trigger_async_id_ = env()->get_default_trigger_async_id(); switch (provider_type()) { #define V(PROVIDER) \ @@ -777,7 +777,7 @@ async_context EmitAsyncInit(Isolate* isolate, // Initialize async context struct if (trigger_async_id == -1) - trigger_async_id = env->get_init_trigger_async_id(); + trigger_async_id = env->get_default_trigger_async_id(); async_context context = { env->new_async_id(), // async_id_ diff --git a/src/async_wrap.h b/src/async_wrap.h index c5dd4506886984..9b5632598bcc0b 100644 --- a/src/async_wrap.h +++ b/src/async_wrap.h @@ -123,7 +123,6 @@ class AsyncWrap : public BaseObject { static void GetAsyncId(const v8::FunctionCallbackInfo& args); static void PushAsyncIds(const v8::FunctionCallbackInfo& args); static void PopAsyncIds(const v8::FunctionCallbackInfo& args); - static void AsyncIdStackSize(const v8::FunctionCallbackInfo& args); static void ClearAsyncIdStack( const v8::FunctionCallbackInfo& args); static void AsyncReset(const v8::FunctionCallbackInfo& args); diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index de3cb8f89c1ea2..165a8cda20618b 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -1876,60 +1876,42 @@ void AfterGetNameInfo(uv_getnameinfo_t* req, delete req_wrap; } +using ParseIPResult = decltype(static_cast(0)->addr); + +int ParseIP(const char* ip, ParseIPResult* result = nullptr) { + ParseIPResult tmp; + if (result == nullptr) result = &tmp; + if (0 == uv_inet_pton(AF_INET, ip, result)) return 4; + if (0 == uv_inet_pton(AF_INET6, ip, result)) return 6; + return 0; +} void IsIP(const FunctionCallbackInfo& args) { node::Utf8Value ip(args.GetIsolate(), args[0]); - char address_buffer[sizeof(struct in6_addr)]; - - int rc = 0; - if (uv_inet_pton(AF_INET, *ip, &address_buffer) == 0) - rc = 4; - else if (uv_inet_pton(AF_INET6, *ip, &address_buffer) == 0) - rc = 6; - - args.GetReturnValue().Set(rc); + args.GetReturnValue().Set(ParseIP(*ip)); } void IsIPv4(const FunctionCallbackInfo& args) { node::Utf8Value ip(args.GetIsolate(), args[0]); - char address_buffer[sizeof(struct in_addr)]; - - if (uv_inet_pton(AF_INET, *ip, &address_buffer) == 0) { - args.GetReturnValue().Set(true); - } else { - args.GetReturnValue().Set(false); - } + args.GetReturnValue().Set(4 == ParseIP(*ip)); } void IsIPv6(const FunctionCallbackInfo& args) { node::Utf8Value ip(args.GetIsolate(), args[0]); - char address_buffer[sizeof(struct in6_addr)]; - - if (uv_inet_pton(AF_INET6, *ip, &address_buffer) == 0) { - args.GetReturnValue().Set(true); - } else { - args.GetReturnValue().Set(false); - } + args.GetReturnValue().Set(6 == ParseIP(*ip)); } void CanonicalizeIP(const FunctionCallbackInfo& args) { v8::Isolate* isolate = args.GetIsolate(); node::Utf8Value ip(isolate, args[0]); - char address_buffer[sizeof(struct in6_addr)]; - char canonical_ip[INET6_ADDRSTRLEN]; - int af; - if (uv_inet_pton(AF_INET, *ip, &address_buffer) == 0) - af = AF_INET; - else if (uv_inet_pton(AF_INET6, *ip, &address_buffer) == 0) - af = AF_INET6; - else - return; - - int err = uv_inet_ntop(af, address_buffer, canonical_ip, - sizeof(canonical_ip)); - CHECK_EQ(err, 0); + ParseIPResult result; + const int rc = ParseIP(*ip, &result); + if (rc == 0) return; + char canonical_ip[INET6_ADDRSTRLEN]; + const int af = (rc == 4 ? AF_INET : AF_INET6); + CHECK_EQ(0, uv_inet_ntop(af, &result, canonical_ip, sizeof(canonical_ip))); args.GetReturnValue().Set(String::NewFromUtf8(isolate, canonical_ip)); } diff --git a/src/connection_wrap.cc b/src/connection_wrap.cc index d82e7195d76579..8de77f361dcde4 100644 --- a/src/connection_wrap.cc +++ b/src/connection_wrap.cc @@ -49,7 +49,6 @@ void ConnectionWrap::OnConnection(uv_stream_t* handle, }; if (status == 0) { - env->set_init_trigger_async_id(wrap_data->get_async_id()); // Instantiate the client javascript object and handle. Local client_obj = WrapType::Instantiate(env, wrap_data, diff --git a/src/env-inl.h b/src/env-inl.h index 955cf2688f88fa..7cdd9cecd378b9 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -53,11 +53,11 @@ inline MultiIsolatePlatform* IsolateData::platform() const { return platform_; } -inline Environment::AsyncHooks::AsyncHooks(v8::Isolate* isolate) - : isolate_(isolate), - fields_(isolate, kFieldsCount), - async_id_fields_(isolate, kUidFieldsCount) { - v8::HandleScope handle_scope(isolate_); +inline Environment::AsyncHooks::AsyncHooks() + : async_ids_stack_(env()->isolate(), 16 * 2), + fields_(env()->isolate(), kFieldsCount), + async_id_fields_(env()->isolate(), kUidFieldsCount) { + v8::HandleScope handle_scope(env()->isolate()); // Always perform async_hooks checks, not just when async_hooks is enabled. // TODO(AndreasMadsen): Consider removing this for LTS releases. @@ -66,6 +66,12 @@ inline Environment::AsyncHooks::AsyncHooks(v8::Isolate* isolate) // and flag changes won't be included. fields_[kCheck] = 1; + // kDefaultTriggerAsyncId should be -1, this indicates that there is no + // specified default value and it should fallback to the executionAsyncId. + // 0 is not used as the magic value, because that indicates a missing context + // which is different from a default context. + async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1; + // kAsyncIdCounter should start at 1 because that'll be the id the execution // context during bootstrap (code that runs before entering uv_run()). async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1; @@ -75,9 +81,9 @@ inline Environment::AsyncHooks::AsyncHooks(v8::Isolate* isolate) // strings can be retrieved quickly. #define V(Provider) \ providers_[AsyncWrap::PROVIDER_ ## Provider].Set( \ - isolate_, \ + env()->isolate(), \ v8::String::NewFromOneByte( \ - isolate_, \ + env()->isolate(), \ reinterpret_cast(#Provider), \ v8::NewStringType::kInternalized, \ sizeof(#Provider) - 1).ToLocalChecked()); @@ -95,8 +101,13 @@ Environment::AsyncHooks::async_id_fields() { return async_id_fields_; } +inline AliasedBuffer& +Environment::AsyncHooks::async_ids_stack() { + return async_ids_stack_; +} + inline v8::Local Environment::AsyncHooks::provider_string(int idx) { - return providers_[idx].Get(isolate_); + return providers_[idx].Get(env()->isolate()); } inline void Environment::AsyncHooks::no_force_checks() { @@ -104,6 +115,11 @@ inline void Environment::AsyncHooks::no_force_checks() { fields_[kCheck] = fields_[kCheck] - 1; } +inline Environment* Environment::AsyncHooks::env() { + return Environment::ForAsyncHooks(this); +} + +// Remember to keep this code aligned with pushAsyncIds() in JS. inline void Environment::AsyncHooks::push_async_ids(double async_id, double trigger_async_id) { // Since async_hooks is experimental, do only perform the check @@ -113,16 +129,21 @@ inline void Environment::AsyncHooks::push_async_ids(double async_id, CHECK_GE(trigger_async_id, -1); } - async_ids_stack_.push({ async_id_fields_[kExecutionAsyncId], - async_id_fields_[kTriggerAsyncId] }); + uint32_t offset = fields_[kStackLength]; + if (offset * 2 >= async_ids_stack_.Length()) + grow_async_ids_stack(); + async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId]; + async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId]; + fields_[kStackLength] = fields_[kStackLength] + 1; async_id_fields_[kExecutionAsyncId] = async_id; async_id_fields_[kTriggerAsyncId] = trigger_async_id; } +// Remember to keep this code aligned with popAsyncIds() in JS. inline bool Environment::AsyncHooks::pop_async_id(double async_id) { // In case of an exception then this may have already been reset, if the // stack was multiple MakeCallback()'s deep. - if (async_ids_stack_.empty()) return false; + if (fields_[kStackLength] == 0) return false; // Ask for the async_id to be restored as a check that the stack // hasn't been corrupted. @@ -134,51 +155,55 @@ inline bool Environment::AsyncHooks::pop_async_id(double async_id) { "actual: %.f, expected: %.f)\n", async_id_fields_.GetValue(kExecutionAsyncId), async_id); - Environment* env = Environment::GetCurrent(isolate_); DumpBacktrace(stderr); fflush(stderr); - if (!env->abort_on_uncaught_exception()) + if (!env()->abort_on_uncaught_exception()) exit(1); fprintf(stderr, "\n"); fflush(stderr); ABORT_NO_BACKTRACE(); } - auto async_ids = async_ids_stack_.top(); - async_ids_stack_.pop(); - async_id_fields_[kExecutionAsyncId] = async_ids.async_id; - async_id_fields_[kTriggerAsyncId] = async_ids.trigger_async_id; - return !async_ids_stack_.empty(); -} + uint32_t offset = fields_[kStackLength] - 1; + async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset]; + async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1]; + fields_[kStackLength] = offset; -inline size_t Environment::AsyncHooks::stack_size() { - return async_ids_stack_.size(); + return fields_[kStackLength] > 0; } inline void Environment::AsyncHooks::clear_async_id_stack() { - while (!async_ids_stack_.empty()) - async_ids_stack_.pop(); async_id_fields_[kExecutionAsyncId] = 0; async_id_fields_[kTriggerAsyncId] = 0; + fields_[kStackLength] = 0; } -inline Environment::AsyncHooks::InitScope::InitScope( - Environment* env, double init_trigger_async_id) - : env_(env), - async_id_fields_ref_(env->async_hooks()->async_id_fields()) { - if (env_->async_hooks()->fields()[AsyncHooks::kCheck] > 0) { - CHECK_GE(init_trigger_async_id, -1); +inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope + ::DefaultTriggerAsyncIdScope(Environment* env, + double default_trigger_async_id) + : async_id_fields_ref_(env->async_hooks()->async_id_fields()) { + if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) { + CHECK_GE(default_trigger_async_id, 0); } - env->async_hooks()->push_async_ids( - async_id_fields_ref_[AsyncHooks::kExecutionAsyncId], - init_trigger_async_id); + + old_default_trigger_async_id_ = + async_id_fields_ref_[AsyncHooks::kDefaultTriggerAsyncId]; + async_id_fields_ref_[AsyncHooks::kDefaultTriggerAsyncId] = + default_trigger_async_id; } -inline Environment::AsyncHooks::InitScope::~InitScope() { - env_->async_hooks()->pop_async_id( - async_id_fields_ref_[AsyncHooks::kExecutionAsyncId]); +inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope + ::~DefaultTriggerAsyncIdScope() { + async_id_fields_ref_[AsyncHooks::kDefaultTriggerAsyncId] = + old_default_trigger_async_id_; } + +Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) { + return ContainerOf(&Environment::async_hooks_, hooks); +} + + inline Environment::AsyncCallbackScope::AsyncCallbackScope(Environment* env) : env_(env) { env_->makecallback_cntr_++; @@ -252,7 +277,6 @@ inline Environment::Environment(IsolateData* isolate_data, v8::Local context) : isolate_(context->GetIsolate()), isolate_data_(isolate_data), - async_hooks_(context->GetIsolate()), timer_base_(uv_now(isolate_data->event_loop())), using_domains_(false), printed_error_(false), @@ -274,22 +298,10 @@ inline Environment::Environment(IsolateData* isolate_data, v8::Context::Scope context_scope(context); set_as_external(v8::External::New(isolate(), this)); - v8::Local null = v8::Null(isolate()); - v8::Local binding_cache_object = v8::Object::New(isolate()); - CHECK(binding_cache_object->SetPrototype(context, null).FromJust()); - set_binding_cache_object(binding_cache_object); - - v8::Local internal_binding_cache_object = - v8::Object::New(isolate()); - CHECK(internal_binding_cache_object->SetPrototype(context, null).FromJust()); - set_internal_binding_cache_object(internal_binding_cache_object); - - set_module_load_list_array(v8::Array::New(isolate())); - AssignToContext(context, ContextInfo("")); destroy_async_id_list_.reserve(512); - performance_state_ = Calloc(1); + performance_state_.reset(new performance::performance_state(isolate())); performance_state_->milestones[ performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT] = PERFORMANCE_NOW(); @@ -322,7 +334,6 @@ inline Environment::~Environment() { delete[] heap_statistics_buffer_; delete[] heap_space_statistics_buffer_; delete[] http_parser_buffer_; - free(performance_state_); } inline v8::Isolate* Environment::isolate() const { @@ -440,17 +451,13 @@ inline double Environment::trigger_async_id() { return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId]; } -inline double Environment::get_init_trigger_async_id() { - AliasedBuffer& async_id_fields = - async_hooks()->async_id_fields(); - double tid = async_id_fields[AsyncHooks::kInitTriggerAsyncId]; - async_id_fields[AsyncHooks::kInitTriggerAsyncId] = 0; - if (tid <= 0) tid = execution_async_id(); - return tid; -} - -inline void Environment::set_init_trigger_async_id(const double id) { - async_hooks()->async_id_fields()[AsyncHooks::kInitTriggerAsyncId] = id; +inline double Environment::get_default_trigger_async_id() { + double default_trigger_async_id = + async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId]; + // If defaultTriggerAsyncId isn't set, use the executionAsyncId + if (default_trigger_async_id < 0) + default_trigger_async_id = execution_async_id(); + return default_trigger_async_id; } inline double* Environment::heap_statistics_buffer() const { @@ -521,7 +528,7 @@ void Environment::SetImmediate(native_immediate_callback cb, } inline performance::performance_state* Environment::performance_state() { - return performance_state_; + return performance_state_.get(); } inline std::map* Environment::performance_marks() { diff --git a/src/env.cc b/src/env.cc index 64fc2dea04e8d1..902429e18a7e74 100644 --- a/src/env.cc +++ b/src/env.cc @@ -323,4 +323,20 @@ void Environment::ActivateImmediateCheck() { uv_idle_start(&immediate_idle_handle_, [](uv_idle_t*){ }); } +void Environment::AsyncHooks::grow_async_ids_stack() { + const uint32_t old_capacity = async_ids_stack_.Length() / 2; + const uint32_t new_capacity = old_capacity * 1.5; + AliasedBuffer new_buffer( + env()->isolate(), new_capacity * 2); + + for (uint32_t i = 0; i < old_capacity * 2; ++i) + new_buffer[i] = async_ids_stack_[i]; + async_ids_stack_ = std::move(new_buffer); + + env()->async_hooks_binding()->Set( + env()->context(), + env()->async_ids_stack_string(), + async_ids_stack_.GetJSArray()).FromJust(); +} + } // namespace node diff --git a/src/env.h b/src/env.h index 79ef42a5c0159e..748c15f8af78f1 100644 --- a/src/env.h +++ b/src/env.h @@ -41,7 +41,6 @@ #include #include #include -#include #include struct nghttp2_rcbuf; @@ -49,7 +48,7 @@ struct nghttp2_rcbuf; namespace node { namespace performance { -struct performance_state; +class performance_state; } namespace loader { @@ -100,6 +99,7 @@ class ModuleWrap; V(address_string, "address") \ V(args_string, "args") \ V(async, "async") \ + V(async_ids_stack_string, "async_ids_stack") \ V(buffer_string, "buffer") \ V(bytes_string, "bytes") \ V(bytes_parsed_string, "bytesParsed") \ @@ -165,7 +165,6 @@ class ModuleWrap; V(internal_string, "internal") \ V(ipv4_string, "IPv4") \ V(ipv6_string, "IPv6") \ - V(isalive_string, "isAlive") \ V(isclosing_string, "isClosing") \ V(issuer_string, "issuer") \ V(issuercert_string, "issuerCertificate") \ @@ -250,7 +249,6 @@ class ModuleWrap; V(subject_string, "subject") \ V(subjectaltname_string, "subjectaltname") \ V(syscall_string, "syscall") \ - V(tick_domain_cb_string, "_tickDomainCallback") \ V(ticketkeycallback_string, "onticketkeycallback") \ V(timeout_string, "timeout") \ V(tls_ticket_string, "tlsTicket") \ @@ -282,15 +280,13 @@ class ModuleWrap; V(async_hooks_before_function, v8::Function) \ V(async_hooks_after_function, v8::Function) \ V(async_hooks_promise_resolve_function, v8::Function) \ - V(binding_cache_object, v8::Object) \ - V(internal_binding_cache_object, v8::Object) \ + V(async_hooks_binding, v8::Object) \ V(buffer_prototype_object, v8::Object) \ V(context, v8::Context) \ V(http2ping_constructor_template, v8::ObjectTemplate) \ V(http2stream_constructor_template, v8::ObjectTemplate) \ V(http2settings_constructor_template, v8::ObjectTemplate) \ V(inspector_console_api_object, v8::Object) \ - V(module_load_list_array, v8::Array) \ V(pbkdf2_constructor_template, v8::ObjectTemplate) \ V(pipe_constructor_template, v8::FunctionTemplate) \ V(performance_entry_callback, v8::Function) \ @@ -314,11 +310,6 @@ class ModuleWrap; class Environment; -struct node_async_ids { - double async_id; - double trigger_async_id; -}; - class IsolateData { public: IsolateData(v8::Isolate* isolate, uv_loop_t* event_loop, @@ -382,6 +373,7 @@ class Environment { kPromiseResolve, kTotals, kCheck, + kStackLength, kFieldsCount, }; @@ -389,55 +381,57 @@ class Environment { kExecutionAsyncId, kTriggerAsyncId, kAsyncIdCounter, - kInitTriggerAsyncId, + kDefaultTriggerAsyncId, kUidFieldsCount, }; - AsyncHooks() = delete; - inline AliasedBuffer& fields(); inline AliasedBuffer& async_id_fields(); + inline AliasedBuffer& async_ids_stack(); inline v8::Local provider_string(int idx); inline void no_force_checks(); + inline Environment* env(); inline void push_async_ids(double async_id, double trigger_async_id); inline bool pop_async_id(double async_id); - inline size_t stack_size(); inline void clear_async_id_stack(); // Used in fatal exceptions. - // Used to propagate the trigger_async_id to the constructor of any newly - // created resources using RAII. Instead of needing to pass the - // trigger_async_id along with other constructor arguments. - class InitScope { + // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of + // passing the trigger_async_id along with other constructor arguments. + class DefaultTriggerAsyncIdScope { public: - InitScope() = delete; - explicit InitScope(Environment* env, double init_trigger_async_id); - ~InitScope(); + DefaultTriggerAsyncIdScope() = delete; + explicit DefaultTriggerAsyncIdScope(Environment* env, + double init_trigger_async_id); + ~DefaultTriggerAsyncIdScope(); private: - Environment* env_; AliasedBuffer async_id_fields_ref_; + double old_default_trigger_async_id_; - DISALLOW_COPY_AND_ASSIGN(InitScope); + DISALLOW_COPY_AND_ASSIGN(DefaultTriggerAsyncIdScope); }; + private: friend class Environment; // So we can call the constructor. - inline explicit AsyncHooks(v8::Isolate* isolate); + inline AsyncHooks(); // Keep a list of all Persistent strings used for Provider types. v8::Eternal providers_[AsyncWrap::PROVIDERS_LENGTH]; - // Used by provider_string(). - v8::Isolate* isolate_; + // Keep track of the environment copy itself. + Environment* env_; // Stores the ids of the current execution context stack. - std::stack async_ids_stack_; + AliasedBuffer async_ids_stack_; // Attached to a Uint32Array that tracks the number of active hooks for // each type. AliasedBuffer fields_; // Attached to a Float64Array that tracks the state of async resources. AliasedBuffer async_id_fields_; + void grow_async_ids_stack(); + DISALLOW_COPY_AND_ASSIGN(AsyncHooks); }; @@ -565,8 +559,7 @@ class Environment { inline double new_async_id(); inline double execution_async_id(); inline double trigger_async_id(); - inline double get_init_trigger_async_id(); - inline void set_init_trigger_async_id(const double id); + inline double get_default_trigger_async_id(); // List of id's that have been destroyed and need the destroy() cb called. inline std::vector* destroy_async_id_list(); @@ -683,6 +676,8 @@ class Environment { inline bool inside_should_not_abort_on_uncaught_scope() const; + static inline Environment* ForAsyncHooks(AsyncHooks* hooks); + private: inline void ThrowError(v8::Local (*fun)(v8::Local), const char* errmsg); @@ -710,7 +705,7 @@ class Environment { int should_not_abort_scope_counter_ = 0; - performance::performance_state* performance_state_ = nullptr; + std::unique_ptr performance_state_; std::map performance_marks_; #if HAVE_INSPECTOR diff --git a/src/js_stream.cc b/src/js_stream.cc index c4e32feeba0f7d..7d1115f12ac3e2 100644 --- a/src/js_stream.cc +++ b/src/js_stream.cc @@ -14,9 +14,9 @@ using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Local; -using v8::MaybeLocal; using v8::Object; using v8::String; +using v8::TryCatch; using v8::Value; @@ -80,37 +80,48 @@ AsyncWrap* JSStream::GetAsyncWrap() { bool JSStream::IsAlive() { - HandleScope scope(env()->isolate()); - Context::Scope context_scope(env()->context()); - v8::Local fn = object()->Get(env()->isalive_string()); - if (!fn->IsFunction()) - return false; - return MakeCallback(fn.As(), 0, nullptr) - .ToLocalChecked()->IsTrue(); + return true; } bool JSStream::IsClosing() { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); - return MakeCallback(env()->isclosing_string(), 0, nullptr) - .ToLocalChecked()->IsTrue(); + TryCatch try_catch(env()->isolate()); + Local value; + if (!MakeCallback(env()->isclosing_string(), 0, nullptr).ToLocal(&value)) { + FatalException(env()->isolate(), try_catch); + return true; + } + return value->IsTrue(); } int JSStream::ReadStart() { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); - return MakeCallback(env()->onreadstart_string(), 0, nullptr) - .ToLocalChecked()->Int32Value(); + TryCatch try_catch(env()->isolate()); + Local value; + int value_int = UV_EPROTO; + if (!MakeCallback(env()->onreadstart_string(), 0, nullptr).ToLocal(&value) || + !value->Int32Value(env()->context()).To(&value_int)) { + FatalException(env()->isolate(), try_catch); + } + return value_int; } int JSStream::ReadStop() { HandleScope scope(env()->isolate()); Context::Scope context_scope(env()->context()); - return MakeCallback(env()->onreadstop_string(), 0, nullptr) - .ToLocalChecked()->Int32Value(); + TryCatch try_catch(env()->isolate()); + Local value; + int value_int = UV_EPROTO; + if (!MakeCallback(env()->onreadstop_string(), 0, nullptr).ToLocal(&value) || + !value->Int32Value(env()->context()).To(&value_int)) { + FatalException(env()->isolate(), try_catch); + } + return value_int; } @@ -123,10 +134,17 @@ int JSStream::DoShutdown(ShutdownWrap* req_wrap) { }; req_wrap->Dispatched(); - MaybeLocal res = - MakeCallback(env()->onshutdown_string(), arraysize(argv), argv); - return res.ToLocalChecked()->Int32Value(); + TryCatch try_catch(env()->isolate()); + Local value; + int value_int = UV_EPROTO; + if (!MakeCallback(env()->onshutdown_string(), + arraysize(argv), + argv).ToLocal(&value) || + !value->Int32Value(env()->context()).To(&value_int)) { + FatalException(env()->isolate(), try_catch); + } + return value_int; } @@ -152,10 +170,17 @@ int JSStream::DoWrite(WriteWrap* w, }; w->Dispatched(); - MaybeLocal res = - MakeCallback(env()->onwrite_string(), arraysize(argv), argv); - return res.ToLocalChecked()->Int32Value(); + TryCatch try_catch(env()->isolate()); + Local value; + int value_int = UV_EPROTO; + if (!MakeCallback(env()->onwrite_string(), + arraysize(argv), + argv).ToLocal(&value) || + !value->Int32Value(env()->context()).To(&value_int)) { + FatalException(env()->isolate(), try_catch); + } + return value_int; } diff --git a/src/node.cc b/src/node.cc index 55e5ad3dd71a75..cc2bdefbb41f66 100644 --- a/src/node.cc +++ b/src/node.cc @@ -1379,17 +1379,13 @@ MaybeLocal InternalMakeCallback(Environment* env, return Undefined(env->isolate()); } - MaybeLocal ret; + MaybeLocal ret = callback->Call(env->context(), recv, argc, argv); - { - ret = callback->Call(env->context(), recv, argc, argv); - - if (ret.IsEmpty()) { - // NOTE: For backwards compatibility with public API we return Undefined() - // if the top level call threw. - scope.MarkAsFailed(); - return scope.IsInnerMakeCallback() ? ret : Undefined(env->isolate()); - } + if (ret.IsEmpty()) { + // NOTE: For backwards compatibility with public API we return Undefined() + // if the top level call threw. + scope.MarkAsFailed(); + return scope.IsInnerMakeCallback() ? ret : Undefined(env->isolate()); } scope.Close(); @@ -2839,22 +2835,6 @@ Maybe ProcessEmitDeprecationWarning(Environment* env, } -static bool PullFromCache(Environment* env, - const FunctionCallbackInfo& args, - Local module, - Local cache) { - Local context = env->context(); - Local exports_v; - Local exports; - if (cache->Get(context, module).ToLocal(&exports_v) && - exports_v->IsObject() && - exports_v->ToObject(context).ToLocal(&exports)) { - args.GetReturnValue().Set(exports); - return true; - } - return false; -} - static Local InitModule(Environment* env, node_module* mod, Local module) { @@ -2882,22 +2862,10 @@ static void ThrowIfNoSuchModule(Environment* env, const char* module_v) { static void Binding(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - Local module; - if (!args[0]->ToString(env->context()).ToLocal(&module)) return; - - Local cache = env->binding_cache_object(); - - if (PullFromCache(env, args, module, cache)) - return; + CHECK(args[0]->IsString()); - // Append a string to process.moduleLoadList - char buf[1024]; + Local module = args[0].As(); node::Utf8Value module_v(env->isolate(), module); - snprintf(buf, sizeof(buf), "Binding %s", *module_v); - - Local modules = env->module_load_list_array(); - uint32_t l = modules->Length(); - modules->Set(l, OneByteString(env->isolate(), buf)); node_module* mod = get_builtin_module(*module_v); Local exports; @@ -2914,7 +2882,6 @@ static void Binding(const FunctionCallbackInfo& args) { } else { return ThrowIfNoSuchModule(env, *module_v); } - cache->Set(module, exports); args.GetReturnValue().Set(exports); } @@ -2922,27 +2889,14 @@ static void Binding(const FunctionCallbackInfo& args) { static void InternalBinding(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - Local module; - if (!args[0]->ToString(env->context()).ToLocal(&module)) return; - - Local cache = env->internal_binding_cache_object(); - - if (PullFromCache(env, args, module, cache)) - return; + CHECK(args[0]->IsString()); - // Append a string to process.moduleLoadList - char buf[1024]; + Local module = args[0].As(); node::Utf8Value module_v(env->isolate(), module); - snprintf(buf, sizeof(buf), "Internal Binding %s", *module_v); - - Local modules = env->module_load_list_array(); - uint32_t l = modules->Length(); - modules->Set(l, OneByteString(env->isolate(), buf)); node_module* mod = get_internal_module(*module_v); if (mod == nullptr) return ThrowIfNoSuchModule(env, *module_v); Local exports = InitModule(env, mod, module); - cache->Set(module, exports); args.GetReturnValue().Set(exports); } @@ -2950,14 +2904,9 @@ static void InternalBinding(const FunctionCallbackInfo& args) { static void LinkedBinding(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); - Local module_name; - if (!args[0]->ToString(env->context()).ToLocal(&module_name)) return; - - Local cache = env->binding_cache_object(); - Local exports_v = cache->Get(module_name); + CHECK(args[0]->IsString()); - if (exports_v->IsObject()) - return args.GetReturnValue().Set(exports_v.As()); + Local module_name = args[0].As(); node::Utf8Value module_name_v(env->isolate(), module_name); node_module* mod = get_linked_module(*module_name_v); @@ -2988,7 +2937,6 @@ static void LinkedBinding(const FunctionCallbackInfo& args) { } auto effective_exports = module->Get(exports_prop); - cache->Set(module_name, effective_exports); args.GetReturnValue().Set(effective_exports); } @@ -3323,11 +3271,6 @@ void SetupProcessObject(Environment* env, "version", FIXED_ONE_BYTE_STRING(env->isolate(), NODE_VERSION)); - // process.moduleLoadList - READONLY_PROPERTY(process, - "moduleLoadList", - env->module_load_list_array()); - // process.versions Local versions = Object::New(env->isolate()); READONLY_PROPERTY(process, "versions", versions); @@ -3368,6 +3311,12 @@ void SetupProcessObject(Environment* env, "nghttp2", FIXED_ONE_BYTE_STRING(env->isolate(), NGHTTP2_VERSION)); + const char node_napi_version[] = NODE_STRINGIFY(NAPI_VERSION); + READONLY_PROPERTY( + versions, + "napi", + FIXED_ONE_BYTE_STRING(env->isolate(), node_napi_version)); + // process._promiseRejectEvent Local promiseRejectEvent = Object::New(env->isolate()); READONLY_DONT_ENUM_PROPERTY(process, diff --git a/src/node_api.cc b/src/node_api.cc index ac0b0959b599d6..27ab6707de7a6f 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -18,8 +18,6 @@ #include "node_api.h" #include "node_internals.h" -#define NAPI_VERSION 2 - static napi_status napi_set_last_error(napi_env env, napi_status error_code, uint32_t engine_error_code = 0, @@ -144,6 +142,30 @@ struct napi_env__ { (!try_catch.HasCaught() ? napi_ok \ : napi_set_last_error((env), napi_pending_exception)) +#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ + do { \ + if (!(condition)) { \ + napi_throw_range_error((env), (error), (message)); \ + return napi_set_last_error((env), napi_generic_failure); \ + } \ + } while (0) + +#define CREATE_TYPED_ARRAY( \ + env, type, size_of_element, buffer, byte_offset, length, out) \ + do { \ + if ((size_of_element) > 1) { \ + THROW_RANGE_ERROR_IF_FALSE( \ + (env), (byte_offset) % (size_of_element) == 0, \ + "ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT", \ + "start offset of "#type" should be a multiple of "#size_of_element); \ + } \ + THROW_RANGE_ERROR_IF_FALSE((env), (length) * (size_of_element) + \ + (byte_offset) <= buffer->ByteLength(), \ + "ERR_NAPI_INVALID_TYPEDARRAY_LENGTH", \ + "Invalid typed array length"); \ + (out) = v8::type::New((buffer), (byte_offset), (length)); \ + } while (0) + namespace { namespace v8impl { @@ -3065,31 +3087,40 @@ napi_status napi_create_typedarray(napi_env env, switch (type) { case napi_int8_array: - typedArray = v8::Int8Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Int8Array, 1, buffer, byte_offset, length, typedArray); break; case napi_uint8_array: - typedArray = v8::Uint8Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Uint8Array, 1, buffer, byte_offset, length, typedArray); break; case napi_uint8_clamped_array: - typedArray = v8::Uint8ClampedArray::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Uint8ClampedArray, 1, buffer, byte_offset, length, typedArray); break; case napi_int16_array: - typedArray = v8::Int16Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Int16Array, 2, buffer, byte_offset, length, typedArray); break; case napi_uint16_array: - typedArray = v8::Uint16Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Uint16Array, 2, buffer, byte_offset, length, typedArray); break; case napi_int32_array: - typedArray = v8::Int32Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Int32Array, 4, buffer, byte_offset, length, typedArray); break; case napi_uint32_array: - typedArray = v8::Uint32Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Uint32Array, 4, buffer, byte_offset, length, typedArray); break; case napi_float32_array: - typedArray = v8::Float32Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Float32Array, 4, buffer, byte_offset, length, typedArray); break; case napi_float64_array: - typedArray = v8::Float64Array::New(buffer, byte_offset, length); + CREATE_TYPED_ARRAY( + env, Float64Array, 8, buffer, byte_offset, length, typedArray); break; default: return napi_set_last_error(env, napi_invalid_arg); @@ -3170,6 +3201,14 @@ napi_status napi_create_dataview(napi_env env, RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg); v8::Local buffer = value.As(); + if (byte_length + byte_offset > buffer->ByteLength()) { + napi_throw_range_error( + env, + "ERR_NAPI_INVALID_DATAVIEW_ARGS", + "byte_offset + byte_length should be less than or " + "equal to the size in bytes of the array passed in"); + return napi_set_last_error(env, napi_pending_exception); + } v8::Local DataView = v8::DataView::New(buffer, byte_offset, byte_length); diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 7008395ce46392..dff9d3c0995e02 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -303,15 +303,14 @@ MaybeLocal New(Environment* env, size_t length) { data, length, ArrayBufferCreationMode::kInternalized); - Local ui = Uint8Array::New(ab, 0, length); - Maybe mb = - ui->SetPrototype(env->context(), env->buffer_prototype_object()); - if (mb.FromMaybe(false)) - return scope.Escape(ui); + MaybeLocal ui = Buffer::New(env, ab, 0, length); - // Object failed to be created. Clean up resources. - free(data); - return Local(); + if (ui.IsEmpty()) { + // Object failed to be created. Clean up resources. + free(data); + } + + return scope.Escape(ui.FromMaybe(Local())); } @@ -349,15 +348,14 @@ MaybeLocal Copy(Environment* env, const char* data, size_t length) { new_data, length, ArrayBufferCreationMode::kInternalized); - Local ui = Uint8Array::New(ab, 0, length); - Maybe mb = - ui->SetPrototype(env->context(), env->buffer_prototype_object()); - if (mb.FromMaybe(false)) - return scope.Escape(ui); + MaybeLocal ui = Buffer::New(env, ab, 0, length); - // Object failed to be created. Clean up resources. - free(new_data); - return Local(); + if (ui.IsEmpty()) { + // Object failed to be created. Clean up resources. + free(new_data); + } + + return scope.Escape(ui.FromMaybe(Local())); } @@ -392,15 +390,14 @@ MaybeLocal New(Environment* env, // correct. if (data == nullptr) ab->Neuter(); - Local ui = Uint8Array::New(ab, 0, length); - Maybe mb = - ui->SetPrototype(env->context(), env->buffer_prototype_object()); + MaybeLocal ui = Buffer::New(env, ab, 0, length); - if (!mb.FromMaybe(false)) + if (ui.IsEmpty()) { return Local(); + } CallbackInfo::New(env->isolate(), ab, callback, data, hint); - return scope.Escape(ui); + return scope.Escape(ui.ToLocalChecked()); } @@ -415,8 +412,6 @@ MaybeLocal New(Isolate* isolate, char* data, size_t length) { MaybeLocal New(Environment* env, char* data, size_t length) { - EscapableHandleScope scope(env->isolate()); - if (length > 0) { CHECK_NE(data, nullptr); CHECK(length <= kMaxLength); @@ -427,12 +422,7 @@ MaybeLocal New(Environment* env, char* data, size_t length) { data, length, ArrayBufferCreationMode::kInternalized); - Local ui = Uint8Array::New(ab, 0, length); - Maybe mb = - ui->SetPrototype(env->context(), env->buffer_prototype_object()); - if (mb.FromMaybe(false)) - return scope.Escape(ui); - return Local(); + return Buffer::New(env, ab, 0, length).FromMaybe(Local()); } namespace { diff --git a/src/node_http2.cc b/src/node_http2.cc index 238e2afc1deb71..bd7eeee8655e52 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -9,6 +9,7 @@ namespace node { +using v8::ArrayBuffer; using v8::Boolean; using v8::Context; using v8::Float64Array; @@ -553,7 +554,8 @@ Http2Session::~Http2Session() { } inline bool HasHttp2Observer(Environment* env) { - uint32_t* observers = env->performance_state()->observers; + AliasedBuffer& observers = + env->performance_state()->observers; return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0; } @@ -831,7 +833,7 @@ inline int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle, } // Called by nghttp2 for each header name/value pair in a HEADERS block. -// This had to have been preceeded by a call to OnBeginHeadersCallback so +// This had to have been preceded by a call to OnBeginHeadersCallback so // the Http2Stream is guaranteed to already exist. inline int Http2Session::OnHeaderCallback(nghttp2_session* handle, const nghttp2_frame* frame, @@ -978,7 +980,6 @@ inline int Http2Session::OnStreamClose(nghttp2_session* handle, // Intentionally ignore the callback if the stream does not exist or has // already been destroyed if (stream != nullptr && !stream->IsDestroyed()) { - stream->AddChunk(nullptr, 0); stream->Close(code); // It is possible for the stream close to occur before the stream is // ever passed on to the javascript side. If that happens, skip straight @@ -989,9 +990,8 @@ inline int Http2Session::OnStreamClose(nghttp2_session* handle, stream->object()->Get(context, env->onstreamclose_string()) .ToLocalChecked(); if (fn->IsFunction()) { - Local argv[2] = { - Integer::NewFromUnsigned(isolate, code), - Boolean::New(isolate, stream->HasDataChunks(true)) + Local argv[] = { + Integer::NewFromUnsigned(isolate, code) }; stream->MakeCallback(fn.As(), arraysize(argv), argv); } else { @@ -1028,6 +1028,8 @@ inline int Http2Session::OnDataChunkReceived(nghttp2_session* handle, Http2Session* session = static_cast(user_data); DEBUG_HTTP2SESSION2(session, "buffering data chunk for stream %d, size: " "%d, flags: %d", id, len, flags); + Environment* env = session->env(); + HandleScope scope(env->isolate()); // We should never actually get a 0-length chunk so this check is // only a precaution at this point. if (len > 0) { @@ -1039,8 +1041,25 @@ inline int Http2Session::OnDataChunkReceived(nghttp2_session* handle, // If the stream has been destroyed, ignore this chunk if (stream->IsDestroyed()) return 0; + stream->statistics_.received_bytes += len; - stream->AddChunk(data, len); + + // There is a single large array buffer for the entire data read from the + // network; create a slice of that array buffer and emit it as the + // received data buffer. + CHECK(!session->stream_buf_ab_.IsEmpty()); + size_t offset = reinterpret_cast(data) - session->stream_buf_; + // Verify that the data offset is inside the current read buffer. + CHECK_LE(offset, session->stream_buf_size_); + + Local buf = + Buffer::New(env, session->stream_buf_ab_, offset, len).ToLocalChecked(); + + stream->EmitData(len, buf, Local()); + if (!stream->IsReading()) + stream->inbound_consumed_data_while_paused_ += len; + else + nghttp2_session_consume_stream(handle, id, len); } return 0; } @@ -1226,9 +1245,8 @@ inline void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) { // Called by OnFrameReceived when a complete DATA frame has been received. -// If we know that this is the last DATA frame (because the END_STREAM flag -// is set), then we'll terminate the readable side of the StreamBase. If -// the StreamBase is flowing, we'll push the chunks of data out to JS land. +// If we know that this was the last DATA frame (because the END_STREAM flag +// is set), then we'll terminate the readable side of the StreamBase. inline void Http2Session::HandleDataFrame(const nghttp2_frame* frame) { int32_t id = GetFrameID(frame); DEBUG_HTTP2SESSION2(this, "handling data frame for stream %d", id); @@ -1239,11 +1257,8 @@ inline void Http2Session::HandleDataFrame(const nghttp2_frame* frame) { return; if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) { - stream->AddChunk(nullptr, 0); + stream->EmitData(UV_EOF, Local(), Local()); } - - if (stream->IsReading()) - stream->FlushDataChunks(); } @@ -1618,45 +1633,67 @@ void Http2Session::OnStreamAllocImpl(size_t suggested_size, uv_buf_t* buf, void* ctx) { Http2Session* session = static_cast(ctx); - buf->base = session->stream_alloc(); - buf->len = kAllocBufferSize; + CHECK_EQ(session->stream_buf_, nullptr); + CHECK_EQ(session->stream_buf_size_, 0); + buf->base = session->stream_buf_ = Malloc(suggested_size); + buf->len = session->stream_buf_size_ = suggested_size; + session->IncrementCurrentSessionMemory(suggested_size); } // Callback used to receive inbound data from the i/o stream void Http2Session::OnStreamReadImpl(ssize_t nread, - const uv_buf_t* bufs, + const uv_buf_t* buf, uv_handle_type pending, void* ctx) { Http2Session* session = static_cast(ctx); Http2Scope h2scope(session); CHECK_NE(session->stream_, nullptr); DEBUG_HTTP2SESSION2(session, "receiving %d bytes", nread); - if (nread < 0) { - uv_buf_t tmp_buf; - tmp_buf.base = nullptr; - tmp_buf.len = 0; - session->prev_read_cb_.fn(nread, - &tmp_buf, - pending, - session->prev_read_cb_.ctx); - return; - } - if (bufs->len > 0) { + if (nread <= 0) { + free(session->stream_buf_); + if (nread < 0) { + uv_buf_t tmp_buf = uv_buf_init(nullptr, 0); + session->prev_read_cb_.fn(nread, + &tmp_buf, + pending, + session->prev_read_cb_.ctx); + } + } else { // Only pass data on if nread > 0 - uv_buf_t buf[] { uv_buf_init((*bufs).base, nread) }; + + // Verify that currently: There is memory allocated into which + // the data has been read, and that memory buffer is at least as large + // as the amount of data we have read, but we have not yet made an + // ArrayBuffer out of it. + CHECK_NE(session->stream_buf_, nullptr); + CHECK_EQ(session->stream_buf_, buf->base); + CHECK_EQ(session->stream_buf_size_, buf->len); + CHECK_GE(session->stream_buf_size_, static_cast(nread)); + CHECK(session->stream_buf_ab_.IsEmpty()); + + Environment* env = session->env(); + Isolate* isolate = env->isolate(); + HandleScope scope(isolate); + Local context = env->context(); + Context::Scope context_scope(context); + + // Create an array buffer for the read data. DATA frames will be emitted + // as slices of this array buffer to avoid having to copy memory. + session->stream_buf_ab_ = + ArrayBuffer::New(isolate, + session->stream_buf_, + session->stream_buf_size_, + v8::ArrayBufferCreationMode::kInternalized); + + uv_buf_t buf_ = uv_buf_init(buf->base, nread); session->statistics_.data_received += nread; - ssize_t ret = session->Write(buf, 1); + ssize_t ret = session->Write(&buf_, 1); // Note: if ssize_t is not defined (e.g. on Win32), nghttp2 will typedef // ssize_t to int. Cast here so that the < 0 check actually works on // Windows. if (static_cast(ret) < 0) { DEBUG_HTTP2SESSION2(session, "fatal error receiving data: %d", ret); - Environment* env = session->env(); - Isolate* isolate = env->isolate(); - HandleScope scope(isolate); - Local context = env->context(); - Context::Scope context_scope(context); Local argv[1] = { Integer::New(isolate, ret), @@ -1667,6 +1704,13 @@ void Http2Session::OnStreamReadImpl(ssize_t nread, nghttp2_session_want_read(**session)); } } + + // Since we are finished handling this write, reset the stream buffer. + // The memory has either been free()d or was handed over to V8. + session->DecrementCurrentSessionMemory(session->stream_buf_size_); + session->stream_buf_ = nullptr; + session->stream_buf_size_ = 0; + session->stream_buf_ab_ = Local(); } void Http2Session::OnStreamDestructImpl(void* ctx) { @@ -1781,30 +1825,6 @@ void Http2Stream::OnTrailers(const SubmitTrailers& submit_trailers) { } } -inline bool Http2Stream::HasDataChunks(bool ignore_eos) { - return data_chunks_.size() > (ignore_eos ? 1 : 0); -} - -// Appends a chunk of received DATA frame data to this Http2Streams internal -// queue. Note that we must memcpy each chunk because of the way that nghttp2 -// handles it's internal memory`. -inline void Http2Stream::AddChunk(const uint8_t* data, size_t len) { - CHECK(!this->IsDestroyed()); - if (this->statistics_.first_byte == 0) - this->statistics_.first_byte = uv_hrtime(); - if (flags_ & NGHTTP2_STREAM_FLAG_EOS) - return; - char* buf = nullptr; - if (len > 0 && data != nullptr) { - buf = Malloc(len); - memcpy(buf, data, len); - } else if (data == nullptr) { - flags_ |= NGHTTP2_STREAM_FLAG_EOS; - } - data_chunks_.emplace(uv_buf_init(buf, len)); -} - - inline void Http2Stream::Close(int32_t code) { CHECK(!this->IsDestroyed()); flags_ |= NGHTTP2_STREAM_FLAG_CLOSED; @@ -1841,13 +1861,6 @@ inline void Http2Stream::Destroy() { DEBUG_HTTP2STREAM(this, "destroying stream"); - // Free any remaining incoming data chunks. - while (!data_chunks_.empty()) { - uv_buf_t buf = data_chunks_.front(); - free(buf.base); - data_chunks_.pop(); - } - // Wait until the start of the next loop to delete because there // may still be some pending operations queued for this stream. env()->SetImmediate([](Environment* env, void* data) { @@ -1873,39 +1886,6 @@ inline void Http2Stream::Destroy() { } -// Uses the StreamBase API to push a single chunk of queued inbound DATA -// to JS land. -void Http2Stream::OnDataChunk(uv_buf_t* chunk) { - CHECK(!this->IsDestroyed()); - Isolate* isolate = env()->isolate(); - HandleScope scope(isolate); - ssize_t len = -1; - Local buf; - if (chunk != nullptr) { - len = chunk->len; - buf = Buffer::New(isolate, chunk->base, len).ToLocalChecked(); - } - EmitData(len, buf, this->object()); -} - - -inline void Http2Stream::FlushDataChunks() { - CHECK(!this->IsDestroyed()); - Http2Scope h2scope(this); - if (!data_chunks_.empty()) { - uv_buf_t buf = data_chunks_.front(); - data_chunks_.pop(); - if (buf.len > 0) { - CHECK_EQ(nghttp2_session_consume_stream(session_->session(), - id_, buf.len), 0); - OnDataChunk(&buf); - } else { - OnDataChunk(nullptr); - } - } -} - - // Initiates a response on the Http2Stream using data provided via the // StreamBase Streams API. inline int Http2Stream::SubmitResponse(nghttp2_nv* nva, @@ -2012,13 +1992,20 @@ inline Http2Stream* Http2Stream::SubmitPushPromise(nghttp2_nv* nva, // Switch the StreamBase into flowing mode to begin pushing chunks of data // out to JS land. inline int Http2Stream::ReadStart() { + Http2Scope h2scope(this); CHECK(!this->IsDestroyed()); flags_ |= NGHTTP2_STREAM_FLAG_READ_START; flags_ &= ~NGHTTP2_STREAM_FLAG_READ_PAUSED; - // Flush any queued data chunks immediately out to the JS layer - FlushDataChunks(); DEBUG_HTTP2STREAM(this, "reading starting"); + + // Tell nghttp2 about our consumption of the data that was handed + // off to JS land. + nghttp2_session_consume_stream(session_->session(), + id_, + inbound_consumed_data_while_paused_); + inbound_consumed_data_while_paused_ = 0; + return 0; } @@ -2731,7 +2718,7 @@ void Http2Session::Ping(const FunctionCallbackInfo& args) { return args.GetReturnValue().Set(false); } - // The Ping itself is an Async resource. When the acknowledgement is recieved, + // The Ping itself is an Async resource. When the acknowledgement is received, // the callback will be invoked and a notification sent out to JS land. The // notification will include the duration of the ping, allowing the round // trip to be measured. diff --git a/src/node_http2.h b/src/node_http2.h index 765f7294768489..9027ed7feb7dad 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -550,12 +550,6 @@ class Http2Stream : public AsyncWrap, inline void EmitStatistics(); - inline bool HasDataChunks(bool ignore_eos = false); - - inline void AddChunk(const uint8_t* data, size_t len); - - inline void FlushDataChunks(); - // Process a Data Chunk void OnDataChunk(uv_buf_t* chunk); @@ -740,8 +734,11 @@ class Http2Stream : public AsyncWrap, uint32_t current_headers_length_ = 0; // total number of octets std::vector current_headers_; - // Inbound Data... This is the data received via DATA frames for this stream. - std::queue data_chunks_; + // This keeps track of the amount of data read from the socket while the + // socket was in paused mode. When `ReadStart()` is called (and not before + // then), we tell nghttp2 that we consumed that data to get proper + // backpressure handling. + size_t inbound_consumed_data_while_paused_ = 0; // Outbound Data... This is the data written by the JS layer that is // waiting to be written out to the socket. @@ -1048,24 +1045,6 @@ class Http2Session : public AsyncWrap { int lib_error_code, void* user_data); - - static inline ssize_t OnStreamReadFD( - nghttp2_session* session, - int32_t id, - uint8_t* buf, - size_t length, - uint32_t* flags, - nghttp2_data_source* source, - void* user_data); - static inline ssize_t OnStreamRead( - nghttp2_session* session, - int32_t id, - uint8_t* buf, - size_t length, - uint32_t* flags, - nghttp2_data_source* source, - void* user_data); - struct Callbacks { inline explicit Callbacks(bool kHasGetPaddingCallback); inline ~Callbacks(); @@ -1103,8 +1082,9 @@ class Http2Session : public AsyncWrap { // use this to allow timeout tracking during long-lasting writes uint32_t chunks_sent_since_last_write_ = 0; - uv_prepare_t* prep_ = nullptr; - char stream_buf_[kAllocBufferSize]; + char* stream_buf_ = nullptr; + size_t stream_buf_size_ = 0; + v8::Local stream_buf_ab_; size_t max_outstanding_pings_ = DEFAULT_MAX_PINGS; std::queue outstanding_pings_; diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index f378a0475a65c0..9debb8a205ef1c 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -72,22 +72,6 @@ const uint32_t kOnMessageComplete = 3; const uint32_t kOnExecute = 4; -#define HTTP_CB(name) \ - static int name(http_parser* p_) { \ - Parser* self = ContainerOf(&Parser::parser_, p_); \ - return self->name##_(); \ - } \ - int name##_() - - -#define HTTP_DATA_CB(name) \ - static int name(http_parser* p_, const char* at, size_t length) { \ - Parser* self = ContainerOf(&Parser::parser_, p_); \ - return self->name##_(at, length); \ - } \ - int name##_(const char* at, size_t length) - - // helper class for the Parser struct StringPtr { StringPtr() { @@ -182,7 +166,7 @@ class Parser : public AsyncWrap { } - HTTP_CB(on_message_begin) { + int on_message_begin() { num_fields_ = num_values_ = 0; url_.Reset(); status_message_.Reset(); @@ -190,19 +174,19 @@ class Parser : public AsyncWrap { } - HTTP_DATA_CB(on_url) { + int on_url(const char* at, size_t length) { url_.Update(at, length); return 0; } - HTTP_DATA_CB(on_status) { + int on_status(const char* at, size_t length) { status_message_.Update(at, length); return 0; } - HTTP_DATA_CB(on_header_field) { + int on_header_field(const char* at, size_t length) { if (num_fields_ == num_values_) { // start of new field name num_fields_++; @@ -224,7 +208,7 @@ class Parser : public AsyncWrap { } - HTTP_DATA_CB(on_header_value) { + int on_header_value(const char* at, size_t length) { if (num_values_ != num_fields_) { // start of new header value num_values_++; @@ -240,7 +224,7 @@ class Parser : public AsyncWrap { } - HTTP_CB(on_headers_complete) { + int on_headers_complete() { // Arguments for the on-headers-complete javascript callback. This // list needs to be kept in sync with the actual argument list for // `parserOnHeadersComplete` in lib/_http_common.js. @@ -317,7 +301,7 @@ class Parser : public AsyncWrap { } - HTTP_DATA_CB(on_body) { + int on_body(const char* at, size_t length) { EscapableHandleScope scope(env()->isolate()); Local obj = object(); @@ -354,7 +338,7 @@ class Parser : public AsyncWrap { } - HTTP_CB(on_message_complete) { + int on_message_complete() { HandleScope scope(env()->isolate()); if (num_fields_) @@ -392,8 +376,7 @@ class Parser : public AsyncWrap { Parser* parser; ASSIGN_OR_RETURN_UNWRAP(&parser, args.Holder()); - if (--parser->refcount_ == 0) - delete parser; + delete parser; } @@ -559,22 +542,6 @@ class Parser : public AsyncWrap { } protected: - class ScopedRetainParser { - public: - explicit ScopedRetainParser(Parser* p) : p_(p) { - CHECK_GT(p_->refcount_, 0); - p_->refcount_++; - } - - ~ScopedRetainParser() { - if (0 == --p_->refcount_) - delete p_; - } - - private: - Parser* const p_; - }; - static const size_t kAllocBufferSize = 64 * 1024; static void OnAllocImpl(size_t suggested_size, uv_buf_t* buf, void* ctx) { @@ -611,8 +578,6 @@ class Parser : public AsyncWrap { if (nread == 0) return; - ScopedRetainParser retain(parser); - parser->current_buffer_.Clear(); Local ret = parser->Execute(buf->base, nread); @@ -750,22 +715,33 @@ class Parser : public AsyncWrap { char* current_buffer_data_; StreamResource::Callback prev_alloc_cb_; StreamResource::Callback prev_read_cb_; - int refcount_ = 1; - static const struct http_parser_settings settings; - friend class ScopedRetainParser; -}; + // These are helper functions for filling `http_parser_settings`, which turn + // a member function of Parser into a C-style HTTP parser callback. + template struct Proxy; + template + struct Proxy { + static int Raw(http_parser* p, Args ... args) { + Parser* parser = ContainerOf(&Parser::parser_, p); + return (parser->*Member)(std::forward(args)...); + } + }; + + typedef int (Parser::*Call)(); + typedef int (Parser::*DataCall)(const char* at, size_t length); + static const struct http_parser_settings settings; +}; const struct http_parser_settings Parser::settings = { - Parser::on_message_begin, - Parser::on_url, - Parser::on_status, - Parser::on_header_field, - Parser::on_header_value, - Parser::on_headers_complete, - Parser::on_body, - Parser::on_message_complete, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, + Proxy::Raw, nullptr, // on_chunk_header nullptr // on_chunk_complete }; diff --git a/src/node_i18n.cc b/src/node_i18n.cc index 041eda94f3bdd5..71ae6a000336e2 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -788,7 +788,8 @@ static int GetColumnWidth(UChar32 codepoint, if (ambiguous_as_full_width) { return 2; } - // Fall through if ambiguous_as_full_width if false. + // If ambiguous_as_full_width is false: + // Fall through case U_EA_NEUTRAL: if (u_hasBinaryProperty(codepoint, UCHAR_EMOJI_PRESENTATION)) { return 2; diff --git a/src/node_internals.h b/src/node_internals.h index 758df736d35545..06f7b6bdeb23ed 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -357,6 +357,19 @@ v8::MaybeLocal New(Environment* env, // Mixing operator new and free() is undefined behavior so don't do that. v8::MaybeLocal New(Environment* env, char* data, size_t length); +inline +v8::MaybeLocal New(Environment* env, + v8::Local ab, + size_t byte_offset, + size_t length) { + v8::Local ui = v8::Uint8Array::New(ab, byte_offset, length); + v8::Maybe mb = + ui->SetPrototype(env->context(), env->buffer_prototype_object()); + if (mb.IsNothing()) + return v8::MaybeLocal(); + return ui; +} + // Construct a Buffer from a MaybeStackBuffer (and also its subclasses like // Utf8Value and TwoByteValue). // If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is diff --git a/src/node_perf.cc b/src/node_perf.cc index 97d3a2d99522fe..38dbdaca5adce1 100644 --- a/src/node_perf.cc +++ b/src/node_perf.cc @@ -7,7 +7,6 @@ namespace node { namespace performance { using v8::Array; -using v8::ArrayBuffer; using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; @@ -85,9 +84,9 @@ void PerformanceEntry::Notify(Environment* env, PerformanceEntryType type, Local object) { Context::Scope scope(env->context()); - uint32_t* observers = env->performance_state()->observers; - if (observers != nullptr && - type != NODE_PERFORMANCE_ENTRY_TYPE_INVALID && + AliasedBuffer& observers = + env->performance_state()->observers; + if (type != NODE_PERFORMANCE_ENTRY_TYPE_INVALID && observers[type]) { node::MakeCallback(env->isolate(), env->process_object(), @@ -130,7 +129,8 @@ void Measure(const FunctionCallbackInfo& args) { Utf8Value startMark(env->isolate(), args[1]); Utf8Value endMark(env->isolate(), args[2]); - double* milestones = env->performance_state()->milestones; + AliasedBuffer& milestones = + env->performance_state()->milestones; uint64_t startTimestamp = timeOrigin; uint64_t start = GetPerformanceMark(env, *startMark); @@ -165,7 +165,8 @@ void Measure(const FunctionCallbackInfo& args) { void MarkMilestone(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Local context = env->context(); - double* milestones = env->performance_state()->milestones; + AliasedBuffer& milestones = + env->performance_state()->milestones; PerformanceMilestone milestone = static_cast( args[0]->Int32Value(context).ToChecked()); @@ -188,7 +189,8 @@ void PerformanceGCCallback(uv_async_t* handle) { HandleScope scope(env->isolate()); Local context = env->context(); - uint32_t* observers = env->performance_state()->observers; + AliasedBuffer& observers = + env->performance_state()->observers; if (observers[NODE_PERFORMANCE_ENTRY_TYPE_GC]) { Local obj = entry->ToObject(); v8::PropertyAttribute attr = @@ -297,8 +299,8 @@ void TimerFunctionCall(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(ret.ToLocalChecked()); } - - uint32_t* observers = env->performance_state()->observers; + AliasedBuffer& observers = + env->performance_state()->observers; if (!observers[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION]) return; @@ -329,18 +331,13 @@ void Init(Local target, Environment* env = Environment::GetCurrent(context); Isolate* isolate = env->isolate(); performance_state* state = env->performance_state(); - auto state_ab = ArrayBuffer::New(isolate, state, sizeof(*state)); - - #define SET_STATE_TYPEDARRAY(name, type, field) \ - target->Set(context, \ - FIXED_ONE_BYTE_STRING(isolate, (name)), \ - type::New(state_ab, \ - offsetof(performance_state, field), \ - arraysize(state->field))) \ - .FromJust() - SET_STATE_TYPEDARRAY("observerCounts", v8::Uint32Array, observers); - SET_STATE_TYPEDARRAY("milestones", v8::Float64Array, milestones); - #undef SET_STATE_TYPEDARRAY + + target->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "observerCounts"), + state->observers.GetJSArray()).FromJust(); + target->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "milestones"), + state->milestones.GetJSArray()).FromJust(); Local performanceEntryString = FIXED_ONE_BYTE_STRING(isolate, "PerformanceEntry"); diff --git a/src/node_perf_common.h b/src/node_perf_common.h index 713f126d7f70d9..435a4cffe5a753 100644 --- a/src/node_perf_common.h +++ b/src/node_perf_common.h @@ -61,10 +61,33 @@ enum PerformanceEntryType { node::performance::NODE_PERFORMANCE_MILESTONE_##n); \ } while (0); -struct performance_state { - // doubles first so that they are always sizeof(double)-aligned - double milestones[NODE_PERFORMANCE_MILESTONE_INVALID]; - uint32_t observers[NODE_PERFORMANCE_ENTRY_TYPE_INVALID]; +class performance_state { + public: + explicit performance_state(v8::Isolate* isolate) : + root( + isolate, + sizeof(performance_state_internal)), + milestones( + isolate, + offsetof(performance_state_internal, milestones), + NODE_PERFORMANCE_MILESTONE_INVALID, + root), + observers( + isolate, + offsetof(performance_state_internal, observers), + NODE_PERFORMANCE_ENTRY_TYPE_INVALID, + root) {} + + AliasedBuffer root; + AliasedBuffer milestones; + AliasedBuffer observers; + + private: + struct performance_state_internal { + // doubles first so that they are always sizeof(double)-aligned + double milestones[NODE_PERFORMANCE_MILESTONE_INVALID]; + uint32_t observers[NODE_PERFORMANCE_ENTRY_TYPE_INVALID]; + }; }; } // namespace performance diff --git a/src/node_version.h b/src/node_version.h index aa271549247d15..35d856fd6ee1e7 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -23,7 +23,7 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 9 -#define NODE_MINOR_VERSION 4 +#define NODE_MINOR_VERSION 5 #define NODE_PATCH_VERSION 1 #define NODE_VERSION_IS_LTS 0 @@ -108,4 +108,7 @@ */ #define NODE_MODULE_VERSION 59 +// the NAPI_VERSION provided by this version of the runtime +#define NAPI_VERSION 2 + #endif // SRC_NODE_VERSION_H_ diff --git a/src/pipe_wrap.cc b/src/pipe_wrap.cc index 76280f0ce77e86..465cbf4d16dbfe 100644 --- a/src/pipe_wrap.cc +++ b/src/pipe_wrap.cc @@ -53,7 +53,8 @@ Local PipeWrap::Instantiate(Environment* env, AsyncWrap* parent, PipeWrap::SocketType type) { EscapableHandleScope handle_scope(env->isolate()); - AsyncHooks::InitScope init_scope(env, parent->get_async_id()); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(env, + parent->get_async_id()); CHECK_EQ(false, env->pipe_constructor_template().IsEmpty()); Local constructor = env->pipe_constructor_template()->GetFunction(); CHECK_EQ(false, constructor.IsEmpty()); diff --git a/src/stream_base-inl.h b/src/stream_base-inl.h index cc89a11bac249c..cdcff67cc55e66 100644 --- a/src/stream_base-inl.h +++ b/src/stream_base-inl.h @@ -143,7 +143,8 @@ void StreamBase::JSMethod(const FunctionCallbackInfo& args) { if (!wrap->IsAlive()) return args.GetReturnValue().Set(UV_EINVAL); - AsyncHooks::InitScope init_scope(handle->env(), handle->get_async_id()); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope( + handle->env(), handle->get_async_id()); args.GetReturnValue().Set((wrap->*Method)(args)); } diff --git a/src/stream_base.cc b/src/stream_base.cc index bb25fc1cff0e9c..ecb5f3dd1b954e 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -52,7 +52,7 @@ int StreamBase::Shutdown(const FunctionCallbackInfo& args) { AsyncWrap* wrap = GetAsyncWrap(); CHECK_NE(wrap, nullptr); - env->set_init_trigger_async_id(wrap->get_async_id()); + AsyncHooks::DefaultTriggerAsyncIdScope(env, wrap->get_async_id()); ShutdownWrap* req_wrap = new ShutdownWrap(env, req_wrap_obj, this); @@ -109,7 +109,6 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { size_t storage_size = 0; uint32_t bytes = 0; size_t offset; - AsyncWrap* wrap; WriteWrap* req_wrap; int err; @@ -153,10 +152,13 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { goto done; } - wrap = GetAsyncWrap(); - CHECK_NE(wrap, nullptr); - env->set_init_trigger_async_id(wrap->get_async_id()); - req_wrap = WriteWrap::New(env, req_wrap_obj, this, storage_size); + { + AsyncWrap* wrap = GetAsyncWrap(); + CHECK_NE(wrap, nullptr); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(env, + wrap->get_async_id()); + req_wrap = WriteWrap::New(env, req_wrap_obj, this, storage_size); + } offset = 0; if (!all_buffers) { @@ -226,7 +228,6 @@ int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { const char* data = Buffer::Data(args[1]); size_t length = Buffer::Length(args[1]); - AsyncWrap* wrap; WriteWrap* req_wrap; uv_buf_t buf; buf.base = const_cast(data); @@ -242,11 +243,14 @@ int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { goto done; CHECK_EQ(count, 1); - wrap = GetAsyncWrap(); - if (wrap != nullptr) - env->set_init_trigger_async_id(wrap->get_async_id()); // Allocate, or write rest - req_wrap = WriteWrap::New(env, req_wrap_obj, this); + { + AsyncWrap* wrap = GetAsyncWrap(); + CHECK_NE(wrap, nullptr); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(env, + wrap->get_async_id()); + req_wrap = WriteWrap::New(env, req_wrap_obj, this); + } err = DoWrite(req_wrap, bufs, count, nullptr); req_wrap_obj->Set(env->async(), True(env->isolate())); @@ -276,7 +280,6 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { Local req_wrap_obj = args[0].As(); Local string = args[1].As(); Local send_handle_obj; - AsyncWrap* wrap; if (args[2]->IsObject()) send_handle_obj = args[2].As(); @@ -327,10 +330,13 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { CHECK_EQ(count, 1); } - wrap = GetAsyncWrap(); - if (wrap != nullptr) - env->set_init_trigger_async_id(wrap->get_async_id()); - req_wrap = WriteWrap::New(env, req_wrap_obj, this, storage_size); + { + AsyncWrap* wrap = GetAsyncWrap(); + CHECK_NE(wrap, nullptr); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(env, + wrap->get_async_id()); + req_wrap = WriteWrap::New(env, req_wrap_obj, this, storage_size); + } data = req_wrap->Extra(); diff --git a/src/tcp_wrap.cc b/src/tcp_wrap.cc index 8dd14e2e16c18b..bdae0ee994360c 100644 --- a/src/tcp_wrap.cc +++ b/src/tcp_wrap.cc @@ -56,7 +56,8 @@ Local TCPWrap::Instantiate(Environment* env, AsyncWrap* parent, TCPWrap::SocketType type) { EscapableHandleScope handle_scope(env->isolate()); - AsyncHooks::InitScope init_scope(env, parent->get_async_id()); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope( + env, parent->get_async_id()); CHECK_EQ(env->tcp_constructor_template().IsEmpty(), false); Local constructor = env->tcp_constructor_template()->GetFunction(); CHECK_EQ(constructor.IsEmpty(), false); @@ -293,7 +294,8 @@ void TCPWrap::Connect(const FunctionCallbackInfo& args) { int err = uv_ip4_addr(*ip_address, port, &addr); if (err == 0) { - env->set_init_trigger_async_id(wrap->get_async_id()); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope( + env, wrap->get_async_id()); ConnectWrap* req_wrap = new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP); err = uv_tcp_connect(req_wrap->req(), @@ -329,7 +331,8 @@ void TCPWrap::Connect6(const FunctionCallbackInfo& args) { int err = uv_ip6_addr(*ip_address, port, &addr); if (err == 0) { - env->set_init_trigger_async_id(wrap->get_async_id()); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope( + env, wrap->get_async_id()); ConnectWrap* req_wrap = new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP); err = uv_tcp_connect(req_wrap->req(), diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index c661a0ac32ab2b..85858577c54a68 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -118,20 +118,18 @@ TLSWrap::~TLSWrap() { void TLSWrap::MakePending() { - write_item_queue_.MoveBack(&pending_write_items_); + write_callback_scheduled_ = true; } bool TLSWrap::InvokeQueued(int status, const char* error_str) { - if (pending_write_items_.IsEmpty()) + if (!write_callback_scheduled_) return false; - // Process old queue - WriteItemList queue; - pending_write_items_.MoveBack(&queue); - while (WriteItem* wi = queue.PopFront()) { - wi->w_->Done(status, error_str); - delete wi; + if (current_write_ != nullptr) { + WriteWrap* w = current_write_; + current_write_ = nullptr; + w->Done(status, error_str); } return true; @@ -301,7 +299,7 @@ void TLSWrap::EncOut() { return; // Split-off queue - if (established_ && !write_item_queue_.IsEmpty()) + if (established_ && current_write_ != nullptr) MakePending(); if (ssl_ == nullptr) @@ -619,8 +617,9 @@ int TLSWrap::DoWrite(WriteWrap* w, } } - // Queue callback to execute it on next tick - write_item_queue_.PushBack(new WriteItem(w)); + // Store the current write wrap + CHECK_EQ(current_write_, nullptr); + current_write_ = w; w->Dispatched(); // Write queued data diff --git a/src/tls_wrap.h b/src/tls_wrap.h index 56bdda03fc0d5b..cd6a46b7d9b32d 100644 --- a/src/tls_wrap.h +++ b/src/tls_wrap.h @@ -90,19 +90,6 @@ class TLSWrap : public AsyncWrap, // Maximum number of buffers passed to uv_write() static const int kSimultaneousBufferCount = 10; - // Write callback queue's item - class WriteItem { - public: - explicit WriteItem(WriteWrap* w) : w_(w) { - } - ~WriteItem() { - w_ = nullptr; - } - - WriteWrap* w_; - ListNode member_; - }; - TLSWrap(Environment* env, Kind kind, StreamBase* stream, @@ -174,9 +161,8 @@ class TLSWrap : public AsyncWrap, BIO* enc_out_; crypto::NodeBIO* clear_in_; size_t write_size_; - typedef ListHead WriteItemList; - WriteItemList write_item_queue_; - WriteItemList pending_write_items_; + WriteWrap* current_write_ = nullptr; + bool write_callback_scheduled_ = false; bool started_; bool established_; bool shutdown_; diff --git a/src/udp_wrap.cc b/src/udp_wrap.cc index ff6dd73041ee80..0d7a048a7d7eb2 100644 --- a/src/udp_wrap.cc +++ b/src/udp_wrap.cc @@ -353,8 +353,12 @@ void UDPWrap::DoSend(const FunctionCallbackInfo& args, int family) { node::Utf8Value address(env->isolate(), args[4]); const bool have_callback = args[5]->IsTrue(); - env->set_init_trigger_async_id(wrap->get_async_id()); - SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback); + SendWrap* req_wrap; + { + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope( + env, wrap->get_async_id()); + req_wrap = new SendWrap(env, req_wrap_obj, have_callback); + } size_t msg_size = 0; MaybeStackBuffer bufs(count); @@ -503,7 +507,9 @@ Local UDPWrap::Instantiate(Environment* env, AsyncWrap* parent, UDPWrap::SocketType type) { EscapableHandleScope scope(env->isolate()); - AsyncHooks::InitScope init_scope(env, parent->get_async_id()); + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope( + env, parent->get_async_id()); + // If this assert fires then Initialize hasn't been called yet. CHECK_EQ(env->udp_constructor_function().IsEmpty(), false); Local instance = env->udp_constructor_function() diff --git a/test/README.md b/test/README.md index d214f2fc10c246..bc2464bcfaecdf 100644 --- a/test/README.md +++ b/test/README.md @@ -6,7 +6,7 @@ For a detailed guide on how to write tests in this directory, see [the guide on writing tests](../doc/guides/writing-tests.md). On how to run tests in this directory, see -[the contributing guide](../CONTRIBUTING.md#step-6-test). +[the contributing guide](../doc/guides/contributing/pull-requests.md#step-6-test). ## Test Directories diff --git a/test/abort/test-http-parser-consume.js b/test/abort/test-http-parser-consume.js index 9115aba70dbf17..673e04cfa3a573 100644 --- a/test/abort/test-http-parser-consume.js +++ b/test/abort/test-http-parser-consume.js @@ -11,12 +11,12 @@ if (process.argv[2] === 'child') { const rr = get({ port: server.address().port }, common.mustCall(() => { // This bad input (0) should abort the parser and the process rr.parser.consume(0); - // This line should be unreachanble. + // This line should be unreachable. assert.fail('this should be unreachable'); })); })); } else { - // super-proces + // super-process const child = spawn(process.execPath, [__filename, 'child']); child.stdout.on('data', common.mustNotCall()); diff --git a/test/addons-napi/test_dataview/test.js b/test/addons-napi/test_dataview/test.js index 711ab01ddb3cb6..a6be58494069e5 100644 --- a/test/addons-napi/test_dataview/test.js +++ b/test/addons-napi/test_dataview/test.js @@ -5,10 +5,20 @@ const assert = require('assert'); // Testing api calls for arrays const test_dataview = require(`./build/${common.buildType}/test_dataview`); -//create dataview -const buffer = new ArrayBuffer(128); -const template = Reflect.construct(DataView, [buffer]); +// Test for creating dataview +{ + const buffer = new ArrayBuffer(128); + const template = Reflect.construct(DataView, [buffer]); -const theDataview = test_dataview.CreateDataView(template); -assert.ok(theDataview instanceof DataView, - `Expect ${theDataview} to be a DataView`); + const theDataview = test_dataview.CreateDataViewFromJSDataView(template); + assert.ok(theDataview instanceof DataView, + `Expect ${theDataview} to be a DataView`); +} + +// Test for creating dataview with invalid range +{ + const buffer = new ArrayBuffer(128); + assert.throws(() => { + test_dataview.CreateDataView(buffer, 10, 200); + }, RangeError); +} diff --git a/test/addons-napi/test_dataview/test_dataview.c b/test/addons-napi/test_dataview/test_dataview.c index 5f95eef0f38032..4d29ed07e9e6f7 100644 --- a/test/addons-napi/test_dataview/test_dataview.c +++ b/test/addons-napi/test_dataview/test_dataview.c @@ -3,6 +3,53 @@ #include "../common.h" napi_value CreateDataView(napi_env env, napi_callback_info info) { + size_t argc = 3; + napi_value args [3]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + + NAPI_ASSERT(env, argc == 3, "Wrong number of arguments"); + + napi_valuetype valuetype0; + napi_value arraybuffer = args[0]; + + NAPI_CALL(env, napi_typeof(env, arraybuffer, &valuetype0)); + NAPI_ASSERT(env, valuetype0 == napi_object, + "Wrong type of arguments. Expects a ArrayBuffer as the first " + "argument."); + + bool is_arraybuffer; + NAPI_CALL(env, napi_is_arraybuffer(env, arraybuffer, &is_arraybuffer)); + NAPI_ASSERT(env, is_arraybuffer, + "Wrong type of arguments. Expects a ArrayBuffer as the first " + "argument."); + + napi_valuetype valuetype1; + NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + + NAPI_ASSERT(env, valuetype1 == napi_number, + "Wrong type of arguments. Expects a number as second argument."); + + size_t byte_offset = 0; + NAPI_CALL(env, napi_get_value_uint32(env, args[1], (uint32_t*)(&byte_offset))); + + napi_valuetype valuetype2; + NAPI_CALL(env, napi_typeof(env, args[2], &valuetype2)); + + NAPI_ASSERT(env, valuetype2 == napi_number, + "Wrong type of arguments. Expects a number as third argument."); + + size_t length = 0; + NAPI_CALL(env, napi_get_value_uint32(env, args[2], (uint32_t*)(&length))); + + napi_value output_dataview; + NAPI_CALL(env, + napi_create_dataview(env, length, arraybuffer, + byte_offset, &output_dataview)); + + return output_dataview; +} + +napi_value CreateDataViewFromJSDataView(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args [1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -34,12 +81,15 @@ napi_value CreateDataView(napi_env env, napi_callback_info info) { napi_create_dataview(env, length, buffer, byte_offset, &output_dataview)); + return output_dataview; } napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { - DECLARE_NAPI_PROPERTY("CreateDataView", CreateDataView) + DECLARE_NAPI_PROPERTY("CreateDataView", CreateDataView), + DECLARE_NAPI_PROPERTY("CreateDataViewFromJSDataView", + CreateDataViewFromJSDataView) }; NAPI_CALL(env, napi_define_properties( diff --git a/test/addons-napi/test_exception/test.js b/test/addons-napi/test_exception/test.js index 8bd2f50b12b15f..83961411df7574 100644 --- a/test/addons-napi/test_exception/test.js +++ b/test/addons-napi/test_exception/test.js @@ -4,49 +4,47 @@ const common = require('../../common'); const test_exception = require(`./build/${common.buildType}/test_exception`); const assert = require('assert'); const theError = new Error('Some error'); -function throwTheError() { - throw theError; + +{ + const throwTheError = () => { throw theError; }; + + // Test that the native side successfully captures the exception + let returnedError = test_exception.returnException(throwTheError); + assert.strictEqual(theError, returnedError); + + // Test that the native side passes the exception through + assert.throws( + () => { test_exception.allowException(throwTheError); }, + (err) => err === theError + ); + + // Test that the exception thrown above was marked as pending + // before it was handled on the JS side + assert.strictEqual(test_exception.wasPending(), true, + 'VM was marked as having an exception pending' + + ' when it was allowed through'); + + // Test that the native side does not capture a non-existing exception + returnedError = test_exception.returnException(common.mustCall()); + assert.strictEqual(returnedError, undefined, + 'Returned error should be undefined when no exception is' + + ` thrown, but ${returnedError} was passed`); } -let caughtError; - -// Test that the native side successfully captures the exception -let returnedError = test_exception.returnException(throwTheError); -assert.strictEqual(theError, returnedError); - -// Test that the native side passes the exception through -assert.throws( - () => { - test_exception.allowException(throwTheError); - }, - function(err) { - return err === theError; - }, - 'Thrown exception was allowed to pass through unhindered' -); - -// Test that the exception thrown above was marked as pending -// before it was handled on the JS side -assert.strictEqual(test_exception.wasPending(), true, - 'VM was marked as having an exception pending' + - ' when it was allowed through'); - -// Test that the native side does not capture a non-existing exception -returnedError = test_exception.returnException(common.mustCall()); -assert.strictEqual(undefined, returnedError, - 'Returned error should be undefined when no exception is' + - ` thrown, but ${returnedError} was passed`); - -// Test that no exception appears that was not thrown by us -try { - test_exception.allowException(common.mustCall()); -} catch (anError) { - caughtError = anError; + +{ + // Test that no exception appears that was not thrown by us + let caughtError; + try { + test_exception.allowException(common.mustCall()); + } catch (anError) { + caughtError = anError; + } + assert.strictEqual(caughtError, undefined, + 'No exception originated on the native side, but' + + ` ${caughtError} was passed`); + + // Test that the exception state remains clear when no exception is thrown + assert.strictEqual(test_exception.wasPending(), false, + 'VM was not marked as having an exception pending' + + ' when none was allowed through'); } -assert.strictEqual(undefined, caughtError, - 'No exception originated on the native side, but' + - ` ${caughtError} was passed`); - -// Test that the exception state remains clear when no exception is thrown -assert.strictEqual(test_exception.wasPending(), false, - 'VM was not marked as having an exception pending' + - ' when none was allowed through'); diff --git a/test/addons-napi/test_symbol/test_symbol.c b/test/addons-napi/test_symbol/test_symbol.c index 6acc4c55db0b2b..c91b6ae54f4932 100644 --- a/test/addons-napi/test_symbol/test_symbol.c +++ b/test/addons-napi/test_symbol/test_symbol.c @@ -12,7 +12,7 @@ napi_value Test(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_symbol, - "Wrong type of argments. Expects a symbol."); + "Wrong type of arguments. Expects a symbol."); char buffer[128]; size_t buffer_size = 128; diff --git a/test/addons-napi/test_typedarray/test.js b/test/addons-napi/test_typedarray/test.js index 27ef054fe4635e..4a4e79ebe7bcdb 100644 --- a/test/addons-napi/test_typedarray/test.js +++ b/test/addons-napi/test_typedarray/test.js @@ -55,3 +55,21 @@ arrayTypes.forEach((currentType) => { assert.notStrictEqual(theArray, template); assert.strictEqual(theArray.buffer, buffer); }); + +arrayTypes.forEach((currentType) => { + const template = Reflect.construct(currentType, buffer); + assert.throws(() => { + test_typedarray.CreateTypedArray(template, buffer, 0, 136); + }, /Invalid typed array length/); +}); + +const nonByteArrayTypes = [ Int16Array, Uint16Array, Int32Array, Uint32Array, + Float32Array, Float64Array ]; +nonByteArrayTypes.forEach((currentType) => { + const template = Reflect.construct(currentType, buffer); + assert.throws(() => { + test_typedarray.CreateTypedArray(template, buffer, + currentType.BYTES_PER_ELEMENT + 1, 1); + console.log(`start of offset ${currentType}`); + }, /start offset of/); +}); diff --git a/test/addons-napi/test_typedarray/test_typedarray.c b/test/addons-napi/test_typedarray/test_typedarray.c index 0325faedd09f8e..2758a6f53298fe 100644 --- a/test/addons-napi/test_typedarray/test_typedarray.c +++ b/test/addons-napi/test_typedarray/test_typedarray.c @@ -13,20 +13,20 @@ napi_value Multiply(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, - "Wrong type of argments. Expects a typed array as first argument."); + "Wrong type of arguments. Expects a typed array as first argument."); napi_value input_array = args[0]; bool is_typedarray; NAPI_CALL(env, napi_is_typedarray(env, input_array, &is_typedarray)); NAPI_ASSERT(env, is_typedarray, - "Wrong type of argments. Expects a typed array as first argument."); + "Wrong type of arguments. Expects a typed array as first argument."); napi_valuetype valuetype1; NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_number, - "Wrong type of argments. Expects a number as second argument."); + "Wrong type of arguments. Expects a number as second argument."); double multiplier; NAPI_CALL(env, napi_get_value_double(env, args[1], &multiplier)); @@ -97,37 +97,37 @@ napi_value External(napi_env env, napi_callback_info info) { } napi_value CreateTypedArray(napi_env env, napi_callback_info info) { - size_t argc = 2; - napi_value args[2]; + size_t argc = 4; + napi_value args[4]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); + NAPI_ASSERT(env, argc == 2 || argc == 4, "Wrong number of arguments"); napi_value input_array = args[0]; napi_valuetype valuetype0; NAPI_CALL(env, napi_typeof(env, input_array, &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_object, - "Wrong type of argments. Expects a typed array as first argument."); + "Wrong type of arguments. Expects a typed array as first argument."); bool is_typedarray; NAPI_CALL(env, napi_is_typedarray(env, input_array, &is_typedarray)); NAPI_ASSERT(env, is_typedarray, - "Wrong type of argments. Expects a typed array as first argument."); + "Wrong type of arguments. Expects a typed array as first argument."); napi_valuetype valuetype1; napi_value input_buffer = args[1]; NAPI_CALL(env, napi_typeof(env, input_buffer, &valuetype1)); NAPI_ASSERT(env, valuetype1 == napi_object, - "Wrong type of argments. Expects an array buffer as second argument."); + "Wrong type of arguments. Expects an array buffer as second argument."); bool is_arraybuffer; NAPI_CALL(env, napi_is_arraybuffer(env, input_buffer, &is_arraybuffer)); NAPI_ASSERT(env, is_arraybuffer, - "Wrong type of argments. Expects an array buffer as second argument."); + "Wrong type of arguments. Expects an array buffer as second argument."); napi_typedarray_type type; napi_value in_array_buffer; @@ -136,6 +136,28 @@ napi_value CreateTypedArray(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_get_typedarray_info( env, input_array, &type, &length, NULL, &in_array_buffer, &byte_offset)); + if (argc == 4) { + napi_valuetype valuetype2; + NAPI_CALL(env, napi_typeof(env, args[2], &valuetype2)); + + NAPI_ASSERT(env, valuetype2 == napi_number, + "Wrong type of arguments. Expects a number as third argument."); + + uint32_t uint32_length; + NAPI_CALL(env, napi_get_value_uint32(env, args[2], &uint32_length)); + length = uint32_length; + + napi_valuetype valuetype3; + NAPI_CALL(env, napi_typeof(env, args[3], &valuetype3)); + + NAPI_ASSERT(env, valuetype3 == napi_number, + "Wrong type of arguments. Expects a number as third argument."); + + uint32_t uint32_byte_offset; + NAPI_CALL(env, napi_get_value_uint32(env, args[3], &uint32_byte_offset)); + byte_offset = uint32_byte_offset; + } + napi_value output_array; NAPI_CALL(env, napi_create_typedarray( env, type, length, input_buffer, byte_offset, &output_array)); diff --git a/test/addons/callback-scope/test-resolve-async.js b/test/addons/callback-scope/test-resolve-async.js index 98e1910b49df7b..3e96234787c7b3 100644 --- a/test/addons/callback-scope/test-resolve-async.js +++ b/test/addons/callback-scope/test-resolve-async.js @@ -4,6 +4,8 @@ const common = require('../../common'); const assert = require('assert'); const { testResolveAsync } = require(`./build/${common.buildType}/binding`); +common.crashOnUnhandledRejection(); + let called = false; testResolveAsync().then(() => { called = true; }); diff --git a/test/addons/openssl-binding/binding.gyp b/test/addons/openssl-binding/binding.gyp index 425b38caa3f659..3bfe93350fe3bf 100644 --- a/test/addons/openssl-binding/binding.gyp +++ b/test/addons/openssl-binding/binding.gyp @@ -1,8 +1,4 @@ { - 'includes': ['../../../config.gypi'], - 'variables': { - 'node_target_type%': '', - }, 'targets': [ { 'target_name': 'binding', @@ -10,13 +6,6 @@ ['node_use_openssl=="true"', { 'sources': ['binding.cc'], 'include_dirs': ['../../../deps/openssl/openssl/include'], - 'conditions': [ - ['OS=="win" and node_target_type=="static_library"', { - 'libraries': [ - '../../../../$(Configuration)/lib/<(OPENSSL_PRODUCT)' - ], - }], - ], }] ] }, diff --git a/test/addons/zlib-binding/binding.gyp b/test/addons/zlib-binding/binding.gyp index 24c3ae78a2440a..60a9bb82661820 100644 --- a/test/addons/zlib-binding/binding.gyp +++ b/test/addons/zlib-binding/binding.gyp @@ -1,22 +1,9 @@ { - 'includes': ['../../../config.gypi'], - 'variables': { - 'node_target_type%': '', - }, 'targets': [ { 'target_name': 'binding', 'sources': ['binding.cc'], 'include_dirs': ['../../../deps/zlib'], - 'conditions': [ - ['node_target_type=="static_library"', { - 'conditions': [ - ['OS=="win"', { - 'libraries': ['../../../../$(Configuration)/lib/zlib.lib'], - }], - ], - }], - ], }, ] } diff --git a/test/async-hooks/hook-checks.js b/test/async-hooks/hook-checks.js index 60f505a24a95de..2abed61555a158 100644 --- a/test/async-hooks/hook-checks.js +++ b/test/async-hooks/hook-checks.js @@ -11,7 +11,7 @@ require('../common'); * @param {Object} activity including timestamps for each life time event, * i.e. init, before ... * @param {Object} hooks the expected life time event invocations with a count - * indicating how oftn they should have been invoked, + * indicating how often they should have been invoked, * i.e. `{ init: 1, before: 2, after: 2 }` * @param {String} stage the name of the stage in the test at which we are * checking the invocations diff --git a/test/async-hooks/test-callback-error.js b/test/async-hooks/test-callback-error.js index c45856f60da2fa..450f34bee1021a 100644 --- a/test/async-hooks/test-callback-error.js +++ b/test/async-hooks/test-callback-error.js @@ -94,7 +94,7 @@ assert.ok(!arg); assert.strictEqual(code, null); // most posix systems will show 'SIGABRT', but alpine34 does not if (signal !== 'SIGABRT') { - console.log(`parent recived signal ${signal}\nchild's stderr:`); + console.log(`parent received signal ${signal}\nchild's stderr:`); console.log(stderr); process.exit(1); } diff --git a/test/async-hooks/test-graph.http.js b/test/async-hooks/test-graph.http.js new file mode 100644 index 00000000000000..eea72ca3bac72c --- /dev/null +++ b/test/async-hooks/test-graph.http.js @@ -0,0 +1,63 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasIPv6) + common.skip('IPv6 support required'); + +const initHooks = require('./init-hooks'); +const verifyGraph = require('./verify-graph'); +const http = require('http'); + +const hooks = initHooks(); +hooks.enable(); + +const server = http.createServer(common.mustCall(function(req, res) { + res.end(); + this.close(common.mustCall()); +})); +server.listen(0, common.mustCall(function() { + http.get({ + host: '::1', + family: 6, + port: server.address().port + }, common.mustCall()); +})); + +process.on('exit', function() { + hooks.disable(); + + verifyGraph( + hooks, + [ { type: 'TCPSERVERWRAP', + id: 'tcpserver:1', + triggerAsyncId: null }, + { type: 'TCPWRAP', id: 'tcp:1', triggerAsyncId: 'tcpserver:1' }, + { type: 'TCPCONNECTWRAP', + id: 'tcpconnect:1', + triggerAsyncId: 'tcp:1' }, + { type: 'HTTPPARSER', + id: 'httpparser:1', + triggerAsyncId: 'tcpserver:1' }, + { type: 'HTTPPARSER', + id: 'httpparser:2', + triggerAsyncId: 'tcpserver:1' }, + { type: 'TCPWRAP', id: 'tcp:2', triggerAsyncId: 'tcpserver:1' }, + { type: 'Timeout', id: 'timeout:1', triggerAsyncId: 'tcp:2' }, + { type: 'TIMERWRAP', id: 'timer:1', triggerAsyncId: 'tcp:2' }, + { type: 'HTTPPARSER', + id: 'httpparser:3', + triggerAsyncId: 'tcp:2' }, + { type: 'HTTPPARSER', + id: 'httpparser:4', + triggerAsyncId: 'tcp:2' }, + { type: 'Timeout', + id: 'timeout:2', + triggerAsyncId: 'httpparser:4' }, + { type: 'TIMERWRAP', + id: 'timer:2', + triggerAsyncId: 'httpparser:4' }, + { type: 'SHUTDOWNWRAP', + id: 'shutdown:1', + triggerAsyncId: 'tcp:2' } ] + ); +}); diff --git a/test/async-hooks/test-internal-nexttick-default-trigger.js b/test/async-hooks/test-internal-nexttick-default-trigger.js index ad352a8c147247..ed541868542206 100644 --- a/test/async-hooks/test-internal-nexttick-default-trigger.js +++ b/test/async-hooks/test-internal-nexttick-default-trigger.js @@ -3,7 +3,7 @@ const common = require('../common'); // This tests ensures that the triggerId of both the internal and external -// nexTick function sets the triggerAsyncId correctly. +// nextTick function sets the triggerAsyncId correctly. const assert = require('assert'); const async_hooks = require('async_hooks'); diff --git a/test/async-hooks/test-pipeconnectwrap.js b/test/async-hooks/test-pipeconnectwrap.js index 81a5abd42a3004..a993f0c8feedd3 100644 --- a/test/async-hooks/test-pipeconnectwrap.js +++ b/test/async-hooks/test-pipeconnectwrap.js @@ -53,7 +53,7 @@ function onlisten() { const awaitOnconnectCalls = new Set(['server', 'client']); function maybeOnconnect(source) { // both server and client must call onconnect. On most OS's waiting for - // the client is sufficient, but on CertOS 5 the sever needs to respond too. + // the client is sufficient, but on CentOS 5 the sever needs to respond too. assert.ok(awaitOnconnectCalls.size > 0); awaitOnconnectCalls.delete(source); if (awaitOnconnectCalls.size > 0) return; diff --git a/test/async-hooks/verify-graph.js b/test/async-hooks/verify-graph.js index 451550d33fc8e1..95c55c15958b2c 100644 --- a/test/async-hooks/verify-graph.js +++ b/test/async-hooks/verify-graph.js @@ -32,7 +32,7 @@ function pruneTickObjects(activities) { foundTickObject = true; // point all triggerAsyncIds that point to the tickObject - // to its triggerAsyncId and findally remove it from the activities + // to its triggerAsyncId and finally remove it from the activities const tickObject = activities[tickObjectIdx]; const newTriggerId = tickObject.triggerAsyncId; const oldTriggerId = tickObject.uid; diff --git a/test/common/README.md b/test/common/README.md index d3010d632ac5d5..da38de742e4805 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -119,15 +119,6 @@ Tests whether `name` and `expected` are part of a raised warning. Checks if `pathname` exists -### fires(promise, [error], [timeoutMs]) -* promise [<Promise] -* error [<String] default = 'timeout' -* timeoutMs [<Number] default = 100 - -Returns a new promise that will propagate `promise` resolution or rejection if -that happens within the `timeoutMs` timespan, or rejects with `error` as -a reason otherwise. - ### getArrayBufferViews(buf) * `buf` [<Buffer>] * return [<ArrayBufferView[]>] @@ -277,6 +268,17 @@ fail. If `fn` is not provided, an empty function will be used. +### mustCallAsync([fn][, exact]) +* `fn` [<Function>] +* `exact` [<Number>] default = 1 +* return [<Function>] + +The same as `mustCall()`, except that it is also checked that the Promise +returned by the function is fulfilled for each invocation of the function. + +The return value of the wrapped function is the return value of the original +function, if necessary wrapped as a promise. + ### mustCallAtLeast([fn][, minimum]) * `fn` [<Function>] default = () => {} * `minimum` [<Number>] default = 1 @@ -666,7 +668,7 @@ internet-related tests. A set of addresses for internet-related tests. All properties are configurable via `NODE_TEST_*` environment variables. For example, to configure `internet.addresses.INET_HOST`, set the environment -vairable `NODE_TEST_INET_HOST` to a specified host. +variable `NODE_TEST_INET_HOST` to a specified host. ## WPT Module diff --git a/test/common/index.js b/test/common/index.js index 80f59333626b9a..9ae27e232e3ca8 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -81,7 +81,7 @@ if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { const async_wrap = process.binding('async_wrap'); process.on('exit', () => { - // itterate through handles to make sure nothing crashes + // iterate through handles to make sure nothing crashes for (const k in initHandles) util.inspect(initHandles[k]); }); @@ -501,6 +501,12 @@ exports.mustCallAtLeast = function(fn, minimum) { return _mustCallInner(fn, minimum, 'minimum'); }; +exports.mustCallAsync = function(fn, exact) { + return exports.mustCall((...args) => { + return Promise.resolve(fn(...args)).then(exports.mustCall((val) => val)); + }, exact); +}; + function _mustCallInner(fn, criteria = 1, field) { if (process._exiting) throw new Error('Cannot use common.mustCall*() in process exit handler'); @@ -866,32 +872,6 @@ function restoreWritable(name) { delete process[name].writeTimes; } -function onResolvedOrRejected(promise, callback) { - return promise.then((result) => { - callback(); - return result; - }, (error) => { - callback(); - throw error; - }); -} - -function timeoutPromise(error, timeoutMs) { - let clearCallback = null; - let done = false; - const promise = onResolvedOrRejected(new Promise((resolve, reject) => { - const timeout = setTimeout(() => reject(error), timeoutMs); - clearCallback = () => { - if (done) - return; - clearTimeout(timeout); - resolve(); - }; - }), () => done = true); - promise.clear = clearCallback; - return promise; -} - exports.hijackStdout = hijackStdWritable.bind(null, 'stdout'); exports.hijackStderr = hijackStdWritable.bind(null, 'stderr'); exports.restoreStdout = restoreWritable.bind(null, 'stdout'); @@ -905,19 +885,3 @@ exports.firstInvalidFD = function firstInvalidFD() { } catch (e) {} return fd; }; - -exports.fires = function fires(promise, error, timeoutMs) { - if (!timeoutMs && util.isNumber(error)) { - timeoutMs = error; - error = null; - } - if (!error) - error = 'timeout'; - if (!timeoutMs) - timeoutMs = 100; - const timeout = timeoutPromise(error, timeoutMs); - return Promise.race([ - onResolvedOrRejected(promise, () => timeout.clear()), - timeout - ]); -}; diff --git a/test/common/inspector-helper.js b/test/common/inspector-helper.js index 0d010a8ca70617..1f1738e31b75a8 100644 --- a/test/common/inspector-helper.js +++ b/test/common/inspector-helper.js @@ -216,7 +216,7 @@ class InspectorSession { waitForNotification(methodOrPredicate, description) { const desc = description || methodOrPredicate; const message = `Timed out waiting for matching notification (${desc}))`; - return common.fires( + return fires( this._asyncWaitForNotification(methodOrPredicate), message, TIMEOUT); } @@ -323,7 +323,7 @@ class NodeInstance { const instance = new NodeInstance( [], `${scriptContents}\nprocess._rawDebug('started');`, undefined); const msg = 'Timed out waiting for process to start'; - while (await common.fires(instance.nextStderrString(), msg, TIMEOUT) !== + while (await fires(instance.nextStderrString(), msg, TIMEOUT) !== 'started') {} process._debugProcess(instance._process.pid); return instance; @@ -431,6 +431,43 @@ function readMainScriptSource() { return fs.readFileSync(_MAINSCRIPT, 'utf8'); } +function onResolvedOrRejected(promise, callback) { + return promise.then((result) => { + callback(); + return result; + }, (error) => { + callback(); + throw error; + }); +} + +function timeoutPromise(error, timeoutMs) { + let clearCallback = null; + let done = false; + const promise = onResolvedOrRejected(new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(error), timeoutMs); + clearCallback = () => { + if (done) + return; + clearTimeout(timeout); + resolve(); + }; + }), () => done = true); + promise.clear = clearCallback; + return promise; +} + +// Returns a new promise that will propagate `promise` resolution or rejection +// if that happens within the `timeoutMs` timespan, or rejects with `error` as +// a reason otherwise. +function fires(promise, error, timeoutMs) { + const timeout = timeoutPromise(error, timeoutMs); + return Promise.race([ + onResolvedOrRejected(promise, () => timeout.clear()), + timeout + ]); +} + module.exports = { mainScriptPath: _MAINSCRIPT, readMainScriptSource, diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index 40d7b54f59320a..bd1c5ddecac321 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -1,9 +1,9 @@ 'use strict'; const common = require('../common'); -// The doctool currently uses js-yaml from the tool/eslint/ tree. +// The doctool currently uses js-yaml from the tool/node_modules/eslint/ tree. try { - require('../../tools/eslint/node_modules/js-yaml'); + require('../../tools/node_modules/eslint/node_modules/js-yaml'); } catch (e) { common.skip('missing js-yaml (eslint not present)'); } diff --git a/test/fixtures/loop.js b/test/fixtures/loop.js index 461fb393583e68..1f093bdf574660 100644 --- a/test/fixtures/loop.js +++ b/test/fixtures/loop.js @@ -4,7 +4,7 @@ console.log('A message', 5); while (t > 0) { if (t++ === 1000) { t = 0; - console.log(`Outputed message #${k++}`); + console.log(`Outputted message #${k++}`); } } process.exit(55); diff --git a/test/fixtures/net-fd-passing-receiver.js b/test/fixtures/net-fd-passing-receiver.js index 8559f116c54956..7d328ac28c9029 100644 --- a/test/fixtures/net-fd-passing-receiver.js +++ b/test/fixtures/net-fd-passing-receiver.js @@ -45,7 +45,7 @@ receiver = net.createServer(function(socket) { }); }); -/* To signal the test runne we're up and listening */ +/* To signal the test runner we're up and listening */ receiver.on('listening', function() { console.log('ready'); }); diff --git a/test/fixtures/tls-connect.js b/test/fixtures/tls-connect.js index cff424008663e2..43c3e6f0fd9fa0 100644 --- a/test/fixtures/tls-connect.js +++ b/test/fixtures/tls-connect.js @@ -44,10 +44,7 @@ exports.connect = function connect(options, callback) { const server = {}; const client = {}; - const pair = { - server: server, - client: client, - }; + const pair = { server, client }; tls.createServer(options.server, function(conn) { server.conn = conn; diff --git a/test/internet/test-dgram-multicast-set-interface-lo.js b/test/internet/test-dgram-multicast-set-interface-lo.js index 740b175d69be8a..c869b87d8a7507 100644 --- a/test/internet/test-dgram-multicast-set-interface-lo.js +++ b/test/internet/test-dgram-multicast-set-interface-lo.js @@ -22,7 +22,6 @@ if (common.isSunOS) { } const networkInterfaces = require('os').networkInterfaces(); -const Buffer = require('buffer').Buffer; const fork = require('child_process').fork; const MULTICASTS = { IPv4: ['224.0.0.115', '224.0.0.116', '224.0.0.117'], diff --git a/test/internet/test-tls-reuse-host-from-socket.js b/test/internet/test-tls-reuse-host-from-socket.js index 8501efd74e619f..f7093856c6ab95 100644 --- a/test/internet/test-tls-reuse-host-from-socket.js +++ b/test/internet/test-tls-reuse-host-from-socket.js @@ -30,7 +30,7 @@ const tls = require('tls'); const net = require('net'); const socket = net.connect(443, 'www.example.org', common.mustCall(() => { - const secureSocket = tls.connect({ socket: socket }, common.mustCall(() => { + const secureSocket = tls.connect({ socket }, common.mustCall(() => { secureSocket.destroy(); console.log('ok'); })); diff --git a/test/known_issues/known_issues.status b/test/known_issues/known_issues.status index 46c8ed32741c7d..e21913e232c03f 100644 --- a/test/known_issues/known_issues.status +++ b/test/known_issues/known_issues.status @@ -7,8 +7,6 @@ prefix known_issues [true] # This section applies to all platforms [$system==win32] -test-stdout-buffer-flush-on-exit: SKIP -test-cluster-disconnect-handles: SKIP [$system==linux] diff --git a/test/known_issues/test-http-path-contains-unicode.js b/test/known_issues/test-http-path-contains-unicode.js index 68b66b7c6940ed..4d50c8865ba542 100644 --- a/test/known_issues/test-http-path-contains-unicode.js +++ b/test/known_issues/test-http-path-contains-unicode.js @@ -10,11 +10,7 @@ const http = require('http'); const expected = '/café🐶'; -assert.strictEqual( - expected, - '/caf\u{e9}\u{1f436}', - 'Sanity check that string literal produced the expected string' -); +assert.strictEqual('/caf\u{e9}\u{1f436}', expected); const server = http.createServer(common.mustCall(function(req, res) { assert.strictEqual(req.url, expected); diff --git a/test/message/error_exit.js b/test/message/error_exit.js index e33e5d6929f501..057a371df24851 100644 --- a/test/message/error_exit.js +++ b/test/message/error_exit.js @@ -24,7 +24,7 @@ require('../common'); const assert = require('assert'); process.on('exit', function(code) { - console.error('Exiting with code=%d', code); + console.error(`Exiting with code=${code}`); }); assert.strictEqual(1, 2); diff --git a/test/message/max_tick_depth.js b/test/message/max_tick_depth.js index 89dcf398f65d4c..15462157d2160d 100644 --- a/test/message/max_tick_depth.js +++ b/test/message/max_tick_depth.js @@ -25,7 +25,7 @@ require('../common'); process.maxTickDepth = 10; let i = 20; process.nextTick(function f() { - console.error('tick %d', i); + console.error(`tick ${i}`); if (i-- > 0) process.nextTick(f); }); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 885ac0013b2a5a..971c99be918d6a 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -623,7 +623,7 @@ testAssertionMessage({ a: undefined, b: null }, '{ a: undefined, b: null }'); testAssertionMessage({ a: NaN, b: Infinity, c: -Infinity }, '{ a: NaN, b: Infinity, c: -Infinity }'); -// #2893 +// https://github.com/nodejs/node-v0.x-archive/issues/2893 { let threw = false; try { @@ -638,7 +638,7 @@ testAssertionMessage({ a: NaN, b: Infinity, c: -Infinity }, assert.ok(threw); } -// #5292 +// https://github.com/nodejs/node-v0.x-archive/issues/5292 try { assert.strictEqual(1, 2); } catch (e) { diff --git a/test/parallel/test-async-hooks-http-agent.js b/test/parallel/test-async-hooks-http-agent.js index ff19d089a02099..e10820c3c202b6 100644 --- a/test/parallel/test-async-hooks-http-agent.js +++ b/test/parallel/test-async-hooks-http-agent.js @@ -8,7 +8,7 @@ const http = require('http'); // Checks that an http.Agent properly asyncReset()s a reused socket handle, and // re-assigns the fresh async id to the reused `net.Socket` instance. -// Make sure a single socket is transpartently reused for 2 requests. +// Make sure a single socket is transparently reused for 2 requests. const agent = new http.Agent({ keepAlive: true, keepAliveMsecs: Infinity, diff --git a/test/parallel/test-async-hooks-promise-enable-disable.js b/test/parallel/test-async-hooks-promise-enable-disable.js index 075b29e4e50a70..b7692c45cd9b2e 100644 --- a/test/parallel/test-async-hooks-promise-enable-disable.js +++ b/test/parallel/test-async-hooks-promise-enable-disable.js @@ -11,13 +11,13 @@ let p_inits = 0; common.crashOnUnhandledRejection(); // Not useful to place common.mustCall() around 'exit' event b/c it won't be -// able to check it anway. +// able to check it anyway. process.on('exit', (code) => { if (code !== 0) return; if (p_er !== null) throw p_er; - // Expecint exactly 2 PROMISE types to reach init. + // Expecting exactly 2 PROMISE types to reach init. assert.strictEqual(p_inits, EXPECTED_INITS); }); diff --git a/test/parallel/test-async-hooks-recursive-stack.js b/test/parallel/test-async-hooks-recursive-stack.js new file mode 100644 index 00000000000000..7ab73dc1bf4538 --- /dev/null +++ b/test/parallel/test-async-hooks-recursive-stack.js @@ -0,0 +1,20 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const async_hooks = require('async_hooks'); + +// This test verifies that the async ID stack can grow indefinitely. + +function recurse(n) { + const a = new async_hooks.AsyncResource('foobar'); + a.emitBefore(); + assert.strictEqual(a.asyncId(), async_hooks.executionAsyncId()); + assert.strictEqual(a.triggerAsyncId(), async_hooks.triggerAsyncId()); + if (n >= 0) + recurse(n - 1); + assert.strictEqual(a.asyncId(), async_hooks.executionAsyncId()); + assert.strictEqual(a.triggerAsyncId(), async_hooks.triggerAsyncId()); + a.emitAfter(); +} + +recurse(1000); diff --git a/test/parallel/test-async-wrap-pop-id-during-load.js b/test/parallel/test-async-wrap-pop-id-during-load.js index 1017fc02a72b05..4f39a4fdf01b34 100644 --- a/test/parallel/test-async-wrap-pop-id-during-load.js +++ b/test/parallel/test-async-wrap-pop-id-during-load.js @@ -8,7 +8,7 @@ if (process.argv[2] === 'async') { throw new Error(); } (async function() { await fn(); })(); - // While the above should error, just in case it dosn't the script shouldn't + // While the above should error, just in case it doesn't the script shouldn't // fork itself indefinitely so return early. return; } diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index 38b0b5a4e5e387..7143133cd103ff 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -636,7 +636,8 @@ assert.strictEqual('', x.inspect()); } { - // #1210 Test UTF-8 string includes null character + // https://github.com/nodejs/node-v0.x-archive/pull/1210 + // Test UTF-8 string includes null character let buf = Buffer.from('\0'); assert.strictEqual(buf.length, 1); buf = Buffer.from('\0\0'); @@ -660,7 +661,8 @@ assert.strictEqual('', x.inspect()); } { - // #243 Test write() with maxLength + // https://github.com/nodejs/node-v0.x-archive/issues/243 + // Test write() with maxLength const buf = Buffer.allocUnsafe(4); buf.fill(0xFF); assert.strictEqual(buf.write('abcd', 1, 2, 'utf8'), 2); @@ -886,7 +888,8 @@ assert.throws(() => Buffer.allocUnsafe(8).writeFloatLE(0.0, -1), RangeError); assert.strictEqual(buf.readIntBE(0, 5), -0x0012000000); } -// Regression test for #5482: should throw but not assert in C++ land. +// Regression test for https://github.com/nodejs/node-v0.x-archive/issues/5482: +// should throw but not assert in C++ land. common.expectsError( () => Buffer.from('', 'buffer'), { @@ -896,8 +899,9 @@ common.expectsError( } ); -// Regression test for #6111. Constructing a buffer from another buffer -// should a) work, and b) not corrupt the source buffer. +// Regression test for https://github.com/nodejs/node-v0.x-archive/issues/6111. +// Constructing a buffer from another buffer should a) work, and b) not corrupt +// the source buffer. { const a = [...Array(128).keys()]; // [0, 1, 2, 3, ... 126, 127] const b = Buffer.from(a); diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 604f6d9a7dab9c..2b36af38d0b2b8 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -368,7 +368,7 @@ Buffer.alloc(8, ''); return 0; } else { elseWasLast = true; - // Once buffer.js calls the C++ implemenation of fill, return -1 + // Once buffer.js calls the C++ implementation of fill, return -1 return -1; } } @@ -405,7 +405,7 @@ common.expectsError(() => { return 1; } else { elseWasLast = true; - // Once buffer.js calls the C++ implemenation of fill, return -1 + // Once buffer.js calls the C++ implementation of fill, return -1 return -1; } } diff --git a/test/parallel/test-buffer-from.js b/test/parallel/test-buffer-from.js index 7e1bac38245e85..e8a9196b3d9d8c 100644 --- a/test/parallel/test-buffer-from.js +++ b/test/parallel/test-buffer-from.js @@ -2,7 +2,6 @@ const common = require('../common'); const { deepStrictEqual, throws } = require('assert'); -const { Buffer } = require('buffer'); const { runInNewContext } = require('vm'); const checkString = 'test'; diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 609d931c87e7ee..50f0d469b649eb 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -137,7 +137,7 @@ assert.strictEqual( ); -// test usc2 encoding +// test ucs2 encoding let twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); assert(twoByteString.includes('\u0395', 4, 'ucs2')); diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index dbf84cd6ac8f69..08d640b1dc1924 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -554,7 +554,7 @@ assert.strictEqual(511, longBufferString.lastIndexOf(pattern, 1534)); // "yolo swag swag yolo swag yolo yolo swag" ..., goes on for about 5MB. // This is hard to search because it all looks similar, but never repeats. -// countBits returns the number of bits in the binary reprsentation of n. +// countBits returns the number of bits in the binary representation of n. function countBits(n) { let count; for (count = 0; n > 0; count++) { diff --git a/test/parallel/test-buffer-over-max-length.js b/test/parallel/test-buffer-over-max-length.js index 41d8defa094143..b1267b19ff439e 100644 --- a/test/parallel/test-buffer-over-max-length.js +++ b/test/parallel/test-buffer-over-max-length.js @@ -3,7 +3,6 @@ const common = require('../common'); const assert = require('assert'); const buffer = require('buffer'); -const Buffer = buffer.Buffer; const SlowBuffer = buffer.SlowBuffer; const kMaxLength = buffer.kMaxLength; diff --git a/test/parallel/test-buffer-read.js b/test/parallel/test-buffer-read.js index 88f97db3097b6e..8a8d239a6f30e1 100644 --- a/test/parallel/test-buffer-read.js +++ b/test/parallel/test-buffer-read.js @@ -22,11 +22,11 @@ function read(buff, funx, args, expected) { } -// testing basic functionality of readDoubleBE() and readDOubleLE() +// 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() +// testing basic functionality of readFloatBE() and readFloatLE() read(buf, 'readFloatBE', [1], -1.6691549692541768e+37); read(buf, 'readFloatLE', [1], -7861303808); diff --git a/test/parallel/test-child-process-env.js b/test/parallel/test-child-process-env.js index 4582c48fda5db1..af1a47ab0e7f03 100644 --- a/test/parallel/test-child-process-env.js +++ b/test/parallel/test-child-process-env.js @@ -35,10 +35,10 @@ Object.setPrototypeOf(env, { let child; if (common.isWindows) { child = spawn('cmd.exe', ['/c', 'set'], - Object.assign({}, process.env, { env: env })); + Object.assign({}, process.env, { env })); } else { child = spawn('/usr/bin/env', [], - Object.assign({}, process.env, { env: env })); + Object.assign({}, process.env, { env })); } diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js index 4b22b4060307ed..c99010aeb8935a 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -32,7 +32,7 @@ if (process.argv[2] === 'child') { //send non-internal message containing PREFIX at a non prefix position process.send(normal); - //send inernal message + //send internal message process.send(internal); process.exit(0); diff --git a/test/parallel/test-child-process-send-returns-boolean.js b/test/parallel/test-child-process-send-returns-boolean.js index 2fbba1a4544ced..4c986e307e083a 100644 --- a/test/parallel/test-child-process-send-returns-boolean.js +++ b/test/parallel/test-child-process-send-returns-boolean.js @@ -14,7 +14,7 @@ const fixtures = require('../common/fixtures'); const subScript = fixtures.path('child-process-persistent.js'); { - // Test `send` return value on `fork` that opens and IPC by deafult. + // Test `send` return value on `fork` that opens and IPC by default. const n = fork(subScript); // `subprocess.send` should always return `true` for the first send. const rv = n.send({ h: 'w' }, (err) => { if (err) assert.fail(err); }); @@ -31,12 +31,12 @@ const subScript = fixtures.path('child-process-persistent.js'); const server = net.createServer(common.mustNotCall()).listen(0, () => { const handle = server._handle; - // Sending a handle and not giving the tickQueue time to acknoladge should + // Sending a handle and not giving the tickQueue time to acknowledge should // create the internal backlog, but leave it empty. const rv1 = s.send('one', handle, (err) => { if (err) assert.fail(err); }); assert.strictEqual(rv1, true); - // Since the first `send` included a handle (should be unackoladged), - // we can safly queue up only one more message. + // Since the first `send` included a handle (should be unacknowledged), + // we can safely queue up only one more message. const rv2 = s.send('two', (err) => { if (err) assert.fail(err); }); assert.strictEqual(rv2, true); // The backlog should now be indicate to backoff. diff --git a/test/parallel/test-cluster-cwd.js b/test/parallel/test-cluster-cwd.js new file mode 100644 index 00000000000000..ce3fdca51e907c --- /dev/null +++ b/test/parallel/test-cluster-cwd.js @@ -0,0 +1,22 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); + +if (cluster.isMaster) { + common.refreshTmpDir(); + + assert.strictEqual(cluster.settings.cwd, undefined); + cluster.fork().on('message', common.mustCall((msg) => { + assert.strictEqual(msg, process.cwd()); + })); + + cluster.setupMaster({ cwd: common.tmpDir }); + assert.strictEqual(cluster.settings.cwd, common.tmpDir); + cluster.fork().on('message', common.mustCall((msg) => { + assert.strictEqual(msg, common.tmpDir); + })); +} else { + process.send(process.cwd()); + process.disconnect(); +} diff --git a/test/parallel/test-cluster-dgram-1.js b/test/parallel/test-cluster-dgram-1.js index 5de04b3b7cb2d3..4e7bf97d271eaf 100644 --- a/test/parallel/test-cluster-dgram-1.js +++ b/test/parallel/test-cluster-dgram-1.js @@ -102,7 +102,7 @@ function worker() { // Every 10 messages, notify the master. if (received === PACKETS_PER_WORKER) { - process.send({ received: received }); + process.send({ received }); socket.close(); } }, PACKETS_PER_WORKER)); diff --git a/test/parallel/test-cluster-net-listen-relative-path.js b/test/parallel/test-cluster-net-listen-relative-path.js new file mode 100644 index 00000000000000..0fcc6a0dca4160 --- /dev/null +++ b/test/parallel/test-cluster-net-listen-relative-path.js @@ -0,0 +1,44 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); +const path = require('path'); +const fs = require('fs'); + +if (common.isWindows) + common.skip('On Windows named pipes live in their own ' + + 'filesystem and don\'t have a ~100 byte limit'); + +// Choose a socket name such that the absolute path would exceed 100 bytes. +const socketDir = './unix-socket-dir'; +const socketName = 'A'.repeat(100 - socketDir.length - 1); + +// Make sure we're not in a weird environment +assert.strictEqual(path.resolve(socketDir, socketName).length > 100, true, + 'absolute socket path should be longer than 100 bytes'); + +if (cluster.isMaster) { + // ensure that the worker exits peacefully + process.chdir(common.tmpDir); + fs.mkdirSync(socketDir); + cluster.fork().on('exit', common.mustCall(function(statusCode) { + assert.strictEqual(statusCode, 0); + + assert.strictEqual( + fs.existsSync(path.join(socketDir, socketName)), false, + 'Socket should be removed when the worker exits'); + })); +} else { + process.chdir(socketDir); + + const server = net.createServer(common.mustNotCall()); + + server.listen(socketName, common.mustCall(function() { + assert.strictEqual( + fs.existsSync(socketName), true, + 'Socket created in CWD'); + + process.disconnect(); + })); +} diff --git a/test/parallel/test-cluster-net-send.js b/test/parallel/test-cluster-net-send.js index bf0ee4e4f47f37..14ce58474f128e 100644 --- a/test/parallel/test-cluster-net-send.js +++ b/test/parallel/test-cluster-net-send.js @@ -26,7 +26,7 @@ const fork = require('child_process').fork; const net = require('net'); if (process.argv[2] !== 'child') { - console.error('[%d] master', process.pid); + console.error(`[${process.pid}] master`); const worker = fork(__filename, ['child']); let called = false; @@ -50,7 +50,7 @@ if (process.argv[2] !== 'child') { assert.ok(called); }); } else { - console.error('[%d] worker', process.pid); + console.error(`[${process.pid}] worker`); let socket; let cbcalls = 0; diff --git a/test/parallel/test-cluster-worker-init.js b/test/parallel/test-cluster-worker-init.js index fd4e43fb863a20..47a884c1cdcc22 100644 --- a/test/parallel/test-cluster-worker-init.js +++ b/test/parallel/test-cluster-worker-init.js @@ -42,7 +42,7 @@ if (cluster.isMaster) { worker.send(msg); }); } else { - // GH #7998 + // https://github.com/nodejs/node-v0.x-archive/issues/7998 cluster.worker.on('message', (message) => { process.send(message === msg); }); diff --git a/test/parallel/test-cluster-worker-no-exit.js b/test/parallel/test-cluster-worker-no-exit.js index 490000aeb6c42d..b87b58b3f8b74a 100644 --- a/test/parallel/test-cluster-worker-no-exit.js +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -60,7 +60,7 @@ if (cluster.isMaster) { worker = cluster.fork() .on('online', function() { - this.send({ port: port }); + this.send({ port }); }); }); process.on('exit', function() { diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 75820a97634576..ad11b59f096dfd 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -411,7 +411,8 @@ fileStream.on('close', common.mustCall(function() { ); })); -// Issue #2227: unknown digest method should throw an error. +// Unknown digest method should throw an error: +// https://github.com/nodejs/node-v0.x-archive/issues/2227 assert.throws(function() { crypto.createHash('xyzzy'); }, /^Error: Digest method not supported$/); diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index b0d7feb1071a51..1752d903cfcb09 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -70,7 +70,8 @@ testCipher1(Buffer.from('MySecretKey123')); testCipher2('0123456789abcdef'); testCipher2(Buffer.from('0123456789abcdef')); -// Base64 padding regression test, see #4837. +// Base64 padding regression test, see +// https://github.com/nodejs/node-v0.x-archive/issues/4837. { const c = crypto.createCipher('aes-256-cbc', 'secret'); const s = c.update('test', 'utf8', 'base64') + c.final('base64'); @@ -78,7 +79,7 @@ testCipher2(Buffer.from('0123456789abcdef')); } // Calling Cipher.final() or Decipher.final() twice should error but -// not assert. See #4886. +// not assert. See https://github.com/nodejs/node-v0.x-archive/issues/4886. { const c = crypto.createCipher('aes-256-cbc', 'secret'); try { c.final('xxx'); } catch (e) { /* Ignore. */ } @@ -90,14 +91,16 @@ testCipher2(Buffer.from('0123456789abcdef')); try { d.final('xxx'); } catch (e) { /* Ignore. */ } } -// Regression test for #5482: string to Cipher#update() should not assert. +// Regression test for https://github.com/nodejs/node-v0.x-archive/issues/5482: +// string to Cipher#update() should not assert. { const c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update'); c.final(); } -// #5655 regression tests, 'utf-8' and 'utf8' are identical. +// https://github.com/nodejs/node-v0.x-archive/issues/5655 regression tests, +// 'utf-8' and 'utf8' are identical. { let c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', ''); // Defaults to "utf8". diff --git a/test/parallel/test-crypto-deprecated.js b/test/parallel/test-crypto-deprecated.js index 84f25316d49b61..acdd71301fbed0 100644 --- a/test/parallel/test-crypto-deprecated.js +++ b/test/parallel/test-crypto-deprecated.js @@ -14,7 +14,7 @@ common.expectWarning('DeprecationWarning', [ // Accessing the deprecated function is enough to trigger the warning event. // It does not need to be called. So the assert serves the purpose of both -// triggering the warning event and confirming that the deprected function is +// triggering the warning event and confirming that the deprecated function is // mapped to the correct non-deprecated function. assert.strictEqual(crypto.Credentials, tls.SecureContext); assert.strictEqual(crypto.createCredentials, tls.createSecureContext); diff --git a/test/parallel/test-crypto-fips.js b/test/parallel/test-crypto-fips.js index faf5ab9588d21f..5334668a4447ea 100644 --- a/test/parallel/test-crypto-fips.js +++ b/test/parallel/test-crypto-fips.js @@ -96,7 +96,7 @@ testHelper( // to try to call the fips setter, to try to detect this situation, as // that would throw an error: // ("Error: Cannot set FIPS mode in a non-FIPS build."). -// Due to this uncertanty the following tests are skipped when configured +// Due to this uncertainty the following tests are skipped when configured // with --shared-openssl. if (!sharedOpenSSL()) { // OpenSSL config file should be able to turn on FIPS mode diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index 4702a9a5f175df..bf080b1970369e 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -105,7 +105,8 @@ fileStream.on('close', common.mustCall(function() { 'Test SHA1 of sample.png'); })); -// Issue #2227: unknown digest method should throw an error. +// Issue https://github.com/nodejs/node-v0.x-archive/issues/2227: unknown digest +// method should throw an error. assert.throws(function() { crypto.createHash('xyzzy'); }, /Digest method not supported/); diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index 3926eb385044d9..10d45e0a67ac12 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -476,8 +476,9 @@ process.setMaxListeners(256); } } -// #5126, "FATAL ERROR: v8::Object::SetIndexedPropertiesToExternalArrayData() -// length exceeds max acceptable value" +// https://github.com/nodejs/node-v0.x-archive/issues/5126, +// "FATAL ERROR: v8::Object::SetIndexedPropertiesToExternalArrayData() length +// exceeds max acceptable value" common.expectsError( () => crypto.randomBytes((-1 >>> 0) + 1), { diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index 69f3a7f4198835..1156fe688cb8d2 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -162,8 +162,8 @@ 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. +// Regression tests for https://github.com/nodejs/node-v0.x-archive/pull/5725: +// hex input that's not a power of two should throw, not assert in C++ land. assert.throws(function() { crypto.createCipher('aes192', 'test').update('0', 'hex'); }, (err) => { diff --git a/test/parallel/test-dgram-ref.js b/test/parallel/test-dgram-ref.js index 1a531db9aa194a..b3b8488297507c 100644 --- a/test/parallel/test-dgram-ref.js +++ b/test/parallel/test-dgram-ref.js @@ -23,7 +23,7 @@ const common = require('../common'); const dgram = require('dgram'); -// should not hang, see #1282 +// should not hang, see https://github.com/nodejs/node-v0.x-archive/issues/1282 dgram.createSocket('udp4'); dgram.createSocket('udp6'); diff --git a/test/parallel/test-dns-regress-7070.js b/test/parallel/test-dns-regress-7070.js index c1f698c3a65035..ada5bf2d91c0d6 100644 --- a/test/parallel/test-dns-regress-7070.js +++ b/test/parallel/test-dns-regress-7070.js @@ -23,7 +23,8 @@ const common = require('../common'); const dns = require('dns'); -// Should not raise assertion error. Issue #7070 +// Should not raise assertion error. +// Issue https://github.com/nodejs/node-v0.x-archive/issues/7070 common.expectsError(() => dns.resolveNs([]), // bad name { code: 'ERR_INVALID_ARG_TYPE', diff --git a/test/parallel/test-domain-http-server.js b/test/parallel/test-domain-http-server.js index 43b8d5d3809e17..47e87b34be5bb3 100644 --- a/test/parallel/test-domain-http-server.js +++ b/test/parallel/test-domain-http-server.js @@ -62,7 +62,7 @@ server.listen(0, next); function next() { const port = this.address().port; - console.log('listening on localhost:%d', port); + console.log(`listening on localhost:${port}`); let requests = 0; let responses = 0; @@ -87,7 +87,7 @@ function next() { dom.add(req); req.on('response', function(res) { responses++; - console.error('requests=%d responses=%d', requests, responses); + console.error(`requests=${requests} responses=${responses}`); if (responses === requests) { console.error('done, closing server'); // no more coming. 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 089300bc481c10..a2afebd838f410 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 @@ -25,7 +25,7 @@ if (process.argv[2] === 'child') { // is not properly flushed in V8's Isolate::Throw right before the // process aborts due to an uncaught exception, and thus the error // message representing the error that was thrown cannot be read by the - // parent process. So instead of parsing the child process' stdandard + // parent process. So instead of parsing the child process' standard // error, the parent process will check that in the case // --abort-on-uncaught-exception was passed, the process did not exit // with exit code RAN_UNCAUGHT_EXCEPTION_HANDLER_EXIT_CODE. diff --git a/test/parallel/test-eslint-alphabetize-errors.js b/test/parallel/test-eslint-alphabetize-errors.js index 83c73fc78c8486..220f09d54eb69e 100644 --- a/test/parallel/test-eslint-alphabetize-errors.js +++ b/test/parallel/test-eslint-alphabetize-errors.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/alphabetize-errors'); new RuleTester().run('alphabetize-errors', rule, { diff --git a/test/parallel/test-eslint-buffer-constructor.js b/test/parallel/test-eslint-buffer-constructor.js index dfff1374c1b9c0..6b9254f9379b06 100644 --- a/test/parallel/test-eslint-buffer-constructor.js +++ b/test/parallel/test-eslint-buffer-constructor.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/buffer-constructor'); const message = 'Use of the Buffer() constructor has been deprecated. ' + diff --git a/test/parallel/test-eslint-crypto-check.js b/test/parallel/test-eslint-crypto-check.js index 102560e78ecee7..325fb7a057c98b 100644 --- a/test/parallel/test-eslint-crypto-check.js +++ b/test/parallel/test-eslint-crypto-check.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/crypto-check'); const message = 'Please add a hasCrypto check to allow this test to be ' + diff --git a/test/parallel/test-eslint-documented-errors.js b/test/parallel/test-eslint-documented-errors.js index 94e81ff3abaecc..50c92acd151215 100644 --- a/test/parallel/test-eslint-documented-errors.js +++ b/test/parallel/test-eslint-documented-errors.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/documented-errors'); const invalidCode = 'UNDOCUMENTED ERROR CODE'; diff --git a/test/parallel/test-eslint-inspector-check.js b/test/parallel/test-eslint-inspector-check.js index 20774284abccdd..ab8314b63818c7 100644 --- a/test/parallel/test-eslint-inspector-check.js +++ b/test/parallel/test-eslint-inspector-check.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/inspector-check'); const message = 'Please add a skipIfInspectorDisabled() call to allow this ' + diff --git a/test/parallel/test-eslint-lowercase-name-for-primitive.js b/test/parallel/test-eslint-lowercase-name-for-primitive.js index 3eb0d838346865..3449095d6639f9 100644 --- a/test/parallel/test-eslint-lowercase-name-for-primitive.js +++ b/test/parallel/test-eslint-lowercase-name-for-primitive.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/lowercase-name-for-primitive'); const valid = [ diff --git a/test/parallel/test-eslint-no-let-in-for-declaration.js b/test/parallel/test-eslint-no-let-in-for-declaration.js index c3c1e17a729252..ea5b681854621c 100644 --- a/test/parallel/test-eslint-no-let-in-for-declaration.js +++ b/test/parallel/test-eslint-no-let-in-for-declaration.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/no-let-in-for-declaration'); const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6 } }); diff --git a/test/parallel/test-eslint-no-unescaped-regexp-dot.js b/test/parallel/test-eslint-no-unescaped-regexp-dot.js index 5dbd355e71f47d..38a9f3efcc6ff5 100644 --- a/test/parallel/test-eslint-no-unescaped-regexp-dot.js +++ b/test/parallel/test-eslint-no-unescaped-regexp-dot.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/no-unescaped-regexp-dot'); new RuleTester().run('no-unescaped-regexp-dot', rule, { diff --git a/test/parallel/test-eslint-number-isnan.js b/test/parallel/test-eslint-number-isnan.js index deeac48bcccb68..9f6af407e469a6 100644 --- a/test/parallel/test-eslint-number-isnan.js +++ b/test/parallel/test-eslint-number-isnan.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/number-isnan'); const message = 'Please use Number.isNaN instead of the global isNaN function'; diff --git a/test/parallel/test-eslint-prefer-assert-iferror.js b/test/parallel/test-eslint-prefer-assert-iferror.js index 00df47975b8007..6e577b1fc35ace 100644 --- a/test/parallel/test-eslint-prefer-assert-iferror.js +++ b/test/parallel/test-eslint-prefer-assert-iferror.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/prefer-assert-iferror'); new RuleTester().run('prefer-assert-iferror', rule, { diff --git a/test/parallel/test-eslint-prefer-assert-methods.js b/test/parallel/test-eslint-prefer-assert-methods.js index 2129c083224f0e..57596132d88ec3 100644 --- a/test/parallel/test-eslint-prefer-assert-methods.js +++ b/test/parallel/test-eslint-prefer-assert-methods.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/prefer-assert-methods'); new RuleTester().run('prefer-assert-methods', rule, { diff --git a/test/parallel/test-eslint-prefer-common-expectserror.js b/test/parallel/test-eslint-prefer-common-expectserror.js index 16ce66bc24e644..1fe7b1bc9761ac 100644 --- a/test/parallel/test-eslint-prefer-common-expectserror.js +++ b/test/parallel/test-eslint-prefer-common-expectserror.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/prefer-common-expectserror'); const message = 'Please use common.expectsError(fn, err) instead of ' + diff --git a/test/parallel/test-eslint-prefer-common-mustnotcall.js b/test/parallel/test-eslint-prefer-common-mustnotcall.js index 848e762ce38ff2..c2e298cde2153c 100644 --- a/test/parallel/test-eslint-prefer-common-mustnotcall.js +++ b/test/parallel/test-eslint-prefer-common-mustnotcall.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/prefer-common-mustnotcall'); const message = 'Please use common.mustNotCall(msg) instead of ' + diff --git a/test/parallel/test-eslint-prefer-util-format-errors.js b/test/parallel/test-eslint-prefer-util-format-errors.js index 265a0752c50d43..7ccbb8a1335dfa 100644 --- a/test/parallel/test-eslint-prefer-util-format-errors.js +++ b/test/parallel/test-eslint-prefer-util-format-errors.js @@ -4,7 +4,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/prefer-util-format-errors'); new RuleTester({ parserOptions: { ecmaVersion: 6 } }) diff --git a/test/parallel/test-eslint-require-buffer.js b/test/parallel/test-eslint-require-buffer.js index 282f983c782d4e..23bf7c0afa05dd 100644 --- a/test/parallel/test-eslint-require-buffer.js +++ b/test/parallel/test-eslint-require-buffer.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/require-buffer'); const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6 }, diff --git a/test/parallel/test-eslint-required-modules.js b/test/parallel/test-eslint-required-modules.js index 8203cd0d0a0317..1ef96521ec7037 100644 --- a/test/parallel/test-eslint-required-modules.js +++ b/test/parallel/test-eslint-required-modules.js @@ -2,7 +2,7 @@ require('../common'); -const RuleTester = require('../../tools/eslint').RuleTester; +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/required-modules'); new RuleTester().run('required-modules', rule, { diff --git a/test/parallel/test-event-emitter-remove-listeners.js b/test/parallel/test-event-emitter-remove-listeners.js index 612c405442e2a3..75a4c876506eb0 100644 --- a/test/parallel/test-event-emitter-remove-listeners.js +++ b/test/parallel/test-event-emitter-remove-listeners.js @@ -119,10 +119,10 @@ function listener2() {} // listener4 will still be called although it is removed by listener 3. ee.emit('hello'); - // This is so because the interal listener array at time of emit + // This is so because the internal listener array at time of emit // was [listener3,listener4] - // Interal listener array [listener3] + // Internal listener array [listener3] ee.emit('hello'); } diff --git a/test/parallel/test-file-write-stream2.js b/test/parallel/test-file-write-stream2.js index 757d9d91b31041..1f838f0869260a 100644 --- a/test/parallel/test-file-write-stream2.js +++ b/test/parallel/test-file-write-stream2.js @@ -41,8 +41,8 @@ process.on('exit', function() { removeTestFile(); if (cb_occurred !== cb_expected) { console.log(' Test callback events missing or out of order:'); - console.log(' expected: %j', cb_expected); - console.log(' occurred: %j', cb_occurred); + console.log(` expected: ${cb_expected}`); + console.log(` occurred: ${cb_occurred}`); assert.strictEqual( cb_occurred, cb_expected, `events missing or out of order: "${cb_occurred}" !== "${cb_expected}"`); @@ -78,7 +78,7 @@ file.on('drain', function() { if (countDrains === 1) { console.error('drain=1, write again'); assert.strictEqual(fs.readFileSync(filepath, 'utf8'), EXPECTED); - console.error('ondrain write ret=%j', file.write(EXPECTED)); + console.error(`ondrain write ret= ${file.write(EXPECTED)}`); cb_occurred += 'write '; } else if (countDrains === 2) { console.error('second drain, end'); @@ -102,7 +102,7 @@ file.on('error', function(err) { for (let i = 0; i < 11; i++) { const ret = file.write(String(i)); - console.error('%d %j', i, ret); + console.error(`${i} ${ret}`); // return false when i hits 10 assert.strictEqual(ret, i !== 10); diff --git a/test/parallel/test-file-write-stream3.js b/test/parallel/test-file-write-stream3.js index cdc01e873389a2..fe9a61c5827338 100644 --- a/test/parallel/test-file-write-stream3.js +++ b/test/parallel/test-file-write-stream3.js @@ -42,8 +42,8 @@ const fileDataExpected_3 = 'abcdefghij\u2026\u2026qrstuvwxyz'; process.on('exit', function() { if (cb_occurred !== cb_expected) { console.log(' Test callback events missing or out of order:'); - console.log(' expected: %j', cb_expected); - console.log(' occurred: %j', cb_occurred); + console.log(` expected: ${cb_expected}`); + console.log(` occurred: ${cb_occurred}`); assert.strictEqual( cb_occurred, cb_expected, `events missing or out of order: "${cb_occurred}" !== "${cb_expected}"`); diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index d3140941bd0e72..3e90bf94859266 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -28,7 +28,7 @@ createFileWithPerms(readWriteFile, 0o666); * The change of user id is done after creating the fixtures files for the same * reason: the test may be run as the superuser within a directory in which * only the superuser can create files, and thus it may need superuser - * priviledges to create them. + * privileges to create them. * * There's not really any point in resetting the process' user id to 0 after * changing it to 'nobody', since in the case that the test runs without diff --git a/test/parallel/test-fs-read-stream-double-close.js b/test/parallel/test-fs-read-stream-double-close.js index 5f36c03bdbf243..38556e6e644a3d 100644 --- a/test/parallel/test-fs-read-stream-double-close.js +++ b/test/parallel/test-fs-read-stream-double-close.js @@ -13,7 +13,7 @@ const fs = require('fs'); { const s = fs.createReadStream(__filename); - // this is a private API, but it is worth esting. close calls this + // this is a private API, but it is worth testing. close calls this s.destroy(null, common.mustCall()); s.destroy(null, common.mustCall()); } diff --git a/test/parallel/test-fs-read-stream-fd-leak.js b/test/parallel/test-fs-read-stream-fd-leak.js index 28ec7b91b4c35b..5bf0157ff4e7ae 100644 --- a/test/parallel/test-fs-read-stream-fd-leak.js +++ b/test/parallel/test-fs-read-stream-fd-leak.js @@ -24,7 +24,7 @@ fs.close = function() { }; function testLeak(endFn, callback) { - console.log('testing for leaks from fs.createReadStream().%s()...', endFn); + console.log(`testing for leaks from fs.createReadStream().${endFn}()...`); let i = 0; let check = 0; diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js index ecc00edc851c55..ef6cae87068ac9 100644 --- a/test/parallel/test-fs-read-stream.js +++ b/test/parallel/test-fs-read-stream.js @@ -164,6 +164,20 @@ common.expectsError( })); } +{ + // Verify that end works when start is not specified. + const stream = new fs.createReadStream(rangeFile, { end: 1 }); + stream.data = ''; + + stream.on('data', function(chunk) { + stream.data += chunk; + }); + + stream.on('end', common.mustCall(function() { + assert.strictEqual('xy', stream.data); + })); +} + { // pause and then resume immediately. const pauseRes = fs.createReadStream(rangeFile); diff --git a/test/parallel/test-fs-realpath-buffer-encoding.js b/test/parallel/test-fs-realpath-buffer-encoding.js index 3b56a6abf8c265..6952e0c46c689e 100644 --- a/test/parallel/test-fs-realpath-buffer-encoding.js +++ b/test/parallel/test-fs-realpath-buffer-encoding.js @@ -21,13 +21,13 @@ for (encoding in expected) { const expected_value = expected[encoding]; let result; - result = fs.realpathSync(string_dir, { encoding: encoding }); + result = fs.realpathSync(string_dir, { encoding }); assert.strictEqual(result, expected_value); result = fs.realpathSync(string_dir, encoding); assert.strictEqual(result, expected_value); - result = fs.realpathSync(buffer_dir, { encoding: encoding }); + result = fs.realpathSync(buffer_dir, { encoding }); assert.strictEqual(result, expected_value); result = fs.realpathSync(buffer_dir, encoding); @@ -53,7 +53,7 @@ for (encoding in expected) { fs.realpath( string_dir, - { encoding: encoding }, + { encoding }, common.mustCall((err, res) => { assert.ifError(err); assert.strictEqual(res, expected_value); @@ -65,7 +65,7 @@ for (encoding in expected) { })); fs.realpath( buffer_dir, - { encoding: encoding }, + { encoding }, common.mustCall((err, res) => { assert.ifError(err); assert.strictEqual(res, expected_value); diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js index 570fe743fd1318..aa3864962c90af 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -51,7 +51,7 @@ common.refreshTmpDir(); // Test writeFileSync const file1 = path.join(common.tmpDir, 'testWriteFileSync.txt'); -fs.writeFileSync(file1, '123', { mode: mode }); +fs.writeFileSync(file1, '123', { mode }); content = fs.readFileSync(file1, { encoding: 'utf8' }); assert.strictEqual(content, '123'); @@ -61,7 +61,7 @@ assert.strictEqual(fs.statSync(file1).mode & 0o777, mode); // Test appendFileSync const file2 = path.join(common.tmpDir, 'testAppendFileSync.txt'); -fs.appendFileSync(file2, 'abc', { mode: mode }); +fs.appendFileSync(file2, 'abc', { mode }); content = fs.readFileSync(file2, { encoding: 'utf8' }); assert.strictEqual(content, 'abc'); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index 1af93ff269219e..9356bc71850303 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -19,8 +19,8 @@ fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { assert.strictEqual(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn, 'utf8'); - console.log('expected: "%s"', expected); - console.log('found: "%s"', found); + console.log(`expected: "${expected}"`); + console.log(`found: "${found}"`); fs.unlinkSync(fn); assert.strictEqual(expected, found); })); diff --git a/test/parallel/test-http-agent-keepalive.js b/test/parallel/test-http-agent-keepalive.js index 2c8b6c1cc98d2d..8ac8d79df192b0 100644 --- a/test/parallel/test-http-agent-keepalive.js +++ b/test/parallel/test-http-agent-keepalive.js @@ -89,7 +89,7 @@ function remoteClose() { process.nextTick(common.mustCall(() => { assert.strictEqual(agent.sockets[name], undefined); assert.strictEqual(agent.freeSockets[name].length, 1); - // waitting remote server close the socket + // waiting remote server close the socket setTimeout(common.mustCall(() => { assert.strictEqual(agent.sockets[name], undefined); assert.strictEqual(agent.freeSockets[name], undefined, @@ -102,7 +102,7 @@ function remoteClose() { } function remoteError() { - // remove server will destroy ths socket + // remote server will destroy the socket const req = get('/error', common.mustNotCall()); req.on('error', common.mustCall((err) => { assert(err); diff --git a/test/parallel/test-http-client-read-in-error.js b/test/parallel/test-http-client-read-in-error.js index dbf103013175d3..73b86b0d7edd62 100644 --- a/test/parallel/test-http-client-read-in-error.js +++ b/test/parallel/test-http-client-read-in-error.js @@ -34,7 +34,7 @@ class Agent extends http.Agent { const agent = new Agent(); http.request({ - agent: agent + agent }).once('error', function() { console.log('ignore'); }); diff --git a/test/parallel/test-http-client-timeout-agent.js b/test/parallel/test-http-client-timeout-agent.js index 641de122d57abd..2779c21394ae44 100644 --- a/test/parallel/test-http-client-timeout-agent.js +++ b/test/parallel/test-http-client-timeout-agent.js @@ -90,7 +90,7 @@ server.listen(0, options.host, function() { }); process.on('exit', function() { - console.error('done=%j sent=%j', requests_done, requests_sent); + console.error(`done=${requests_done} sent=${requests_sent}`); assert.strictEqual(requests_done, requests_sent, 'timeout on http request called too much'); }); diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js index 7c9514232c7ba8..6d1a770487402d 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -51,7 +51,6 @@ const server = net.createServer(function(socket) { if (postBody.includes('\r\n')) { socket.write(fullResponse); - // omg, I wrote the response twice, what a terrible HTTP server I am. socket.end(fullResponse); } }); diff --git a/test/parallel/test-http-outgoing-finish.js b/test/parallel/test-http-outgoing-finish.js index a242a4728e24eb..c805a89cc165f2 100644 --- a/test/parallel/test-http-outgoing-finish.js +++ b/test/parallel/test-http-outgoing-finish.js @@ -58,19 +58,19 @@ function write(out) { // that 'finish' isn't emitted until the stream is fully flushed. out.on('finish', function() { finishEvent = true; - console.error('%s finish event', name); + console.error(`${name} finish event`); process.nextTick(function() { assert(endCb, `${name} got finish event before endcb!`); - console.log('ok - %s finishEvent', name); + console.log(`ok - ${name} finishEvent`); }); }); out.end(buf, function() { endCb = true; - console.error('%s endCb', name); + console.error(`${name} endCb`); process.nextTick(function() { assert(finishEvent, `${name} got endCb event before finishEvent!`); - console.log('ok - %s endCb', name); + console.log(`ok - ${name} endCb`); }); }); } diff --git a/test/parallel/test-http-parser-freed-before-upgrade.js b/test/parallel/test-http-parser-freed-before-upgrade.js new file mode 100644 index 00000000000000..4ba1de9501681c --- /dev/null +++ b/test/parallel/test-http-parser-freed-before-upgrade.js @@ -0,0 +1,33 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); + +const server = http.createServer(); + +server.on('upgrade', common.mustCall((request, socket) => { + assert.strictEqual(socket.parser, null); + socket.write([ + 'HTTP/1.1 101 Switching Protocols', + 'Connection: Upgrade', + 'Upgrade: WebSocket', + '\r\n' + ].join('\r\n')); +})); + +server.listen(common.mustCall(() => { + const request = http.get({ + port: server.address().port, + headers: { + Connection: 'Upgrade', + Upgrade: 'WebSocket' + } + }); + + request.on('upgrade', common.mustCall((response, socket) => { + assert.strictEqual(socket.parser, null); + socket.destroy(); + server.close(); + })); +})); diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index 81aadf26169179..df3a87f73c8d15 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -20,15 +20,11 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -const common = require('../common'); +const { mustCall, mustNotCall } = require('../common'); const assert = require('assert'); -const binding = process.binding('http_parser'); -const methods = binding.methods; -const HTTPParser = binding.HTTPParser; - -const REQUEST = HTTPParser.REQUEST; -const RESPONSE = HTTPParser.RESPONSE; +const { methods, HTTPParser } = process.binding('http_parser'); +const { REQUEST, RESPONSE } = HTTPParser; const kOnHeaders = HTTPParser.kOnHeaders | 0; const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; @@ -55,7 +51,7 @@ function newParser(type) { parser[kOnHeadersComplete] = function() { }; - parser[kOnBody] = common.mustNotCall('kOnBody should not be called'); + parser[kOnBody] = mustNotCall('kOnBody should not be called'); parser[kOnMessageComplete] = function() { }; @@ -64,21 +60,6 @@ function newParser(type) { } -function mustCall(f, times) { - let actual = 0; - - process.setMaxListeners(256); - process.on('exit', function() { - assert.strictEqual(actual, times || 1); - }); - - return function() { - actual++; - return f.apply(this, Array.prototype.slice.call(arguments)); - }; -} - - function expectBody(expected) { return mustCall(function(buf, start, len) { const body = String(buf.slice(start, start + len)); diff --git a/test/parallel/test-http-pipeline-flood.js b/test/parallel/test-http-pipeline-flood.js index 34a7e37dff0241..3d6167d3870566 100644 --- a/test/parallel/test-http-pipeline-flood.js +++ b/test/parallel/test-http-pipeline-flood.js @@ -66,7 +66,7 @@ function child() { const net = require('net'); const port = +process.argv[3]; - const conn = net.connect({ port: port }); + const conn = net.connect({ port }); let req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`; diff --git a/test/parallel/test-http-response-status-message.js b/test/parallel/test-http-response-status-message.js index e52abc57e6ce54..0f9bce8fa87d67 100644 --- a/test/parallel/test-http-response-status-message.js +++ b/test/parallel/test-http-response-status-message.js @@ -24,8 +24,7 @@ require('../common'); const assert = require('assert'); const http = require('http'); const net = require('net'); - -let testsComplete = 0; +const Countdown = require('../common/countdown'); const testCases = [ { path: '/200', statusMessage: 'OK', @@ -59,6 +58,8 @@ const server = net.createServer(function(connection) { }); }); +const countdown = new Countdown(testCases.length, () => server.close()); + function runTest(testCaseIndex) { const testCase = testCases[testCaseIndex]; @@ -71,12 +72,9 @@ function runTest(testCaseIndex) { assert.strictEqual(testCase.statusMessage, response.statusMessage); response.on('end', function() { - testsComplete++; - + countdown.dec(); if (testCaseIndex + 1 < testCases.length) { runTest(testCaseIndex + 1); - } else { - server.close(); } }); @@ -85,7 +83,3 @@ function runTest(testCaseIndex) { } server.listen(0, function() { runTest(0); }); - -process.on('exit', function() { - assert.strictEqual(testCases.length, testsComplete); -}); diff --git a/test/parallel/test-http-upgrade-binary.js b/test/parallel/test-http-upgrade-binary.js new file mode 100644 index 00000000000000..002ac9c564ad1e --- /dev/null +++ b/test/parallel/test-http-upgrade-binary.js @@ -0,0 +1,28 @@ +'use strict'; +const { mustCall } = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); + +// https://github.com/nodejs/node/issues/17789 - a connection upgrade response +// that has a Transfer-Encoding header and a body whose first byte is > 127 +// triggers a bug where said byte is skipped over. +net.createServer(mustCall(function(conn) { + conn.write('HTTP/1.1 101 Switching Protocols\r\n' + + 'Connection: upgrade\r\n' + + 'Transfer-Encoding: chunked\r\n' + + 'Upgrade: websocket\r\n' + + '\r\n' + + '\u0080', 'latin1'); + this.close(); +})).listen(0, mustCall(function() { + http.get({ + host: this.address().host, + port: this.address().port, + headers: { 'Connection': 'upgrade', 'Upgrade': 'websocket' }, + }).on('upgrade', mustCall((res, conn, head) => { + assert.strictEqual(head.length, 1); + assert.strictEqual(head[0], 128); + conn.destroy(); + })); +})); diff --git a/test/parallel/test-http2-backpressure.js b/test/parallel/test-http2-backpressure.js new file mode 100644 index 00000000000000..9b69dddbfd2e26 --- /dev/null +++ b/test/parallel/test-http2-backpressure.js @@ -0,0 +1,49 @@ +'use strict'; + +// Verifies that a full HTTP2 pipeline handles backpressure. + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); +const makeDuplexPair = require('../common/duplexpair'); + +common.crashOnUnhandledRejection(); + +{ + let req; + const server = http2.createServer(); + server.on('stream', common.mustCallAsync(async (stream, headers) => { + stream.respond({ + 'content-type': 'text/html', + ':status': 200 + }); + req._readableState.highWaterMark = 20; + stream._writableState.highWaterMark = 20; + assert.strictEqual(stream.write('A'.repeat(5)), true); + assert.strictEqual(stream.write('A'.repeat(40)), false); + assert.strictEqual(await event(req, 'data'), 'A'.repeat(5)); + assert.strictEqual(await event(req, 'data'), 'A'.repeat(40)); + await event(stream, 'drain'); + assert.strictEqual(stream.write('A'.repeat(5)), true); + assert.strictEqual(stream.write('A'.repeat(40)), false); + })); + + const { clientSide, serverSide } = makeDuplexPair(); + server.emit('connection', serverSide); + + const client = http2.connect('http://localhost:80', { + createConnection: common.mustCall(() => clientSide) + }); + + req = client.request({ ':path': '/' }); + req.setEncoding('utf8'); + req.end(); +} + +function event(ee, eventName) { + return new Promise((resolve) => { + ee.once(eventName, common.mustCall(resolve)); + }); +} diff --git a/test/parallel/test-http2-create-client-connect.js b/test/parallel/test-http2-create-client-connect.js index fa9711fe1b28a7..02c6c70642acb0 100644 --- a/test/parallel/test-http2-create-client-connect.js +++ b/test/parallel/test-http2-create-client-connect.js @@ -22,8 +22,8 @@ const URL = url.URL; [`http://localhost:${port}`], [new URL(`http://localhost:${port}`)], [url.parse(`http://localhost:${port}`)], - [{ port: port }, { protocol: 'http:' }], - [{ port: port, hostname: '127.0.0.1' }, { protocol: 'http:' }] + [{ port }, { protocol: 'http:' }], + [{ port, hostname: '127.0.0.1' }, { protocol: 'http:' }] ]; const serverClose = new Countdown(items.length + 1, diff --git a/test/parallel/test-http2-create-client-secure-session.js b/test/parallel/test-http2-create-client-secure-session.js index 6120a58602065d..b0111e15b69c15 100644 --- a/test/parallel/test-http2-create-client-secure-session.js +++ b/test/parallel/test-http2-create-client-secure-session.js @@ -38,6 +38,7 @@ function onStream(stream, headers) { function verifySecureSession(key, cert, ca, opts) { const server = h2.createSecureServer({ cert, key }); server.on('stream', common.mustCall(onStream)); + server.on('close', common.mustCall()); server.listen(0, common.mustCall(() => { opts = opts || { }; opts.secureContext = tls.createSecureContext({ ca }); @@ -72,7 +73,7 @@ function verifySecureSession(key, cert, ca, opts) { assert.strictEqual(jsonData.servername, opts.servername || 'localhost'); assert.strictEqual(jsonData.alpnProtocol, 'h2'); - server.close(); + server.close(common.mustCall()); client[kSocket].destroy(); })); })); diff --git a/test/parallel/test-http2-create-client-session.js b/test/parallel/test-http2-create-client-session.js index b5be6bc8581452..963db2faa173b7 100644 --- a/test/parallel/test-http2-create-client-session.js +++ b/test/parallel/test-http2-create-client-session.js @@ -29,6 +29,8 @@ function onStream(stream, headers, flags) { stream.end(body.slice(20)); } +server.on('close', common.mustCall()); + server.listen(0); server.on('listening', common.mustCall(() => { @@ -46,7 +48,7 @@ server.on('listening', common.mustCall(() => { const countdown = new Countdown(count, () => { client.close(); - server.close(); + server.close(common.mustCall()); }); for (let n = 0; n < count; n++) { diff --git a/test/parallel/test-http2-createwritereq.js b/test/parallel/test-http2-createwritereq.js index 1d2b31676284d0..1575424d1609b4 100644 --- a/test/parallel/test-http2-createwritereq.js +++ b/test/parallel/test-http2-createwritereq.js @@ -60,7 +60,7 @@ server.listen(0, common.mustCall(function() { testsFinished++; if (testsFinished === testsToRun) { - server.close(); + server.close(common.mustCall()); } })); diff --git a/test/parallel/test-http2-misbehaving-flow-control-paused.js b/test/parallel/test-http2-misbehaving-flow-control-paused.js index 0b7299d5ac80a8..d69e0fd802979a 100644 --- a/test/parallel/test-http2-misbehaving-flow-control-paused.js +++ b/test/parallel/test-http2-misbehaving-flow-control-paused.js @@ -56,6 +56,9 @@ let client; const server = h2.createServer({ settings: { initialWindowSize: 36 } }); server.on('stream', (stream) => { + // Set the high water mark to zero, since otherwise we still accept + // reads from the source stream (if we can consume them). + stream._readableState.highWaterMark = 0; stream.pause(); stream.on('error', common.expectsError({ code: 'ERR_HTTP2_STREAM_ERROR', diff --git a/test/parallel/test-http2-misbehaving-flow-control.js b/test/parallel/test-http2-misbehaving-flow-control.js index 8a0b411b8de65c..161a88ea1fb407 100644 --- a/test/parallel/test-http2-misbehaving-flow-control.js +++ b/test/parallel/test-http2-misbehaving-flow-control.js @@ -72,7 +72,7 @@ server.on('stream', (stream) => { message: 'Stream closed with error code 3' })); stream.on('close', common.mustCall(() => { - server.close(); + server.close(common.mustCall()); client.destroy(); })); stream.resume(); @@ -80,6 +80,8 @@ server.on('stream', (stream) => { stream.end('ok'); }); +server.on('close', common.mustCall()); + server.listen(0, () => { client = net.connect(server.address().port, () => { client.write(preamble); diff --git a/test/parallel/test-http2-perf_hooks.js b/test/parallel/test-http2-perf_hooks.js index 07d9c55ed7e0d2..e30d0ac83e0d1f 100644 --- a/test/parallel/test-http2-perf_hooks.js +++ b/test/parallel/test-http2-perf_hooks.js @@ -6,7 +6,7 @@ if (!common.hasCrypto) const assert = require('assert'); const h2 = require('http2'); -const { PerformanceObserver } = require('perf_hooks'); +const { PerformanceObserver, performance } = require('perf_hooks'); const obs = new PerformanceObserver(common.mustCall((items) => { const entry = items.getEntries()[0]; @@ -46,6 +46,7 @@ const obs = new PerformanceObserver(common.mustCall((items) => { default: assert.fail('invalid entry name'); } + performance.clearEntries('http2'); }, 4)); obs.observe({ entryTypes: ['http2'] }); @@ -100,3 +101,10 @@ server.on('listening', common.mustCall(() => { })); })); + +process.on('exit', () => { + const entries = performance.getEntries(); + // There shouldn't be any http2 entries left over. + assert.strictEqual(entries.length, 1); + assert.strictEqual(entries[0], performance.nodeTiming); +}); diff --git a/test/parallel/test-http2-sent-headers.js b/test/parallel/test-http2-sent-headers.js new file mode 100644 index 00000000000000..bffa4d71c6d5f3 --- /dev/null +++ b/test/parallel/test-http2-sent-headers.js @@ -0,0 +1,47 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const h2 = require('http2'); + +const server = h2.createServer(); + +server.on('stream', common.mustCall((stream) => { + stream.additionalHeaders({ ':status': 102 }); + assert.strictEqual(stream.sentInfoHeaders[0][':status'], 102); + + stream.respond({ abc: 'xyz' }, { + getTrailers(headers) { + headers.xyz = 'abc'; + } + }); + assert.strictEqual(stream.sentHeaders.abc, 'xyz'); + assert.strictEqual(stream.sentHeaders[':status'], 200); + assert.notStrictEqual(stream.sentHeaders.date, undefined); + stream.end(); + stream.on('close', () => { + assert.strictEqual(stream.sentTrailers.xyz, 'abc'); + }); +})); + +server.listen(0, common.mustCall(() => { + const client = h2.connect(`http://localhost:${server.address().port}`); + const req = client.request(); + + req.on('headers', common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 102); + })); + + assert.strictEqual(req.sentHeaders[':method'], 'GET'); + assert.strictEqual(req.sentHeaders[':authority'], + `localhost:${server.address().port}`); + assert.strictEqual(req.sentHeaders[':scheme'], 'http'); + assert.strictEqual(req.sentHeaders[':path'], '/'); + req.resume(); + req.on('close', () => { + server.close(); + client.close(); + }); +})); diff --git a/test/parallel/test-http2-server-push-disabled.js b/test/parallel/test-http2-server-push-disabled.js index 9a0b748d354276..78b3e26ad4968b 100644 --- a/test/parallel/test-http2-server-push-disabled.js +++ b/test/parallel/test-http2-server-push-disabled.js @@ -42,7 +42,7 @@ server.listen(0, common.mustCall(() => { options); const req = client.request({ ':path': '/' }); - // Because push stream sre disabled, this must not be called. + // Because push streams are disabled, this must not be called. client.on('stream', common.mustNotCall()); req.resume(); diff --git a/test/parallel/test-http2-server-timeout.js b/test/parallel/test-http2-server-timeout.js index 581a409ce9171d..4410cb51c169c5 100755 --- a/test/parallel/test-http2-server-timeout.js +++ b/test/parallel/test-http2-server-timeout.js @@ -18,12 +18,12 @@ server.once('timeout', onServerTimeout); server.listen(0, common.mustCall(() => { const url = `http://localhost:${server.address().port}`; const client = http2.connect(url); - // Because of the timeout, an ECONRESET error may or may not happen here. + // Because of the timeout, an ECONNRESET error may or may not happen here. // Keep this as a non-op and do not use common.mustCall() client.on('error', () => {}); client.on('close', common.mustCall(() => { const client2 = http2.connect(url); - // Because of the timeout, an ECONRESET error may or may not happen here. + // Because of the timeout, an ECONNRESET error may or may not happen here. // Keep this as a non-op and do not use common.mustCall() client2.on('error', () => {}); client2.on('close', common.mustCall(() => server.close())); diff --git a/test/parallel/test-http2-too-many-streams.js b/test/parallel/test-http2-too-many-streams.js index a4a67befa0f50a..c4ed5d52c25832 100644 --- a/test/parallel/test-http2-too-many-streams.js +++ b/test/parallel/test-http2-too-many-streams.js @@ -19,7 +19,7 @@ server.on('stream', common.mustCall((stream) => { // c should never be greater than 1. assert.strictEqual(++c, 1); stream.respond(); - // Force some asynchronos stuff. + // Force some asynchronous stuff. setImmediate(() => { stream.end('ok'); assert.strictEqual(--c, 0); diff --git a/test/parallel/test-https-agent-create-connection.js b/test/parallel/test-https-agent-create-connection.js index 4ad3554f791524..5dcf73cc76d6aa 100644 --- a/test/parallel/test-https-agent-create-connection.js +++ b/test/parallel/test-https-agent-create-connection.js @@ -51,10 +51,7 @@ function createServer() { port: port, host: host, rejectUnauthorized: false, - _agentKey: agent.getName({ - port: port, - host: host, - }), + _agentKey: agent.getName({ port, host }) }; const socket = agent.createConnection(options); @@ -70,10 +67,7 @@ function createServer() { const host = 'localhost'; const options = { rejectUnauthorized: false, - _agentKey: agent.getName({ - port: port, - host: host, - }), + _agentKey: agent.getName({ port, host }) }; const socket = agent.createConnection(port, options); checkRequest(socket, server); @@ -88,10 +82,7 @@ function createServer() { const host = 'localhost'; const options = { rejectUnauthorized: false, - _agentKey: agent.getName({ - port: port, - host: host, - }), + _agentKey: agent.getName({ port, host }) }; const socket = agent.createConnection(port, host, options); checkRequest(socket, server); diff --git a/test/parallel/test-https-agent-secure-protocol.js b/test/parallel/test-https-agent-secure-protocol.js index 4963b55febe345..82554952e8446b 100644 --- a/test/parallel/test-https-agent-secure-protocol.js +++ b/test/parallel/test-https-agent-secure-protocol.js @@ -42,7 +42,7 @@ server.listen(0, common.mustCall(function() { }, common.mustCall(function(res) { res.resume(); globalAgent.once('free', common.mustCall(function() { - // Verify that two keep-alived connections are created + // Verify that two keep-alive connections are created // due to the different secureProtocol settings: const keys = Object.keys(globalAgent.freeSockets); assert.strictEqual(keys.length, 2); diff --git a/test/parallel/test-https-socket-options.js b/test/parallel/test-https-socket-options.js index 2ba1b883684205..b41054d5aa0824 100644 --- a/test/parallel/test-https-socket-options.js +++ b/test/parallel/test-https-socket-options.js @@ -61,7 +61,7 @@ server_http.listen(0, function() { }); // Then try https server (requires functions to be -// mirroed in tls.js's CryptoStream) +// mirrored in tls.js's CryptoStream) const server_https = https.createServer(options, function(req, res) { console.log('got HTTPS request'); diff --git a/test/parallel/test-https-strict.js b/test/parallel/test-https-strict.js index 05bbe43a8428dd..f575f524061580 100644 --- a/test/parallel/test-https-strict.js +++ b/test/parallel/test-https-strict.js @@ -112,11 +112,7 @@ function listening() { function makeReq(path, port, error, host, ca) { pending++; - const options = { - port: port, - path: path, - ca: ca - }; + const options = { port, path, ca }; if (!ca) { options.agent = agent0; @@ -134,7 +130,7 @@ function makeReq(path, port, error, host, ca) { } if (host) { - options.headers = { host: host }; + options.headers = { host }; } const req = https.get(options); const server = port === server1.address().port ? server1 : diff --git a/test/parallel/test-https-truncate.js b/test/parallel/test-https-truncate.js index 9d2679ee9a5352..1a14cf54088a30 100644 --- a/test/parallel/test-https-truncate.js +++ b/test/parallel/test-https-truncate.js @@ -38,7 +38,7 @@ const data = Buffer.alloc(1024 * 32 + 1); httpsTest(); function httpsTest() { - const sopt = { key: key, cert: cert }; + const sopt = { key, cert }; const server = https.createServer(sopt, function(req, res) { res.setHeader('content-length', data.length); diff --git a/test/parallel/test-internal-fs-syncwritestream.js b/test/parallel/test-internal-fs-syncwritestream.js index 166692f4e6236e..9e0024df3481b2 100644 --- a/test/parallel/test-internal-fs-syncwritestream.js +++ b/test/parallel/test-internal-fs-syncwritestream.js @@ -31,7 +31,7 @@ const filename = path.join(common.tmpDir, 'sync-write-stream.txt'); assert.strictEqual(stream.listenerCount('end'), 1); } -// Verfiy that the file will be written synchronously. +// Verify that the file will be written synchronously. { const fd = fs.openSync(filename, 'w'); const stream = new SyncWriteStream(fd); @@ -54,7 +54,7 @@ const filename = path.join(common.tmpDir, 'sync-write-stream.txt'); assert.strictEqual(stream.destroySoon(), true); } -// Verfit that the 'end' event listener will also destroy the stream. +// Verify that the 'end' event listener will also destroy the stream. { const fd = fs.openSync(filename, 'w'); const stream = new SyncWriteStream(fd); diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js index 4f74a5b22d6eb8..da8abd868300e3 100644 --- a/test/parallel/test-listen-fd-cluster.js +++ b/test/parallel/test-listen-fd-cluster.js @@ -85,7 +85,7 @@ function test(cb) { conn.end('hello from parent\n'); }).listen(0, function() { const port = this.address().port; - console.error('server listening on %d', port); + console.error(`server listening on ${port}`); const spawn = require('child_process').spawn; const master = spawn(process.execPath, [__filename, 'master'], { diff --git a/test/parallel/test-net-connect-options-port.js b/test/parallel/test-net-connect-options-port.js index 37dc1d58b4519f..8152424c52c8fc 100644 --- a/test/parallel/test-net-connect-options-port.js +++ b/test/parallel/test-net-connect-options-port.js @@ -60,7 +60,7 @@ const net = require('net'); { // connect({hint}, cb) and connect({hint}) const hints = (dns.ADDRCONFIG | dns.V4MAPPED) + 42; - const hintOptBlocks = doConnect([{ hints: hints }], + const hintOptBlocks = doConnect([{ hints }], () => common.mustNotCall()); for (const block of hintOptBlocks) { common.expectsError(block, { diff --git a/test/parallel/test-net-listen-error.js b/test/parallel/test-net-listen-error.js index 26a74a72c38b85..05ca799d3e7351 100644 --- a/test/parallel/test-net-listen-error.js +++ b/test/parallel/test-net-listen-error.js @@ -25,5 +25,5 @@ const net = require('net'); const server = net.createServer(function(socket) { }); -server.listen(1, '1.1.1.1', common.mustNotCall()); // EACCESS or EADDRNOTAVAIL +server.listen(1, '1.1.1.1', common.mustNotCall()); // EACCES or EADDRNOTAVAIL server.on('error', common.mustCall()); diff --git a/test/parallel/test-net-pipe-connect-errors.js b/test/parallel/test-net-pipe-connect-errors.js index 91c4f7efd07966..119bca19fcc762 100644 --- a/test/parallel/test-net-pipe-connect-errors.js +++ b/test/parallel/test-net-pipe-connect-errors.js @@ -37,7 +37,7 @@ if (common.isWindows) { emptyTxt = fixtures.path('empty.txt'); } else { common.refreshTmpDir(); - // Keep the file name very short so tht we don't exceed the 108 char limit + // Keep the file name very short so that we don't exceed the 108 char limit // on CI for a POSIX socket. Even though this isn't actually a socket file, // the error will be different from the one we are expecting if we exceed the // limit. diff --git a/test/parallel/test-net-server-listen-handle.js b/test/parallel/test-net-server-listen-handle.js index de1f1ca375d98e..2b56817d2c61d7 100644 --- a/test/parallel/test-net-server-listen-handle.js +++ b/test/parallel/test-net-server-listen-handle.js @@ -144,7 +144,7 @@ if (!common.isWindows) { // Windows doesn't support {fd: } // Test invalid fd const fd = fs.openSync(__filename, 'r'); net.createServer() - .listen({ fd: fd }, common.mustNotCall()) + .listen({ fd }, common.mustNotCall()) .on('error', common.mustCall(function(err) { assert.strictEqual(String(err), 'Error: listen EINVAL'); this.close(); diff --git a/test/parallel/test-net-server-listen-options.js b/test/parallel/test-net-server-listen-options.js index f969fa9d43d2da..83984844388a82 100644 --- a/test/parallel/test-net-server-listen-options.js +++ b/test/parallel/test-net-server-listen-options.js @@ -17,7 +17,7 @@ function close() { this.close(); } .on('listening', common.mustCall(close)); } -// Test listen(port, cb) and listen({port: port}, cb) combinations +// Test listen(port, cb) and listen({ port }, cb) combinations const listenOnPort = [ (port, cb) => net.createServer().listen({ port }, cb), (port, cb) => net.createServer().listen(port, cb) diff --git a/test/parallel/test-net-server-max-connections.js b/test/parallel/test-net-server-max-connections.js index cfe4fa999dc8ff..c73efb3c1ef406 100644 --- a/test/parallel/test-net-server-max-connections.js +++ b/test/parallel/test-net-server-max-connections.js @@ -55,7 +55,7 @@ function makeConnection(index) { } c.on('close', function() { - console.error('closed %d', index); + console.error(`closed ${index}`); closes++; if (closes < N / 2) { @@ -97,7 +97,7 @@ function makeConnection(index) { if (common.isSunOS && (e.code === 'ECONNREFUSED')) { c.connect(server.address().port); } - console.error('error %d: %s', index, e); + console.error(`error ${index}: ${e}`); }); } diff --git a/test/parallel/test-net-write-after-close.js b/test/parallel/test-net-write-after-close.js index 05669e476c7670..f17273f9417a2a 100644 --- a/test/parallel/test-net-write-after-close.js +++ b/test/parallel/test-net-write-after-close.js @@ -39,7 +39,7 @@ const server = net.createServer(common.mustCall(function(socket) { server.listen(0, function() { const client = net.connect(this.address().port, function() { - // cliend.end() will close both the readable and writable side + // client.end() will close both the readable and writable side // of the duplex because allowHalfOpen defaults to false. // Then 'end' will be emitted when it receives a FIN packet from // the other side. diff --git a/test/parallel/test-os.js b/test/parallel/test-os.js index f8e383e497a154..47d4209c36a20b 100644 --- a/test/parallel/test-os.js +++ b/test/parallel/test-os.js @@ -113,7 +113,7 @@ is.string(arch); assert.ok(arch.length > 0); if (!common.isSunOS) { - // not implemeneted yet + // not implemented yet assert.ok(os.loadavg().length > 0); assert.ok(os.freemem() > 0); assert.ok(os.totalmem() > 0); diff --git a/test/parallel/test-path-normalize.js b/test/parallel/test-path-normalize.js index 0820052446367e..0dd1b8339f4c64 100644 --- a/test/parallel/test-path-normalize.js +++ b/test/parallel/test-path-normalize.js @@ -27,6 +27,18 @@ assert.strictEqual(path.win32.normalize('..\\foo..\\..\\..\\bar'), '..\\..\\bar'); assert.strictEqual(path.win32.normalize('..\\...\\..\\.\\...\\..\\..\\bar'), '..\\..\\bar'); +assert.strictEqual(path.win32.normalize('../../../foo/../../../bar'), + '..\\..\\..\\..\\..\\bar'); +assert.strictEqual(path.win32.normalize('../../../foo/../../../bar/../../'), + '..\\..\\..\\..\\..\\..\\'); +assert.strictEqual( + path.win32.normalize('../foobar/barfoo/foo/../../../bar/../../'), + '..\\..\\' +); +assert.strictEqual( + path.win32.normalize('../.../../foobar/../../../bar/../../baz'), + '..\\..\\..\\..\\baz' +); assert.strictEqual(path.posix.normalize('./fixtures///b/../b/c.js'), 'fixtures/b/c.js'); @@ -44,3 +56,15 @@ assert.strictEqual(path.posix.normalize('bar/foo..'), 'bar/foo..'); assert.strictEqual(path.posix.normalize('../foo../../../bar'), '../../bar'); assert.strictEqual(path.posix.normalize('../.../.././.../../../bar'), '../../bar'); +assert.strictEqual(path.posix.normalize('../../../foo/../../../bar'), + '../../../../../bar'); +assert.strictEqual(path.posix.normalize('../../../foo/../../../bar/../../'), + '../../../../../../'); +assert.strictEqual( + path.posix.normalize('../foobar/barfoo/foo/../../../bar/../../'), + '../../' +); +assert.strictEqual( + path.posix.normalize('../.../../foobar/../../../bar/../../baz'), + '../../../../baz' +); diff --git a/test/parallel/test-process-exit-code.js b/test/parallel/test-process-exit-code.js index 55120f66926374..f5f8099c8d2439 100644 --- a/test/parallel/test-process-exit-code.js +++ b/test/parallel/test-process-exit-code.js @@ -93,7 +93,7 @@ function parent() { assert.strictEqual( code, exit, `wrong exit for ${arg}\nexpected:${exit} but got:${code}`); - console.log('ok - %s exited with %d', arg, exit); + console.log(`ok - ${arg} exited with ${exit}`); }); }; diff --git a/test/parallel/test-process-versions.js b/test/parallel/test-process-versions.js index 5644ac4658b534..8f706c6954cd2c 100644 --- a/test/parallel/test-process-versions.js +++ b/test/parallel/test-process-versions.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const expected_keys = ['ares', 'http_parser', 'modules', 'node', - 'uv', 'v8', 'zlib', 'nghttp2']; + 'uv', 'v8', 'zlib', 'nghttp2', 'napi']; if (common.hasCrypto) { expected_keys.push('openssl'); diff --git a/test/parallel/test-promises-unhandled-rejections.js b/test/parallel/test-promises-unhandled-rejections.js index a00a7836252c91..ed5d485ac72e96 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -293,7 +293,7 @@ asyncTest('While inside setImmediate, catching a rejected promise derived ' + }); }); -// State adapation tests +// State adaptation tests asyncTest('catching a promise which is asynchronously rejected (via ' + 'resolution to an asynchronously-rejected promise) prevents' + ' unhandledRejection', function(done) { diff --git a/test/parallel/test-punycode.js b/test/parallel/test-punycode.js index 334fceadbe9983..9f7f772e17b0fe 100644 --- a/test/parallel/test-punycode.js +++ b/test/parallel/test-punycode.js @@ -200,10 +200,7 @@ const tests = [ let errors = 0; const handleError = (error, name) => { console.error( - 'FAIL: %s expected %j, got %j', - name, - error.expected, - error.actual + `FAIL: ${name} expected ${error.expected}, got ${error.actual}` ); errors++; }; diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 22cb5891bb5d74..69c0f113ff103b 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -808,7 +808,7 @@ function isWarned(emitter) { assert.strictEqual(isWarned(process.stdout._events), false); } - // can create a new readline Interface with a null output arugument + // can create a new readline Interface with a null output argument { const fi = new FakeInput(); const rli = new readline.Interface( diff --git a/test/parallel/test-repl-syntax-error-handling.js b/test/parallel/test-repl-syntax-error-handling.js index 67bf5f6038bf63..f61ab077eb638c 100644 --- a/test/parallel/test-repl-syntax-error-handling.js +++ b/test/parallel/test-repl-syntax-error-handling.js @@ -38,7 +38,7 @@ function parent() { child.stderr.setEncoding('utf8'); child.stderr.on('data', function(c) { - console.error('%j', c); + console.error(`${c}`); throw new Error('should not get stderr data'); }); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index c9583e4fdf3c40..7419148dfaf2df 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -23,540 +23,748 @@ const common = require('../common'); const fixtures = require('../common/fixtures'); const assert = require('assert'); +const net = require('net'); +const repl = require('repl'); common.globalCheck = false; common.refreshTmpDir(); +common.crashOnUnhandledRejection(); -const net = require('net'); -const repl = require('repl'); const message = 'Read, Eval, Print Loop'; const prompt_unix = 'node via Unix socket> '; const prompt_tcp = 'node via TCP socket> '; -const prompt_multiline = '... '; -const prompt_npm = 'npm should be run outside of the ' + - 'node repl, in your normal shell.\n' + - '(Press Control-D to exit.)\n'; -const expect_npm = prompt_npm + prompt_unix; -let server_tcp, server_unix, client_tcp, client_unix, replServer; - // absolute path to test/fixtures/a.js const moduleFilename = fixtures.path('a'); -console.error('repl test'); - // function for REPL to run global.invoke_me = function(arg) { return `invoked ${arg}`; }; -function send_expect(list) { - if (list.length > 0) { - const cur = list.shift(); - console.error(`sending ${JSON.stringify(cur.send)}`); +// Helpers for describing the expected output: +const kArrow = /^ *\^+ *$/; // Arrow of ^ pointing to syntax error location +const kSource = Symbol('kSource'); // Placeholder standing for input readback - cur.client.expect = cur.expect; - cur.client.list = list; - if (cur.send.length > 0) { - cur.client.write(`${cur.send}\n`); - } - } -} +async function runReplTests(socket, prompt, tests) { + let lineBuffer = ''; -function clean_up() { - client_tcp.end(); - client_unix.end(); -} + for (const { send, expect } of tests) { + // expect can be a single line or multiple lines + const expectedLines = Array.isArray(expect) ? expect : [ expect ]; -function strict_mode_error_test() { - send_expect([ - { client: client_unix, send: 'ref = 1', - expect: /^ReferenceError:\s/ }, - ]); -} + console.error('out:', JSON.stringify(send)); + socket.write(`${send}\n`); -function error_test() { - // The other stuff is done so reuse unix socket - let read_buffer = ''; - let run_strict_test = true; - client_unix.removeAllListeners('data'); - - client_unix.on('data', function(data) { - read_buffer += data.toString('ascii', 0, data.length); - console.error( - `Unix data: ${JSON.stringify(read_buffer)}, expecting ${ - client_unix.expect.exec ? - client_unix.expect : - JSON.stringify(client_unix.expect)}`); - - if (read_buffer.includes(prompt_unix)) { - // if it's an exact match, then don't do the regexp - if (read_buffer !== client_unix.expect) { - let expect = client_unix.expect; - if (expect === prompt_multiline) - expect = /[.]{3} /; - assert.ok(RegExp(expect).test(read_buffer)); - console.error('match'); - } - read_buffer = ''; - if (client_unix.list && client_unix.list.length > 0) { - send_expect(client_unix.list); - } else if (run_strict_test) { - replServer.replMode = repl.REPL_MODE_STRICT; - run_strict_test = false; - strict_mode_error_test(); - } else { - console.error('End of Error test, running TCP test.'); - tcp_test(); + for (let expectedLine of expectedLines) { + // special value: kSource refers to last sent source text + if (expectedLine === kSource) + expectedLine = send; + + while (!lineBuffer.includes('\n')) { + lineBuffer += await event(socket, 'data'); + + // Cut away the initial prompt + while (lineBuffer.startsWith(prompt)) + lineBuffer = lineBuffer.substr(prompt.length); + + // Allow to match partial text if no newline was received, because + // sending newlines from the REPL itself would be redundant + // (e.g. in the `... ` multiline prompt: The user already pressed + // enter for that, so the REPL shouldn't do it again!). + if (lineBuffer === expectedLine && !expectedLine.includes('\n')) + lineBuffer += '\n'; } - } else if (read_buffer.includes(prompt_multiline)) { - // Check that you meant to send a multiline test - assert.strictEqual(prompt_multiline, client_unix.expect); - read_buffer = ''; - if (client_unix.list && client_unix.list.length > 0) { - send_expect(client_unix.list); - } else if (run_strict_test) { - replServer.replMode = repl.REPL_MODE_STRICT; - run_strict_test = false; - strict_mode_error_test(); + // Split off the current line. + const newlineOffset = lineBuffer.indexOf('\n'); + let actualLine = lineBuffer.substr(0, newlineOffset); + lineBuffer = lineBuffer.substr(newlineOffset + 1); + + // This might have been skipped in the loop above because the buffer + // already contained a \n to begin with and the entire loop was skipped. + while (actualLine.startsWith(prompt)) + actualLine = actualLine.substr(prompt.length); + + console.error('in:', JSON.stringify(actualLine)); + + // Match a string directly, or a RegExp through .test(). + if (typeof expectedLine === 'string') { + assert.strictEqual(actualLine, expectedLine); } else { - console.error('End of Error test, running TCP test.\n'); - tcp_test(); + assert(expectedLine.test(actualLine), + `${actualLine} match ${expectedLine}`); } - - } else { - console.error('didn\'t see prompt yet, buffering.'); } - }); + } - send_expect([ - // Uncaught error throws and prints out - { client: client_unix, send: 'throw new Error(\'test error\');', - expect: /^Error: test error/ }, - // Common syntax error is treated as multiline command - { client: client_unix, send: 'function test_func() {', - expect: prompt_multiline }, - // You can recover with the .break command - { client: client_unix, send: '.break', - expect: prompt_unix }, - // But passing the same string to eval() should throw - { client: client_unix, send: 'eval("function test_func() {")', - expect: /^SyntaxError: / }, - // Can handle multiline template literals - { client: client_unix, send: '`io.js', - expect: prompt_multiline }, - // Special REPL commands still available - { client: client_unix, send: '.break', - expect: prompt_unix }, - // Template expressions can cross lines - { client: client_unix, send: '`io.js ${"1.0"', - expect: prompt_multiline }, - { client: client_unix, send: '+ ".2"}`', - expect: `'io.js 1.0.2'\n${prompt_unix}` }, - // Dot prefix in multiline commands aren't treated as commands - { client: client_unix, send: '("a"', - expect: prompt_multiline }, - { client: client_unix, send: '.charAt(0))', - expect: `'a'\n${prompt_unix}` }, - // Floating point numbers are not interpreted as REPL commands. - { client: client_unix, send: '.1234', - expect: '0.1234' }, - // Floating point expressions are not interpreted as REPL commands - { client: client_unix, send: '.1+.1', - expect: '0.2' }, - // Can parse valid JSON - { client: client_unix, send: 'JSON.parse(\'{"valid": "json"}\');', - expect: '{ valid: \'json\' }' }, - // invalid input to JSON.parse error is special case of syntax error, - // should throw - { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');', - expect: /^SyntaxError: / }, - // end of input to JSON.parse error is special case of syntax error, - // should throw - { client: client_unix, send: 'JSON.parse(\'066\');', - expect: /^SyntaxError: / }, - // should throw - { client: client_unix, send: 'JSON.parse(\'{\');', - expect: /^SyntaxError: / }, - // invalid RegExps are a special case of syntax error, - // should throw - { client: client_unix, send: '/(/;', - expect: /^SyntaxError: / }, - // invalid RegExp modifiers are a special case of syntax error, - // should throw (GH-4012) - { client: client_unix, send: 'new RegExp("foo", "wrong modifier");', - expect: /^SyntaxError: / }, - // strict mode syntax errors should be caught (GH-5178) - { client: client_unix, - send: '(function() { "use strict"; return 0755; })()', - expect: /\bSyntaxError: / }, - { - client: client_unix, - send: '(function(a, a, b) { "use strict"; return a + b + c; })()', - expect: /\bSyntaxError: / - }, - { - client: client_unix, - send: '(function() { "use strict"; with (this) {} })()', - expect: /\bSyntaxError: / - }, - { - client: client_unix, - send: '(function() { "use strict"; var x; delete x; })()', - expect: /\bSyntaxError: / - }, - { client: client_unix, - send: '(function() { "use strict"; eval = 17; })()', - expect: /\bSyntaxError: / }, - { - client: client_unix, - send: '(function() { "use strict"; if (true) function f() { } })()', - expect: /\bSyntaxError: / - }, - // Named functions can be used: - { client: client_unix, send: 'function blah() { return 1; }', - expect: prompt_unix }, - { client: client_unix, send: 'blah()', - expect: `1\n${prompt_unix}` }, - // Functions should not evaluate twice (#2773) - { client: client_unix, send: 'var I = [1,2,3,function() {}]; I.pop()', - expect: '[Function]' }, - // Multiline object - { client: client_unix, send: '{ a: ', - expect: prompt_multiline }, - { client: client_unix, send: '1 }', - expect: '{ a: 1 }' }, - // Multiline anonymous function with comment - { client: client_unix, send: '(function() {', - expect: prompt_multiline }, - { client: client_unix, send: '// blah', - expect: prompt_multiline }, - { client: client_unix, send: 'return 1;', - expect: prompt_multiline }, - { client: client_unix, send: '})()', - expect: '1' }, - // Multiline function call - { client: client_unix, send: 'function f(){}; f(f(1,', - expect: prompt_multiline }, - { client: client_unix, send: '2)', - expect: prompt_multiline }, - { client: client_unix, send: ')', - expect: `undefined\n${prompt_unix}` }, - // npm prompt error message - { client: client_unix, send: 'npm install foobar', - expect: expect_npm }, - { client: client_unix, send: '(function() {\n\nreturn 1;\n})()', - expect: '1' }, - { client: client_unix, send: '{\n\na: 1\n}', - expect: '{ a: 1 }' }, - { client: client_unix, send: 'url.format("http://google.com")', - expect: 'http://google.com/' }, - { client: client_unix, send: 'var path = 42; path', - expect: '42' }, - // this makes sure that we don't print `undefined` when we actually print - // the error message - { client: client_unix, send: '.invalid_repl_command', - expect: `Invalid REPL keyword\n${prompt_unix}` }, - // this makes sure that we don't crash when we use an inherited property as - // a REPL command - { client: client_unix, send: '.toString', - expect: `Invalid REPL keyword\n${prompt_unix}` }, - // fail when we are not inside a String and a line continuation is used - { client: client_unix, send: '[] \\', - expect: /\bSyntaxError: / }, - // do not fail when a String is created with line continuation - { client: client_unix, send: '\'the\\\nfourth\\\neye\'', - expect: `${prompt_multiline}${prompt_multiline}'thefourtheye'\n${ - prompt_unix}` }, - // Don't fail when a partial String is created and line continuation is used - // with whitespace characters at the end of the string. We are to ignore it. - // This test is to make sure that we properly remove the whitespace - // characters at the end of line, unlike the buggy `trimWhitespace` function - { client: client_unix, send: ' \t .break \t ', - expect: prompt_unix }, - // multiline strings preserve whitespace characters in them - { client: client_unix, send: '\'the \\\n fourth\t\t\\\n eye \'', - expect: `${prompt_multiline}${ - prompt_multiline}'the fourth\\t\\t eye '\n${prompt_unix}` }, - // more than one multiline strings also should preserve whitespace chars - { client: client_unix, send: '\'the \\\n fourth\' + \'\t\t\\\n eye \'', - expect: `${prompt_multiline}${ - prompt_multiline}'the fourth\\t\\t eye '\n${prompt_unix}` }, - // using REPL commands within a string literal should still work - { client: client_unix, send: '\'\\\n.break', - expect: prompt_unix }, - // using REPL command "help" within a string literal should still work - { client: client_unix, send: '\'thefourth\\\n.help\neye\'', - expect: /'thefourtheye'/ }, - // empty lines in the REPL should be allowed - { client: client_unix, send: '\n\r\n\r\n', - expect: prompt_unix + prompt_unix + prompt_unix }, - // empty lines in the string literals should not affect the string - { client: client_unix, send: '\'the\\\n\\\nfourtheye\'\n', - expect: `${prompt_multiline}${ - prompt_multiline}'thefourtheye'\n${prompt_unix}` }, - // Regression test for https://github.com/nodejs/node/issues/597 - { client: client_unix, - send: '/(.)(.)(.)(.)(.)(.)(.)(.)(.)/.test(\'123456789\')\n', - expect: `true\n${prompt_unix}` }, - // the following test's result depends on the RegEx's match from the above - { client: client_unix, - send: 'RegExp.$1\nRegExp.$2\nRegExp.$3\nRegExp.$4\nRegExp.$5\n' + - 'RegExp.$6\nRegExp.$7\nRegExp.$8\nRegExp.$9\n', - expect: ['\'1\'\n', '\'2\'\n', '\'3\'\n', '\'4\'\n', '\'5\'\n', '\'6\'\n', - '\'7\'\n', '\'8\'\n', '\'9\'\n'].join(`${prompt_unix}`) }, - // regression tests for https://github.com/nodejs/node/issues/2749 - { client: client_unix, send: 'function x() {\nreturn \'\\n\';\n }', - expect: `${prompt_multiline}${prompt_multiline}undefined\n${ - prompt_unix}` }, - { client: client_unix, send: 'function x() {\nreturn \'\\\\\';\n }', - expect: `${prompt_multiline}${prompt_multiline}undefined\n${ - prompt_unix}` }, - // regression tests for https://github.com/nodejs/node/issues/3421 - { client: client_unix, send: 'function x() {\n//\'\n }', - expect: `${prompt_multiline}${prompt_multiline}undefined\n${ - prompt_unix}` }, - { client: client_unix, send: 'function x() {\n//"\n }', - expect: `${prompt_multiline}${prompt_multiline}undefined\n${ - prompt_unix}` }, - { client: client_unix, send: 'function x() {//\'\n }', - expect: `${prompt_multiline}undefined\n${prompt_unix}` }, - { client: client_unix, send: 'function x() {//"\n }', - expect: `${prompt_multiline}undefined\n${prompt_unix}` }, - { client: client_unix, send: 'function x() {\nvar i = "\'";\n }', - expect: `${prompt_multiline}${prompt_multiline}undefined\n${ - prompt_unix}` }, - { client: client_unix, send: 'function x(/*optional*/) {}', - expect: `undefined\n${prompt_unix}` }, - { client: client_unix, send: 'function x(/* // 5 */) {}', - expect: `undefined\n${prompt_unix}` }, - { client: client_unix, send: '// /* 5 */', - expect: `undefined\n${prompt_unix}` }, - { client: client_unix, send: '"//"', - expect: `'//'\n${prompt_unix}` }, - { client: client_unix, send: '"data /*with*/ comment"', - expect: `'data /*with*/ comment'\n${prompt_unix}` }, - { client: client_unix, send: 'function x(/*fn\'s optional params*/) {}', - expect: `undefined\n${prompt_unix}` }, - { client: client_unix, send: '/* \'\n"\n\'"\'\n*/', - expect: `undefined\n${prompt_unix}` }, - // REPL should get a normal require() function, not one that allows - // access to internal modules without the --expose_internals flag. - { client: client_unix, send: 'require("internal/repl")', - expect: /^Error: Cannot find module 'internal\/repl'/ }, - // REPL should handle quotes within regexp literal in multiline mode - { client: client_unix, - send: "function x(s) {\nreturn s.replace(/'/,'');\n}", - expect: `${prompt_multiline}${prompt_multiline}` + - `undefined\n${prompt_unix}` }, - { client: client_unix, - send: "function x(s) {\nreturn s.replace(/'/,'');\n}", - expect: `${prompt_multiline}${prompt_multiline}` + - `undefined\n${prompt_unix}` }, - { client: client_unix, - send: 'function x(s) {\nreturn s.replace(/"/,"");\n}', - expect: `${prompt_multiline}${prompt_multiline}` + - `undefined\n${prompt_unix}` }, - { client: client_unix, - send: 'function x(s) {\nreturn s.replace(/.*/,"");\n}', - expect: `${prompt_multiline}${prompt_multiline}` + - `undefined\n${prompt_unix}` }, - { client: client_unix, send: '{ var x = 4; }', - expect: `undefined\n${prompt_unix}` }, - // Illegal token is not recoverable outside string literal, RegExp literal, - // or block comment. https://github.com/nodejs/node/issues/3611 - { client: client_unix, send: 'a = 3.5e', - expect: /\bSyntaxError: Invalid or unexpected token/ }, - // Mitigate https://github.com/nodejs/node/issues/548 - { client: client_unix, send: 'function name(){ return "node"; };name()', - expect: `'node'\n${prompt_unix}` }, - { client: client_unix, send: 'function name(){ return "nodejs"; };name()', - expect: `'nodejs'\n${prompt_unix}` }, - // Avoid emitting repl:line-number for SyntaxError - { client: client_unix, send: 'a = 3.5e', - expect: /^(?!repl)/ }, - // Avoid emitting stack trace - { client: client_unix, send: 'a = 3.5e', - expect: /^(?!\s+at\s)/m }, - - // https://github.com/nodejs/node/issues/9850 - { client: client_unix, send: 'function* foo() {}; foo().next();', - expect: '{ value: undefined, done: true }' }, - - { client: client_unix, send: 'function *foo() {}; foo().next();', - expect: '{ value: undefined, done: true }' }, - - { client: client_unix, send: 'function*foo() {}; foo().next();', - expect: '{ value: undefined, done: true }' }, - - { client: client_unix, send: 'function * foo() {}; foo().next()', - expect: '{ value: undefined, done: true }' }, - - // https://github.com/nodejs/node/issues/9300 - { - client: client_unix, send: 'function foo() {\nvar bar = 1 / 1; // "/"\n}', - expect: `${prompt_multiline}${prompt_multiline}undefined\n${prompt_unix}` - }, - - { - client: client_unix, send: '(function() {\nreturn /foo/ / /bar/;\n}())', - expect: `${prompt_multiline}${prompt_multiline}NaN\n${prompt_unix}` - }, - - { - client: client_unix, send: '(function() {\nif (false) {} /bar"/;\n}())', - expect: `${prompt_multiline}${prompt_multiline}undefined\n${prompt_unix}` - }, - - // Newline within template string maintains whitespace. - { client: client_unix, send: '`foo \n`', - expect: `${prompt_multiline}'foo \\n'\n${prompt_unix}` }, - // Whitespace is not evaluated. - { client: client_unix, send: ' \t \n', - expect: prompt_unix }, - // Do not parse `...[]` as a REPL keyword - { client: client_unix, send: '...[]\n', - expect: `${prompt_multiline}` }, - // bring back the repl to prompt - { client: client_unix, send: '.break', - expect: `${prompt_unix}` } - ]); + const remainder = socket.read(); + assert(remainder === '' || remainder === null); } -function tcp_test() { - server_tcp = net.createServer(function(socket) { - assert.strictEqual(server_tcp, socket.server); +const unixTests = [ + { + send: '', + expect: '' + }, + { + send: 'message', + expect: `'${message}'` + }, + { + send: 'invoke_me(987)', + expect: '\'invoked 987\'' + }, + { + send: 'a = 12345', + expect: '12345' + }, + { + send: '{a:1}', + expect: '{ a: 1 }' + } +]; + +const strictModeTests = [ + { + send: 'ref = 1', + expect: /^ReferenceError:\s/ + } +]; + +const errorTests = [ + // Uncaught error throws and prints out + { + send: 'throw new Error(\'test error\');', + expect: /^Error: test error/ + }, + // Common syntax error is treated as multiline command + { + send: 'function test_func() {', + expect: '... ' + }, + // You can recover with the .break command + { + send: '.break', + expect: '' + }, + // But passing the same string to eval() should throw + { + send: 'eval("function test_func() {")', + expect: /^SyntaxError: / + }, + // Can handle multiline template literals + { + send: '`io.js', + expect: '... ' + }, + // Special REPL commands still available + { + send: '.break', + expect: '' + }, + // Template expressions can cross lines + { + send: '`io.js ${"1.0"', + expect: '... ' + }, + { + send: '+ ".2"}`', + expect: '\'io.js 1.0.2\'' + }, + // Dot prefix in multiline commands aren't treated as commands + { + send: '("a"', + expect: '... ' + }, + { + send: '.charAt(0))', + expect: '\'a\'' + }, + // Floating point numbers are not interpreted as REPL commands. + { + send: '.1234', + expect: '0.1234' + }, + // Floating point expressions are not interpreted as REPL commands + { + send: '.1+.1', + expect: '0.2' + }, + // Can parse valid JSON + { + send: 'JSON.parse(\'{"valid": "json"}\');', + expect: '{ valid: \'json\' }' + }, + // invalid input to JSON.parse error is special case of syntax error, + // should throw + { + send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');', + expect: [/^SyntaxError: /, ''] + }, + // end of input to JSON.parse error is special case of syntax error, + // should throw + { + send: 'JSON.parse(\'066\');', + expect: [/^SyntaxError: /, ''] + }, + // should throw + { + send: 'JSON.parse(\'{\');', + expect: [/^SyntaxError: /, ''] + }, + // invalid RegExps are a special case of syntax error, + // should throw + { + send: '/(/;', + expect: /^SyntaxError: / + }, + // invalid RegExp modifiers are a special case of syntax error, + // should throw (GH-4012) + { + send: 'new RegExp("foo", "wrong modifier");', + expect: [/^SyntaxError: /, ''] + }, + // strict mode syntax errors should be caught (GH-5178) + { + send: '(function() { "use strict"; return 0755; })()', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + { + send: '(function(a, a, b) { "use strict"; return a + b + c; })()', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + { + send: '(function() { "use strict"; with (this) {} })()', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + { + send: '(function() { "use strict"; var x; delete x; })()', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + { + send: '(function() { "use strict"; eval = 17; })()', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + { + send: '(function() { "use strict"; if (true) function f() { } })()', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + // Named functions can be used: + { + send: 'function blah() { return 1; }', + expect: 'undefined' + }, + { + send: 'blah()', + expect: '1' + }, + // Functions should not evaluate twice (#2773) + { + send: 'var I = [1,2,3,function() {}]; I.pop()', + expect: '[Function]' + }, + // Multiline object + { + send: '{ a: ', + expect: '... ' + }, + { + send: '1 }', + expect: '{ a: 1 }' + }, + // Multiline anonymous function with comment + { + send: '(function() {', + expect: '... ' + }, + { + send: '// blah', + expect: '... ' + }, + { + send: 'return 1;', + expect: '... ' + }, + { + send: '})()', + expect: '1' + }, + // Multiline function call + { + send: 'function f(){}; f(f(1,', + expect: '... ' + }, + { + send: '2)', + expect: '... ' + }, + { + send: ')', + expect: 'undefined' + }, + // npm prompt error message + { + send: 'npm install foobar', + expect: [ + 'npm should be run outside of the node repl, in your normal shell.', + '(Press Control-D to exit.)' + ] + }, + { + send: '(function() {\n\nreturn 1;\n})()', + expect: '... ... ... 1' + }, + { + send: '{\n\na: 1\n}', + expect: '... ... ... { a: 1 }' + }, + { + send: 'url.format("http://google.com")', + expect: '\'http://google.com/\'' + }, + { + send: 'var path = 42; path', + expect: '42' + }, + // this makes sure that we don't print `undefined` when we actually print + // the error message + { + send: '.invalid_repl_command', + expect: 'Invalid REPL keyword' + }, + // this makes sure that we don't crash when we use an inherited property as + // a REPL command + { + send: '.toString', + expect: 'Invalid REPL keyword' + }, + // fail when we are not inside a String and a line continuation is used + { + send: '[] \\', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + // do not fail when a String is created with line continuation + { + send: '\'the\\\nfourth\\\neye\'', + expect: ['... ... \'thefourtheye\''] + }, + // Don't fail when a partial String is created and line continuation is used + // with whitespace characters at the end of the string. We are to ignore it. + // This test is to make sure that we properly remove the whitespace + // characters at the end of line, unlike the buggy `trimWhitespace` function + { + send: ' \t .break \t ', + expect: '' + }, + // multiline strings preserve whitespace characters in them + { + send: '\'the \\\n fourth\t\t\\\n eye \'', + expect: '... ... \'the fourth\\t\\t eye \'' + }, + // more than one multiline strings also should preserve whitespace chars + { + send: '\'the \\\n fourth\' + \'\t\t\\\n eye \'', + expect: '... ... \'the fourth\\t\\t eye \'' + }, + // using REPL commands within a string literal should still work + { + send: '\'\\\n.break', + expect: '... ' + prompt_unix + }, + // using REPL command "help" within a string literal should still work + { + send: '\'thefourth\\\n.help\neye\'', + expect: [ + /\.break/, + /\.clear/, + /\.editor/, + /\.exit/, + /\.help/, + /\.load/, + /\.save/, + /'thefourtheye'/ + ] + }, + // empty lines in the REPL should be allowed + { + send: '\n\r\n\r\n', + expect: '' + }, + // empty lines in the string literals should not affect the string + { + send: '\'the\\\n\\\nfourtheye\'\n', + expect: '... ... \'thefourtheye\'' + }, + // Regression test for https://github.com/nodejs/node/issues/597 + { + send: '/(.)(.)(.)(.)(.)(.)(.)(.)(.)/.test(\'123456789\')\n', + expect: 'true' + }, + // the following test's result depends on the RegExp's match from the above + { + send: 'RegExp.$1\nRegExp.$2\nRegExp.$3\nRegExp.$4\nRegExp.$5\n' + + 'RegExp.$6\nRegExp.$7\nRegExp.$8\nRegExp.$9\n', + expect: ['\'1\'', '\'2\'', '\'3\'', '\'4\'', '\'5\'', '\'6\'', + '\'7\'', '\'8\'', '\'9\''] + }, + // regression tests for https://github.com/nodejs/node/issues/2749 + { + send: 'function x() {\nreturn \'\\n\';\n }', + expect: '... ... undefined' + }, + { + send: 'function x() {\nreturn \'\\\\\';\n }', + expect: '... ... undefined' + }, + // regression tests for https://github.com/nodejs/node/issues/3421 + { + send: 'function x() {\n//\'\n }', + expect: '... ... undefined' + }, + { + send: 'function x() {\n//"\n }', + expect: '... ... undefined' + }, + { + send: 'function x() {//\'\n }', + expect: '... undefined' + }, + { + send: 'function x() {//"\n }', + expect: '... undefined' + }, + { + send: 'function x() {\nvar i = "\'";\n }', + expect: '... ... undefined' + }, + { + send: 'function x(/*optional*/) {}', + expect: 'undefined' + }, + { + send: 'function x(/* // 5 */) {}', + expect: 'undefined' + }, + { + send: '// /* 5 */', + expect: 'undefined' + }, + { + send: '"//"', + expect: '\'//\'' + }, + { + send: '"data /*with*/ comment"', + expect: '\'data /*with*/ comment\'' + }, + { + send: 'function x(/*fn\'s optional params*/) {}', + expect: 'undefined' + }, + { + send: '/* \'\n"\n\'"\'\n*/', + expect: '... ... ... undefined' + }, + // REPL should get a normal require() function, not one that allows + // access to internal modules without the --expose_internals flag. + { + send: 'require("internal/repl")', + expect: [ + /^Error: Cannot find module 'internal\/repl'/, + /^ at .*/, + /^ at .*/, + /^ at .*/, + /^ at .*/ + ] + }, + // REPL should handle quotes within regexp literal in multiline mode + { + send: "function x(s) {\nreturn s.replace(/'/,'');\n}", + expect: '... ... undefined' + }, + { + send: "function x(s) {\nreturn s.replace(/'/,'');\n}", + expect: '... ... undefined' + }, + { + send: 'function x(s) {\nreturn s.replace(/"/,"");\n}', + expect: '... ... undefined' + }, + { + send: 'function x(s) {\nreturn s.replace(/.*/,"");\n}', + expect: '... ... undefined' + }, + { + send: '{ var x = 4; }', + expect: 'undefined' + }, + // Illegal token is not recoverable outside string literal, RegExp literal, + // or block comment. https://github.com/nodejs/node/issues/3611 + { + send: 'a = 3.5e', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + // Mitigate https://github.com/nodejs/node/issues/548 + { + send: 'function name(){ return "node"; };name()', + expect: '\'node\'' + }, + { + send: 'function name(){ return "nodejs"; };name()', + expect: '\'nodejs\'' + }, + // Avoid emitting repl:line-number for SyntaxError + { + send: 'a = 3.5e', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + // Avoid emitting stack trace + { + send: 'a = 3.5e', + expect: [ + kSource, + kArrow, + '', + /^SyntaxError: /, + '' + ] + }, + + // https://github.com/nodejs/node/issues/9850 + { + send: 'function* foo() {}; foo().next();', + expect: '{ value: undefined, done: true }' + }, + + { + send: 'function *foo() {}; foo().next();', + expect: '{ value: undefined, done: true }' + }, + + { + send: 'function*foo() {}; foo().next();', + expect: '{ value: undefined, done: true }' + }, + + { + send: 'function * foo() {}; foo().next()', + expect: '{ value: undefined, done: true }' + }, + + // https://github.com/nodejs/node/issues/9300 + { + send: 'function foo() {\nvar bar = 1 / 1; // "/"\n}', + expect: '... ... undefined' + }, + + { + send: '(function() {\nreturn /foo/ / /bar/;\n}())', + expect: '... ... NaN' + }, + + { + send: '(function() {\nif (false) {} /bar"/;\n}())', + expect: '... ... undefined' + }, + + // Newline within template string maintains whitespace. + { + send: '`foo \n`', + expect: '... \'foo \\n\'' + }, + // Whitespace is not evaluated. + { + send: ' \t \n', + expect: 'undefined' + }, + // Do not parse `...[]` as a REPL keyword + { + send: '...[]\n', + expect: '... ... ' + }, + // bring back the repl to prompt + { + send: '.break', + expect: '' + } +]; + +const tcpTests = [ + { + send: '', + expect: '' + }, + { + send: 'invoke_me(333)', + expect: '\'invoked 333\'' + }, + { + send: 'a += 1', + expect: '12346' + }, + { + send: `require(${JSON.stringify(moduleFilename)}).number`, + expect: '42' + } +]; + +(async function() { + { + const [ socket, replServer ] = await startUnixRepl(); - socket.on('end', function() { + await runReplTests(socket, prompt_unix, unixTests); + await runReplTests(socket, prompt_unix, errorTests); + replServer.replMode = repl.REPL_MODE_STRICT; + await runReplTests(socket, prompt_unix, strictModeTests); + + socket.end(); + } + { + const [ socket ] = await startTCPRepl(); + + await runReplTests(socket, prompt_tcp, tcpTests); + + socket.end(); + } +})(); + +function startTCPRepl() { + let resolveSocket, resolveReplServer; + + const server = net.createServer(common.mustCall((socket) => { + assert.strictEqual(server, socket.server); + + socket.on('end', common.mustCall(() => { socket.end(); - }); + })); - repl.start(prompt_tcp, socket); - }); + resolveReplServer(repl.start(prompt_tcp, socket)); + })); - server_tcp.listen(0, function() { - let read_buffer = ''; - - client_tcp = net.createConnection(this.address().port); - - client_tcp.on('connect', function() { - assert.strictEqual(true, client_tcp.readable); - assert.strictEqual(true, client_tcp.writable); - - send_expect([ - { client: client_tcp, send: '', - expect: prompt_tcp }, - { client: client_tcp, send: 'invoke_me(333)', - expect: (`'invoked 333'\n${prompt_tcp}`) }, - { client: client_tcp, send: 'a += 1', - expect: (`12346\n${prompt_tcp}`) }, - { client: client_tcp, - send: `require(${JSON.stringify(moduleFilename)}).number`, - expect: (`42\n${prompt_tcp}`) } - ]); - }); + server.listen(0, common.mustCall(() => { + const client = net.createConnection(server.address().port); - client_tcp.on('data', function(data) { - read_buffer += data.toString('ascii', 0, data.length); - console.error(`TCP data: ${JSON.stringify(read_buffer)}, expecting ${ - JSON.stringify(client_tcp.expect)}`); - if (read_buffer.includes(prompt_tcp)) { - assert.strictEqual(client_tcp.expect, read_buffer); - console.error('match'); - read_buffer = ''; - if (client_tcp.list && client_tcp.list.length > 0) { - send_expect(client_tcp.list); - } else { - console.error('End of TCP test.\n'); - clean_up(); - } - } else { - console.error('didn\'t see prompt yet, buffering'); - } - }); + client.setEncoding('utf8'); - client_tcp.on('error', function(e) { - throw e; - }); + client.on('connect', common.mustCall(() => { + assert.strictEqual(true, client.readable); + assert.strictEqual(true, client.writable); - client_tcp.on('close', function() { - server_tcp.close(); - }); - }); + resolveSocket(client); + })); + + client.on('close', common.mustCall(() => { + server.close(); + })); + })); + return Promise.all([ + new Promise((resolve) => resolveSocket = resolve), + new Promise((resolve) => resolveReplServer = resolve) + ]); } -function unix_test() { - server_unix = net.createServer(function(socket) { - assert.strictEqual(server_unix, socket.server); +function startUnixRepl() { + let resolveSocket, resolveReplServer; + + const server = net.createServer(common.mustCall((socket) => { + assert.strictEqual(server, socket.server); - socket.on('end', function() { + socket.on('end', common.mustCall(() => { socket.end(); - }); + })); - replServer = repl.start({ + const replServer = repl.start({ prompt: prompt_unix, input: socket, output: socket, useGlobal: true }); replServer.context.message = message; - }); + resolveReplServer(replServer); + })); - server_unix.on('listening', function() { - let read_buffer = ''; - - client_unix = net.createConnection(common.PIPE); - - client_unix.on('connect', function() { - assert.strictEqual(true, client_unix.readable); - assert.strictEqual(true, client_unix.writable); - - send_expect([ - { client: client_unix, send: '', - expect: prompt_unix }, - { client: client_unix, send: 'message', - expect: (`'${message}'\n${prompt_unix}`) }, - { client: client_unix, send: 'invoke_me(987)', - expect: (`'invoked 987'\n${prompt_unix}`) }, - { client: client_unix, send: 'a = 12345', - expect: (`12345\n${prompt_unix}`) }, - { client: client_unix, send: '{a:1}', - expect: (`{ a: 1 }\n${prompt_unix}`) } - ]); - }); + server.listen(common.PIPE, common.mustCall(() => { + const client = net.createConnection(common.PIPE); - client_unix.on('data', function(data) { - read_buffer += data.toString('ascii', 0, data.length); - console.error(`Unix data: ${JSON.stringify(read_buffer)}, expecting ${ - JSON.stringify(client_unix.expect)}`); - if (read_buffer.includes(prompt_unix)) { - assert.strictEqual(client_unix.expect, read_buffer); - console.error('match'); - read_buffer = ''; - if (client_unix.list && client_unix.list.length > 0) { - send_expect(client_unix.list); - } else { - console.error('End of Unix test, running Error test.\n'); - process.nextTick(error_test); - } - } else { - console.error('didn\'t see prompt yet, buffering.'); - } - }); + client.setEncoding('utf8'); - client_unix.on('error', function(e) { - throw e; - }); + client.on('connect', common.mustCall(() => { + assert.strictEqual(true, client.readable); + assert.strictEqual(true, client.writable); - client_unix.on('close', function() { - server_unix.close(); - }); - }); + resolveSocket(client); + })); + + client.on('close', common.mustCall(() => { + server.close(); + })); + })); - server_unix.listen(common.PIPE); + return Promise.all([ + new Promise((resolve) => resolveSocket = resolve), + new Promise((resolve) => resolveReplServer = resolve) + ]); } -unix_test(); +function event(ee, eventName) { + return new Promise((resolve) => { + ee.once(eventName, common.mustCall(resolve)); + }); +} diff --git a/test/parallel/test-require-symlink.js b/test/parallel/test-require-symlink.js index 7dde2a1a974087..60962156f2f286 100644 --- a/test/parallel/test-require-symlink.js +++ b/test/parallel/test-require-symlink.js @@ -38,7 +38,8 @@ function copyDir(source, target) { copyDir(fixtureSource, tmpDirTarget); // Move to tmp dir and do everything with relative paths there so that the test -// doesn't incorrectly fail due to a symlink somewhere else in the absolte path. +// doesn't incorrectly fail due to a symlink somewhere else in the absolute +// path. process.chdir(common.tmpDir); const linkDir = path.join(dirName, diff --git a/test/parallel/test-stream-buffer-list.js b/test/parallel/test-stream-buffer-list.js index ddbff452de4be9..6ea359b458f61b 100644 --- a/test/parallel/test-stream-buffer-list.js +++ b/test/parallel/test-stream-buffer-list.js @@ -14,14 +14,19 @@ assert.strictEqual(emptyList.join(','), ''); assert.deepStrictEqual(emptyList.concat(0), Buffer.alloc(0)); +const buf = Buffer.from('foo'); + // Test buffer list with one element. const list = new BufferList(); -list.push('foo'); +list.push(buf); + +const copy = list.concat(3); -assert.strictEqual(list.concat(1), 'foo'); +assert.notStrictEqual(copy, buf); +assert.deepStrictEqual(copy, buf); assert.strictEqual(list.join(','), 'foo'); const shifted = list.shift(); -assert.strictEqual(shifted, 'foo'); +assert.strictEqual(shifted, buf); assert.deepStrictEqual(list, new BufferList()); diff --git a/test/parallel/test-stream-transform-final-sync.js b/test/parallel/test-stream-transform-final-sync.js index de3f0904885bb9..7dbd06d60c3625 100644 --- a/test/parallel/test-stream-transform-final-sync.js +++ b/test/parallel/test-stream-transform-final-sync.js @@ -7,7 +7,7 @@ let state = 0; /* What you do -var stream = new tream.Transform({ +var stream = new stream.Transform({ transform: function transformCallback(chunk, _, next) { // part 1 this.push(chunk); diff --git a/test/parallel/test-stream-transform-final.js b/test/parallel/test-stream-transform-final.js index 56566152e69165..22128b4d9a9f7b 100644 --- a/test/parallel/test-stream-transform-final.js +++ b/test/parallel/test-stream-transform-final.js @@ -7,7 +7,7 @@ let state = 0; /* What you do -var stream = new tream.Transform({ +var stream = new stream.Transform({ transform: function transformCallback(chunk, _, next) { // part 1 this.push(chunk); diff --git a/test/parallel/test-stream-unshift-read-race.js b/test/parallel/test-stream-unshift-read-race.js index cfa90c7f2bff1c..f2977b285f4db3 100644 --- a/test/parallel/test-stream-unshift-read-race.js +++ b/test/parallel/test-stream-unshift-read-race.js @@ -111,9 +111,9 @@ w.on('finish', common.mustCall(function() { // lacking that piece. assert.strictEqual(written[0], 'asdfasdfas'); let asdf = 'd'; - console.error('0: %s', written[0]); + console.error(`0: ${written[0]}`); for (let i = 1; i < written.length; i++) { - console.error('%s: %s', i.toString(32), written[i]); + console.error(`${i.toString(32)}: ${written[i]}`); assert.strictEqual(written[i].slice(0, 4), '1234'); for (let j = 4; j < written[i].length; j++) { const c = written[i].charAt(j); diff --git a/test/parallel/test-stream-writable-write-writev-finish.js b/test/parallel/test-stream-writable-write-writev-finish.js index c4aaa36606c5f4..c0bb60f925cfd8 100644 --- a/test/parallel/test-stream-writable-write-writev-finish.js +++ b/test/parallel/test-stream-writable-write-writev-finish.js @@ -154,3 +154,27 @@ const stream = require('stream'); }; rs.pipe(ws); } + +{ + const w = new stream.Writable(); + w._write = (chunk, encoding, cb) => { + process.nextTick(cb); + }; + w.on('error', common.mustCall()); + w.on('prefinish', () => { + w.write("shouldn't write in prefinish listener"); + }); + w.end(); +} + +{ + const w = new stream.Writable(); + w._write = (chunk, encoding, cb) => { + process.nextTick(cb); + }; + w.on('error', common.mustCall()); + w.on('finish', () => { + w.write("should't write in finish listener"); + }); + w.end(); +} diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 654b46254d8ee7..a0d344440ee7bb 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -45,7 +45,7 @@ function run() { } function test(decode, uncork, multi, next) { - console.log('# decode=%j uncork=%j multi=%j', decode, uncork, multi); + console.log(`# decode=${decode} uncork=${uncork} multi=${multi}`); let counter = 0; let expectCount = 0; function cnt(msg) { diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 92c35e35413240..2d44bb7f783b9d 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -43,9 +43,9 @@ r.on('readable', function() { console.error('>> readable'); let ret; do { - console.error(' > read(%d)', READSIZE); + console.error(` > read(${READSIZE})`); ret = r.read(READSIZE); - console.error(' < %j (%d remain)', ret && ret.length, rs.length); + console.error(` < ${ret && ret.length} (${rs.length} remain)`); } while (ret && ret.length === READSIZE); console.error('<< after read()', @@ -68,7 +68,7 @@ function push() { return r.push(null); } - console.error(' push #%d', pushes); + console.error(` push #${pushes}`); if (r.push(Buffer.allocUnsafe(PUSHSIZE))) setTimeout(push, 1); } diff --git a/test/parallel/test-stream2-push.js b/test/parallel/test-stream2-push.js index cc4dce4a871344..33645df8a5541c 100644 --- a/test/parallel/test-stream2-push.js +++ b/test/parallel/test-stream2-push.js @@ -89,7 +89,7 @@ const expectWritten = 'asdfgasdfgasdfgasdfg' ]; writer._write = function(chunk, encoding, cb) { - console.error('WRITE %s', chunk); + console.error(`WRITE ${chunk}`); written.push(chunk); process.nextTick(cb); }; diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index 4299f31ea12986..3c0b5eb4085e2e 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -51,7 +51,7 @@ test.on('readable', function() { const res = test.read(b); if (res) { bytesread += res.length; - console.error('br=%d len=%d', bytesread, len); + console.error(`br=${bytesread} len=${len}`); 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 fe9e8ce30dcf93..0c9cb5861d936e 100644 --- a/test/parallel/test-stream2-readable-wrap.js +++ b/test/parallel/test-stream2-readable-wrap.js @@ -29,8 +29,7 @@ const EE = require('events').EventEmitter; function runTest(highWaterMark, objectMode, produce) { const old = new EE(); - const r = new Readable({ highWaterMark: highWaterMark, - objectMode: objectMode }); + const r = new Readable({ highWaterMark, objectMode }); assert.strictEqual(r, r.wrap(old)); r.on('end', common.mustCall()); @@ -63,7 +62,7 @@ function runTest(highWaterMark, objectMode, produce) { } const w = new Writable({ highWaterMark: highWaterMark * 2, - objectMode: objectMode }); + objectMode }); const written = []; w._write = function(chunk, encoding, cb) { written.push(chunk); diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index d0859265428b81..13032e4c4b57a9 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -175,7 +175,7 @@ const Transform = require('_stream_transform'); } { - // Verify assymetric transform (expand) + // Verify asymmetric transform (expand) const pt = new Transform(); // emit each chunk 2 times. @@ -207,7 +207,7 @@ const Transform = require('_stream_transform'); } { - // Verify assymetric trasform (compress) + // Verify asymmetric transform (compress) const pt = new Transform(); // each output is the first char of 3 consecutive chunks, @@ -262,7 +262,7 @@ const Transform = require('_stream_transform'); // this tests for a stall when data is written to a full stream // that has empty transforms. { - // Verify compex transform behavior + // Verify complex transform behavior let count = 0; let saved = null; const pt = new Transform({ highWaterMark: 3 }); diff --git a/test/parallel/test-stream3-cork-uncork.js b/test/parallel/test-stream3-cork-uncork.js index aa9df481cd720e..91d27c916cef45 100644 --- a/test/parallel/test-stream3-cork-uncork.js +++ b/test/parallel/test-stream3-cork-uncork.js @@ -65,7 +65,7 @@ writeChunks(inputChunks, () => { // trigger writing out the buffer w.uncork(); - // buffered bytes shoud be seen in current tick + // buffered bytes should be seen in current tick assert.strictEqual(seenChunks.length, 4); // did the chunks match diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js index f7bfadaf9d124c..4e1b71d74df10b 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -60,7 +60,7 @@ function read100() { } function readn(n, then) { - console.error('read %d', n); + console.error(`read ${n}`); expectEndingData -= n; (function read() { const c = r.read(n); diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index 35d773da26f4d4..2a04159ce9db3c 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -82,7 +82,7 @@ assert.strictEqual(c_bin.toString('latin1'), ucs2_control); assert.strictEqual(c_ucs.toString('latin1'), ucs2_control); -// now let's test BASE64 and HEX ecoding/decoding +// now let's test BASE64 and HEX encoding/decoding const RADIOS = 2; const PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; const PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 0078d2dae352d5..9e5a4228ba92ed 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -71,7 +71,8 @@ const check_unref = setInterval(() => { setInterval(() => timeout.unref(), SHORT_TIME); } -// Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. +// Should not assert on args.Holder()->InternalFieldCount() > 0. +// See https://github.com/nodejs/node-v0.x-archive/issues/4261. { const t = setInterval(() => {}, 1); process.nextTick(t.unref.bind({})); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index 9329dea9fb194d..478402772eb0df 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -68,8 +68,8 @@ sPWhSOb9VQjMXekI4Y2l8fqAVTS2Fn6+8jkVKxXBywSVCw== function test(cert, key, cb) { const server = tls.createServer({ - cert: cert, - key: key + cert, + key }).listen(0, function() { server.close(cb); }); diff --git a/test/parallel/test-tls-client-getephemeralkeyinfo.js b/test/parallel/test-tls-client-getephemeralkeyinfo.js index fcb93aa3b6fe0b..ed628204025b16 100644 --- a/test/parallel/test-tls-client-getephemeralkeyinfo.js +++ b/test/parallel/test-tls-client-getephemeralkeyinfo.js @@ -6,7 +6,6 @@ const fixtures = require('../common/fixtures'); const assert = require('assert'); const tls = require('tls'); -const fs = require('fs'); const key = fixtures.readKey('agent2-key.pem'); const cert = fixtures.readKey('agent2-cert.pem'); @@ -15,9 +14,7 @@ let ntests = 0; let nsuccess = 0; function loadDHParam(n) { - let path = fixtures.fixturesDir; - if (n !== 'error') path += '/keys'; - return fs.readFileSync(`${path}/dh${n}.pem`); + return fixtures.readKey(`dh${n}.pem`); } const cipherlist = { diff --git a/test/parallel/test-tls-client-mindhsize.js b/test/parallel/test-tls-client-mindhsize.js index cc613ae6b708ac..3017d30e6c5e9e 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -14,10 +14,7 @@ let nsuccess = 0; let nerror = 0; function loadDHParam(n) { - const params = [`dh${n}.pem`]; - if (n !== 'error') - params.unshift('keys'); - return fixtures.readSync(params); + return fixtures.readKey(`dh${n}.pem`); } function test(size, err, next) { diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index 0f28bdcd0f454f..83b9142dea9266 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -142,6 +142,6 @@ runTest(0); process.on('exit', function() { - console.log('successful tests: %d', successfulTests); + console.log(`successful tests: ${successfulTests}`); assert.strictEqual(successfulTests, testCases.length); }); diff --git a/test/parallel/test-tls-cnnic-whitelist.js b/test/parallel/test-tls-cnnic-whitelist.js index c269835428e52d..d118567089d44d 100644 --- a/test/parallel/test-tls-cnnic-whitelist.js +++ b/test/parallel/test-tls-cnnic-whitelist.js @@ -31,7 +31,7 @@ const testCases = [ errorCode: 'CERT_REVOKED' }, // Test 1: for the fix of node#2061 - // agent6-cert.pem is signed by intermidate cert of ca3. + // agent6-cert.pem is signed by intermediate cert of ca3. // The server has a cert chain of agent6->ca3->ca1(root) but // tls.connect should be failed with an error of // UNABLE_TO_GET_ISSUER_CERT_LOCALLY since the root CA of ca1 is not diff --git a/test/parallel/test-tls-connect-no-host.js b/test/parallel/test-tls-connect-no-host.js index 7a0806e66748f3..d685ba90ccdd84 100644 --- a/test/parallel/test-tls-connect-no-host.js +++ b/test/parallel/test-tls-connect-no-host.js @@ -16,8 +16,8 @@ const key = fixtures.readSync('test_key.pem'); // tls.connect(options) with no options.host should accept a cert with // CN:'localhost' tls.createServer({ - key: key, - cert: cert + key, + cert }).listen(0, function() { const socket = tls.connect({ port: this.address().port, diff --git a/test/parallel/test-tls-ecdh-disable.js b/test/parallel/test-tls-ecdh-disable.js index af97fbfcdd0492..7726a0655edd02 100644 --- a/test/parallel/test-tls-ecdh-disable.js +++ b/test/parallel/test-tls-ecdh-disable.js @@ -19,7 +19,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -// Test that the usage of eliptic curves are not permitted if disabled during +// Test that the usage of elliptic curves are not permitted if disabled during // server initialization. 'use strict'; diff --git a/test/parallel/test-tls-ecdh-multiple.js b/test/parallel/test-tls-ecdh-multiple.js index 3ea17a99e98532..dee75f972167a5 100644 --- a/test/parallel/test-tls-ecdh-multiple.js +++ b/test/parallel/test-tls-ecdh-multiple.js @@ -74,7 +74,7 @@ process.on('exit', function() { unsupportedCurves.push('brainpoolP256r1'); unsupportedCurves.forEach((ecdhCurve) => { - assert.throws(() => tls.createServer({ ecdhCurve: ecdhCurve }), + assert.throws(() => tls.createServer({ ecdhCurve }), /Error: Failed to set ECDH curve/); }); }); diff --git a/test/parallel/test-tls-env-extra-ca.js b/test/parallel/test-tls-env-extra-ca.js index 80d9cc9ec3ecef..c4f647a735d72f 100644 --- a/test/parallel/test-tls-env-extra-ca.js +++ b/test/parallel/test-tls-env-extra-ca.js @@ -38,7 +38,7 @@ const server = tls.createServer(options, common.mustCall(function(s) { NODE_EXTRA_CA_CERTS: fixtures.path('keys', 'ca1-cert.pem') }); - fork(__filename, { env: env }).on('exit', common.mustCall(function(status) { + fork(__filename, { env }).on('exit', common.mustCall(function(status) { assert.strictEqual(status, 0, 'client did not succeed in connecting'); })); })); diff --git a/test/parallel/test-tls-friendly-error-message.js b/test/parallel/test-tls-friendly-error-message.js index 2989837b19f38e..b52918be27ac9b 100644 --- a/test/parallel/test-tls-friendly-error-message.js +++ b/test/parallel/test-tls-friendly-error-message.js @@ -31,7 +31,7 @@ const tls = require('tls'); const key = fixtures.readKey('agent1-key.pem'); const cert = fixtures.readKey('agent1-cert.pem'); -tls.createServer({ key: key, cert: cert }, common.mustCall(function(conn) { +tls.createServer({ key, cert }, common.mustCall(function(conn) { conn.end(); this.close(); })).listen(0, common.mustCall(function() { diff --git a/test/parallel/test-tls-no-sslv3.js b/test/parallel/test-tls-no-sslv3.js index aa37fc2e3b64fa..92f85128625261 100644 --- a/test/parallel/test-tls-no-sslv3.js +++ b/test/parallel/test-tls-no-sslv3.js @@ -13,7 +13,7 @@ const fixtures = require('../common/fixtures'); const cert = fixtures.readSync('test_cert.pem'); const key = fixtures.readSync('test_key.pem'); -const server = tls.createServer({ cert: cert, key: key }, common.mustNotCall()); +const server = tls.createServer({ cert, key }, common.mustNotCall()); const errors = []; let stderr = ''; diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index d316a517af8e58..8e9bafda5394d6 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -35,10 +35,7 @@ let gotRequest = false; const key = fixtures.readKey('agent1-key.pem'); const cert = fixtures.readKey('agent1-cert.pem'); -const options = { - key: key, - cert: cert -}; +const options = { key, cert }; const server = https.createServer(options, function(req, res) { console.log('SERVER: got request'); diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js index 1572bd2288d421..75c2832f7332f8 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -57,7 +57,7 @@ server.listen(0, function() { function send() { console.error('sending'); const ret = client.write(Buffer.allocUnsafe(bufSize)); - console.error('write => %j', ret); + console.error(`write => ${ret}`); if (false !== ret) { console.error('write again'); sent += bufSize; diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js index 9dceb4c4e4dd88..056eebda0e69e7 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -42,7 +42,7 @@ function log(a) { const server = net.createServer(common.mustCall(function(socket) { log(`connection fd=${socket.fd}`); - const sslcontext = tls.createSecureContext({ key: key, cert: cert }); + const sslcontext = tls.createSecureContext({ key, cert }); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); const pair = tls.createSecurePair(sslcontext, true); diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js index 69378aab94e4b3..eeea8b030da719 100644 --- a/test/parallel/test-tls-server-verify.js +++ b/test/parallel/test-tls-server-verify.js @@ -259,7 +259,7 @@ function runTest(port, testIndex) { const tcase = testCases[testIndex]; if (!tcase) return; - console.error(`${prefix}Running '%s'`, tcase.title); + console.error(`${prefix}Running '${tcase.title}'`); const cas = tcase.CAs.map(loadPEM); @@ -286,8 +286,8 @@ function runTest(port, testIndex) { let renegotiated = false; const server = tls.Server(serverOptions, function handleConnection(c) { c.on('error', function(e) { - // child.kill() leads ECONNRESET errro in the TLS connection of - // openssl s_client via spawn(). A Test result is already + // child.kill() leads ECONNRESET error in the TLS connection of + // openssl s_client via spawn(). A test result is already // checked by the data of client.stdout before child.kill() so // these tls errors can be ignored. }); @@ -327,7 +327,7 @@ function runTest(port, testIndex) { } else { server.close(); successfulTests++; - runTest(port, nextTest++); + runTest(0, nextTest++); } } @@ -345,7 +345,7 @@ function runTest(port, testIndex) { if (clientsCompleted === tcase.clients.length) { server.close(); successfulTests++; - runTest(port, nextTest++); + runTest(0, nextTest++); } }); } @@ -356,7 +356,6 @@ function runTest(port, testIndex) { let nextTest = 0; runTest(0, nextTest++); -runTest(0, nextTest++); process.on('exit', function() { diff --git a/test/parallel/test-tls-session-cache.js b/test/parallel/test-tls-session-cache.js index 73ccdd8396cecd..2bbf3b642da1b8 100644 --- a/test/parallel/test-tls-session-cache.js +++ b/test/parallel/test-tls-session-cache.js @@ -71,10 +71,7 @@ function doTest(testOptions, callback) { // Emulate asynchronous store setTimeout(function() { assert.ok(!session); - session = { - id: id, - data: data - }; + session = { id, data }; cb(); }, 1000); }); diff --git a/test/parallel/test-tls-set-encoding.js b/test/parallel/test-tls-set-encoding.js index cf621420774973..b3aa52a22a73f3 100644 --- a/test/parallel/test-tls-set-encoding.js +++ b/test/parallel/test-tls-set-encoding.js @@ -63,7 +63,7 @@ server.listen(0, function() { client.on('close', function() { // readyState is deprecated but we want to make // sure this isn't triggering an assert in lib/net.js - // See issue #1069. + // See https://github.com/nodejs/node-v0.x-archive/issues/1069. assert.strictEqual('closed', client.readyState); // Confirming the buffer string is encoded in ASCII diff --git a/test/parallel/test-tls-starttls-server.js b/test/parallel/test-tls-starttls-server.js index ea55d397317c87..d9a1c02fc87c0f 100644 --- a/test/parallel/test-tls-starttls-server.js +++ b/test/parallel/test-tls-starttls-server.js @@ -21,10 +21,7 @@ const server = net.createServer(common.mustCall((s) => { isServer: true, server: server, - secureContext: tls.createSecureContext({ - key: key, - cert: cert - }), + secureContext: tls.createSecureContext({ key, cert }), SNICallback: common.mustCall((hostname, callback) => { assert.strictEqual(hostname, 'test.test'); diff --git a/test/parallel/test-tls-zero-clear-in.js b/test/parallel/test-tls-zero-clear-in.js index 006e756826c7d1..b2a07960d4138c 100644 --- a/test/parallel/test-tls-zero-clear-in.js +++ b/test/parallel/test-tls-zero-clear-in.js @@ -32,8 +32,8 @@ const cert = fixtures.readSync('test_cert.pem'); const key = fixtures.readSync('test_key.pem'); const server = tls.createServer({ - cert: cert, - key: key + cert, + key }, function(c) { // Nop setTimeout(function() { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index d64888306719db..5520e8bc2ed4fb 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -149,7 +149,7 @@ for (const showHidden of [true, false]) { // Now do the same checks but from a different context for (const showHidden of [true, false]) { const ab = vm.runInNewContext('new ArrayBuffer(4)'); - const dv = vm.runInNewContext('new DataView(ab, 1, 2)', { ab: ab }); + const dv = vm.runInNewContext('new DataView(ab, 1, 2)', { ab }); assert.strictEqual( util.inspect(ab, showHidden), 'ArrayBuffer { byteLength: 4 }' diff --git a/test/parallel/test-vm-access-process-env.js b/test/parallel/test-vm-access-process-env.js index f3b997748e498b..a2f3cb5741de45 100644 --- a/test/parallel/test-vm-access-process-env.js +++ b/test/parallel/test-vm-access-process-env.js @@ -29,7 +29,7 @@ const assert = require('assert'); const vm = require('vm'); assert.doesNotThrow(function() { - const context = vm.createContext({ process: process }); + const context = vm.createContext({ process }); const result = vm.runInContext('process.env["PATH"]', context); assert.notStrictEqual(undefined, result); }); diff --git a/test/parallel/test-vm-basic.js b/test/parallel/test-vm-basic.js index 864c3553663a2c..3a74cb38d26402 100644 --- a/test/parallel/test-vm-basic.js +++ b/test/parallel/test-vm-basic.js @@ -20,7 +20,7 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const vm = require('vm'); @@ -69,3 +69,56 @@ assert.strictEqual(result, 'undefined'); const sandbox3 = {}; const context2 = vm.createContext(sandbox3); assert.strictEqual(sandbox3, context2); + +// Test 6: invalid arguments +common.expectsError(() => { + vm.createContext({}, null); +}, { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "options" argument must be of type object. Received type null' +}); + +common.expectsError(() => { + vm.createContext({}, 'string'); +}, { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "options" argument must be of type object. Received type string' +}); + +common.expectsError(() => { + vm.createContext({}, { name: null }); +}, { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "options.name" property must be of type string. ' + + 'Received type null' +}); + +common.expectsError(() => { + vm.createContext({}, { origin: null }); +}, { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "options.origin" property must be of type string. ' + + 'Received type null' +}); + +common.expectsError(() => { + vm.runInNewContext('', {}, { contextName: null }); +}, { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "options.contextName" property must be of type string. ' + + 'Received type null' +}); + +common.expectsError(() => { + vm.runInNewContext('', {}, { contextOrigin: null }); +}, { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "options.contextOrigin" property must be of type string. ' + + 'Received type null' +}); diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js index 8ef89cba107876..368a40cbd42c03 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -81,7 +81,7 @@ const contextifiedSandboxErrorMsg = script = vm.createScript('const assert = require(\'assert\'); assert.throws(' + 'function() { throw "hello world"; }, /hello/);', 'some.js'); -script.runInNewContext({ require: require }); +script.runInNewContext({ require }); // Issue GH-7529 script = vm.createScript('delete b'); diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js index 875ecef22a7851..0f6f19b13ebcf1 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -24,7 +24,7 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -const o = vm.createContext({ console: console }); +const o = vm.createContext({ console }); // Function declaration and expression should both be copied to the // sandboxed context. diff --git a/test/parallel/test-vm-global-define-property.js b/test/parallel/test-vm-global-define-property.js index 00bd21052884d8..0b9a4dfb88cb02 100644 --- a/test/parallel/test-vm-global-define-property.js +++ b/test/parallel/test-vm-global-define-property.js @@ -36,7 +36,7 @@ const code = 'f;\n'; const x = {}; -const o = vm.createContext({ console: console, x: x }); +const o = vm.createContext({ console, x }); const res = vm.runInContext(code, o, 'test'); diff --git a/test/parallel/test-vm-harmony-symbols.js b/test/parallel/test-vm-harmony-symbols.js index 901380f4d63a57..593602507046ef 100644 --- a/test/parallel/test-vm-harmony-symbols.js +++ b/test/parallel/test-vm-harmony-symbols.js @@ -31,7 +31,7 @@ assert.strictEqual(typeof sandbox.Symbol, 'function'); assert.notStrictEqual(sandbox.Symbol, Symbol); // Unless we copy the Symbol constructor explicitly, of course. -sandbox = { Symbol: Symbol }; +sandbox = { Symbol }; vm.runInNewContext('this.Symbol = Symbol', sandbox); assert.strictEqual(typeof sandbox.Symbol, 'function'); assert.strictEqual(sandbox.Symbol, Symbol); diff --git a/test/parallel/test-vm-new-script-new-context.js b/test/parallel/test-vm-new-script-new-context.js index 7015499879959f..dfb43e42d1cc82 100644 --- a/test/parallel/test-vm-new-script-new-context.js +++ b/test/parallel/test-vm-new-script-new-context.js @@ -91,7 +91,7 @@ const Script = require('vm').Script; { const script = new Script('f.a = 2'); const f = { a: 1 }; - script.runInNewContext({ f: f }); + script.runInNewContext({ f }); assert.strictEqual(f.a, 2); assert.throws(() => { diff --git a/test/parallel/test-vm-proxies.js b/test/parallel/test-vm-proxies.js index 266b212fb827b8..405f730577be30 100644 --- a/test/parallel/test-vm-proxies.js +++ b/test/parallel/test-vm-proxies.js @@ -12,7 +12,7 @@ assert.strictEqual(typeof sandbox.Proxy, 'function'); assert.notStrictEqual(sandbox.Proxy, Proxy); // Unless we copy the Proxy object explicitly, of course. -sandbox = { Proxy: Proxy }; +sandbox = { Proxy }; vm.runInNewContext('this.Proxy = Proxy', sandbox); assert.strictEqual(typeof sandbox.Proxy, 'function'); assert.strictEqual(sandbox.Proxy, Proxy); diff --git a/test/parallel/test-vm-run-in-new-context.js b/test/parallel/test-vm-run-in-new-context.js index 082682f8438c5d..1edb061ea6a871 100644 --- a/test/parallel/test-vm-run-in-new-context.js +++ b/test/parallel/test-vm-run-in-new-context.js @@ -65,7 +65,7 @@ assert.strictEqual(global.foo, 100); // Modify an object by reference const f = { a: 1 }; -vm.runInNewContext('f.a = 2', { f: f }); +vm.runInNewContext('f.a = 2', { f }); assert.strictEqual(f.a, 2); // Use function in context without referencing context diff --git a/test/parallel/test-vm-timeout.js b/test/parallel/test-vm-timeout.js index a53883bef7c0b2..51239ffed58efd 100644 --- a/test/parallel/test-vm-timeout.js +++ b/test/parallel/test-vm-timeout.js @@ -47,7 +47,7 @@ assert.throws(function() { const context = { log: console.log, runInVM: function(timeout) { - vm.runInNewContext('while(true) {}', context, { timeout: timeout }); + vm.runInNewContext('while(true) {}', context, { timeout }); } }; vm.runInNewContext('runInVM(10)', context, { timeout: 10000 }); @@ -58,7 +58,7 @@ assert.throws(function() { assert.throws(function() { const context = { runInVM: function(timeout) { - vm.runInNewContext('while(true) {}', context, { timeout: timeout }); + vm.runInNewContext('while(true) {}', context, { timeout }); } }; vm.runInNewContext('runInVM(10000)', context, { timeout: 100 }); @@ -69,9 +69,7 @@ assert.throws(function() { assert.throws(function() { const context = { runInVM: function(timeout) { - vm.runInNewContext('throw new Error(\'foobar\')', context, { - timeout: timeout - }); + vm.runInNewContext('throw new Error(\'foobar\')', context, { timeout }); } }; vm.runInNewContext('runInVM(10000)', context, { timeout: 100000 }); diff --git a/test/parallel/test-whatwg-encoding-textdecoder.js b/test/parallel/test-whatwg-encoding-textdecoder.js index c4f919289adf2f..5f9499930a07a0 100644 --- a/test/parallel/test-whatwg-encoding-textdecoder.js +++ b/test/parallel/test-whatwg-encoding-textdecoder.js @@ -91,18 +91,35 @@ if (common.hasIntl) { } { - const fn = TextDecoder.prototype[inspect]; - assert.doesNotThrow(() => { - fn.call(new TextDecoder(), Infinity, {}); - }); - - [{}, [], true, 1, '', new TextEncoder()].forEach((i) => { - common.expectsError(() => fn.call(i, Infinity, {}), - { - code: 'ERR_INVALID_THIS', - type: TypeError, - message: 'Value of "this" must be of type TextDecoder' - }); + const inspectFn = TextDecoder.prototype[inspect]; + const decodeFn = TextDecoder.prototype.decode; + const { + encoding: { get: encodingGetter }, + fatal: { get: fatalGetter }, + ignoreBOM: { get: ignoreBOMGetter }, + } = Object.getOwnPropertyDescriptors(TextDecoder.prototype); + + const instance = new TextDecoder(); + + const expectedError = { + code: 'ERR_INVALID_THIS', + type: TypeError, + message: 'Value of "this" must be of type TextDecoder' + }; + + assert.doesNotThrow(() => inspectFn.call(instance, Infinity, {})); + assert.doesNotThrow(() => decodeFn.call(instance)); + assert.doesNotThrow(() => encodingGetter.call(instance)); + assert.doesNotThrow(() => fatalGetter.call(instance)); + assert.doesNotThrow(() => ignoreBOMGetter.call(instance)); + + const invalidThisArgs = [{}, [], true, 1, '', new TextEncoder()]; + invalidThisArgs.forEach((i) => { + common.expectsError(() => inspectFn.call(i, Infinity, {}), expectedError); + common.expectsError(() => decodeFn.call(i), expectedError); + common.expectsError(() => encodingGetter.call(i), expectedError); + common.expectsError(() => fatalGetter.call(i), expectedError); + common.expectsError(() => ignoreBOMGetter.call(i), expectedError); }); } diff --git a/test/parallel/test-whatwg-encoding-textencoder.js b/test/parallel/test-whatwg-encoding-textencoder.js index fba5445c81941c..4096a02432e900 100644 --- a/test/parallel/test-whatwg-encoding-textencoder.js +++ b/test/parallel/test-whatwg-encoding-textencoder.js @@ -35,17 +35,27 @@ assert(TextEncoder); } { - const fn = TextEncoder.prototype[inspect]; - assert.doesNotThrow(() => { - fn.call(new TextEncoder(), Infinity, {}); - }); - - [{}, [], true, 1, '', new TextDecoder()].forEach((i) => { - common.expectsError(() => fn.call(i, Infinity, {}), - { - code: 'ERR_INVALID_THIS', - type: TypeError, - message: 'Value of "this" must be of type TextEncoder' - }); + const inspectFn = TextEncoder.prototype[inspect]; + const encodeFn = TextEncoder.prototype.encode; + const encodingGetter = + Object.getOwnPropertyDescriptor(TextEncoder.prototype, 'encoding').get; + + const instance = new TextEncoder(); + + const expectedError = { + code: 'ERR_INVALID_THIS', + type: TypeError, + message: 'Value of "this" must be of type TextEncoder' + }; + + assert.doesNotThrow(() => inspectFn.call(instance, Infinity, {})); + assert.doesNotThrow(() => encodeFn.call(instance)); + assert.doesNotThrow(() => encodingGetter.call(instance)); + + const invalidThisArgs = [{}, [], true, 1, '', new TextDecoder()]; + invalidThisArgs.forEach((i) => { + common.expectsError(() => inspectFn.call(i, Infinity, {}), expectedError); + common.expectsError(() => encodeFn.call(i), expectedError); + common.expectsError(() => encodingGetter.call(i), expectedError); }); } diff --git a/test/parallel/test-wrap-js-stream-exceptions.js b/test/parallel/test-wrap-js-stream-exceptions.js new file mode 100644 index 00000000000000..57ecd70189d106 --- /dev/null +++ b/test/parallel/test-wrap-js-stream-exceptions.js @@ -0,0 +1,19 @@ +// Flags: --expose-internals +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const JSStreamWrap = require('internal/wrap_js_stream'); +const { Duplex } = require('stream'); + +process.once('uncaughtException', common.mustCall((err) => { + assert.strictEqual(err.message, 'exception!'); +})); + +const socket = new JSStreamWrap(new Duplex({ + read: common.mustCall(), + write: common.mustCall((buffer, data, cb) => { + throw new Error('exception!'); + }) +})); + +assert.throws(() => socket.end('foo'), /Error: write EPROTO/); diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index b2201fca4c9aae..a36e8166ab726a 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -157,7 +157,7 @@ assert.doesNotThrow(() => { }, 'windowsBits set to 8 should follow legacy zlib behavior'); { - const node = fs.createReadStream(process.execPath); + const node = fs.createReadStream(fixtures.path('person.jpg')); const raw = []; const reinflated = []; node.on('data', (chunk) => raw.push(chunk)); @@ -191,10 +191,7 @@ testKeys.forEach(common.mustCall((file) => { zlibPairs.forEach(common.mustCall((pair) => { const Def = pair[0]; const Inf = pair[1]; - const opts = { level: level, - windowBits: windowBits, - memLevel: memLevel, - strategy: strategy }; + const opts = { level, windowBits, memLevel, strategy }; const def = new Def(opts); const inf = new Inf(opts); diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index e6e88f53e1f623..92b5cb64ec67e3 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -79,7 +79,7 @@ exec('thisisnotavalidcommand', function(err, stdout, stderr) { const sleeperStart = new Date(); exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { const diff = (new Date()) - sleeperStart; - console.log('\'sleep 3\' with timeout 50 took %d ms', diff); + console.log(`'sleep 3' with timeout 50 took ${diff} ms`); assert.ok(diff < 500); assert.ok(err); assert.ok(err.killed); @@ -94,7 +94,7 @@ const killMeTwice = exec(SLEEP3_COMMAND, { timeout: 1000 }, killMeTwiceCallback); process.nextTick(function() { - console.log('kill pid %d', killMeTwice.pid); + console.log(`kill pid ${killMeTwice.pid}`); // make sure there is no race condition in starting the process // the PID SHOULD exist directly following the exec() call. assert.strictEqual('number', typeof killMeTwice._handle.pid); @@ -113,7 +113,7 @@ function killMeTwiceCallback(err, stdout, stderr) { assert.strictEqual(stderr, ''); // the timeout should still be in effect - console.log('\'sleep 3\' was already killed. Took %d ms', diff); + console.log(`'sleep 3' was already killed. Took ${diff} ms`); assert.ok(diff < 1500); } diff --git a/test/pummel/test-net-write-callbacks.js b/test/pummel/test-net-write-callbacks.js index 10aff090583cea..a4a6096d633165 100644 --- a/test/pummel/test-net-write-callbacks.js +++ b/test/pummel/test-net-write-callbacks.js @@ -29,7 +29,7 @@ const N = 500000; const server = net.Server(function(socket) { socket.on('data', function(d) { - console.error('got %d bytes', d.length); + console.error(`got ${d.length} bytes`); }); socket.on('end', function() { diff --git a/test/pummel/test-regress-GH-892.js b/test/pummel/test-regress-GH-892.js index 05e27628b14388..4021a53736421b 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -102,11 +102,11 @@ const server = https.Server(serverOptions, function(req, res) { }); server.listen(common.PORT, function() { - console.log('expecting %d bytes', bytesExpected); + console.log(`expecting ${bytesExpected} bytes`); makeRequest(); }); process.on('exit', function() { - console.error('got %d bytes', uploadCount); + console.error(`got ${uploadCount} bytes`); assert.strictEqual(uploadCount, bytesExpected); }); diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index dbcd33d53466dc..8e56e11fabd5ae 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -117,7 +117,7 @@ function test(keyfn, certfn, check, next) { function startClient() { const s = new net.Stream(); - const sslcontext = tls.createSecureContext({ key: key, cert: cert }); + const sslcontext = tls.createSecureContext({ key, cert }); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); const pair = tls.createSecurePair(sslcontext, false); diff --git a/test/pummel/test-tls-throttle.js b/test/pummel/test-tls-throttle.js index 3e18c4cff43a75..af588dfa91fb94 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -72,8 +72,8 @@ server.listen(common.PORT, function() { function displayCounts() { - console.log('body.length: %d', body.length); - console.log(' recvCount: %d', recvCount); + console.log(`body.length: ${body.length}`); + console.log(` recvCount: ${recvCount}`); } diff --git a/test/pummel/test-vm-memleak.js b/test/pummel/test-vm-memleak.js index 601781fec2a5d6..cb96512d384556 100644 --- a/test/pummel/test-vm-memleak.js +++ b/test/pummel/test-vm-memleak.js @@ -57,6 +57,6 @@ function testContextLeak() { } process.on('exit', function() { - console.error('max mem: %dmb', Math.round(maxMem / (1024 * 1024))); + console.error(`max mem: ${Math.round(maxMem / (1024 * 1024))}mb`); assert.ok(maxMem < 64 * 1024 * 1024); }); diff --git a/test/sequential/test-async-wrap-getasyncid.js b/test/sequential/test-async-wrap-getasyncid.js index 5a6d4e0758adc1..fa8e310540103e 100644 --- a/test/sequential/test-async-wrap-getasyncid.js +++ b/test/sequential/test-async-wrap-getasyncid.js @@ -146,6 +146,8 @@ if (common.hasCrypto) { // eslint-disable-line crypto-check } { + common.refreshTmpDir(); + const server = net.createServer(common.mustCall((socket) => { server.close(); })).listen(common.PIPE, common.mustCall(() => { diff --git a/test/sequential/test-benchmark-http.js b/test/sequential/test-benchmark-http.js index edb61a0601c70b..e23a4a1753b00d 100644 --- a/test/sequential/test-benchmark-http.js +++ b/test/sequential/test-benchmark-http.js @@ -25,4 +25,7 @@ runBenchmark('http', 'res=normal', 'type=asc' ], - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); + { + NODEJS_BENCHMARK_ZERO_ALLOWED: 1, + duration: 0 + }); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 8b360f4f21e095..da80e80bce01d2 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -93,7 +93,8 @@ ret = execFileSync(process.execPath, args, { encoding: 'utf8' }); assert.strictEqual(ret, `${msg}\n`); -// Verify that the cwd option works - GH #7824 +// Verify that the cwd option works. +// See https://github.com/nodejs/node-v0.x-archive/issues/7824. { const cwd = common.rootDir; const cmd = common.isWindows ? 'echo %cd%' : 'pwd'; @@ -102,7 +103,8 @@ assert.strictEqual(ret, `${msg}\n`); assert.strictEqual(response.toString().trim(), cwd); } -// Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 +// Verify that stderr is not accessed when stdio = 'ignore'. +// See https://github.com/nodejs/node-v0.x-archive/issues/7966. { assert.throws(function() { execSync('exit -1', { stdio: 'ignore' }); diff --git a/test/sequential/test-inspector-async-hook-setup-at-signal.js b/test/sequential/test-inspector-async-hook-setup-at-signal.js index 96e8b28a7a250e..5ff7dec9473ac2 100644 --- a/test/sequential/test-inspector-async-hook-setup-at-signal.js +++ b/test/sequential/test-inspector-async-hook-setup-at-signal.js @@ -17,7 +17,7 @@ function waitUntilDebugged() { // call stack depth is 0. We need a chance to call // Debugger.setAsyncCallStackDepth *before* activating the actual timer for // async stack traces to work. Directly using a debugger statement would be - // too brittle, and using a longer timeout would unnecesarily slow down the + // too brittle, and using a longer timeout would unnecessarily slow down the // test on most machines. Triggering a debugger break through an interval is // a faster and more reliable way. process._rawDebug('Signal received, waiting for debugger setup'); diff --git a/test/sequential/test-inspector-contexts.js b/test/sequential/test-inspector-contexts.js index 6ad02edeb1a59c..fb59e9dee14892 100644 --- a/test/sequential/test-inspector-contexts.js +++ b/test/sequential/test-inspector-contexts.js @@ -27,9 +27,10 @@ async function testContextCreatedAndDestroyed() { const { name, origin, auxData } = contextCreated.params.context; if (common.isSunOS || common.isWindows) { // uv_get_process_title() is unimplemented on Solaris-likes, it returns - // an empy string. On the Windows CI buildbots it returns "Administrator: - // Windows PowerShell[42]" because of a GetConsoleTitle() quirk. Not much - // we can do about either, just verify that it contains the PID. + // an empty string. On the Windows CI buildbots it returns + // "Administrator: Windows PowerShell[42]" because of a GetConsoleTitle() + // quirk. Not much we can do about either, just verify that it contains + // the PID. strictEqual(name.includes(`[${process.pid}]`), true); } else { strictEqual(`${process.argv0}[${process.pid}]`, name); diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index 47916d352d729a..6f40e8d8008ec3 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -222,7 +222,8 @@ try { } { - // #1357 Loading JSON files with require() + // Loading JSON files with require() + // See https://github.com/nodejs/node-v0.x-archive/issues/1357. const json = require('../fixtures/packages/main/package.json'); assert.deepStrictEqual(json, { name: 'package-name', @@ -337,7 +338,8 @@ process.on('exit', function() { }); -// #1440 Loading files with a byte order marker. +// Loading files with a byte order marker. +// See https://github.com/nodejs/node-v0.x-archive/issues/1440. assert.strictEqual(require('../fixtures/utf8-bom.js'), 42); assert.strictEqual(require('../fixtures/utf8-bom.json'), 42); diff --git a/test/sequential/test-readline-interface.js b/test/sequential/test-readline-interface.js index 5c1a0e08a13ae7..488dd8338da761 100644 --- a/test/sequential/test-readline-interface.js +++ b/test/sequential/test-readline-interface.js @@ -24,7 +24,7 @@ const common = require('../common'); // These test cases are in `sequential` rather than the analogous test file in -// `parallel` because they become unrelaible under load. The unreliability under +// `parallel` because they become unreliable under load. The unreliability under // load was determined empirically when the test cases were in `parallel` by // running: // tools/test.py -j 96 --repeat 192 test/parallel/test-readline-interface.js diff --git a/test/sequential/test-require-cache-without-stat.js b/test/sequential/test-require-cache-without-stat.js index 41d2980dcd8021..3064bf3f3dda12 100644 --- a/test/sequential/test-require-cache-without-stat.js +++ b/test/sequential/test-require-cache-without-stat.js @@ -52,7 +52,7 @@ require('../fixtures/a.js'); require('./../fixtures/a.js'); require('http'); -console.log('counterBefore = %d', counter); +console.log(`counterBefore = ${counter}`); const counterBefore = counter; // Now load the module a bunch of times with equivalent paths. @@ -68,7 +68,7 @@ for (let i = 0; i < 100; i++) { require('http'); } -console.log('counterAfter = %d', counter); +console.log(`counterAfter = ${counter}`); const counterAfter = counter; assert.strictEqual(counterBefore, counterAfter); diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js index 6eff05513fbec7..40995394ac5530 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -38,7 +38,7 @@ function parent() { child.on('close', function() { assert.strictEqual(err, `child ${c}\nfoo\nbar\nbaz\n`); - console.log('ok %d child #%d', ++i, c); + console.log(`ok ${++i} child #${c}`); if (i === children.length) console.log(`1..${i}`); }); diff --git a/tools/doc/node_modules/js-yaml/index.js b/tools/doc/node_modules/js-yaml/index.js index 620bc293ffe032..476b3a0d487c4a 100644 --- a/tools/doc/node_modules/js-yaml/index.js +++ b/tools/doc/node_modules/js-yaml/index.js @@ -7,6 +7,7 @@ const path = require('path'); const realJSYaml = path.resolve( __dirname, '..', '..', '..', // tools/ + 'node_modules', 'eslint', 'node_modules', 'js-yaml' diff --git a/tools/doc/type-parser.js b/tools/doc/type-parser.js index 3bcdd817a2f134..4ef0a6d04cb581 100644 --- a/tools/doc/type-parser.js +++ b/tools/doc/type-parser.js @@ -43,9 +43,14 @@ const typeMap = { 'http.Server': 'http.html#http_class_http_server', 'http.ServerResponse': 'http.html#http_class_http_serverresponse', + 'HTTP2 Headers Object': 'http2.html#http2_headers_object', + 'HTTP2 Settings Object': 'http2.html#http2_settings_object', + 'Handle': 'net.html#net_server_listen_handle_backlog_callback', 'net.Socket': 'net.html#net_class_net_socket', + 'ServerHttp2Stream': 'http2.html#http2_class_serverhttp2stream', + 'Stream': 'stream.html#stream_stream', 'stream.Readable': 'stream.html#stream_class_stream_readable', 'stream.Writable': 'stream.html#stream_class_stream_writable', diff --git a/tools/eslint/README.md b/tools/eslint/README.md deleted file mode 100644 index 5a23d6295deff4..00000000000000 --- a/tools/eslint/README.md +++ /dev/null @@ -1,254 +0,0 @@ -[![NPM version][npm-image]][npm-url] -[![build status][travis-image]][travis-url] -[![Build status][appveyor-image]][appveyor-url] -[![Test coverage][coveralls-image]][coveralls-url] -[![Downloads][downloads-image]][downloads-url] -[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=282608)](https://www.bountysource.com/trackers/282608-eslint?utm_source=282608&utm_medium=shield&utm_campaign=TRACKER_BADGE) -[![Join the chat at https://gitter.im/eslint/eslint](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/eslint/eslint?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_shield) - -# ESLint - -[Website](https://eslint.org) | -[Configuring](https://eslint.org/docs/user-guide/configuring) | -[Rules](https://eslint.org/docs/rules/) | -[Contributing](https://eslint.org/docs/developer-guide/contributing) | -[Reporting Bugs](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) | -[Code of Conduct](https://js.foundation/community/code-of-conduct) | -[Twitter](https://twitter.com/geteslint) | -[Mailing List](https://groups.google.com/group/eslint) | -[Chat Room](https://gitter.im/eslint/eslint) - -ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: - -* ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. -* ESLint uses an AST to evaluate patterns in code. -* ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. - -## Installation and Usage - -Prerequisites: [Node.js](https://nodejs.org/en/) (>=4.x), npm version 2+. - -There are two ways to install ESLint: globally and locally. - -### Local Installation and Usage - -If you want to include ESLint as part of your project's build system, we recommend installing it locally. You can do so using npm: - -``` -$ npm install eslint --save-dev -``` - -You should then setup a configuration file: - -``` -$ ./node_modules/.bin/eslint --init -``` - -After that, you can run ESLint on any file or directory like this: - -``` -$ ./node_modules/.bin/eslint yourfile.js -``` - -Any plugins or shareable configs that you use must also be installed locally to work with a locally-installed ESLint. - -### Global Installation and Usage - -If you want to make ESLint available to tools that run across all of your projects, we recommend installing ESLint globally. You can do so using npm: - -``` -$ npm install -g eslint -``` - -You should then setup a configuration file: - -``` -$ eslint --init -``` - -After that, you can run ESLint on any file or directory like this: - -``` -$ eslint yourfile.js -``` - -Any plugins or shareable configs that you use must also be installed globally to work with a globally-installed ESLint. - -**Note:** `eslint --init` is intended for setting up and configuring ESLint on a per-project basis and will perform a local installation of ESLint and its plugins in the directory in which it is run. If you prefer using a global installation of ESLint, any plugins used in your configuration must also be installed globally. - -## Configuration - -After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: - -```json -{ - "rules": { - "semi": ["error", "always"], - "quotes": ["error", "double"] - } -} -``` - -The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: - -* `"off"` or `0` - turn the rule off -* `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) -* `"error"` or `2` - turn the rule on as an error (exit code will be 1) - -The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). - -## Sponsors - -* Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) - -## Team - -These folks keep the project moving and are resources for help. - -### Technical Steering Committee (TSC) - -* Nicholas C. Zakas ([@nzakas](https://github.com/nzakas)) -* Ilya Volodin ([@ilyavolodin](https://github.com/ilyavolodin)) -* Brandon Mills ([@btmills](https://github.com/btmills)) -* Gyandeep Singh ([@gyandeeps](https://github.com/gyandeeps)) -* Toru Nagashima ([@mysticatea](https://github.com/mysticatea)) -* Alberto Rodríguez ([@alberto](https://github.com/alberto)) -* Kai Cataldo ([@kaicataldo](https://github.com/kaicataldo)) -* Teddy Katz ([@not-an-aardvark](https://github.com/not-an-aardvark)) -* Kevin Partington ([@platinumazure](https://github.com/platinumazure)) - -### Development Team - -* Mathias Schreck ([@lo1tuma](https://github.com/lo1tuma)) -* Jamund Ferguson ([@xjamundx](https://github.com/xjamundx)) -* Ian VanSchooten ([@ianvs](https://github.com/ianvs)) -* Burak Yiğit Kaya ([@byk](https://github.com/byk)) -* Michael Ficarra ([@michaelficarra](https://github.com/michaelficarra)) -* Mark Pedrotti ([@pedrottimark](https://github.com/pedrottimark)) -* Oleg Gaidarenko ([@markelog](https://github.com/markelog)) -* Mike Sherov ([@mikesherov](https://github.com/mikesherov)) -* Henry Zhu ([@hzoo](https://github.com/hzoo)) -* Marat Dulin ([@mdevils](https://github.com/mdevils)) -* Alexej Yaroshevich ([@zxqfox](https://github.com/zxqfox)) -* Vitor Balocco ([@vitorbal](https://github.com/vitorbal)) -* James Henry ([@JamesHenry](https://github.com/JamesHenry)) -* Reyad Attiyat ([@soda0289](https://github.com/soda0289)) -* 薛定谔的猫 ([@Aladdin-ADD](https://github.com/Aladdin-ADD)) -* Victor Hom ([@VictorHom](https://github.com/VictorHom)) - -## Releases - -We have scheduled releases every two weeks on Friday or Saturday. - -## Code of Conduct - -ESLint adheres to the [JS Foundation Code of Conduct](https://js.foundation/community/code-of-conduct). - -## Filing Issues - -Before filing an issue, please be sure to read the guidelines for what you're reporting: - -* [Bug Report](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) -* [Propose a New Rule](https://eslint.org/docs/developer-guide/contributing/new-rules) -* [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) -* [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) - -## Semantic Versioning Policy - -ESLint follows [semantic versioning](http://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: - -* Patch release (intended to not break your lint build) - * A bug fix in a rule that results in ESLint reporting fewer errors. - * A bug fix to the CLI or core (including formatters). - * Improvements to documentation. - * Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. - * Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). -* Minor release (might break your lint build) - * A bug fix in a rule that results in ESLint reporting more errors. - * A new rule is created. - * A new option to an existing rule that does not result in ESLint reporting more errors by default. - * An existing rule is deprecated. - * A new CLI capability is created. - * New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). - * A new formatter is created. -* Major release (likely to break your lint build) - * `eslint:recommended` is updated. - * A new option to an existing rule that results in ESLint reporting more errors by default. - * An existing formatter is removed. - * Part of the public API is removed or changed in an incompatible way. - -According to our policy, any minor update may report more errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. - -## License - -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) - -## Frequently Asked Questions - -### How is ESLint different from JSHint? - -The most significant difference is that ESlint has pluggable linting rules. That means you can use the rules it comes with, or you can extend it with rules created by others or by yourself! - -### How does ESLint performance compare to JSHint? - -ESLint is slower than JSHint, usually 2-3x slower on a single file. This is because ESLint uses Espree to construct an AST before it can evaluate your code whereas JSHint evaluates your code as it's being parsed. The speed is also based on the number of rules you enable; the more rules you enable, the slower the process. - -Despite being slower, we believe that ESLint is fast enough to replace JSHint without causing significant pain. - -### I heard ESLint is going to replace JSCS? - -Yes. Since we are solving the same problems, ESLint and JSCS teams have decided to join forces and work together in the development of ESLint instead of competing with each other. You can read more about this in both [ESLint](https://eslint.org/blog/2016/04/welcoming-jscs-to-eslint) and [JSCS](https://medium.com/@markelog/jscs-end-of-the-line-bc9bf0b3fdb2#.u76sx334n) announcements. - -### So, should I stop using JSCS and start using ESLint? - -Maybe, depending on how much you need it. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life), but if it is working for you then there is no reason to move yet. We are still working to smooth the transition. You can see our progress [here](https://github.com/eslint/eslint/milestones/JSCS%20Compatibility). We’ll announce when all of the changes necessary to support JSCS users in ESLint are complete and will start encouraging JSCS users to switch to ESLint at that time. - -If you are having issues with JSCS, you can try to move to ESLint. We are focusing our time and energy on JSCS compatibility issues. - -### Is ESLint just linting or does it also check style? - -ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use it for both. - -### Why can't ESLint find my plugins? - -ESLint can be [globally or locally installed](#installation-and-usage). If you install ESLint globally, your plugins must also be installed globally; if you install ESLint locally, your plugins must also be installed locally. - -If you are trying to run globally, make sure your plugins are installed globally (use `npm ls -g`). - -If you are trying to run locally: - -* Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). -* Make sure you have run `npm install` and all your dependencies are installed. - -In all cases, make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDepencies` to see what peer dependencies `eslint-plugin-myplugin` has. - -### Does ESLint support JSX? - -Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. - -### What about ECMAScript 6 support? - -ESLint has full support for ECMAScript 6. By default, this support is off. You can enable ECMAScript 6 syntax and global variables through [configuration](https://eslint.org/docs/user-guide/configuring). - -### What about experimental features? - -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 (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](https://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? - -Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://gitter.im/eslint/eslint) - - -[npm-image]: https://img.shields.io/npm/v/eslint.svg?style=flat-square -[npm-url]: https://www.npmjs.com/package/eslint -[travis-image]: https://img.shields.io/travis/eslint/eslint/master.svg?style=flat-square -[travis-url]: https://travis-ci.org/eslint/eslint -[appveyor-image]: https://ci.appveyor.com/api/projects/status/iwxmiobcvbw3b0av/branch/master?svg=true -[appveyor-url]: https://ci.appveyor.com/project/nzakas/eslint/branch/master -[coveralls-image]: https://img.shields.io/coveralls/eslint/eslint/master.svg?style=flat-square -[coveralls-url]: https://coveralls.io/r/eslint/eslint?branch=master -[downloads-image]: https://img.shields.io/npm/dm/eslint.svg?style=flat-square -[downloads-url]: https://www.npmjs.com/package/eslint diff --git a/tools/eslint/lib/options.js b/tools/eslint/lib/options.js deleted file mode 100644 index ee1d3369cecf36..00000000000000 --- a/tools/eslint/lib/options.js +++ /dev/null @@ -1,235 +0,0 @@ -/** - * @fileoverview Options configuration for optionator. - * @author George Zahariev - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const optionator = require("optionator"); - -//------------------------------------------------------------------------------ -// Initialization and Public Interface -//------------------------------------------------------------------------------ - -// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)" -module.exports = optionator({ - prepend: "eslint [options] file.js [file.js] [dir]", - defaults: { - concatRepeatedArrays: true, - mergeRepeatedObjects: true - }, - options: [ - { - heading: "Basic configuration" - }, - { - option: "config", - alias: "c", - type: "path::String", - description: "Use configuration from this file or shareable config" - }, - { - option: "eslintrc", - type: "Boolean", - default: "true", - description: "Disable use of configuration from .eslintrc" - }, - { - option: "env", - type: "[String]", - description: "Specify environments" - }, - { - option: "ext", - type: "[String]", - default: ".js", - description: "Specify JavaScript file extensions" - }, - { - option: "global", - type: "[String]", - description: "Define global variables" - }, - { - option: "parser", - type: "String", - description: "Specify the parser to be used" - }, - { - option: "parser-options", - type: "Object", - description: "Specify parser options" - }, - { - heading: "Caching" - }, - { - option: "cache", - type: "Boolean", - default: "false", - description: "Only check changed files" - }, - { - option: "cache-file", - type: "path::String", - default: ".eslintcache", - description: "Path to the cache file. Deprecated: use --cache-location" - }, - { - option: "cache-location", - type: "path::String", - description: "Path to the cache file or directory" - }, - { - heading: "Specifying rules and plugins" - }, - { - option: "rulesdir", - type: "[path::String]", - description: "Use additional rules from this directory" - }, - { - option: "plugin", - type: "[String]", - description: "Specify plugins" - }, - { - option: "rule", - type: "Object", - description: "Specify rules" - }, - { - heading: "Ignoring files" - }, - { - option: "ignore-path", - type: "path::String", - description: "Specify path of ignore file" - }, - { - option: "ignore", - type: "Boolean", - default: "true", - description: "Disable use of ignore files and patterns" - }, - { - option: "ignore-pattern", - type: "[String]", - description: "Pattern of files to ignore (in addition to those in .eslintignore)", - concatRepeatedArrays: [true, { - oneValuePerFlag: true - }] - }, - { - heading: "Using stdin" - }, - { - option: "stdin", - type: "Boolean", - default: "false", - description: "Lint code provided on " - }, - { - option: "stdin-filename", - type: "String", - description: "Specify filename to process STDIN as" - }, - { - heading: "Handling warnings" - }, - { - option: "quiet", - type: "Boolean", - default: "false", - description: "Report errors only" - }, - { - option: "max-warnings", - type: "Int", - default: "-1", - description: "Number of warnings to trigger nonzero exit code" - }, - { - heading: "Output" - }, - { - option: "output-file", - alias: "o", - type: "path::String", - description: "Specify file to write report to" - }, - { - option: "format", - alias: "f", - type: "String", - default: "stylish", - description: "Use a specific output format" - }, - { - option: "color", - type: "Boolean", - alias: "no-color", - description: "Force enabling/disabling of color" - }, - { - heading: "Miscellaneous" - }, - { - option: "init", - type: "Boolean", - default: "false", - description: "Run config initialization wizard" - }, - { - option: "fix", - type: "Boolean", - default: false, - description: "Automatically fix problems" - }, - { - option: "fix-dry-run", - type: "Boolean", - default: false, - description: "Automatically fix problems without saving the changes to the file system" - }, - { - option: "debug", - type: "Boolean", - default: false, - description: "Output debugging information" - }, - { - option: "help", - alias: "h", - type: "Boolean", - description: "Show help" - }, - { - option: "version", - alias: "v", - type: "Boolean", - description: "Output the version number" - }, - { - option: "inline-config", - type: "Boolean", - default: "true", - description: "Prevent comments from changing config or rules" - }, - { - option: "report-unused-disable-directives", - type: "Boolean", - default: false, - description: "Adds reported errors for unused eslint-disable directives" - }, - { - option: "print-config", - type: "path::String", - description: "Print the configuration for the given file" - } - ] -}); diff --git a/tools/eslint/lib/rules/.eslintrc.yml b/tools/eslint/lib/rules/.eslintrc.yml deleted file mode 100644 index 2a8d907935b5f7..00000000000000 --- a/tools/eslint/lib/rules/.eslintrc.yml +++ /dev/null @@ -1,3 +0,0 @@ -rules: - rulesdir/no-invalid-meta: "error" - rulesdir/consistent-docs-description: "error" diff --git a/tools/eslint/lib/rules/lines-between-class-members.js b/tools/eslint/lib/rules/lines-between-class-members.js deleted file mode 100644 index 85e8c69358c9f3..00000000000000 --- a/tools/eslint/lib/rules/lines-between-class-members.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @fileoverview Rule to check empty newline between class members - * @author 薛定谔的猫 - */ -"use strict"; - -const astUtils = require("../ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - docs: { - description: "require or disallow an empty line between class members", - category: "Stylistic Issues", - recommended: false - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptAfterSingleLine: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const options = []; - - options[0] = context.options[0] || "always"; - options[1] = context.options[1] || { exceptAfterSingleLine: false }; - - const ALWAYS_MESSAGE = "Expected blank line between class members."; - const NEVER_MESSAGE = "Unexpected blank line between class members."; - - const sourceCode = context.getSourceCode(); - - /** - * Checks if there is padding between two tokens - * @param {Token} first The first token - * @param {Token} second The second token - * @returns {boolean} True if there is at least a line between the tokens - */ - function isPaddingBetweenTokens(first, second) { - return second.loc.start.line - first.loc.end.line >= 2; - } - - return { - ClassBody(node) { - const body = node.body; - - for (let i = 0; i < body.length - 1; i++) { - const curFirst = sourceCode.getFirstToken(body[i]); - const curLast = sourceCode.getLastToken(body[i]); - const comments = sourceCode.getCommentsBefore(body[i + 1]); - const nextFirst = comments.length ? comments[0] : sourceCode.getFirstToken(body[i + 1]); - const isPadded = isPaddingBetweenTokens(curLast, nextFirst); - const isMulti = !astUtils.isTokenOnSameLine(curFirst, curLast); - const skip = !isMulti && options[1].exceptAfterSingleLine; - - - if ((options[0] === "always" && !skip && !isPadded) || - (options[0] === "never" && isPadded)) { - context.report({ - node: body[i + 1], - message: isPadded ? NEVER_MESSAGE : ALWAYS_MESSAGE, - fix(fixer) { - return isPadded - ? fixer.replaceTextRange([curLast.range[1], nextFirst.range[0]], "\n") - : fixer.insertTextAfter(curLast, "\n"); - } - }); - } - } - } - }; - } -}; diff --git a/tools/eslint/lib/util/traverser.js b/tools/eslint/lib/util/traverser.js deleted file mode 100644 index fc070186b3b60e..00000000000000 --- a/tools/eslint/lib/util/traverser.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @fileoverview Wrapper around estraverse - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const estraverse = require("estraverse"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const KEY_BLACKLIST = new Set([ - "parent", - "leadingComments", - "trailingComments" -]); - -/** - * Wrapper around an estraverse controller that ensures the correct keys - * are visited. - * @constructor - */ -class Traverser extends estraverse.Controller { - traverse(node, visitor) { - visitor.fallback = Traverser.getKeys; - return super.traverse(node, visitor); - } - - /** - * Calculates the keys to use for traversal. - * @param {ASTNode} node The node to read keys from. - * @returns {string[]} An array of keys to visit on the node. - * @private - */ - static getKeys(node) { - return Object.keys(node).filter(key => !KEY_BLACKLIST.has(key)); - } -} - -module.exports = Traverser; diff --git a/tools/eslint/node_modules/acorn-jsx/node_modules/acorn/package.json b/tools/eslint/node_modules/acorn-jsx/node_modules/acorn/package.json deleted file mode 100644 index c62e197f4931b7..00000000000000 --- a/tools/eslint/node_modules/acorn-jsx/node_modules/acorn/package.json +++ /dev/null @@ -1,250 +0,0 @@ -{ - "_from": "acorn@^3.0.4", - "_id": "acorn@3.3.0", - "_inBundle": false, - "_integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=", - "_location": "/eslint/acorn-jsx/acorn", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "acorn@^3.0.4", - "name": "acorn", - "escapedName": "acorn", - "rawSpec": "^3.0.4", - "saveSpec": null, - "fetchSpec": "^3.0.4" - }, - "_requiredBy": [ - "/eslint/acorn-jsx" - ], - "_resolved": "https://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz", - "_shasum": "45e37fb39e8da3f25baee3ff5369e2bb5f22017a", - "_spec": "acorn@^3.0.4", - "_where": "/Users/cjihrig/iojs/node/tools/eslint-tmp/node_modules/eslint/node_modules/acorn-jsx", - "bin": { - "acorn": "./bin/acorn" - }, - "bugs": { - "url": "https://github.com/ternjs/acorn/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "List of Acorn contributors. Updated before every release." - }, - { - "name": "Adrian Rakovsky" - }, - { - "name": "Alistair Braidwood" - }, - { - "name": "Amila Welihinda" - }, - { - "name": "Andres Suarez" - }, - { - "name": "Angelo" - }, - { - "name": "Aparajita Fishman" - }, - { - "name": "Arian Stolwijk" - }, - { - "name": "Artem Govorov" - }, - { - "name": "Brandon Mills" - }, - { - "name": "Charles Hughes" - }, - { - "name": "Conrad Irwin" - }, - { - "name": "Daniel Tschinder" - }, - { - "name": "David Bonnet" - }, - { - "name": "Domenico Matteo" - }, - { - "name": "ForbesLindesay" - }, - { - "name": "Forbes Lindesay" - }, - { - "name": "Gilad Peleg" - }, - { - "name": "impinball" - }, - { - "name": "Ingvar Stepanyan" - }, - { - "name": "Jackson Ray Hamilton" - }, - { - "name": "Jesse McCarthy" - }, - { - "name": "Jiaxing Wang" - }, - { - "name": "Joel Kemp" - }, - { - "name": "Johannes Herr" - }, - { - "name": "Jordan Klassen" - }, - { - "name": "Jürg Lehni" - }, - { - "name": "keeyipchan" - }, - { - "name": "Keheliya Gallaba" - }, - { - "name": "Kevin Irish" - }, - { - "name": "Kevin Kwok" - }, - { - "name": "krator" - }, - { - "name": "Marijn Haverbeke" - }, - { - "name": "Martin Carlberg" - }, - { - "name": "Mathias Bynens" - }, - { - "name": "Mathieu 'p01' Henri" - }, - { - "name": "Matthew Bastien" - }, - { - "name": "Max Schaefer" - }, - { - "name": "Max Zerzouri" - }, - { - "name": "Mihai Bazon" - }, - { - "name": "Mike Rennie" - }, - { - "name": "Nicholas C. Zakas" - }, - { - "name": "Nick Fitzgerald" - }, - { - "name": "Olivier Thomann" - }, - { - "name": "Oskar Schöldström" - }, - { - "name": "Paul Harper" - }, - { - "name": "Peter Rust" - }, - { - "name": "PlNG" - }, - { - "name": "Prayag Verma" - }, - { - "name": "ReadmeCritic" - }, - { - "name": "r-e-d" - }, - { - "name": "Richard Gibson" - }, - { - "name": "Rich Harris" - }, - { - "name": "Rich-Harris" - }, - { - "name": "Sebastian McKenzie" - }, - { - "name": "Timothy Gu" - }, - { - "name": "Toru Nagashima" - }, - { - "name": "zsjforcn" - } - ], - "deprecated": false, - "description": "ECMAScript parser", - "devDependencies": { - "rollup": "^0.34.1", - "rollup-plugin-buble": "^0.11.0", - "unicode-9.0.0": "^0.7.0" - }, - "engines": { - "node": ">=0.4.0" - }, - "homepage": "https://github.com/ternjs/acorn", - "jsnext:main": "dist/acorn.es.js", - "license": "MIT", - "main": "dist/acorn.js", - "maintainers": [ - { - "name": "Marijn Haverbeke", - "email": "marijnh@gmail.com", - "url": "http://marijnhaverbeke.nl" - }, - { - "name": "Ingvar Stepanyan", - "email": "me@rreverser.com", - "url": "http://rreverser.com/" - } - ], - "name": "acorn", - "repository": { - "type": "git", - "url": "git+https://github.com/ternjs/acorn.git" - }, - "scripts": { - "build": "npm run build:main && npm run build:walk && npm run build:loose && npm run build:bin", - "build:bin": "rollup -c rollup/config.bin.js", - "build:loose": "rollup -c rollup/config.loose.js", - "build:main": "rollup -c rollup/config.main.js", - "build:walk": "rollup -c rollup/config.walk.js", - "prepublish": "npm test", - "pretest": "npm run build", - "test": "node test/run.js" - }, - "version": "3.3.0" -} diff --git a/tools/eslint/node_modules/acorn-jsx/package.json b/tools/eslint/node_modules/acorn-jsx/package.json deleted file mode 100644 index 96c127e87b9201..00000000000000 --- a/tools/eslint/node_modules/acorn-jsx/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "_from": "acorn-jsx@^3.0.0", - "_id": "acorn-jsx@3.0.1", - "_inBundle": false, - "_integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", - "_location": "/eslint/acorn-jsx", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "acorn-jsx@^3.0.0", - "name": "acorn-jsx", - "escapedName": "acorn-jsx", - "rawSpec": "^3.0.0", - "saveSpec": null, - "fetchSpec": "^3.0.0" - }, - "_requiredBy": [ - "/eslint/espree" - ], - "_resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz", - "_shasum": "afdf9488fb1ecefc8348f6fb22f464e32a58b36b", - "_spec": "acorn-jsx@^3.0.0", - "_where": "/Users/cjihrig/iojs/node/tools/eslint-tmp/node_modules/eslint/node_modules/espree", - "bugs": { - "url": "https://github.com/RReverser/acorn-jsx/issues" - }, - "bundleDependencies": false, - "dependencies": { - "acorn": "^3.0.4" - }, - "deprecated": false, - "description": "Alternative, faster React.js JSX parser", - "devDependencies": { - "chai": "^3.0.0", - "mocha": "^2.2.5" - }, - "homepage": "https://github.com/RReverser/acorn-jsx", - "license": "MIT", - "maintainers": [ - { - "name": "Ingvar Stepanyan", - "email": "me@rreverser.com", - "url": "http://rreverser.com/" - } - ], - "name": "acorn-jsx", - "repository": { - "type": "git", - "url": "git+https://github.com/RReverser/acorn-jsx.git" - }, - "scripts": { - "test": "node test/run.js" - }, - "version": "3.0.1" -} diff --git a/tools/eslint/node_modules/acorn/README.md b/tools/eslint/node_modules/acorn/README.md deleted file mode 100644 index ab2c12ea51add7..00000000000000 --- a/tools/eslint/node_modules/acorn/README.md +++ /dev/null @@ -1,452 +0,0 @@ -# Acorn - -[![Build Status](https://travis-ci.org/ternjs/acorn.svg?branch=master)](https://travis-ci.org/ternjs/acorn) -[![NPM version](https://img.shields.io/npm/v/acorn.svg)](https://www.npmjs.com/package/acorn) -[![CDNJS](https://img.shields.io/cdnjs/v/acorn.svg)](https://cdnjs.com/libraries/acorn) -[Author funding status: ![maintainer happiness](https://marijnhaverbeke.nl/fund/status_s.png?force)](https://marijnhaverbeke.nl/fund/) - -A tiny, fast JavaScript parser, written completely in JavaScript. - -## Community - -Acorn is open source software released under an -[MIT license](https://github.com/ternjs/acorn/blob/master/LICENSE). - -You are welcome to -[report bugs](https://github.com/ternjs/acorn/issues) or create pull -requests on [github](https://github.com/ternjs/acorn). For questions -and discussion, please use the -[Tern discussion forum](https://discuss.ternjs.net). - -## Installation - -The easiest way to install acorn is with [`npm`][npm]. - -[npm]: https://www.npmjs.com/ - -```sh -npm install acorn -``` - -Alternately, download the source. - -```sh -git clone https://github.com/ternjs/acorn.git -``` - -## Components - -When run in a CommonJS (node.js) or AMD environment, exported values -appear in the interfaces exposed by the individual files, as usual. -When loaded in the browser (Acorn works in any JS-enabled browser more -recent than IE5) without any kind of module management, a single -global object `acorn` will be defined, and all the exported properties -will be added to that. - -### Main parser - -This is implemented in `dist/acorn.js`, and is what you get when you -`require("acorn")` in node.js. - -**parse**`(input, options)` is used to parse a JavaScript program. -The `input` parameter is a string, `options` can be undefined or an -object setting some of the options listed below. The return value will -be an abstract syntax tree object as specified by the -[ESTree spec][estree]. - -When encountering a syntax error, the parser will raise a -`SyntaxError` object with a meaningful message. The error object will -have a `pos` property that indicates the character offset at which the -error occurred, and a `loc` object that contains a `{line, column}` -object referring to that same position. - -[estree]: https://github.com/estree/estree - -- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be - either 3, 5, 6 (2015), 7 (2016), 8 (2017), or 9 (2018, partial - support). This influences support for strict mode, the set of - reserved words, and support for new syntax features. Default is 7. - - **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being - implemented by Acorn. - -- **sourceType**: Indicate 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. - -- **onInsertedSemicolon**: If given a callback, that callback will be - called whenever a missing semicolon is inserted by the parser. The - callback will be given the character offset of the point where the - semicolon is inserted as argument, and if `locations` is on, also a - `{line, column}` object representing this position. - -- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing - commas. - -- **allowReserved**: If `false`, using a reserved word will generate - an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher - versions. When given the value `"never"`, reserved words and - keywords can also not be used as property names (as in Internet - Explorer's old parser). - -- **allowReturnOutsideFunction**: By default, a return statement at - the top level raises an error. Set this to `true` to accept such - code. - -- **allowImportExportEverywhere**: By default, `import` and `export` - declarations can only appear at a program's top level. Setting this - option to `true` allows them anywhere where a statement is allowed. - -- **allowHashBang**: When this is enabled (off by default), if the - code starts with the characters `#!` (as in a shellscript), the - first line will be treated as a comment. - -- **locations**: When `true`, each node has a `loc` object attached - with `start` and `end` subobjects, each of which contains the - one-based line and zero-based column numbers in `{line, column}` - form. Default is `false`. - -- **onToken**: If a function is passed for this option, each found - token will be passed in same format as tokens returned from - `tokenizer().getToken()`. - - If array is passed, each found token is pushed to it. - - Note that you are not allowed to call the parser from the - callback—that will corrupt its internal state. - -- **onComment**: If a function is passed for this option, whenever a - comment is encountered the function will be called with the - following parameters: - - - `block`: `true` if the comment is a block comment, false if it - is a line comment. - - `text`: The content of the comment. - - `start`: Character offset of the start of the comment. - - `end`: Character offset of the end of the comment. - - When the `locations` options is on, the `{line, column}` locations - of the comment’s start and end are passed as two additional - parameters. - - If array is passed for this option, each found comment is pushed - to it as object in Esprima format: - - ```javascript - { - "type": "Line" | "Block", - "value": "comment text", - "start": Number, - "end": Number, - // If `locations` option is on: - "loc": { - "start": {line: Number, column: Number} - "end": {line: Number, column: Number} - }, - // If `ranges` option is on: - "range": [Number, Number] - } - ``` - - Note that you are not allowed to call the parser from the - callback—that will corrupt its internal state. - -- **ranges**: 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`. - -- **program**: It is possible to parse multiple files into a single - AST by passing the tree produced by parsing the first file as the - `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. - -- **sourceFile**: When the `locations` option is `true`, you can pass - this option to add a `source` attribute in every node’s `loc` - object. Note that the contents of this option are not examined or - processed in any way; you are free to use whatever format you - choose. - -- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property - will be added (regardless of the `location` option) directly to the - nodes, rather than the `loc` object. - -- **preserveParens**: If this option is `true`, parenthesized expressions - are represented by (non-standard) `ParenthesizedExpression` nodes - that have a single `expression` property containing the expression - inside parentheses. - -[range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - -**parseExpressionAt**`(input, offset, options)` will parse a single -expression in a string, and return its AST. It will not complain if -there is more of the string left after the expression. - -**getLineInfo**`(input, offset)` can be used to get a `{line, -column}` object for a given program string and character offset. - -**tokenizer**`(input, options)` returns an object with a `getToken` -method that can be called repeatedly to get the next token, a `{start, -end, type, value}` object (with added `loc` property when the -`locations` option is enabled and `range` property when the `ranges` -option is enabled). When the token's type is `tokTypes.eof`, you -should stop calling the method, since it will keep returning that same -token forever. - -In ES6 environment, returned result can be used as any other -protocol-compliant iterable: - -```javascript -for (let token of acorn.tokenizer(str)) { - // iterate over the tokens -} - -// transform code to array of tokens: -var tokens = [...acorn.tokenizer(str)]; -``` - -**tokTypes** holds an object mapping names to the token type objects -that end up in the `type` properties of tokens. - -#### Note on using with [Escodegen][escodegen] - -Escodegen supports generating comments from AST, attached in -Esprima-specific format. In order to simulate same format in -Acorn, consider following example: - -```javascript -var comments = [], tokens = []; - -var ast = acorn.parse('var x = 42; // answer', { - // collect ranges for each node - ranges: true, - // collect comments in Esprima's format - onComment: comments, - // collect token ranges - onToken: tokens -}); - -// attach comments using collected information -escodegen.attachComments(ast, comments, tokens); - -// generate code -console.log(escodegen.generate(ast, {comment: true})); -// > 'var x = 42; // answer' -``` - -[escodegen]: https://github.com/estools/escodegen - -### dist/acorn_loose.js ### - -This file implements an error-tolerant parser. It exposes a single -function. The loose parser is accessible in node.js via `require("acorn/dist/acorn_loose")`. - -**parse_dammit**`(input, options)` takes the same arguments and -returns the same syntax tree as the `parse` function in `acorn.js`, -but never raises an error, and will do its best to parse syntactically -invalid code in as meaningful a way as it can. It'll insert identifier -nodes with name `"✖"` as placeholders in places where it can't make -sense of the input. Depends on `acorn.js`, because it uses the same -tokenizer. - -### dist/walk.js ### - -Implements an abstract syntax tree walker. Will store its interface in -`acorn.walk` when loaded without a module system. - -**simple**`(node, visitors, base, state)` does a 'simple' walk over -a tree. `node` should be the AST node to walk, and `visitors` an -object with properties whose names correspond to node types in the -[ESTree spec][estree]. The properties should contain functions -that will be called with the node object and, if applicable the state -at that point. The last two arguments are optional. `base` is a walker -algorithm, and `state` is a start state. The default walker will -simply visit all statements and expressions and not produce a -meaningful state. (An example of a use of state is to track scope at -each point in the tree.) - -```js -const acorn = require("acorn") -const walk = require("acorn/dist/walk") - -walk.simple(acorn.parse("let x = 10"), { - Literal(node) { - console.log(`Found a literal: ${node.value}`) - } -}) -``` - -**ancestor**`(node, visitors, base, state)` does a 'simple' walk over -a tree, building up an array of ancestor nodes (including the current node) -and passing the array to the callbacks as a third parameter. - -```js -const acorn = require("acorn") -const walk = require("acorn/dist/walk") - -walk.ancestor(acorn.parse("foo('hi')"), { - Literal(_, ancestors) { - console.log("This literal's ancestors are:", - ancestors.map(n => n.type)) - } -}) -``` - -**recursive**`(node, state, functions, base)` does a 'recursive' -walk, where the walker functions are responsible for continuing the -walk on the child nodes of their target node. `state` is the start -state, and `functions` should contain an object that maps node types -to walker functions. Such functions are called with `(node, state, c)` -arguments, and can cause the walk to continue on a sub-node by calling -the `c` argument on it with `(node, state)` arguments. The optional -`base` argument provides the fallback walker functions for node types -that aren't handled in the `functions` object. If not given, the -default walkers will be used. - -**make**`(functions, base)` builds a new walker object by using the -walker functions in `functions` and filling in the missing ones by -taking defaults from `base`. - -**full**`(node, callback, base, state)` does a 'full' -walk over a tree, calling the callback with the arguments (node, state, type) -for each node - -**fullAncestor**`(node, callback, base, state)` does a 'full' walk over -a tree, building up an array of ancestor nodes (including the current node) -and passing the array to the callbacks as a third parameter. - -```js -const acorn = require("acorn") -const walk = require("acorn/dist/walk") - -walk.full(acorn.parse("1 + 1"), node => { - console.log(`There's a ${node.type} node at ${node.ch}`) -}) -``` - -**findNodeAt**`(node, start, end, test, base, state)` tries to -locate a node in a tree at the given start and/or end offsets, which -satisfies the predicate `test`. `start` and `end` can be either `null` -(as wildcard) or a number. `test` may be a string (indicating a node -type) or a function that takes `(nodeType, node)` arguments and -returns a boolean indicating whether this node is interesting. `base` -and `state` are optional, and can be used to specify a custom walker. -Nodes are tested from inner to outer, so if two nodes match the -boundaries, the inner one will be preferred. - -**findNodeAround**`(node, pos, test, base, state)` is a lot like -`findNodeAt`, but will match any node that exists 'around' (spanning) -the given position. - -**findNodeAfter**`(node, pos, test, base, state)` is similar to -`findNodeAround`, but will match all nodes *after* the given position -(testing outer nodes before inner nodes). - -## Command line interface - -The `bin/acorn` utility can be used to parse a file from the command -line. It accepts as arguments its input file and the following -options: - -- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9`: Sets the ECMAScript version - to parse. Default is version 7. - -- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - -- `--locations`: Attaches a "loc" object to each node with "start" and - "end" subobjects, each of which contains the one-based line and - zero-based column numbers in `{line, column}` form. - -- `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - -- `--compact`: No whitespace is used in the AST output. - -- `--silent`: Do not output the AST, just return the exit status. - -- `--help`: Print the usage information and quit. - -The utility spits out the syntax tree as JSON data. - -## Build system - -Acorn is written in ECMAScript 6, as a set of small modules, in the -project's `src` directory, and compiled down to bigger ECMAScript 3 -files in `dist` using [Browserify](http://browserify.org) and -[Babel](http://babeljs.io/). If you are already using Babel, you can -consider including the modules directly. - -The command-line test runner (`npm test`) uses the ES6 modules. The -browser-based test page (`test/index.html`) uses the compiled modules. -The `bin/build-acorn.js` script builds the latter from the former. - -If you are working on Acorn, you'll probably want to try the code out -directly, without an intermediate build step. In your scripts, you can -register the Babel require shim like this: - - require("babel-core/register") - -That will allow you to directly `require` the ES6 modules. - -## Plugins - -Acorn is designed support allow plugins which, within reasonable -bounds, redefine the way the parser works. Plugins can add new token -types and new tokenizer contexts (if necessary), and extend methods in -the parser object. This is not a clean, elegant API—using it requires -an understanding of Acorn's internals, and plugins are likely to break -whenever those internals are significantly changed. But still, it is -_possible_, in this way, to create parsers for JavaScript dialects -without forking all of Acorn. And in principle it is even possible to -combine such plugins, so that if you have, for example, a plugin for -parsing types and a plugin for parsing JSX-style XML literals, you -could load them both and parse code with both JSX tags and types. - -A plugin should register itself by adding a property to -`acorn.plugins`, which holds a function. Calling `acorn.parse`, a -`plugins` option can be passed, holding an object mapping plugin names -to configuration values (or just `true` for plugins that don't take -options). After the parser object has been created, the initialization -functions for the chosen plugins are called with `(parser, -configValue)` arguments. They are expected to use the `parser.extend` -method to extend parser methods. For example, the `readToken` method -could be extended like this: - -```javascript -parser.extend("readToken", function(nextMethod) { - return function(code) { - console.log("Reading a token!") - return nextMethod.call(this, code) - } -}) -``` - -The `nextMethod` argument passed to `extend`'s second argument is the -previous value of this method, and should usually be called through to -whenever the extended method does not handle the call itself. - -Similarly, the loose parser allows plugins to register themselves via -`acorn.pluginsLoose`. The extension mechanism is the same as for the -normal parser: - -```javascript -looseParser.extend("readToken", function(nextMethod) { - return function() { - console.log("Reading a token in the loose parser!") - return nextMethod.call(this) - } -}) -``` - -### Existing plugins - - - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) - - [`acorn-es7-plugin`](https://github.com/MatAtBread/acorn-es7-plugin/): Parse [async/await syntax proposal](https://github.com/tc39/ecmascript-asyncawait) - - [`acorn-object-spread`](https://github.com/UXtemple/acorn-object-spread): Parse [object spread syntax proposal](https://github.com/sebmarkbage/ecmascript-rest-spread) - - [`acorn-es7`](https://www.npmjs.com/package/acorn-es7): Parse [decorator syntax proposal](https://github.com/wycats/javascript-decorators) - - [`acorn-objj`](https://www.npmjs.com/package/acorn-objj): [Objective-J](http://www.cappuccino-project.org/learn/objective-j.html) language parser built as Acorn plugin - - [`acorn-object-rest-spread`](https://github.com/victor-homyakov/acorn-object-rest-spread) Parse [Object Rest/Spread Properties proposal](https://github.com/tc39/proposal-object-rest-spread), works with latest Acorn version (5.0.3) - - [`acorn-static-class-property-initializer`](https://github.com/victor-homyakov/acorn-static-class-property-initializer) Partial support for static class properties from [ES Class Fields & Static Properties Proposal](https://github.com/tc39/proposal-class-public-fields) to support static property initializers in [React components written as ES6+ classes](https://babeljs.io/blog/2015/06/07/react-on-es6-plus) - diff --git a/tools/eslint/node_modules/acorn/package.json b/tools/eslint/node_modules/acorn/package.json deleted file mode 100644 index 610943538459dd..00000000000000 --- a/tools/eslint/node_modules/acorn/package.json +++ /dev/null @@ -1,286 +0,0 @@ -{ - "_from": "acorn@^5.2.1", - "_id": "acorn@5.2.1", - "_inBundle": false, - "_integrity": "sha512-jG0u7c4Ly+3QkkW18V+NRDN+4bWHdln30NL1ZL2AvFZZmQe/BfopYCtghCKKVBUSetZ4QKcyA0pY6/4Gw8Pv8w==", - "_location": "/eslint/acorn", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "acorn@^5.2.1", - "name": "acorn", - "escapedName": "acorn", - "rawSpec": "^5.2.1", - "saveSpec": null, - "fetchSpec": "^5.2.1" - }, - "_requiredBy": [ - "/eslint/espree" - ], - "_resolved": "https://registry.npmjs.org/acorn/-/acorn-5.2.1.tgz", - "_shasum": "317ac7821826c22c702d66189ab8359675f135d7", - "_spec": "acorn@^5.2.1", - "_where": "/Users/cjihrig/iojs/node/tools/eslint-tmp/node_modules/eslint/node_modules/espree", - "bin": { - "acorn": "./bin/acorn" - }, - "bugs": { - "url": "https://github.com/ternjs/acorn/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "List of Acorn contributors. Updated before every release." - }, - { - "name": "Adrian Rakovsky" - }, - { - "name": "Alistair Braidwood" - }, - { - "name": "Amila Welihinda" - }, - { - "name": "Andres Suarez" - }, - { - "name": "Angelo" - }, - { - "name": "Aparajita Fishman" - }, - { - "name": "Arian Stolwijk" - }, - { - "name": "Artem Govorov" - }, - { - "name": "Bradley Heinz" - }, - { - "name": "Brandon Mills" - }, - { - "name": "Charles Hughes" - }, - { - "name": "Conrad Irwin" - }, - { - "name": "Daniel Tschinder" - }, - { - "name": "David Bonnet" - }, - { - "name": "Domenico Matteo" - }, - { - "name": "ehmicky" - }, - { - "name": "Forbes Lindesay" - }, - { - "name": "Gilad Peleg" - }, - { - "name": "impinball" - }, - { - "name": "Ingvar Stepanyan" - }, - { - "name": "Jackson Ray Hamilton" - }, - { - "name": "Jesse McCarthy" - }, - { - "name": "Jiaxing Wang" - }, - { - "name": "Joel Kemp" - }, - { - "name": "Johannes Herr" - }, - { - "name": "John-David Dalton" - }, - { - "name": "Jordan Klassen" - }, - { - "name": "Jürg Lehni" - }, - { - "name": "Kai Cataldo" - }, - { - "name": "keeyipchan" - }, - { - "name": "Keheliya Gallaba" - }, - { - "name": "Kevin Irish" - }, - { - "name": "Kevin Kwok" - }, - { - "name": "krator" - }, - { - "name": "Marek" - }, - { - "name": "Marijn Haverbeke" - }, - { - "name": "Martin Carlberg" - }, - { - "name": "Mat Garcia" - }, - { - "name": "Mathias Bynens" - }, - { - "name": "Mathieu 'p01' Henri" - }, - { - "name": "Matthew Bastien" - }, - { - "name": "Max Schaefer" - }, - { - "name": "Max Zerzouri" - }, - { - "name": "Mihai Bazon" - }, - { - "name": "Mike Rennie" - }, - { - "name": "naoh" - }, - { - "name": "Nicholas C. Zakas" - }, - { - "name": "Nick Fitzgerald" - }, - { - "name": "Olivier Thomann" - }, - { - "name": "Oskar Schöldström" - }, - { - "name": "Paul Harper" - }, - { - "name": "Peter Rust" - }, - { - "name": "PlNG" - }, - { - "name": "Prayag Verma" - }, - { - "name": "ReadmeCritic" - }, - { - "name": "r-e-d" - }, - { - "name": "Richard Gibson" - }, - { - "name": "Rich Harris" - }, - { - "name": "Sebastian McKenzie" - }, - { - "name": "Shahar Soel" - }, - { - "name": "Simen Bekkhus" - }, - { - "name": "Teddy Katz" - }, - { - "name": "Timothy Gu" - }, - { - "name": "Toru Nagashima" - }, - { - "name": "Victor Homyakov" - }, - { - "name": "Wexpo Lyu" - }, - { - "name": "zsjforcn" - } - ], - "deprecated": false, - "description": "ECMAScript parser", - "devDependencies": { - "eslint": "^3.18.0", - "eslint-config-standard": "^7.1.0", - "eslint-plugin-import": "^2.2.0", - "eslint-plugin-promise": "^3.5.0", - "eslint-plugin-standard": "^2.1.1", - "rollup": "^0.43.0", - "rollup-plugin-buble": "^0.15.0", - "unicode-9.0.0": "^0.7.0" - }, - "engines": { - "node": ">=0.4.0" - }, - "homepage": "https://github.com/ternjs/acorn", - "license": "MIT", - "main": "dist/acorn.js", - "maintainers": [ - { - "name": "Marijn Haverbeke", - "email": "marijnh@gmail.com", - "url": "http://marijnhaverbeke.nl" - }, - { - "name": "Ingvar Stepanyan", - "email": "me@rreverser.com", - "url": "http://rreverser.com/" - } - ], - "module": "dist/acorn.es.js", - "name": "acorn", - "repository": { - "type": "git", - "url": "git+https://github.com/ternjs/acorn.git" - }, - "scripts": { - "build": "npm run build:main && npm run build:walk && npm run build:loose && npm run build:bin", - "build:bin": "rollup -c rollup/config.bin.js", - "build:loose": "rollup -c rollup/config.loose.js && rollup -c rollup/config.loose_es.js", - "build:main": "rollup -c rollup/config.main.js", - "build:walk": "rollup -c rollup/config.walk.js", - "lint": "eslint src/", - "prepare": "npm test", - "pretest": "npm run build:main && npm run build:loose", - "test": "node test/run.js && node test/lint.js" - }, - "version": "5.2.1" -} diff --git a/tools/eslint/node_modules/ajv-keywords/package.json b/tools/eslint/node_modules/ajv-keywords/package.json deleted file mode 100644 index 0afdd4666bca8b..00000000000000 --- a/tools/eslint/node_modules/ajv-keywords/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "_from": "ajv-keywords@^2.1.0", - "_id": "ajv-keywords@2.1.1", - "_inBundle": false, - "_integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=", - "_location": "/eslint/ajv-keywords", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "ajv-keywords@^2.1.0", - "name": "ajv-keywords", - "escapedName": "ajv-keywords", - "rawSpec": "^2.1.0", - "saveSpec": null, - "fetchSpec": "^2.1.0" - }, - "_requiredBy": [ - "/eslint/table" - ], - "_resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", - "_shasum": "617997fc5f60576894c435f940d819e135b80762", - "_spec": "ajv-keywords@^2.1.0", - "_where": "/Users/cjihrig/iojs/node/tools/eslint-tmp/node_modules/eslint/node_modules/table", - "author": { - "name": "Evgeny Poberezkin" - }, - "bugs": { - "url": "https://github.com/epoberezkin/ajv-keywords/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Custom JSON-Schema keywords for Ajv validator", - "devDependencies": { - "ajv": "^5.0.0", - "ajv-pack": "^0.3.0", - "chai": "^4.0.2", - "coveralls": "^3.0.0", - "dot": "^1.1.1", - "eslint": "^4.9.0", - "glob": "^7.1.1", - "istanbul": "^0.4.3", - "js-beautify": "^1.7.4", - "json-schema-test": "^1.3.0", - "mocha": "^4.0.0", - "pre-commit": "^1.1.3", - "uuid": "^3.0.1" - }, - "files": [ - "index.js", - "keywords" - ], - "homepage": "https://github.com/epoberezkin/ajv-keywords#readme", - "keywords": [ - "JSON-Schema", - "ajv", - "keywords" - ], - "license": "MIT", - "main": "index.js", - "name": "ajv-keywords", - "peerDependencies": { - "ajv": "^5.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/epoberezkin/ajv-keywords.git" - }, - "scripts": { - "build": "node node_modules/ajv/scripts/compile-dots.js node_modules/ajv/lib keywords", - "eslint": "eslint index.js keywords/*.js", - "prepublish": "npm run build", - "test": "npm run build && npm run eslint && npm run test-cov", - "test-cov": "istanbul cover -x 'spec/**' node_modules/mocha/bin/_mocha -- spec/*.spec.js -R spec", - "test-spec": "mocha spec/*.spec.js -R spec" - }, - "version": "2.1.1" -} diff --git a/tools/eslint/node_modules/ajv/README.md b/tools/eslint/node_modules/ajv/README.md deleted file mode 100644 index fdf6144a20e9c7..00000000000000 --- a/tools/eslint/node_modules/ajv/README.md +++ /dev/null @@ -1,1327 +0,0 @@ -Ajv logo - -# Ajv: Another JSON Schema Validator - -The fastest JSON Schema validator for Node.js and browser with draft 6 support. - - -[![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv) -[![npm version](https://badge.fury.io/js/ajv.svg)](https://www.npmjs.com/package/ajv) -[![npm@beta](https://img.shields.io/npm/v/ajv/beta.svg)](https://github.com/epoberezkin/ajv/tree/beta) -[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) -[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master) -[![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/) -[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) - - -__Please note__: Ajv [version 6](https://github.com/epoberezkin/ajv/tree/beta) with [JSON Schema draft-07](http://json-schema.org/work-in-progress) support is released. Use `npm install ajv@beta` to install. - - -## Using version 5 - -[JSON Schema draft-06](https://trac.tools.ietf.org/html/draft-wright-json-schema-validation-01) is published. - -[Ajv version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0) that supports draft-06 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas). - -__Please note__: To use Ajv with draft-04 schemas you need to explicitly add meta-schema to the validator instance: - -```javascript -ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); -``` - - -## Contents - -- [Performance](#performance) -- [Features](#features) -- [Getting started](#getting-started) -- [Frequently Asked Questions](https://github.com/epoberezkin/ajv/blob/master/FAQ.md) -- [Using in browser](#using-in-browser) -- [Command line interface](#command-line-interface) -- Validation - - [Keywords](#validation-keywords) - - [Formats](#formats) - - [Combining schemas with $ref](#ref) - - [$data reference](#data-reference) - - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - - [Defining custom keywords](#defining-custom-keywords) - - [Asynchronous schema compilation](#asynchronous-schema-compilation) - - [Asynchronous validation](#asynchronous-validation) -- Modifying data during validation - - [Filtering data](#filtering-data) - - [Assigning defaults](#assigning-defaults) - - [Coercing data types](#coercing-data-types) -- API - - [Methods](#api) - - [Options](#options) - - [Validation errors](#validation-errors) -- [Related packages](#related-packages) -- [Packages using Ajv](#some-packages-using-ajv) -- [Tests, Contributing, History, License](#tests) - - -## Performance - -Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON schemas into super-fast validation functions that are efficient for v8 optimization. - -Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - -- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place -- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster -- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) -- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) - - -Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): - -[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:%7Cajv%7Cis-my-json-valid%7Cjsen%7Cschemasaurus%7Cthemis%7Cz-schema%7Cjsck%7Cjsonschema%7Cskeemas%7Ctv4%7Cjayschema&chd=t:100,68,61,22.8,17.6,6.6,2.7,0.9,0.7,0.4,0.1)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) - - -## Features - -- Ajv implements full JSON Schema [draft 6](http://json-schema.org/) and draft 4 standards: - - all validation keywords (see [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md)) - - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - - support of circular references between schemas - - correct string lengths for strings with unicode pairs (can be turned off) - - [formats](#formats) defined by JSON Schema draft 4 standard and custom formats (can be turned off) - - [validates schemas against meta-schema](#api-validateschema) -- supports [browsers](#using-in-browser) and Node.js 0.10-8.x -- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation -- "All errors" validation mode with [option allErrors](#options) -- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages -- i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package -- [filtering data](#filtering-data) from additional properties -- [assigning defaults](#assigning-defaults) to missing properties and items -- [coercing data](#coercing-data-types) to the types specified in `type` keywords -- [custom keywords](#defining-custom-keywords) -- draft-6 keywords `const`, `contains` and `propertyNames` -- draft-6 boolean schemas (`true`/`false` as a schema to always pass/fail). -- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON-schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package -- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords -- [asynchronous validation](#asynchronous-validation) of custom formats and keywords - -Currently Ajv is the only validator that passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), apart from the test that requires that `1.0` is not an integer that is impossible to satisfy in JavaScript). - - -## Install - -``` -npm install ajv -``` - -or to install [version 6](https://github.com/epoberezkin/ajv/tree/beta): - -``` -npm install ajv@beta -``` - - -## Getting started - -Try it in the Node.js REPL: https://tonicdev.com/npm/ajv - - -The fastest validation call: - -```javascript -var Ajv = require('ajv'); -var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} -var validate = ajv.compile(schema); -var valid = validate(data); -if (!valid) console.log(validate.errors); -``` - -or with less code - -```javascript -// ... -var valid = ajv.validate(schema, data); -if (!valid) console.log(ajv.errors); -// ... -``` - -or - -```javascript -// ... -var valid = ajv.addSchema(schema, 'mySchema') - .validate('mySchema', data); -if (!valid) console.log(ajv.errorsText()); -// ... -``` - -See [API](#api) and [Options](#options) for more details. - -Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. - -The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). - -__Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) - - -## Using in browser - -You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. - -If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). - -Then you need to load Ajv in the browser: -```html - -``` - -This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. - -The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). - -Ajv is tested with these browsers: - -[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) - -__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/epoberezkin/ajv/issues/234)). - - -## Command line interface - -CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports: - -- compiling JSON-schemas to test their validity -- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack)) -- migrate schemas to draft-06 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) -- validating data file(s) against JSON-schema -- testing expected validity of data against JSON-schema -- referenced schemas -- custom meta-schemas -- files in JSON and JavaScript format -- all Ajv options -- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format - - -## Validation keywords - -Ajv supports all validation keywords from draft 4 of JSON-schema standard: - -- [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type) -- [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf -- [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format -- [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains) -- [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#propertynames) -- [for all types](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#const) -- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf - -With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON-schema standard: - -- [switch](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#switch-proposed) - conditional validation with a sequence of if/then clauses -- [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. -- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. - -See [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details. - - -## Formats - -The following formats are supported for string validation with "format" keyword: - -- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). -- _time_: time with optional time-zone. -- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). -- _uri_: full uri with optional protocol. -- _url_: [URL record](https://url.spec.whatwg.org/#concept-url). -- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) -- _email_: email address. -- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). -- _ipv4_: IP address v4. -- _ipv6_: IP address v6. -- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. -- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). -- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). -- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). - -There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `email`, and `hostname`. See [Options](#options) for details. - -You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. - -The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can whitelist specific format(s) to be ignored. See [Options](#options) for details. - -You can find patterns used for format validation and the sources that were used in [formats.js](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js). - - -## Combining schemas with $ref - -You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. - -Example: - -```javascript -var schema = { - "$id": "http://example.com/schemas/schema.json", - "type": "object", - "properties": { - "foo": { "$ref": "defs.json#/definitions/int" }, - "bar": { "$ref": "defs.json#/definitions/str" } - } -}; - -var defsSchema = { - "$id": "http://example.com/schemas/defs.json", - "definitions": { - "int": { "type": "integer" }, - "str": { "type": "string" } - } -}; -``` - -Now to compile your schema you can either pass all schemas to Ajv instance: - -```javascript -var ajv = new Ajv({schemas: [schema, defsSchema]}); -var validate = ajv.getSchema('http://example.com/schemas/schema.json'); -``` - -or use `addSchema` method: - -```javascript -var ajv = new Ajv; -var validate = ajv.addSchema(defsSchema) - .compile(schema); -``` - -See [Options](#options) and [addSchema](#api) method. - -__Please note__: -- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). -- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). -- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. -- The actual location of the schema file in the file system is not used. -- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. -- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. -- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). - - -## $data reference - -With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal)) for more information about how it works. - -`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. - -The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). - -Examples. - -This schema requires that the value in property `smaller` is less or equal than the value in the property larger: - -```javascript -var ajv = new Ajv({$data: true}); - -var schema = { - "properties": { - "smaller": { - "type": "number", - "maximum": { "$data": "1/larger" } - }, - "larger": { "type": "number" } - } -}; - -var validData = { - smaller: 5, - larger: 7 -}; - -ajv.validate(schema, validData); // true -``` - -This schema requires that the properties have the same format as their field names: - -```javascript -var schema = { - "additionalProperties": { - "type": "string", - "format": { "$data": "0#" } - } -}; - -var validData = { - 'date-time': '1963-06-19T08:30:06.283185Z', - email: 'joe.bloggs@example.com' -} -``` - -`$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. - - -## $merge and $patch keywords - -With the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON-schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). - -To add keywords `$merge` and `$patch` to Ajv instance use this code: - -```javascript -require('ajv-merge-patch')(ajv); -``` - -Examples. - -Using `$merge`: - -```json -{ - "$merge": { - "source": { - "type": "object", - "properties": { "p": { "type": "string" } }, - "additionalProperties": false - }, - "with": { - "properties": { "q": { "type": "number" } } - } - } -} -``` - -Using `$patch`: - -```json -{ - "$patch": { - "source": { - "type": "object", - "properties": { "p": { "type": "string" } }, - "additionalProperties": false - }, - "with": [ - { "op": "add", "path": "/properties/q", "value": { "type": "number" } } - ] - } -} -``` - -The schemas above are equivalent to this schema: - -```json -{ - "type": "object", - "properties": { - "p": { "type": "string" }, - "q": { "type": "number" } - }, - "additionalProperties": false -} -``` - -The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. - -See the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) for more information. - - -## Defining custom keywords - -The advantages of using custom keywords are: - -- allow creating validation scenarios that cannot be expressed using JSON Schema -- simplify your schemas -- help bringing a bigger part of the validation logic to your schemas -- make your schemas more expressive, less verbose and closer to your application domain -- implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated - -If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). - -The concerns you have to be aware of when extending JSON-schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. - -You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. - -Ajv allows defining keywords with: -- validation function -- compilation function -- macro function -- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. - -Example. `range` and `exclusiveRange` keywords using compiled schema: - -```javascript -ajv.addKeyword('range', { - type: 'number', - compile: function (sch, parentSchema) { - var min = sch[0]; - var max = sch[1]; - - return parentSchema.exclusiveRange === true - ? function (data) { return data > min && data < max; } - : function (data) { return data >= min && data <= max; } - } -}); - -var schema = { "range": [2, 4], "exclusiveRange": true }; -var validate = ajv.compile(schema); -console.log(validate(2.01)); // true -console.log(validate(3.99)); // true -console.log(validate(2)); // false -console.log(validate(4)); // false -``` - -Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. - -See [Defining custom keywords](https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md) for more details. - - -## Asynchronous schema compilation - -During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). - -Example: - -```javascript -var ajv = new Ajv({ loadSchema: loadSchema }); - -ajv.compileAsync(schema).then(function (validate) { - var valid = validate(data); - // ... -}); - -function loadSchema(uri) { - return request.json(uri).then(function (res) { - if (res.statusCode >= 400) - throw new Error('Loading error: ' + res.statusCode); - return res.body; - }); -} -``` - -__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. - - -## Asynchronous validation - -Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation - -You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). - -If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. - -__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. - -Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to either [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent) or with [regenerator](https://github.com/facebook/regenerator) or to [generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) that can be optionally transpiled with regenerator as well. You can also supply any other transpiler as a function. See [Options](#options). - -The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. - -If you are using generators, the compiled validation function can be either wrapped with [co](https://github.com/tj/co) (default) or returned as generator function, that can be used directly, e.g. in [koa](http://koajs.com/) 1.0. `co` is a small library, it is included in Ajv (both as npm dependency and in the browser bundle). - -Async functions are currently supported in Chrome 55, Firefox 52, Node.js 7 (with --harmony-async-await) and MS Edge 13 (with flag). - -Generator functions are currently supported in Chrome, Firefox and Node.js. - -If you are using Ajv in other browsers or in older versions of Node.js you should use one of available transpiling options. All provided async modes use global Promise class. If your platform does not have Promise you should use a polyfill that defines it. - -Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. - - -Example: - -```javascript -/** - * Default mode is non-transpiled generator function wrapped with `co`. - * Using package ajv-async (https://github.com/epoberezkin/ajv-async) - * you can auto-detect the best async mode. - * In this case, without "async" and "transpile" options - * (or with option {async: true}) - * Ajv will choose the first supported/installed option in this order: - * 1. native async function - * 2. native generator function wrapped with co - * 3. es7 async functions transpiled with nodent - * 4. es7 async functions transpiled with regenerator - */ - -var setupAsync = require('ajv-async'); -var ajv = setupAsync(new Ajv); - -ajv.addKeyword('idExists', { - async: true, - type: 'number', - validate: checkIdExists -}); - - -function checkIdExists(schema, data) { - return knex(schema.table) - .select('id') - .where('id', data) - .then(function (rows) { - return !!rows.length; // true if record is found - }); -} - -var schema = { - "$async": true, - "properties": { - "userId": { - "type": "integer", - "idExists": { "table": "users" } - }, - "postId": { - "type": "integer", - "idExists": { "table": "posts" } - } - } -}; - -var validate = ajv.compile(schema); - -validate({ userId: 1, postId: 19 }) -.then(function (data) { - console.log('Data is valid', data); // { userId: 1, postId: 19 } -}) -.catch(function (err) { - if (!(err instanceof Ajv.ValidationError)) throw err; - // data is invalid - console.log('Validation errors:', err.errors); -}); -``` - -### Using transpilers with asynchronous validation functions. - -To use a transpiler you should separately install it (or load its bundle in the browser). - -Ajv npm package includes minified browser bundles of regenerator and nodent in dist folder. - - -#### Using nodent - -```javascript -var setupAsync = require('ajv-async'); -var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' }); -setupAsync(ajv); -var validate = ajv.compile(schema); // transpiled es7 async function -validate(data).then(successFunc).catch(errorFunc); -``` - -`npm install nodent` or use `nodent.min.js` from dist folder of npm package. - - -#### Using regenerator - -```javascript -var setupAsync = require('ajv-async'); -var ajv = new Ajv({ /* async: 'es7', */ transpile: 'regenerator' }); -setupAsync(ajv); -var validate = ajv.compile(schema); // transpiled es7 async function -validate(data).then(successFunc).catch(errorFunc); -``` - -`npm install regenerator` or use `regenerator.min.js` from dist folder of npm package. - - -#### Using other transpilers - -```javascript -var ajv = new Ajv({ async: 'es7', processCode: transpileFunc }); -var validate = ajv.compile(schema); // transpiled es7 async function -validate(data).then(successFunc).catch(errorFunc); -``` - -See [Options](#options). - - -#### Comparison of async modes - -|mode|transpile
speed*|run-time
speed*|bundle
size| -|---|:-:|:-:|:-:| -|es7 async
(native)|-|0.75|-| -|generators
(native)|-|1.0|-| -|es7.nodent|1.35|1.1|215Kb| -|es7.regenerator|1.0|2.7|1109Kb| -|regenerator|1.0|3.2|1109Kb| - -\* Relative performance in Node.js 7.x — smaller is better. - -[nodent](https://github.com/MatAtBread/nodent) has several advantages: - -- much smaller browser bundle than regenerator -- almost the same performance of generated code as native generators in Node.js and the latest Chrome -- much better performance than native generators in other browsers -- works in IE 9 (regenerator does not) - - -## Filtering data - -With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. - -This option modifies original data. - -Example: - -```javascript -var ajv = new Ajv({ removeAdditional: true }); -var schema = { - "additionalProperties": false, - "properties": { - "foo": { "type": "number" }, - "bar": { - "additionalProperties": { "type": "number" }, - "properties": { - "baz": { "type": "string" } - } - } - } -} - -var data = { - "foo": 0, - "additional1": 1, // will be removed; `additionalProperties` == false - "bar": { - "baz": "abc", - "additional2": 2 // will NOT be removed; `additionalProperties` != false - }, -} - -var validate = ajv.compile(schema); - -console.log(validate(data)); // true -console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } -``` - -If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. - -If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). - -__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: - -```json -{ - "type": "object", - "oneOf": [ - { - "properties": { - "foo": { "type": "string" } - }, - "required": [ "foo" ], - "additionalProperties": false - }, - { - "properties": { - "bar": { "type": "integer" } - }, - "required": [ "bar" ], - "additionalProperties": false - } - ] -} -``` - -The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. - -With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). - -While this behaviour is unexpected (issues [#129](https://github.com/epoberezkin/ajv/issues/129), [#134](https://github.com/epoberezkin/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: - -```json -{ - "type": "object", - "properties": { - "foo": { "type": "string" }, - "bar": { "type": "integer" } - }, - "additionalProperties": false, - "oneOf": [ - { "required": [ "foo" ] }, - { "required": [ "bar" ] } - ] -} -``` - -The schema above is also more efficient - it will compile into a faster function. - - -## Assigning defaults - -With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. - -This option modifies original data. - -__Please note__: by default the default value is inserted in the generated validation code as a literal (starting from v4.0), so the value inserted in the data will be the deep clone of the default in the schema. - -If you need to insert the default value in the data by reference pass the option `useDefaults: "shared"`. - -Inserting defaults by reference can be faster (in case you have an object in `default`) and it allows to have dynamic values in defaults, e.g. timestamp, without recompiling the schema. The side effect is that modifying the default value in any validated data instance will change the default in the schema and in other validated data instances. See example 3 below. - - -Example 1 (`default` in `properties`): - -```javascript -var ajv = new Ajv({ useDefaults: true }); -var schema = { - "type": "object", - "properties": { - "foo": { "type": "number" }, - "bar": { "type": "string", "default": "baz" } - }, - "required": [ "foo", "bar" ] -}; - -var data = { "foo": 1 }; - -var validate = ajv.compile(schema); - -console.log(validate(data)); // true -console.log(data); // { "foo": 1, "bar": "baz" } -``` - -Example 2 (`default` in `items`): - -```javascript -var schema = { - "type": "array", - "items": [ - { "type": "number" }, - { "type": "string", "default": "foo" } - ] -} - -var data = [ 1 ]; - -var validate = ajv.compile(schema); - -console.log(validate(data)); // true -console.log(data); // [ 1, "foo" ] -``` - -Example 3 (inserting "defaults" by reference): - -```javascript -var ajv = new Ajv({ useDefaults: 'shared' }); - -var schema = { - properties: { - foo: { - default: { bar: 1 } - } - } -} - -var validate = ajv.compile(schema); - -var data = {}; -console.log(validate(data)); // true -console.log(data); // { foo: { bar: 1 } } - -data.foo.bar = 2; - -var data2 = {}; -console.log(validate(data2)); // true -console.log(data2); // { foo: { bar: 2 } } -``` - -`default` keywords in other cases are ignored: - -- not in `properties` or `items` subschemas -- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/epoberezkin/ajv/issues/42)) -- in `if` subschema of `switch` keyword -- in schemas generated by custom macro keywords - - -## Coercing data types - -When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. - -This option modifies original data. - -__Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. - - -Example 1: - -```javascript -var ajv = new Ajv({ coerceTypes: true }); -var schema = { - "type": "object", - "properties": { - "foo": { "type": "number" }, - "bar": { "type": "boolean" } - }, - "required": [ "foo", "bar" ] -}; - -var data = { "foo": "1", "bar": "false" }; - -var validate = ajv.compile(schema); - -console.log(validate(data)); // true -console.log(data); // { "foo": 1, "bar": false } -``` - -Example 2 (array coercions): - -```javascript -var ajv = new Ajv({ coerceTypes: 'array' }); -var schema = { - "properties": { - "foo": { "type": "array", "items": { "type": "number" } }, - "bar": { "type": "boolean" } - } -}; - -var data = { "foo": "1", "bar": ["false"] }; - -var validate = ajv.compile(schema); - -console.log(validate(data)); // true -console.log(data); // { "foo": [1], "bar": false } -``` - -The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). - -See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details. - - -## API - -##### new Ajv(Object options) -> Object - -Create Ajv instance. - - -##### .compile(Object schema) -> Function<Object data> - -Generate validating function and cache the compiled schema for future use. - -Validating function returns boolean and has properties `errors` with the errors from the last validation (`null` if there were no errors) and `schema` with the reference to the original schema. - -Unless the option `validateSchema` is false, the schema will be validated against meta-schema and if schema is invalid the error will be thrown. See [options](#options). - - -##### .compileAsync(Object schema [, Boolean meta] [, Function callback]) -> Promise - -Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - -- missing schema can't be loaded (`loadSchema` returns a Promise that rejects). -- a schema containing a missing reference is loaded, but the reference cannot be resolved. -- schema (or some loaded/referenced schema) is invalid. - -The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. - -You can asynchronously compile meta-schema by passing `true` as the second parameter. - -See example in [Asynchronous compilation](#asynchronous-schema-compilation). - - -##### .validate(Object schema|String key|String ref, data) -> Boolean - -Validate data using passed schema (it will be compiled and cached). - -Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. - -Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). - -__Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. - -If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). - - -##### .addSchema(Array<Object>|Object schema [, String key]) -> Ajv - -Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. - -Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. - -Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. - - -Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. - -Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. - -By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. - -__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. -This allows you to do nice things like the following. - -```javascript -var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); -``` - -##### .addMetaSchema(Array<Object>|Object schema [, String key]) -> Ajv - -Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). - -There is no need to explicitly add draft 6 meta schema (http://json-schema.org/draft-06/schema and http://json-schema.org/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. - - -##### .validateSchema(Object schema) -> Boolean - -Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. - -By default this method is called automatically when the schema is added, so you rarely need to use it directly. - -If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). - -If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. - -Errors will be available at `ajv.errors`. - - -##### .getSchema(String key) -> Function<Object data> - -Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. - - -##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -> Ajv - -Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. - -Schema can be removed using: -- key passed to `addSchema` -- it's full reference (id) -- RegExp that should match schema id or key (meta-schemas won't be removed) -- actual schema object that will be stable-stringified to remove schema from cache - -If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. - - -##### .addFormat(String name, String|RegExp|Function|Object format) -> Ajv - -Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. - -Strings are converted to RegExp. - -Function should return validation result as `true` or `false`. - -If object is passed it should have properties `validate`, `compare` and `async`: - -- _validate_: a string, RegExp or a function as described above. -- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. -- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. -- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/epoberezkin/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. - -Custom formats can be also added via `formats` option. - - -##### .addKeyword(String keyword, Object definition) -> Ajv - -Add custom validation keyword to Ajv instance. - -Keyword should be different from all standard JSON schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. - -Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. -It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. - -Example Keywords: -- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. -- `"example"`: valid, but not recommended as it could collide with future versions of JSON schema etc. -- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword - -Keyword definition is an object with the following properties: - -- _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. -- _validate_: validating function -- _compile_: compiling function -- _macro_: macro function -- _inline_: compiling function that returns code (as string) -- _schema_: an optional `false` value used with "validate" keyword to not pass schema -- _metaSchema_: an optional meta-schema for keyword schema -- _modifying_: `true` MUST be passed if keyword modifies data -- _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. -- _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). -- _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. -- _errors_: an optional boolean indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. - -_compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. - -__Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. - -See [Defining custom keywords](#defining-custom-keywords) for more details. - - -##### .getKeyword(String keyword) -> Object|Boolean - -Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. - - -##### .removeKeyword(String keyword) -> Ajv - -Removes custom or pre-defined keyword so you can redefine them. - -While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. - -__Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. - - -##### .errorsText([Array<Object> errors [, Object options]]) -> String - -Returns the text with all errors in a String. - -Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). - - -## Options - -Defaults: - -```javascript -{ - // validation and reporting options: - $data: false, - allErrors: false, - verbose: false, - jsonPointers: false, - uniqueItems: true, - unicode: true, - format: 'fast', - formats: {}, - unknownFormats: true, - schemas: {}, - logger: undefined, - // referenced schema options: - schemaId: undefined // recommended '$id' - missingRefs: true, - extendRefs: 'ignore', // recommended 'fail' - loadSchema: undefined, // function(uri: string): Promise {} - // options to modify validated data: - removeAdditional: false, - useDefaults: false, - coerceTypes: false, - // asynchronous validation options: - async: 'co*', - transpile: undefined, // requires ajv-async package - // advanced options: - meta: true, - validateSchema: true, - addUsedSchema: true, - inlineRefs: true, - passContext: false, - loopRequired: Infinity, - ownProperties: false, - multipleOfPrecision: false, - errorDataPath: 'object', - messages: true, - sourceCode: false, - processCode: undefined, // function (str: string): string {} - cache: new Cache, - serialize: undefined -} -``` - -##### Validation and reporting options - -- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). -- _allErrors_: check all rules collecting all errors. Default is to return after the first error. -- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). -- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. -- _uniqueItems_: validate `uniqueItems` keyword (true by default). -- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. -- _format_: formats validation mode ('fast' by default). Pass 'full' for more correct and slow validation or `false` not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. -- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. -- _unknownFormats_: handling of unknown formats. Option values: - - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON-schema specification. -- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. -- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values: - - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - - `false` - logging is disabled. - - -##### Referenced schema options - -- _schemaId_: this option defines which keywords are used as schema URI. Option value: - - `"$id"` (recommended) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06), ignore `id` keyword (if it is present a warning will be logged). - - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - - `undefined` (default) - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. -- _missingRefs_: handling of missing referenced schemas. Option values: - - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - - `"ignore"` - to log error during compilation and always pass validation. - - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. -- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). -- _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). - - -##### Options to modify validated data - -- _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - - `false` (default) - not to remove additional properties - - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). -- _useDefaults_: replace missing properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - - `false` (default) - do not use defaults - - `true` - insert defaults by value (safer and slower, object literal is used). - - `"shared"` - insert defaults by reference (faster). If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. -- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values: - - `false` (default) - no type coercion. - - `true` - coerce scalar data types. - - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). - - -##### Asynchronous validation options - -- _async_: determines how Ajv compiles asynchronous schemas (see [Asynchronous validation](#asynchronous-validation)) to functions. Option values: - - `"*"` / `"co*"` (default) - compile to generator function ("co*" - wrapped with `co.wrap`). If generators are not supported and you don't provide `processCode` option (or `transpile` option if you use [ajv-async](https://github.com/epoberezkin/ajv-async) package), the exception will be thrown when async schema is compiled. - - `"es7"` - compile to es7 async function. Unless your platform supports them you need to provide `processCode` or `transpile` option. According to [compatibility table](http://kangax.github.io/compat-table/es7/)) async functions are supported by: - - Firefox 52, - - Chrome 55, - - Node.js 7 (with `--harmony-async-await`), - - MS Edge 13 (with flag). - - `undefined`/`true` - auto-detect async mode. It requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. If `transpile` option is not passed, ajv-async will choose the first of supported/installed async/transpile modes in this order: - - "es7" (native async functions), - - "co*" (native generators with co.wrap), - - "es7"/"nodent", - - "co*"/"regenerator" during the creation of the Ajv instance. - - If none of the options is available the exception will be thrown. -- _transpile_: Requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - - `"nodent"` - transpile with [nodent](https://github.com/MatAtBread/nodent). If nodent is not installed, the exception will be thrown. nodent can only transpile es7 async functions; it will enforce this mode. - - `"regenerator"` - transpile with [regenerator](https://github.com/facebook/regenerator). If regenerator is not installed, the exception will be thrown. - - a function - this function should accept the code of validation function as a string and return transpiled code. This option allows you to use any other transpiler you prefer. If you are passing a function, you can simply pass it to `processCode` option without using ajv-async. - - -##### Advanced options - -- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. -- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can either be http://json-schema.org/schema or http://json-schema.org/draft-04/schema or absent (draft-4 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - - `true` (default) - if the validation fails, throw the exception. - - `"log"` - if the validation fails, log error. - - `false` - skip schema validation. -- _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. -- _inlineRefs_: Affects compilation of referenced schemas. Option values: - - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - - `false` - to not inline referenced schemas (they will be compiled as separate functions). - - integer number - to limit the maximum number of keywords of the schema that will be inlined. -- _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. -- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. -- _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. -- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/epoberezkin/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). -- _errorDataPath_: set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. -- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)). -- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). -- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass `require('js-beautify').js_beautify`. - - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/epoberezkin/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. -- _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. -- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. - - -## Validation errors - -In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. - - -### Error objects - -Each error is an object with the following properties: - -- _keyword_: validation keyword. -- _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). -- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. -- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package). See below for parameters set by all keywords. -- _message_: the standard error message (can be excluded with option `messages` set to false). -- _schema_: the schema of the keyword (added with `verbose` option). -- _parentSchema_: the schema containing the keyword (added with `verbose` option) -- _data_: the data validated by the keyword (added with `verbose` option). - -__Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. - - -### Error parameters - -Properties of `params` object in errors depend on the keyword that failed validation. - -- `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). -- `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). -- `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). -- `dependencies` - properties: - - `property` (dependent property), - - `missingProperty` (required missing dependency - only the first one is reported currently) - - `deps` (required dependencies, comma separated list as a string), - - `depsCount` (the number of required dependencies). -- `format` - property `format` (the schema of the keyword). -- `maximum`, `minimum` - properties: - - `limit` (number, the schema of the keyword), - - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") -- `multipleOf` - property `multipleOf` (the schema of the keyword) -- `pattern` - property `pattern` (the schema of the keyword) -- `required` - property `missingProperty` (required property that is missing). -- `propertyNames` - property `propertyName` (an invalid property name). -- `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). -- `type` - property `type` (required type(s), a string, can be a comma-separated list) -- `uniqueItems` - properties `i` and `j` (indices of duplicate items). -- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). -- `$ref` - property `ref` with the referenced schema URI. -- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). - - -## Related packages - -- [ajv-async](https://github.com/epoberezkin/ajv-async) - configure async validation mode -- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface -- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - custom error messages -- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages -- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - instrument generated validation code to measure test coverage of your schemas -- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - custom validation keywords (if/then/else, select, typeof, etc.) -- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - keywords $merge and $patch -- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions - - -## Some packages using Ajv - -- [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser -- [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services -- [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition -- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator -- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org -- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON-schema http://jsonschemalint.com -- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js -- [table](https://github.com/gajus/table) - formats data into a string table -- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser -- [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content -- [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation -- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation -- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages -- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema -- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON-schema with expect in mocha tests -- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema -- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file -- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app -- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter -- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - - -## Tests - -``` -npm install -git submodule update --init -npm test -``` - -## Contributing - -All validation functions are generated using doT templates in [dot](https://github.com/epoberezkin/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. - -`npm run build` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder. - -`npm run watch` - automatically compiles templates when files in dot folder change - -Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/master/CONTRIBUTING.md) - - -## Changes history - -See https://github.com/epoberezkin/ajv/releases - -__Please note__: [Changes in version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0). - -[Changes in version 4.6.0](https://github.com/epoberezkin/ajv/releases/tag/4.6.0). - -[Changes in version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0). - -[Changes in version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0). - -[Changes in version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0). - - -## License - -[MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE) diff --git a/tools/eslint/node_modules/ajv/dist/ajv.min.js b/tools/eslint/node_modules/ajv/dist/ajv.min.js deleted file mode 100644 index 2bc334ced96c9f..00000000000000 --- a/tools/eslint/node_modules/ajv/dist/ajv.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/* ajv 5.5.0: Another JSON Schema Validator */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Ajv=e()}}(function(){return function e(r,t,a){function s(i,n){if(!t[i]){if(!r[i]){var l="function"==typeof require&&require;if(!n&&l)return l(i,!0);if(o)return o(i,!0);var h=new Error("Cannot find module '"+i+"'");throw h.code="MODULE_NOT_FOUND",h}var u=t[i]={exports:{}};r[i][0].call(u.exports,function(e){var t=r[i][1][e];return s(t||e)},u,u.exports,e,r,t,a)}return t[i].exports}for(var o="function"==typeof require&&require,i=0;i=1&&t<=12&&a>=1&&a<=h[t]}function o(e,r){var t=e.match(u);if(!t)return!1;return t[1]<=23&&t[2]<=59&&t[3]<=59&&(!r||t[5])}function i(e){if(E.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}var n=e("./util"),l=/^\d\d\d\d-(\d\d)-(\d\d)$/,h=[0,31,29,31,30,31,30,31,31,30,31,30,31],u=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i,c=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i,d=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,f=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,p=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,m=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,v=/^(?:\/(?:[^~/]|~0|~1)*)*$|^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,y=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;r.exports=a,a.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,uri:/^(?:[a-z][a-z0-9+-.]*)(?::|\/)\/?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i,"uri-template":f,url:p,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:c,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:i,uuid:m,"json-pointer":v,"relative-json-pointer":y},a.full={date:s,time:o,"date-time":function(e){var r=e.split(g);return 2==r.length&&s(r[0])&&o(r[1],!0)},uri:function(e){return P.test(e)&&d.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":f,url:p,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:function(e){return e.length<=255&&c.test(e)},ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:i,uuid:m,"json-pointer":v,"relative-json-pointer":y};var g=/t|\s/i,P=/\/|:/,E=/[^\\]\\Z/},{"./util":12}],7:[function(e,r,t){"use strict";function a(e,r,t,P){function E(){var e=C.validate,r=e.apply(null,arguments);return E.errors=e.errors,r}function w(e,t,s,f){var P=!t||t&&t.schema==e;if(t.schema!=r.schema)return a.call($,e,t,s,f);var E=!0===e.$async,w=p({isTop:!0,schema:e,isRoot:P,baseId:f,root:t,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:d.MissingRef,RULES:U,validate:p,util:c,resolve:u,resolveRef:b,usePattern:_,useDefault:x,useCustomRule:F,opts:R,formats:Q,logger:$.logger,self:$});w=h(O,n)+h(I,o)+h(k,i)+h(L,l)+w,R.processCode&&(w=R.processCode(w));var S;try{S=new Function("self","RULES","formats","root","refVal","defaults","customRules","co","equal","ucs2length","ValidationError",w)($,U,Q,r,O,k,L,m,y,v,g),O[0]=S}catch(e){throw $.logger.error("Error compiling schema, function code:",w),e}return S.schema=e,S.errors=null,S.refs=D,S.refVal=O,S.root=P?S:t,E&&(S.$async=!0),!0===R.sourceCode&&(S.source={code:w,patterns:I,defaults:k}),S}function b(e,s,o){s=u.url(e,s);var i,n,l=D[s];if(void 0!==l)return i=O[l],n="refVal["+l+"]",j(i,n);if(!o&&r.refs){var h=r.refs[s];if(void 0!==h)return i=r.refVal[h],n=S(s,i),j(i,n)}n=S(s);var c=u.call($,w,r,s);if(void 0===c){var d=t&&t[s];d&&(c=u.inlineRef(d,R.inlineRefs)?d:a.call($,d,r,t,e))}if(void 0!==c)return function(e,r){O[D[e]]=r}(s,c),j(c,n);!function(e){delete D[e]}(s)}function S(e,r){var t=O.length;return O[t]=r,D[e]=t,"refVal"+t}function j(e,r){return"object"==typeof e||"boolean"==typeof e?{code:r,schema:e,inline:!0}:{code:r,$async:e&&e.$async}}function _(e){var r=A[e];return void 0===r&&(r=A[e]=I.length,I[r]=e),"pattern"+r}function x(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return c.toQuotedString(e);case"object":if(null===e)return"null";var r=f(e),t=q[r];return void 0===t&&(t=q[r]=k.length,k[t]=e),"default"+t}}function F(e,r,t,a){var s=e.definition.validateSchema;if(s&&!1!==$._opts.validateSchema){if(!s(r)){var o="keyword schema is invalid: "+$.errorsText(s.errors);if("log"!=$._opts.validateSchema)throw new Error(o);$.logger.error(o)}}var i,n=e.definition.compile,l=e.definition.inline,h=e.definition.macro;if(n)i=n.call($,r,t,a);else if(h)i=h.call($,r,t,a),!1!==R.validateSchema&&$.validateSchema(i,!0);else if(l)i=l.call($,a,e.keyword,r,t);else if(!(i=e.definition.validate))return;if(void 0===i)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var u=L.length;return L[u]=i,{code:"customRule"+u,validate:i}}var $=this,R=this._opts,O=[void 0],D={},I=[],A={},k=[],q={},L=[],z=function(e,r,t){var a=s.call(this,e,r,t);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:r,baseId:t},{index:a,compiling:!1})}.call(this,e,r=r||{schema:e,refVal:O,refs:D},P),C=this._compilations[z.index];if(z.compiling)return C.callValidate=E;var Q=this._formats,U=this.RULES;try{var V=w(e,r,t,P);C.validate=V;var N=C.callValidate;return N&&(N.schema=V.schema,N.errors=null,N.refs=V.refs,N.refVal=V.refVal,N.root=V.root,N.$async=V.$async,R.sourceCode&&(N.source=V.source)),V}finally{(function(e,r,t){var a=s.call(this,e,r,t);a>=0&&this._compilations.splice(a,1)}).call(this,e,r,P)}}function s(e,r,t){for(var a=0;a=55296&&r<=56319&&s=r)throw new Error("Cannot access property/index "+a+" levels up, current level is "+r);return t[r-a]}if(a>r)throw new Error("Cannot access data "+a+" levels up, current level is "+r);if(i="data"+(r-a||""),!s)return i}for(var l=i,h=s.split("/"),c=0;c",y=f?">":"<",g=void 0;if(e.opts.$data&&m&&m.$data){var P=e.util.getData(m.$data,i,e.dataPathArr),E="exclusive"+o,w="exclType"+o,b="exclIsNumber"+o,S="' + "+(j="op"+o)+" + '";s+=" var schemaExcl"+o+" = "+P+"; ",s+=" var "+E+"; var "+w+" = typeof "+(P="schemaExcl"+o)+"; if ("+w+" != 'boolean' && "+w+" != 'undefined' && "+w+" != 'number') { ";g=p;(_=_||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(g||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+p+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";x=s;s=_.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+w+" == 'number' ? ( ("+E+" = "+a+" === undefined || "+P+" "+v+"= "+a+") ? "+c+" "+y+"= "+P+" : "+c+" "+y+" "+a+" ) : ( ("+E+" = "+P+" === true) ? "+c+" "+y+"= "+a+" : "+c+" "+y+" "+a+" ) || "+c+" !== "+c+") { var op"+o+" = "+E+" ? '"+v+"' : '"+v+"=';"}else{S=v;if((b="number"==typeof m)&&d){j="'"+S+"'";s+=" if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+m+" "+v+"= "+a+" ? "+c+" "+y+"= "+m+" : "+c+" "+y+" "+a+" ) || "+c+" !== "+c+") { "}else{b&&void 0===n?(E=!0,g=p,h=e.errSchemaPath+"/"+p,a=m,y+="="):(b&&(a=Math[f?"min":"max"](m,n)),m===(!b||a)?(E=!0,g=p,h=e.errSchemaPath+"/"+p,y+="="):(E=!1,S+="="));var j="'"+S+"'";s+=" if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+c+" "+y+" "+a+" || "+c+" !== "+c+") { "}}g=g||r;var _=_||[];_.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(g||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { comparison: "+j+", limit: "+a+", exclusive: "+E+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+S+" ",s+=d?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var x=s;return s=_.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { "),s}},{}],14:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;s+="if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+c+".length "+("maxItems"==r?">":"<")+" "+a+") { ";var f=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==r?"more":"less",s+=" than ",s+=d?"' + "+a+" + '":""+n,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},{}],15:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;s+="if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=!1===e.opts.unicode?" "+c+".length ":" ucs2length("+c+") ",s+=" "+("maxLength"==r?">":"<")+" "+a+") { ";var f=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==r?"longer":"shorter",s+=" than ",s+=d?"' + "+a+" + '":""+n,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},{}],16:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;s+="if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+c+").length "+("maxProperties"==r?">":"<")+" "+a+") { ";var f=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==r?"more":"less",s+=" than ",s+=d?"' + "+a+" + '":""+n,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},{}],17:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,n=!e.opts.allErrors,l=e.util.copy(e),h="";l.level++;var u="valid"+l.level,c=l.baseId,d=!0,f=s;if(f)for(var p,m=-1,v=f.length-1;m=0)return h&&(a+=" if (true) { "),a;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var v="object"==typeof m&&!(m instanceof RegExp)&&m.validate,y=v&&m.type||"string";if(v){var g=!0===m.async;m=m.validate}if(y!=t)return h&&(a+=" if (true) { "),a;if(g){if(!e.async)throw new Error("async format in sync schema");P="formats"+e.util.getProperty(i)+".validate";a+=" if (!("+e.yieldAwait+" "+P+"("+u+"))) { "}else{a+=" if (! ";var P="formats"+e.util.getProperty(i);v&&(P+=".validate"),a+="function"==typeof m?" "+P+"("+u+") ":" "+P+".test("+u+") ",a+=") { "}}var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { format: ",a+=d?""+c:""+e.util.toQuotedString(i),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=d?"' + "+c+" + '":""+e.util.escapeQuotes(i),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=d?"validate.schema"+n:""+e.util.toQuotedString(i),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var w=a;return a=E.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+w+"]); ":" validate.errors = ["+w+"]; return false; ":" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",h&&(a+=" else { "),a}},{}],25:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="valid"+s,d="errs__"+s,f=e.util.copy(e),p="";f.level++;var m="valid"+f.level,v="i"+s,y=f.dataLevel=e.dataLevel+1,g="data"+y,P=e.baseId;if(a+="var "+d+" = errors;var "+c+";",Array.isArray(i)){var E=e.schema.additionalItems;if(!1===E){a+=" "+c+" = "+u+".length <= "+i.length+"; ";var w=l;l=e.errSchemaPath+"/additionalItems",a+=" if (!"+c+") { ";var b=b||[];b.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+i.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var S=a;a=b.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+S+"]); ":" validate.errors = ["+S+"]; return false; ":" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",l=w,h&&(p+="}",a+=" else { ")}var j=i;if(j)for(var _,x=-1,F=j.length-1;x "+x+") { ";$=u+"["+x+"]";f.schema=_,f.schemaPath=n+"["+x+"]",f.errSchemaPath=l+"/"+x,f.errorPath=e.util.getPathExpr(e.errorPath,x,e.opts.jsonPointers,!0),f.dataPathArr[y]=x;R=e.validate(f);f.baseId=P,e.util.varOccurences(R,g)<2?a+=" "+e.util.varReplace(R,g,$)+" ":a+=" var "+g+" = "+$+"; "+R+" ",a+=" } ",h&&(a+=" if ("+m+") { ",p+="}")}if("object"==typeof E&&e.util.schemaHasRules(E,e.RULES.all)){f.schema=E,f.schemaPath=e.schemaPath+".additionalItems",f.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+m+" = true; if ("+u+".length > "+i.length+") { for (var "+v+" = "+i.length+"; "+v+" < "+u+".length; "+v+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);$=u+"["+v+"]";f.dataPathArr[y]=v;R=e.validate(f);f.baseId=P,e.util.varOccurences(R,g)<2?a+=" "+e.util.varReplace(R,g,$)+" ":a+=" var "+g+" = "+$+"; "+R+" ",h&&(a+=" if (!"+m+") break; "),a+=" } } ",h&&(a+=" if ("+m+") { ",p+="}")}}else if(e.util.schemaHasRules(i,e.RULES.all)){f.schema=i,f.schemaPath=n,f.errSchemaPath=l,a+=" for (var "+v+" = 0; "+v+" < "+u+".length; "+v+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var $=u+"["+v+"]";f.dataPathArr[y]=v;var R=e.validate(f);f.baseId=P,e.util.varOccurences(R,g)<2?a+=" "+e.util.varReplace(R,g,$)+" ":a+=" var "+g+" = "+$+"; "+R+" ",h&&(a+=" if (!"+m+") break; "),a+=" }"}return h&&(a+=" "+p+" if ("+d+" == errors) {"),a=e.util.cleanUpCode(a)}},{}],26:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n,s+="var division"+o+";if (",d&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+o+" = "+c+" / "+a+", ",s+=e.opts.multipleOfPrecision?" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":" division"+o+" !== parseInt(division"+o+") ",s+=" ) ",d&&(s+=" ) "),s+=" ) { ";var f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=d?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var p=s;return s=f.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},{}],27:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="errs__"+s,d=e.util.copy(e);d.level++;var f="valid"+d.level;if(e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=n,d.errSchemaPath=l,a+=" var "+c+" = errors; ";var p=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var m;d.opts.allErrors&&(m=d.opts.allErrors,d.opts.allErrors=!1),a+=" "+e.validate(d)+" ",d.createErrors=!0,m&&(d.opts.allErrors=m),e.compositeRule=d.compositeRule=p,a+=" if ("+f+") { ";var v=v||[];v.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var y=a;a=v.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",h&&(a+=" if (false) { ");return a}},{}],28:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="valid"+s,d="errs__"+s,f=e.util.copy(e),p="";f.level++;var m="valid"+f.level;a+="var "+d+" = errors;var prevValid"+s+" = false;var "+c+" = false;";var v=f.baseId,y=e.compositeRule;e.compositeRule=f.compositeRule=!0;var g=i;if(g)for(var P,E=-1,w=g.length-1;E5)a+=" || validate.schema"+n+"["+v+"] ";else{var L=w;if(L)for(var z=-1,C=L.length-1;z= "+me+"; ",l=e.errSchemaPath+"/patternGroups/minimum",a+=" if (!"+c+") { ";(Ee=Ee||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'patternGroups' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { reason: '"+ge+"', limit: "+ye+", pattern: '"+e.util.escapeQuotes(he)+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have "+Pe+" than "+ye+' properties matching pattern "'+e.util.escapeQuotes(he)+"\"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";we=a;a=Ee.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+we+"]); ":" validate.errors = ["+we+"]; return false; ":" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",void 0!==ve&&(a+=" else ")}if(void 0!==ve){var ye=ve,ge="maximum",Pe="more";a+=" "+c+" = pgPropCount"+s+" <= "+ve+"; ",l=e.errSchemaPath+"/patternGroups/maximum",a+=" if (!"+c+") { ";var Ee=Ee||[];Ee.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'patternGroups' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { reason: '"+ge+"', limit: "+ye+", pattern: '"+e.util.escapeQuotes(he)+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have "+Pe+" than "+ye+' properties matching pattern "'+e.util.escapeQuotes(he)+"\"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var we=a;a=Ee.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+we+"]); ":" validate.errors = ["+we+"]; return false; ":" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } "}l=te,h&&(a+=" if ("+c+") { ",p+="}")}}}}return h&&(a+=" "+p+" if ("+d+" == errors) {"),a=e.util.cleanUpCode(a)}},{}],31:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="errs__"+s,d=e.util.copy(e);d.level++;var f="valid"+d.level;if(e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=n,d.errSchemaPath=l;var p="key"+s,m="idx"+s,v="i"+s,y="' + "+p+" + '",g="data"+(d.dataLevel=e.dataLevel+1),P="dataProperties"+s,E=e.opts.ownProperties,w=e.baseId;a+=" var "+c+" = errors; ",E&&(a+=" var "+P+" = undefined; "),a+=E?" "+P+" = "+P+" || Object.keys("+u+"); for (var "+m+"=0; "+m+"<"+P+".length; "+m+"++) { var "+p+" = "+P+"["+m+"]; ":" for (var "+p+" in "+u+") { ",a+=" var startErrs"+s+" = errors; ";var b=p,S=e.compositeRule;e.compositeRule=d.compositeRule=!0;var j=e.validate(d);d.baseId=w,e.util.varOccurences(j,g)<2?a+=" "+e.util.varReplace(j,g,b)+" ":a+=" var "+g+" = "+b+"; "+j+" ",e.compositeRule=d.compositeRule=S,a+=" if (!"+f+") { for (var "+v+"=startErrs"+s+"; "+v+"=e.opts.loopRequired,b=e.opts.ownProperties;if(h)if(a+=" var missing"+s+"; ",w){d||(a+=" var "+f+" = validate.schema"+n+"; ");R="' + "+($="schema"+s+"["+(j="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),a+=" var "+c+" = true; ",d&&(a+=" if (schema"+s+" === undefined) "+c+" = true; else if (!Array.isArray(schema"+s+")) "+c+" = false; else {"),a+=" for (var "+j+" = 0; "+j+" < "+f+".length; "+j+"++) { "+c+" = "+u+"["+f+"["+j+"]] !== undefined ",b&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", "+f+"["+j+"]) "),a+="; if (!"+c+") break; } ",d&&(a+=" } "),a+=" if (!"+c+") { ";(x=x||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";F=a;a=x.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+F+"]); ":" validate.errors = ["+F+"]; return false; ":" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var S=p;if(S)for(var j=-1,_=S.length-1;j<_;){D=S[j+=1],j&&(a+=" || ");a+=" ( ( "+(q=u+(k=e.util.getProperty(D)))+" === undefined ",b&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(D)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?D:k)+") ) "}a+=") { ";R="' + "+($="missing"+s)+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,$,!0):E+" + "+$);var x=x||[];x.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var F=a;a=x.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+F+"]); ":" validate.errors = ["+F+"]; return false; ":" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(w){d||(a+=" var "+f+" = validate.schema"+n+"; ");var $="schema"+s+"["+(j="i"+s)+"]",R="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),d&&(a+=" if ("+f+" && !Array.isArray("+f+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+f+" !== undefined) { "),a+=" for (var "+j+" = 0; "+j+" < "+f+".length; "+j+"++) { if ("+u+"["+f+"["+j+"]] === undefined ",b&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", "+f+"["+j+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(a+=" } ")}else{var O=p;if(O)for(var D,I=-1,A=O.length-1;I 1) { var i = "+c+".length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal("+c+"[i], "+c+"[j])) { "+d+" = false; break outer; } } } } ",f&&(s+=" } "),s+=" if (!"+d+") { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=f?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;s=p.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { ")}else u&&(s+=" if (true) { ");return s}},{}],35:[function(e,r,t){"use strict";r.exports=function(e,r,t){function a(e){for(var r=e.rules,t=0;t2&&(r=n.call(arguments,1)),t(r)})})}.call(this,e):Array.isArray(e)?function(e){return Promise.all(e.map(s,this))}.call(this,e):function(e){return Object==e.constructor}(e)?function(e){for(var r=new e.constructor,t=Object.keys(e),a=[],i=0;i1&&(a=t[0]+"@",e=t[1]);return a+o((e=e.replace(O,".")).split("."),r).join(".")}function n(e){for(var r,t,a=[],s=0,o=e.length;s=55296&&r<=56319&&s65535&&(r+=k((e-=65536)>>>10&1023|55296),e=56320|1023&e),r+=k(e)}).join("")}function h(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:E}function u(e,r){return e+22+75*(e<26)-((0!=r)<<5)}function c(e,r,t){var a=0;for(e=t?A(e/j):e>>1,e+=A(e/r);e>I*b>>1;a+=E)e=A(e/I);return A(a+(I+1)*e/(e+S))}function d(e){var r,t,a,o,i,n,u,d,f,p,m=[],v=e.length,y=0,g=x,S=_;for((t=e.lastIndexOf(F))<0&&(t=0),a=0;a=128&&s("not-basic"),m.push(e.charCodeAt(a));for(o=t>0?t+1:0;o=v&&s("invalid-input"),((d=h(e.charCodeAt(o++)))>=E||d>A((P-y)/n))&&s("overflow"),y+=d*n,f=u<=S?w:u>=S+b?b:u-S,!(dA(P/(p=E-f))&&s("overflow"),n*=p;S=c(y-i,r=m.length+1,0==i),A(y/r)>P-g&&s("overflow"),g+=A(y/r),y%=r,m.splice(y++,0,g)}return l(m)}function f(e){var r,t,a,o,i,l,h,d,f,p,m,v,y,g,S,j=[];for(v=(e=n(e)).length,r=x,t=0,i=_,l=0;l=r&&mA((P-t)/(y=a+1))&&s("overflow"),t+=(h-r)*y,r=h,l=0;lP&&s("overflow"),m==r){for(d=t,f=E;p=f<=i?w:f>=i+b?b:f-i,!(d= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=E-w,A=Math.floor,k=String.fromCharCode;if(y={version:"1.4.1",ucs2:{decode:n,encode:l},decode:d,encode:f,toASCII:function(e){return i(e,function(e){return R.test(e)?"xn--"+f(e):e})},toUnicode:function(e){return i(e,function(e){return $.test(e)?d(e.slice(4).toLowerCase()):e})}},p&&m)if(r.exports==p)m.exports=y;else for(g in y)y.hasOwnProperty(g)&&(p[g]=y[g]);else a.punycode=y}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],45:[function(e,r,t){"use strict";function a(e,r){return Object.prototype.hasOwnProperty.call(e,r)}r.exports=function(e,r,t,o){r=r||"&",t=t||"=";var i={};if("string"!=typeof e||0===e.length)return i;var n=/\+/g;e=e.split(r);var l=1e3;o&&"number"==typeof o.maxKeys&&(l=o.maxKeys);var h=e.length;l>0&&h>l&&(h=l);for(var u=0;u=0?(c=m.substr(0,v),d=m.substr(v+1)):(c=m,d=""),f=decodeURIComponent(c),p=decodeURIComponent(d),a(i,f)?s(i[f])?i[f].push(p):i[f]=[i[f],p]:i[f]=p}return i};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],46:[function(e,r,t){"use strict";function a(e,r){if(e.map)return e.map(r);for(var t=[],a=0;a",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(u),d=["%","/","?",";","#"].concat(c),f=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},P=e("querystring");a.prototype.parse=function(e,r,t){if(!i.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var a=e.indexOf("?"),s=-1!==a&&a127?A+="x":A+=I[k];if(!A.match(p)){var L=O.slice(0,_),z=O.slice(_+1),C=I.match(m);C&&(L.push(C[1]),z.unshift(C[2])),z.length&&(u="/"+z.join(".")+u),this.hostname=L.join(".");break}}}this.hostname=this.hostname.length>255?"":this.hostname.toLowerCase(),R||(this.hostname=o.toASCII(this.hostname));T=this.port?":"+this.port:"";this.host=(this.hostname||"")+T,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==u[0]&&(u="/"+u))}if(!v[b])for(var _=0,D=c.length;_0)&&t.host.split("@"))&&(t.auth=$.shift(),t.host=t.hostname=$.shift())}return t.search=e.search,t.query=e.query,i.isNull(t.pathname)&&i.isNull(t.search)||(t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"")),t.href=t.format(),t}if(!E.length)return t.pathname=null,t.path=t.search?"/"+t.search:null,t.href=t.format(),t;for(var S=E.slice(-1)[0],j=(t.host||e.host||E.length>1)&&("."===S||".."===S)||""===S,_=0,x=E.length;x>=0;x--)"."===(S=E[x])?E.splice(x,1):".."===S?(E.splice(x,1),_++):_&&(E.splice(x,1),_--);if(!v&&!P)for(;_--;_)E.unshift("..");!v||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),j&&"/"!==E.join("/").substr(-1)&&E.push("");var F=""===E[0]||E[0]&&"/"===E[0].charAt(0);if(b){t.hostname=t.host=F?"":E.length?E.shift():"";var $=!!(t.host&&t.host.indexOf("@")>0)&&t.host.split("@");$&&(t.auth=$.shift(),t.host=t.hostname=$.shift())}return(v=v||t.host&&E.length)&&!F&&E.unshift(""),E.length?t.pathname=E.join("/"):(t.pathname=null,t.path=null),i.isNull(t.pathname)&&i.isNull(t.search)||(t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"")),t.auth=e.auth||t.auth,t.slashes=t.slashes||e.slashes,t.href=t.format(),t},a.prototype.parseHost=function(){var e=this.host,r=l.exec(e);r&&(":"!==(r=r[0])&&(this.port=r.substr(1)),e=e.substr(0,e.length-r.length)),e&&(this.hostname=e)}},{"./util":49,punycode:44,querystring:47}],49:[function(e,r,t){"use strict";r.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],ajv:[function(e,r,t){"use strict";function a(r){if(!(this instanceof a))return new a(r);r=this._opts=E.copy(r)||{},function(e){var r=e._opts.logger;if(!1===r)e.logger={log:u,warn:u,error:u};else{if(void 0===r&&(r=console),!("object"==typeof r&&r.log&&r.warn&&r.error))throw new Error("logger must implement log, warn and error methods");e.logger=r}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=v(r.format);var t=this._schemaUriFormat=this._formats["uri-reference"];this._schemaUriFormatFunc=function(e){return t.test(e)},this._cache=r.cache||new f,this._loadingSchemas={},this._compilations=[],this.RULES=y(),this._getId=function(e){switch(e.schemaId){case"$id":return n;case"id":return i;default:return l}}(r),r.loopRequired=r.loopRequired||1/0,"property"==r.errorDataPath&&(r._errorDataPathProperty=!0),void 0===r.serialize&&(r.serialize=m),this._metaOpts=function(e){for(var r=E.copy(e._opts),t=0;t<_.length;t++)delete r[_[t]];return r}(this),r.formats&&function(e){for(var r in e._opts.formats){e.addFormat(r,e._opts.formats[r])}}(this),function(r){var t;r._opts.$data&&(t=e("./refs/$data.json"),r.addMetaSchema(t,t.$id,!0));if(!1===r._opts.meta)return;var a=e("./refs/json-schema-draft-06.json");r._opts.$data&&(a=g(a,x));r.addMetaSchema(a,j,!0),r._refs["http://json-schema.org/schema"]=j}(this),"object"==typeof r.meta&&this.addMetaSchema(r.meta),function(e){var r=e._opts.schemas;if(!r)return;if(Array.isArray(r))e.addSchema(r);else for(var t in r)e.addSchema(r[t],t)}(this),r.patternGroups&&P(this)}function s(e,r){return r=d.normalizeId(r),e._schemas[r]||e._refs[r]||e._fragments[r]}function o(e,r,t){for(var a in r){var s=r[a];s.meta||t&&!t.test(a)||(e._cache.del(s.cacheKey),delete r[a])}}function i(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function n(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function l(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function h(e,r){if(e._schemas[r]||e._refs[r])throw new Error('schema with key or id "'+r+'" already exists')}function u(){}var c=e("./compile"),d=e("./compile/resolve"),f=e("./cache"),p=e("./compile/schema_obj"),m=e("fast-json-stable-stringify"),v=e("./compile/formats"),y=e("./compile/rules"),g=e("./$data"),P=e("./patternGroups"),E=e("./compile/util"),w=e("co");r.exports=a,a.prototype.validate=function(e,r){var t;if("string"==typeof e){if(!(t=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);t=a.validate||this._compile(a)}var s=t(r);return!0===t.$async?"*"==this._opts.async?w(s):s:(this.errors=t.errors,s)},a.prototype.compile=function(e,r){var t=this._addSchema(e,void 0,r);return t.validate||this._compile(t)},a.prototype.addSchema=function(e,r,t,a){if(!Array.isArray(e)){var s=this._getId(e);if(void 0!==s&&"string"!=typeof s)throw new Error("schema id must be string");return r=d.normalizeId(r||s),h(this,r),this._schemas[r]=this._addSchema(e,t,a,!0),this}for(var o=0;o=t}function i(e,t,n){var r=t.input.slice(t.start);return n&&(r=r.replace(l,"$1 $3")),e.test(r)}function s(e,t,n,r){var i=new e.constructor(e.options,e.input,t);if(n)for(var s in n)i[s]=n[s];var o=e,a=i;return["inFunction","inAsyncFunction","inAsync","inGenerator","inModule"].forEach(function(e){e in o&&(a[e]=o[e])}),r&&(i.options.preserveParens=!0),i.nextToken(),i}var o={},a=/^async[\t ]+(return|throw)/,u=/^async[\t ]+function/,c=/^\s*[():;]/,l=/([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g,p=/\s*(get|set)\s*\(/;t.exports=function(e,t){var n=function(){};e.extend("initialContext",function(r){return function(){return this.options.ecmaVersion<7&&(n=function(t){e.raise(t.start,"async/await keywords only available when ecmaVersion>=7")}),this.reservedWords=new RegExp(this.reservedWords.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")),this.reservedWordsStrict=new RegExp(this.reservedWordsStrict.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")),this.reservedWordsStrictBind=new RegExp(this.reservedWordsStrictBind.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")),this.inAsyncFunction=t.inAsyncFunction,t.awaitAnywhere&&t.inAsyncFunction&&e.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive"),r.apply(this,arguments)}}),e.extend("shouldParseExportStatement",function(e){return function(){return!("name"!==this.type.label||"async"!==this.value||!i(u,this))||e.apply(this,arguments)}}),e.extend("parseStatement",function(e){return function(n,r){var s=this.start,o=this.startLoc;if("name"===this.type.label)if(i(u,this,!0)){var c=this.inAsyncFunction;try{return this.inAsyncFunction=!0,this.next(),(l=this.parseStatement(n,r)).async=!0,l.start=s,l.loc&&(l.loc.start=o),l.range&&(l.range[0]=s),l}finally{this.inAsyncFunction=c}}else if("object"==typeof t&&t.asyncExits&&i(a,this)){this.next();var l=this.parseStatement(n,r);return l.async=!0,l.start=s,l.loc&&(l.loc.start=o),l.range&&(l.range[0]=s),l}return e.apply(this,arguments)}}),e.extend("parseIdent",function(e){return function(t){var n=e.apply(this,arguments);return this.inAsyncFunction&&"await"===n.name&&0===arguments.length&&this.raise(n.start,"'await' is reserved within async functions"),n}}),e.extend("parseExprAtom",function(e){return function(i){var a,u=this.start,l=this.startLoc,p=e.apply(this,arguments);if("Identifier"===p.type)if("async"!==p.name||r(this,p.end)){if("await"===p.name){var h=this.startNodeAt(p.start,p.loc&&p.loc.start);if(this.inAsyncFunction)return a=this.parseExprSubscripts(),h.operator="await",h.argument=a,h=this.finishNodeAt(h,"AwaitExpression",a.end,a.loc&&a.loc.end),n(h),h;if(this.input.slice(p.end).match(c))return t.awaitAnywhere||"module"!==this.options.sourceType?p:this.raise(p.start,"'await' is reserved within modules");if("object"==typeof t&&t.awaitAnywhere&&(u=this.start,(a=s(this,u-4).parseExprSubscripts()).end<=u))return a=s(this,u).parseExprSubscripts(),h.operator="await",h.argument=a,h=this.finishNodeAt(h,"AwaitExpression",a.end,a.loc&&a.loc.end),this.pos=a.end,this.end=a.end,this.endLoc=a.endLoc,this.next(),n(h),h;if(!t.awaitAnywhere&&"module"===this.options.sourceType)return this.raise(p.start,"'await' is reserved within modules")}}else{var f=this.inAsyncFunction;try{this.inAsyncFunction=!0;var d=this,y=!1,m={parseFunctionBody:function(e,t){try{var n=y;return y=!0,d.parseFunctionBody.apply(this,arguments)}finally{y=n}},raise:function(){try{return d.raise.apply(this,arguments)}catch(e){throw y?e:o}}};if("SequenceExpression"===(a=s(this,this.start,m,!0).parseExpression()).type&&(a=a.expressions[0]),"CallExpression"===a.type&&(a=a.callee),"FunctionExpression"===a.type||"FunctionDeclaration"===a.type||"ArrowFunctionExpression"===a.type)return"SequenceExpression"===(a=s(this,this.start,m).parseExpression()).type&&(a=a.expressions[0]),"CallExpression"===a.type&&(a=a.callee),a.async=!0,a.start=u,a.loc&&(a.loc.start=l),a.range&&(a.range[0]=u),this.pos=a.end,this.end=a.end,this.endLoc=a.endLoc,this.next(),n(a),a}catch(e){if(e!==o)throw e}finally{this.inAsyncFunction=f}}return p}}),e.extend("finishNodeAt",function(e){return function(t,n,r,i){return t.__asyncValue&&(delete t.__asyncValue,t.value.async=!0),e.apply(this,arguments)}}),e.extend("finishNode",function(e){return function(t,n){return t.__asyncValue&&(delete t.__asyncValue,t.value.async=!0),e.apply(this,arguments)}}),e.extend("parsePropertyName",function(e){return function(t){t.key&&t.key.name;var i=e.apply(this,arguments);return"Identifier"!==i.type||"async"!==i.name||r(this,i.end)||this.input.slice(i.end).match(c)||(p.test(this.input.slice(i.end))?(i=e.apply(this,arguments),t.__asyncValue=!0):(n(t),"set"===t.kind&&this.raise(i.start,"'set (value)' cannot be be async"),"Identifier"===(i=e.apply(this,arguments)).type&&"set"===i.name&&this.raise(i.start,"'set (value)' cannot be be async"),t.__asyncValue=!0)),i}}),e.extend("parseClassMethod",function(e){return function(t,n,r){var i;n.__asyncValue&&("constructor"===n.kind&&this.raise(n.start,"class constructor() cannot be be async"),i=this.inAsyncFunction,this.inAsyncFunction=!0);var s=e.apply(this,arguments);return this.inAsyncFunction=i,s}}),e.extend("parseMethod",function(e){return function(t){var n;this.__currentProperty&&this.__currentProperty.__asyncValue&&(n=this.inAsyncFunction,this.inAsyncFunction=!0);var r=e.apply(this,arguments);return this.inAsyncFunction=n,r}}),e.extend("parsePropertyValue",function(e){return function(t,n,r,i,s,o){var a=this.__currentProperty;this.__currentProperty=t;var u;t.__asyncValue&&(u=this.inAsyncFunction,this.inAsyncFunction=!0);var c=e.apply(this,arguments);return this.inAsyncFunction=u,this.__currentProperty=a,c}})}},{}],3:[function(e,t,n){function r(e,t,n){var r=new e.constructor(e.options,e.input,t);if(n)for(var i in n)r[i]=n[i];var s=e,o=r;return["inFunction","inAsync","inGenerator","inModule"].forEach(function(e){e in s&&(o[e]=s[e])}),r.nextToken(),r}var i=/^async[\t ]+(return|throw)/,s=/^\s*[):;]/,o=/([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g;t.exports=function(e,t){t&&"object"==typeof t||(t={}),e.extend("parse",function(n){return function(){return this.inAsync=t.inAsyncFunction,t.awaitAnywhere&&t.inAsyncFunction&&e.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive"),n.apply(this,arguments)}}),e.extend("parseStatement",function(e){return function(n,r){var s=this.start,a=this.startLoc;if("name"===this.type.label&&t.asyncExits&&function(e,t,n){var r=t.input.slice(t.start);return n&&(r=r.replace(o,"$1 $3")),e.test(r)}(i,this)){this.next();var u=this.parseStatement(n,r);return u.async=!0,u.start=s,u.loc&&(u.loc.start=a),u.range&&(u.range[0]=s),u}return e.apply(this,arguments)}}),e.extend("parseIdent",function(e){return function(n){return"module"===this.options.sourceType&&this.options.ecmaVersion>=8&&t.awaitAnywhere?e.call(this,!0):e.apply(this,arguments)}}),e.extend("parseExprAtom",function(e){var n={};return function(i){var s,o=this.start,a=(this.startLoc,e.apply(this,arguments));if("Identifier"===a.type&&"await"===a.name&&!this.inAsync&&t.awaitAnywhere){var u=this.startNodeAt(a.start,a.loc&&a.loc.start);o=this.start;var c={raise:function(){try{return pp.raise.apply(this,arguments)}catch(e){throw n}}};try{if((s=r(this,o-4,c).parseExprSubscripts()).end<=o)return s=r(this,o,c).parseExprSubscripts(),u.argument=s,u=this.finishNodeAt(u,"AwaitExpression",s.end,s.loc&&s.loc.end),this.pos=s.end,this.end=s.end,this.endLoc=s.endLoc,this.next(),u}catch(e){if(e===n)return a;throw e}}return a}});var n={undefined:!0,get:!0,set:!0,static:!0,async:!0,constructor:!0};e.extend("parsePropertyName",function(e){return function(t){var r=t.key&&t.key.name,i=e.apply(this,arguments);return"get"===this.value&&(t.__maybeStaticAsyncGetter=!0),n[this.value]?i:("Identifier"!==i.type||"async"!==i.name&&"async"!==r||function(e,t){return e.lineStart>=t}(this,i.end)||this.input.slice(i.end).match(s)?delete t.__maybeStaticAsyncGetter:"set"===t.kind||"set"===i.name?this.raise(i.start,"'set (value)' cannot be be async"):(this.__isAsyncProp=!0,"Identifier"===(i=e.apply(this,arguments)).type&&"set"===i.name&&this.raise(i.start,"'set (value)' cannot be be async")),i)}}),e.extend("parseClassMethod",function(e){return function(t,n,r){var i=e.apply(this,arguments);return n.__maybeStaticAsyncGetter&&(delete n.__maybeStaticAsyncGetter,"get"!==n.key.name&&(n.kind="get")),i}}),e.extend("parseFunctionBody",function(e){return function(t,n){var r=this.inAsync;this.__isAsyncProp&&(t.async=!0,this.inAsync=!0,delete this.__isAsyncProp);var i=e.apply(this,arguments);return this.inAsync=r,i}})}},{}],4:[function(e,t,n){!function(e,r){"object"==typeof n&&void 0!==t?r(n):"function"==typeof define&&define.amd?define(["exports"],r):r(e.acorn=e.acorn||{})}(this,function(e){"use strict";function t(e,t){for(var n=65536,r=0;re)return!1;if((n+=t[r+1])>=e)return!0}}function n(e,n){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&x.test(String.fromCharCode(e)):!1!==n&&t(e,E)))}function r(e,n){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&w.test(String.fromCharCode(e)):!1!==n&&(t(e,E)||t(e,S)))))}function i(e,t){return new k(e,{beforeExpr:!0,binop:t})}function s(e,t){return void 0===t&&(t={}),t.keyword=e,_[e]=new k(e,t)}function o(e){return 10===e||13===e||8232===e||8233===e}function a(e,t){return $.call(e,t)}function u(e,t){for(var n=1,r=0;;){T.lastIndex=r;var i=T.exec(e);if(!(i&&i.index=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),R(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return R(t.onComment)&&(t.onComment=function(e,t){return function(n,r,i,s,o,a){var u={type:n?"Block":"Line",value:r,start:i,end:s};e.locations&&(u.loc=new j(this,o,a)),e.ranges&&(u.range=[i,s]),t.push(u)}}(t,t.onComment)),t}function l(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}function p(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=-1}function h(e,t,n,r){return e.type=t,e.end=n,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=n),e}function f(e,t,n,r){try{return new RegExp(e,t)}catch(e){if(void 0!==n)throw e instanceof SyntaxError&&r.raise(n,"Error parsing regular expression: "+e.message),e}}function d(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10),56320+(1023&e)))}var y={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"},m="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",g={5:m,6:m+" const class extends export import super"},v="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿕ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",b="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",x=new RegExp("["+v+"]"),w=new RegExp("["+v+b+"]");v=b=null;var E=[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],S=[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],k=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null},A={beforeExpr:!0},C={startsExpr:!0},_={},L={num:new k("num",C),regexp:new k("regexp",C),string:new k("string",C),name:new k("name",C),eof:new k("eof"),bracketL:new k("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new k("]"),braceL:new k("{",{beforeExpr:!0,startsExpr:!0}),braceR:new k("}"),parenL:new k("(",{beforeExpr:!0,startsExpr:!0}),parenR:new k(")"),comma:new k(",",A),semi:new k(";",A),colon:new k(":",A),dot:new k("."),question:new k("?",A),arrow:new k("=>",A),template:new k("template"),invalidTemplate:new k("invalidTemplate"),ellipsis:new k("...",A),backQuote:new k("`",C),dollarBraceL:new k("${",{beforeExpr:!0,startsExpr:!0}),eq:new k("=",{beforeExpr:!0,isAssign:!0}),assign:new k("_=",{beforeExpr:!0,isAssign:!0}),incDec:new k("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new k("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:i("||",1),logicalAND:i("&&",2),bitwiseOR:i("|",3),bitwiseXOR:i("^",4),bitwiseAND:i("&",5),equality:i("==/!=/===/!==",6),relational:i("/<=/>=",7),bitShift:i("<>/>>>",8),plusMin:new k("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:i("%",10),star:i("*",10),slash:i("/",10),starstar:new k("**",{beforeExpr:!0}),_break:s("break"),_case:s("case",A),_catch:s("catch"),_continue:s("continue"),_debugger:s("debugger"),_default:s("default",A),_do:s("do",{isLoop:!0,beforeExpr:!0}),_else:s("else",A),_finally:s("finally"),_for:s("for",{isLoop:!0}),_function:s("function",C),_if:s("if"),_return:s("return",A),_switch:s("switch"),_throw:s("throw",A),_try:s("try"),_var:s("var"),_const:s("const"),_while:s("while",{isLoop:!0}),_with:s("with"),_new:s("new",{beforeExpr:!0,startsExpr:!0}),_this:s("this",C),_super:s("super",C),_class:s("class",C),_extends:s("extends",A),_export:s("export"),_import:s("import"),_null:s("null",C),_true:s("true",C),_false:s("false",C),_in:s("in",{beforeExpr:!0,binop:7}),_instanceof:s("instanceof",{beforeExpr:!0,binop:7}),_typeof:s("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:s("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:s("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},O=/\r\n?|\n|\u2028|\u2029/,T=new RegExp(O.source,"g"),N=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,P=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,F=Object.prototype,$=F.hasOwnProperty,B=F.toString,R=Array.isArray||function(e){return"[object Array]"===B.call(e)},I=function(e,t){this.line=e,this.column=t};I.prototype.offset=function(e){return new I(this.line,this.column+e)};var j=function(e,t,n){this.start=t,this.end=n,null!==e.sourceFile&&(this.source=e.sourceFile)},D={ecmaVersion:7,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowHashBang:!1,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1,plugins:{}},M={},q=function(e,t,n){this.options=e=c(e),this.sourceFile=e.sourceFile,this.keywords=l(g[e.ecmaVersion>=6?6:5]);var r="";if(!e.allowReserved){for(var i=e.ecmaVersion;!(r=y[i]);i--);"module"==e.sourceType&&(r+=" await")}this.reservedWords=l(r);var s=(r?r+" ":"")+y.strict;this.reservedWordsStrict=l(s),this.reservedWordsStrictBind=l(s+" "+y.strictBind),this.input=String(t),this.containsEsc=!1,this.loadPlugins(e.plugins),n?(this.pos=n,this.lineStart=this.input.lastIndexOf("\n",n-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(O).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=L.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.inFunction=this.inGenerator=this.inAsync=!1,this.yieldPos=this.awaitPos=0,this.labels=[],0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterFunctionScope()};q.prototype.isKeyword=function(e){return this.keywords.test(e)},q.prototype.isReservedWord=function(e){return this.reservedWords.test(e)},q.prototype.extend=function(e,t){this[e]=t(this[e])},q.prototype.loadPlugins=function(e){for(var t in e){var n=M[t];if(!n)throw new Error("Plugin '"+t+"' not found");n(this,e[t])}},q.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)};var V=q.prototype,U=/^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;V.strictDirective=function(e){for(;;){P.lastIndex=e,e+=P.exec(this.input)[0].length;var t=U.exec(this.input.slice(e));if(!t)return!1;if("use strict"==(t[1]||t[2]))return!0;e+=t[0].length}},V.eat=function(e){return this.type===e&&(this.next(),!0)},V.isContextual=function(e){return this.type===L.name&&this.value===e},V.eatContextual=function(e){return this.value===e&&this.eat(L.name)},V.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},V.canInsertSemicolon=function(){return this.type===L.eof||this.type===L.braceR||O.test(this.input.slice(this.lastTokEnd,this.start))},V.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},V.semicolon=function(){this.eat(L.semi)||this.insertSemicolon()||this.unexpected()},V.afterTrailingComma=function(e,t){if(this.type==e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},V.expect=function(e){this.eat(e)||this.unexpected()},V.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")},V.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var n=t?e.parenthesizedAssign:e.parenthesizedBind;n>-1&&this.raiseRecoverable(n,"Parenthesized pattern")}},V.checkExpressionErrors=function(e,t){var n=e?e.shorthandAssign:-1;if(!t)return n>=0;n>-1&&this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")},V.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos=6&&(e.sourceType=this.options.sourceType),this.finishNode(e,"Program")};var W={kind:"loop"},G={kind:"switch"};z.isLet=function(){if(this.type!==L.name||this.options.ecmaVersion<6||"let"!=this.value)return!1;P.lastIndex=this.pos;var e=P.exec(this.input),t=this.pos+e[0].length,i=this.input.charCodeAt(t);if(91===i||123==i)return!0;if(n(i,!0)){for(var s=t+1;r(this.input.charCodeAt(s),!0);)++s;var o=this.input.slice(t,s);if(!this.isKeyword(o))return!0}return!1},z.isAsyncFunction=function(){if(this.type!==L.name||this.options.ecmaVersion<8||"async"!=this.value)return!1;P.lastIndex=this.pos;var e=P.exec(this.input),t=this.pos+e[0].length;return!(O.test(this.input.slice(this.pos,t))||"function"!==this.input.slice(t,t+8)||t+8!=this.input.length&&r(this.input.charAt(t+8)))},z.parseStatement=function(e,t,n){var r,i=this.type,s=this.startNode();switch(this.isLet()&&(i=L._var,r="let"),i){case L._break:case L._continue:return this.parseBreakContinueStatement(s,i.keyword);case L._debugger:return this.parseDebuggerStatement(s);case L._do:return this.parseDoStatement(s);case L._for:return this.parseForStatement(s);case L._function:return!e&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(s,!1);case L._class:return e||this.unexpected(),this.parseClass(s,!0);case L._if:return this.parseIfStatement(s);case L._return:return this.parseReturnStatement(s);case L._switch:return this.parseSwitchStatement(s);case L._throw:return this.parseThrowStatement(s);case L._try:return this.parseTryStatement(s);case L._const:case L._var:return r=r||this.value,e||"var"==r||this.unexpected(),this.parseVarStatement(s,r);case L._while:return this.parseWhileStatement(s);case L._with:return this.parseWithStatement(s);case L.braceL:return this.parseBlock();case L.semi:return this.parseEmptyStatement(s);case L._export:case L._import:return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),i===L._import?this.parseImport(s):this.parseExport(s,n);default:if(this.isAsyncFunction()&&e)return this.next(),this.parseFunctionStatement(s,!0);var o=this.value,a=this.parseExpression();return i===L.name&&"Identifier"===a.type&&this.eat(L.colon)?this.parseLabeledStatement(s,o,a):this.parseExpressionStatement(s,a)}},z.parseBreakContinueStatement=function(e,t){var n="break"==t;this.next(),this.eat(L.semi)||this.insertSemicolon()?e.label=null:this.type!==L.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(L.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},z.parseForStatement=function(e){if(this.next(),this.labels.push(W),this.enterLexicalScope(),this.expect(L.parenL),this.type===L.semi)return this.parseFor(e,null);var t=this.isLet();if(this.type===L._var||this.type===L._const||t){var n=this.startNode(),r=t?"let":this.value;return this.next(),this.parseVar(n,!0,r),this.finishNode(n,"VariableDeclaration"),!(this.type===L._in||this.options.ecmaVersion>=6&&this.isContextual("of"))||1!==n.declarations.length||"var"!==r&&n.declarations[0].init?this.parseFor(e,n):this.parseForIn(e,n)}var i=new p,s=this.parseExpression(!0,i);return this.type===L._in||this.options.ecmaVersion>=6&&this.isContextual("of")?(this.toAssignable(s),this.checkLVal(s),this.checkPatternErrors(i,!0),this.parseForIn(e,s)):(this.checkExpressionErrors(i,!0),this.parseFor(e,s))},z.parseFunctionStatement=function(e,t){return this.next(),this.parseFunction(e,!0,!1,t)},z.isFunction=function(){return this.type===L._function||this.isAsyncFunction()},z.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(!this.strict&&this.isFunction()),e.alternate=this.eat(L._else)?this.parseStatement(!this.strict&&this.isFunction()):null,this.finishNode(e,"IfStatement")},z.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(L.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},z.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(L.braceL),this.labels.push(G),this.enterLexicalScope();for(var t,n=!1;this.type!=L.braceR;)if(this.type===L._case||this.type===L._default){var r=this.type===L._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(n&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),n=!0,t.test=null),this.expect(L.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(!0));return this.exitLexicalScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},z.parseThrowStatement=function(e){return this.next(),O.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var J=[];z.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===L._catch){var t=this.startNode();this.next(),this.expect(L.parenL),t.param=this.parseBindingAtom(),this.enterLexicalScope(),this.checkLVal(t.param,"let"),this.expect(L.parenR),t.body=this.parseBlock(!1),this.exitLexicalScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(L._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},z.parseVarStatement=function(e,t){return this.next(),this.parseVar(e,!1,t),this.semicolon(),this.finishNode(e,"VariableDeclaration")},z.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(W),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"WhileStatement")},z.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement(!1),this.finishNode(e,"WithStatement")},z.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},z.parseLabeledStatement=function(e,t,n){for(var r=0,i=this.labels;r=0;o--){var a=this.labels[o];if(a.statementStart!=e.start)break;a.statementStart=this.start,a.kind=s}return this.labels.push({name:t,kind:s,statementStart:this.start}),e.body=this.parseStatement(!0),("ClassDeclaration"==e.body.type||"VariableDeclaration"==e.body.type&&"var"!=e.body.kind||"FunctionDeclaration"==e.body.type&&(this.strict||e.body.generator))&&this.raiseRecoverable(e.body.start,"Invalid labeled declaration"),this.labels.pop(),e.label=n,this.finishNode(e,"LabeledStatement")},z.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},z.parseBlock=function(e){void 0===e&&(e=!0);var t=this.startNode();for(t.body=[],this.expect(L.braceL),e&&this.enterLexicalScope();!this.eat(L.braceR);){var n=this.parseStatement(!0);t.body.push(n)}return e&&this.exitLexicalScope(),this.finishNode(t,"BlockStatement")},z.parseFor=function(e,t){return e.init=t,this.expect(L.semi),e.test=this.type===L.semi?null:this.parseExpression(),this.expect(L.semi),e.update=this.type===L.parenR?null:this.parseExpression(),this.expect(L.parenR),this.exitLexicalScope(),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"ForStatement")},z.parseForIn=function(e,t){var n=this.type===L._in?"ForInStatement":"ForOfStatement";return this.next(),e.left=t,e.right=this.parseExpression(),this.expect(L.parenR),this.exitLexicalScope(),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,n)},z.parseVar=function(e,t,n){for(e.declarations=[],e.kind=n;;){var r=this.startNode();if(this.parseVarId(r,n),this.eat(L.eq)?r.init=this.parseMaybeAssign(t):"const"!==n||this.type===L._in||this.options.ecmaVersion>=6&&this.isContextual("of")?"Identifier"==r.id.type||t&&(this.type===L._in||this.isContextual("of"))?r.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(r,"VariableDeclarator")),!this.eat(L.comma))break}return e},z.parseVarId=function(e,t){e.id=this.parseBindingAtom(t),this.checkLVal(e.id,t,!1)},z.parseFunction=function(e,t,n,r){this.initFunction(e),this.options.ecmaVersion>=6&&!r&&(e.generator=this.eat(L.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&&(e.id="nullableID"===t&&this.type!=L.name?null:this.parseIdent(),e.id&&this.checkLVal(e.id,"var"));var i=this.inGenerator,s=this.inAsync,o=this.yieldPos,a=this.awaitPos,u=this.inFunction;return this.inGenerator=e.generator,this.inAsync=e.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),t||(e.id=this.type==L.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,n),this.inGenerator=i,this.inAsync=s,this.yieldPos=o,this.awaitPos=a,this.inFunction=u,this.finishNode(e,t?"FunctionDeclaration":"FunctionExpression")},z.parseFunctionParams=function(e){this.expect(L.parenL),e.params=this.parseBindingList(L.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},z.parseClass=function(e,t){this.next(),this.parseClassId(e,t),this.parseClassSuper(e);var n=this.startNode(),r=!1;for(n.body=[],this.expect(L.braceL);!this.eat(L.braceR);)if(!this.eat(L.semi)){var i=this.startNode(),s=this.eat(L.star),o=!1,a=this.type===L.name&&"static"===this.value;this.parsePropertyName(i),i.static=a&&this.type!==L.parenL,i.static&&(s&&this.unexpected(),s=this.eat(L.star),this.parsePropertyName(i)),this.options.ecmaVersion>=8&&!s&&!i.computed&&"Identifier"===i.key.type&&"async"===i.key.name&&this.type!==L.parenL&&!this.canInsertSemicolon()&&(o=!0,this.parsePropertyName(i)),i.kind="method";var u=!1;if(!i.computed){var c=i.key;s||o||"Identifier"!==c.type||this.type===L.parenL||"get"!==c.name&&"set"!==c.name||(u=!0,i.kind=c.name,c=this.parsePropertyName(i)),!i.static&&("Identifier"===c.type&&"constructor"===c.name||"Literal"===c.type&&"constructor"===c.value)&&(r&&this.raise(c.start,"Duplicate constructor in the same class"),u&&this.raise(c.start,"Constructor can't have get/set modifier"),s&&this.raise(c.start,"Constructor can't be a generator"),o&&this.raise(c.start,"Constructor can't be an async method"),i.kind="constructor",r=!0)}if(this.parseClassMethod(n,i,s,o),u){var l="get"===i.kind?0:1;if(i.value.params.length!==l){var p=i.value.start;"get"===i.kind?this.raiseRecoverable(p,"getter should have no params"):this.raiseRecoverable(p,"setter should have exactly one param")}else"set"===i.kind&&"RestElement"===i.value.params[0].type&&this.raiseRecoverable(i.value.params[0].start,"Setter cannot use rest params")}}return e.body=this.finishNode(n,"ClassBody"),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},z.parseClassMethod=function(e,t,n,r){t.value=this.parseMethod(n,r),e.body.push(this.finishNode(t,"MethodDefinition"))},z.parseClassId=function(e,t){e.id=this.type===L.name?this.parseIdent():!0===t?this.unexpected():null},z.parseClassSuper=function(e){e.superClass=this.eat(L._extends)?this.parseExprSubscripts():null},z.parseExport=function(e,t){if(this.next(),this.eat(L.star))return this.expectContextual("from"),e.source=this.type===L.string?this.parseExprAtom():this.unexpected(),this.semicolon(),this.finishNode(e,"ExportAllDeclaration");if(this.eat(L._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===L._function||(n=this.isAsyncFunction())){var r=this.startNode();this.next(),n&&this.next(),e.declaration=this.parseFunction(r,"nullableID",!1,n)}else if(this.type===L._class){var i=this.startNode();e.declaration=this.parseClass(i,"nullableID")}else e.declaration=this.parseMaybeAssign(),this.semicolon();return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement())e.declaration=this.parseStatement(!0),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id.name,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))e.source=this.type===L.string?this.parseExprAtom():this.unexpected();else{for(var s=0,o=e.specifiers;s=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Can not use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":break;case"ObjectExpression":e.type="ObjectPattern";for(var n=0,r=e.properties;n=6&&(e.computed||e.method||e.shorthand))){var n,r=e.key;switch(r.type){case"Identifier":n=r.name;break;case"Literal":n=String(r.value);break;default:return}var i=e.kind;if(this.options.ecmaVersion>=6)"__proto__"===n&&"init"===i&&(t.proto&&this.raiseRecoverable(r.start,"Redefinition of __proto__ property"),t.proto=!0);else{var s=t[n="$"+n];if(s){("init"===i?this.strict&&s.init||s.get||s.set:s.init||s[i])&&this.raiseRecoverable(r.start,"Redefinition of property")}else s=t[n]={init:!1,get:!1,set:!1};s[i]=!0}}},Y.parseExpression=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeAssign(e,t);if(this.type===L.comma){var s=this.startNodeAt(n,r);for(s.expressions=[i];this.eat(L.comma);)s.expressions.push(this.parseMaybeAssign(e,t));return this.finishNode(s,"SequenceExpression")}return i},Y.parseMaybeAssign=function(e,t,n){if(this.inGenerator&&this.isContextual("yield"))return this.parseYield();var r=!1,i=-1,s=-1;t?(i=t.parenthesizedAssign,s=t.trailingComma,t.parenthesizedAssign=t.trailingComma=-1):(t=new p,r=!0);var o=this.start,a=this.startLoc;this.type!=L.parenL&&this.type!=L.name||(this.potentialArrowAt=this.start);var u=this.parseMaybeConditional(e,t);if(n&&(u=n.call(this,u,o,a)),this.type.isAssign){this.checkPatternErrors(t,!0),r||p.call(t);var c=this.startNodeAt(o,a);return c.operator=this.value,c.left=this.type===L.eq?this.toAssignable(u):u,t.shorthandAssign=-1,this.checkLVal(u),this.next(),c.right=this.parseMaybeAssign(e),this.finishNode(c,"AssignmentExpression")}return r&&this.checkExpressionErrors(t,!0),i>-1&&(t.parenthesizedAssign=i),s>-1&&(t.trailingComma=s),u},Y.parseMaybeConditional=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if(this.eat(L.question)){var s=this.startNodeAt(n,r);return s.test=i,s.consequent=this.parseMaybeAssign(),this.expect(L.colon),s.alternate=this.parseMaybeAssign(e),this.finishNode(s,"ConditionalExpression")}return i},Y.parseExprOps=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeUnary(t,!1);return this.checkExpressionErrors(t)?i:i.start==n&&"ArrowFunctionExpression"===i.type?i:this.parseExprOp(i,n,r,-1,e)},Y.parseExprOp=function(e,t,n,r,i){var s=this.type.binop;if(null!=s&&(!i||this.type!==L._in)&&s>r){var o=this.type===L.logicalOR||this.type===L.logicalAND,a=this.value;this.next();var u=this.start,c=this.startLoc,l=this.parseExprOp(this.parseMaybeUnary(null,!1),u,c,s,i),p=this.buildBinary(t,n,e,l,a,o);return this.parseExprOp(p,t,n,r,i)}return e},Y.buildBinary=function(e,t,n,r,i,s){var o=this.startNodeAt(e,t);return o.left=n,o.operator=i,o.right=r,this.finishNode(o,s?"LogicalExpression":"BinaryExpression")},Y.parseMaybeUnary=function(e,t){var n,r=this.start,i=this.startLoc;if(this.inAsync&&this.isContextual("await"))n=this.parseAwait(),t=!0;else if(this.type.prefix){var s=this.startNode(),o=this.type===L.incDec;s.operator=this.value,s.prefix=!0,this.next(),s.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(e,!0),o?this.checkLVal(s.argument):this.strict&&"delete"===s.operator&&"Identifier"===s.argument.type?this.raiseRecoverable(s.start,"Deleting local variable in strict mode"):t=!0,n=this.finishNode(s,o?"UpdateExpression":"UnaryExpression")}else{if(n=this.parseExprSubscripts(e),this.checkExpressionErrors(e))return n;for(;this.type.postfix&&!this.canInsertSemicolon();){var a=this.startNodeAt(r,i);a.operator=this.value,a.prefix=!1,a.argument=n,this.checkLVal(n),this.next(),n=this.finishNode(a,"UpdateExpression")}}return!t&&this.eat(L.starstar)?this.buildBinary(r,i,n,this.parseMaybeUnary(null,!1),"**",!1):n},Y.parseExprSubscripts=function(e){var t=this.start,n=this.startLoc,r=this.parseExprAtom(e),i="ArrowFunctionExpression"===r.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd);if(this.checkExpressionErrors(e)||i)return r;var s=this.parseSubscripts(r,t,n);return e&&"MemberExpression"===s.type&&(e.parenthesizedAssign>=s.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=s.start&&(e.parenthesizedBind=-1)),s},Y.parseSubscripts=function(e,t,n,r){for(var i=this.options.ecmaVersion>=8&&"Identifier"===e.type&&"async"===e.name&&this.lastTokEnd==e.end&&!this.canInsertSemicolon(),s=void 0;;)if((s=this.eat(L.bracketL))||this.eat(L.dot)){var o=this.startNodeAt(t,n);o.object=e,o.property=s?this.parseExpression():this.parseIdent(!0),o.computed=!!s,s&&this.expect(L.bracketR),e=this.finishNode(o,"MemberExpression")}else if(!r&&this.eat(L.parenL)){var a=new p,u=this.yieldPos,c=this.awaitPos;this.yieldPos=0,this.awaitPos=0;var l=this.parseExprList(L.parenR,this.options.ecmaVersion>=8,!1,a);if(i&&!this.canInsertSemicolon()&&this.eat(L.arrow))return this.checkPatternErrors(a,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=u,this.awaitPos=c,this.parseArrowExpression(this.startNodeAt(t,n),l,!0);this.checkExpressionErrors(a,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=c||this.awaitPos;var h=this.startNodeAt(t,n);h.callee=e,h.arguments=l,e=this.finishNode(h,"CallExpression")}else{if(this.type!==L.backQuote)return e;var f=this.startNodeAt(t,n);f.tag=e,f.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(f,"TaggedTemplateExpression")}},Y.parseExprAtom=function(e){var t,n=this.potentialArrowAt==this.start;switch(this.type){case L._super:return this.inFunction||this.raise(this.start,"'super' outside of function or class"),t=this.startNode(),this.next(),this.type!==L.dot&&this.type!==L.bracketL&&this.type!==L.parenL&&this.unexpected(),this.finishNode(t,"Super");case L._this:return t=this.startNode(),this.next(),this.finishNode(t,"ThisExpression");case L.name:var r=this.start,i=this.startLoc,s=this.parseIdent(this.type!==L.name);if(this.options.ecmaVersion>=8&&"async"===s.name&&!this.canInsertSemicolon()&&this.eat(L._function))return this.parseFunction(this.startNodeAt(r,i),!1,!1,!0);if(n&&!this.canInsertSemicolon()){if(this.eat(L.arrow))return this.parseArrowExpression(this.startNodeAt(r,i),[s],!1);if(this.options.ecmaVersion>=8&&"async"===s.name&&this.type===L.name)return s=this.parseIdent(),!this.canInsertSemicolon()&&this.eat(L.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(r,i),[s],!0)}return s;case L.regexp:var o=this.value;return t=this.parseLiteral(o.value),t.regex={pattern:o.pattern,flags:o.flags},t;case L.num:case L.string:return this.parseLiteral(this.value);case L._null:case L._true:case L._false:return t=this.startNode(),t.value=this.type===L._null?null:this.type===L._true,t.raw=this.type.keyword,this.next(),this.finishNode(t,"Literal");case L.parenL:var a=this.start,u=this.parseParenAndDistinguishExpression(n);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(u)&&(e.parenthesizedAssign=a),e.parenthesizedBind<0&&(e.parenthesizedBind=a)),u;case L.bracketL:return t=this.startNode(),this.next(),t.elements=this.parseExprList(L.bracketR,!0,!0,e),this.finishNode(t,"ArrayExpression");case L.braceL:return this.parseObj(!1,e);case L._function:return t=this.startNode(),this.next(),this.parseFunction(t,!1);case L._class:return this.parseClass(this.startNode(),!1);case L._new:return this.parseNew();case L.backQuote:return this.parseTemplate();default:this.unexpected()}},Y.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),this.next(),this.finishNode(t,"Literal")},Y.parseParenExpression=function(){this.expect(L.parenL);var e=this.parseExpression();return this.expect(L.parenR),e},Y.parseParenAndDistinguishExpression=function(e){var t,n=this.start,r=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var s,o,a=this.start,u=this.startLoc,c=[],l=!0,h=!1,f=new p,d=this.yieldPos,y=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==L.parenR;){if(l?l=!1:this.expect(L.comma),i&&this.afterTrailingComma(L.parenR,!0)){h=!0;break}if(this.type===L.ellipsis){s=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===L.comma&&this.raise(this.start,"Comma is not permitted after the rest element");break}this.type!==L.parenL||o||(o=this.start),c.push(this.parseMaybeAssign(!1,f,this.parseParenItem))}var m=this.start,g=this.startLoc;if(this.expect(L.parenR),e&&!this.canInsertSemicolon()&&this.eat(L.arrow))return this.checkPatternErrors(f,!1),this.checkYieldAwaitInDefaultParams(),o&&this.unexpected(o),this.yieldPos=d,this.awaitPos=y,this.parseParenArrowList(n,r,c);c.length&&!h||this.unexpected(this.lastTokStart),s&&this.unexpected(s),this.checkExpressionErrors(f,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=y||this.awaitPos,c.length>1?((t=this.startNodeAt(a,u)).expressions=c,this.finishNodeAt(t,"SequenceExpression",m,g)):t=c[0]}else t=this.parseParenExpression();if(this.options.preserveParens){var v=this.startNodeAt(n,r);return v.expression=t,this.finishNode(v,"ParenthesizedExpression")}return t},Y.parseParenItem=function(e){return e},Y.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e,t),n)};var Z=[];Y.parseNew=function(){var e=this.startNode(),t=this.parseIdent(!0);if(this.options.ecmaVersion>=6&&this.eat(L.dot))return e.meta=t,e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is new.target"),this.inFunction||this.raiseRecoverable(e.start,"new.target can only be used in functions"),this.finishNode(e,"MetaProperty");var n=this.start,r=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(),n,r,!0),this.eat(L.parenL)?e.arguments=this.parseExprList(L.parenR,this.options.ecmaVersion>=8,!1):e.arguments=Z,this.finishNode(e,"NewExpression")},Y.parseTemplateElement=function(e){var t=e.isTagged,n=this.startNode();return this.type===L.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),n.value={raw:this.value,cooked:null}):n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),n.tail=this.type===L.backQuote,this.finishNode(n,"TemplateElement")},Y.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var n=this.startNode();this.next(),n.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(n.quasis=[r];!r.tail;)this.expect(L.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(L.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(n,"TemplateLiteral")},Y.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===L.name||this.type===L.num||this.type===L.string||this.type===L.bracketL||this.type.keyword)&&!O.test(this.input.slice(this.lastTokEnd,this.start))},Y.parseObj=function(e,t){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(L.braceR);){if(r)r=!1;else if(this.expect(L.comma),this.afterTrailingComma(L.braceR))break;var s=this.parseProperty(e,t);this.checkPropClash(s,i),n.properties.push(s)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")},Y.parseProperty=function(e,t){var n,r,i,s,o=this.startNode();return this.options.ecmaVersion>=6&&(o.method=!1,o.shorthand=!1,(e||t)&&(i=this.start,s=this.startLoc),e||(n=this.eat(L.star))),this.parsePropertyName(o),!e&&this.options.ecmaVersion>=8&&!n&&this.isAsyncProp(o)?(r=!0,this.parsePropertyName(o,t)):r=!1,this.parsePropertyValue(o,e,n,r,i,s,t),this.finishNode(o,"Property")},Y.parsePropertyValue=function(e,t,n,r,i,s,o){if((n||r)&&this.type===L.colon&&this.unexpected(),this.eat(L.colon))e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind="init";else if(this.options.ecmaVersion>=6&&this.type===L.parenL)t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(n,r);else if(t||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type==L.comma||this.type==L.braceR)this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?(this.checkUnreserved(e.key),e.kind="init",t?e.value=this.parseMaybeDefault(i,s,e.key):this.type===L.eq&&o?(o.shorthandAssign<0&&(o.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,s,e.key)):e.value=e.key,e.shorthand=!0):this.unexpected();else{(n||r)&&this.unexpected(),e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var a="get"===e.kind?0:1;if(e.value.params.length!==a){var u=e.value.start;"get"===e.kind?this.raiseRecoverable(u,"getter should have no params"):this.raiseRecoverable(u,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}},Y.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(L.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(L.bracketR),e.key;e.computed=!1}return e.key=this.type===L.num||this.type===L.string?this.parseExprAtom():this.parseIdent(!0)},Y.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=!1,e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},Y.parseMethod=function(e,t){var n=this.startNode(),r=this.inGenerator,i=this.inAsync,s=this.yieldPos,o=this.awaitPos,a=this.inFunction;return this.initFunction(n),this.options.ecmaVersion>=6&&(n.generator=e),this.options.ecmaVersion>=8&&(n.async=!!t),this.inGenerator=n.generator,this.inAsync=n.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),this.expect(L.parenL),n.params=this.parseBindingList(L.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(n,!1),this.inGenerator=r,this.inAsync=i,this.yieldPos=s,this.awaitPos=o,this.inFunction=a,this.finishNode(n,"FunctionExpression")},Y.parseArrowExpression=function(e,t,n){var r=this.inGenerator,i=this.inAsync,s=this.yieldPos,o=this.awaitPos,a=this.inFunction;return this.enterFunctionScope(),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!n),this.inGenerator=!1,this.inAsync=e.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0),this.inGenerator=r,this.inAsync=i,this.yieldPos=s,this.awaitPos=o,this.inFunction=a,this.finishNode(e,"ArrowFunctionExpression")},Y.parseFunctionBody=function(e,t){var n=t&&this.type!==L.braceL,r=this.strict,i=!1;if(n)e.body=this.parseMaybeAssign(),e.expression=!0,this.checkParams(e,!1);else{var s=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);r&&!s||(i=this.strictDirective(this.end))&&s&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var o=this.labels;this.labels=[],i&&(this.strict=!0),this.checkParams(e,!r&&!i&&!t&&this.isSimpleParamList(e.params)),e.body=this.parseBlock(!1),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=o}this.exitFunctionScope(),this.strict&&e.id&&this.checkLVal(e.id,"none"),this.strict=r},Y.isSimpleParamList=function(e){for(var t=0,n=e;t0;)t[n]=arguments[n+1];for(var r=0,i=t;r=1;e--){var t=this.context[e];if("function"===t.token)return t.generator}return!1},ie.updateContext=function(e){var t,n=this.type;n.keyword&&e==L.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},L.parenR.updateContext=L.braceR.updateContext=function(){if(1!=this.context.length){var e=this.context.pop();e===re.b_stat&&"function"===this.curContext().token&&(e=this.context.pop()),this.exprAllowed=!e.isExpr}else this.exprAllowed=!0},L.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?re.b_stat:re.b_expr),this.exprAllowed=!0},L.dollarBraceL.updateContext=function(){this.context.push(re.b_tmpl),this.exprAllowed=!0},L.parenL.updateContext=function(e){var t=e===L._if||e===L._for||e===L._with||e===L._while;this.context.push(t?re.p_stat:re.p_expr),this.exprAllowed=!0},L.incDec.updateContext=function(){},L._function.updateContext=L._class.updateContext=function(e){e.beforeExpr&&e!==L.semi&&e!==L._else&&(e!==L.colon&&e!==L.braceL||this.curContext()!==re.b_stat)?this.context.push(re.f_expr):this.context.push(re.f_stat),this.exprAllowed=!1},L.backQuote.updateContext=function(){this.curContext()===re.q_tmpl?this.context.pop():this.context.push(re.q_tmpl),this.exprAllowed=!1},L.star.updateContext=function(e){if(e==L._function){var t=this.context.length-1;this.context[t]===re.f_expr?this.context[t]=re.f_expr_gen:this.context[t]=re.f_gen}this.exprAllowed=!0},L.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&("of"==this.value&&!this.exprAllowed||"yield"==this.value&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var se=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new j(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},oe=q.prototype,ae="object"==typeof Packages&&"[object JavaPackage]"==Object.prototype.toString.call(Packages);oe.next=function(){this.options.onToken&&this.options.onToken(new se(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},oe.getToken=function(){return this.next(),new se(this)},"undefined"!=typeof Symbol&&(oe[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===L.eof,value:t}}}}),oe.curContext=function(){return this.context[this.context.length-1]},oe.nextToken=function(){var e=this.curContext();return e&&e.preserveSpace||this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length?this.finishToken(L.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},oe.readToken=function(e){return n(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},oe.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=57344)return e;return(e<<10)+this.input.charCodeAt(this.pos+1)-56613888},oe.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(-1===n&&this.raise(this.pos-2,"Unterminated comment"),this.pos=n+2,this.options.locations){T.lastIndex=t;for(var r;(r=T.exec(this.input))&&r.index8&&e<14||e>=5760&&N.test(String.fromCharCode(e))))break e;++this.pos}}},oe.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var n=this.type;this.type=e,this.value=t,this.updateContext(n)},oe.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(L.ellipsis)):(++this.pos,this.finishToken(L.dot))},oe.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(L.assign,2):this.finishOp(L.slash,1)},oe.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),n=1,r=42===e?L.star:L.modulo;return this.options.ecmaVersion>=7&&42==e&&42===t&&(++n,r=L.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(L.assign,n+1):this.finishOp(r,n)},oe.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.finishOp(124===e?L.logicalOR:L.logicalAND,2):61===t?this.finishOp(L.assign,2):this.finishOp(124===e?L.bitwiseOR:L.bitwiseAND,1)},oe.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(L.assign,2):this.finishOp(L.bitwiseXOR,1)},oe.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!=t||this.inModule||62!=this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!O.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(L.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(L.assign,2):this.finishOp(L.plusMin,1)},oe.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),n=1;return t===e?(n=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+n)?this.finishOp(L.assign,n+1):this.finishOp(L.bitShift,n)):33!=t||60!=e||this.inModule||45!=this.input.charCodeAt(this.pos+2)||45!=this.input.charCodeAt(this.pos+3)?(61===t&&(n=2),this.finishOp(L.relational,n)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},oe.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(L.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(L.arrow)):this.finishOp(61===e?L.eq:L.prefix,1)},oe.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(L.parenL);case 41:return++this.pos,this.finishToken(L.parenR);case 59:return++this.pos,this.finishToken(L.semi);case 44:return++this.pos,this.finishToken(L.comma);case 91:return++this.pos,this.finishToken(L.bracketL);case 93:return++this.pos,this.finishToken(L.bracketR);case 123:return++this.pos,this.finishToken(L.braceL);case 125:return++this.pos,this.finishToken(L.braceR);case 58:return++this.pos,this.finishToken(L.colon);case 63:return++this.pos,this.finishToken(L.question);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(L.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 126:return this.finishOp(L.prefix,1)}this.raise(this.pos,"Unexpected character '"+d(e)+"'")},oe.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)};var ue=!!f("￿","u");oe.readRegexp=function(){for(var e,t,n=this,r=this.pos;;){n.pos>=n.input.length&&n.raise(r,"Unterminated regular expression");var i=n.input.charAt(n.pos);if(O.test(i)&&n.raise(r,"Unterminated regular expression"),e)e=!1;else{if("["===i)t=!0;else if("]"===i&&t)t=!1;else if("/"===i&&!t)break;e="\\"===i}++n.pos}var s=this.input.slice(r,this.pos);++this.pos;var o=this.readWord1(),a=s,u="";if(o){var c=/^[gim]*$/;this.options.ecmaVersion>=6&&(c=/^[gimuy]*$/),c.test(o)||this.raise(r,"Invalid regular expression flag"),o.indexOf("u")>=0&&(ue?u="u":(a=(a=a.replace(/\\u\{([0-9a-fA-F]+)\}/g,function(e,t,i){return(t=Number("0x"+t))>1114111&&n.raise(r+i+3,"Code point out of bounds"),"x"})).replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x"),u=u.replace("u","")))}var l=null;return ae||(f(a,u,r,this),l=f(s,o)),this.finishToken(L.regexp,{pattern:s,flags:o,value:l})},oe.readInt=function(e,t){for(var n=this.pos,r=0,i=0,s=null==t?1/0:t;i=97?o-97+10:o>=65?o-65+10:o>=48&&o<=57?o-48:1/0)>=e)break;++this.pos,r=r*e+a}return this.pos===n||null!=t&&this.pos-n!==t?null:r},oe.readRadixNumber=function(e){this.pos+=2;var t=this.readInt(e);return null==t&&this.raise(this.start+2,"Expected number in radix "+e),n(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(L.num,t)},oe.readNumber=function(e){var t=this.pos,r=!1,i=48===this.input.charCodeAt(this.pos);e||null!==this.readInt(10)||this.raise(t,"Invalid number"),i&&this.pos==t+1&&(i=!1);var s=this.input.charCodeAt(this.pos);46!==s||i||(++this.pos,this.readInt(10),r=!0,s=this.input.charCodeAt(this.pos)),69!==s&&101!==s||i||(43!==(s=this.input.charCodeAt(++this.pos))&&45!==s||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number"),r=!0),n(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var o,a=this.input.slice(t,this.pos);return r?o=parseFloat(a):i&&1!==a.length?this.strict?this.raise(t,"Invalid number"):o=/[89]/.test(a)?parseInt(a,10):parseInt(a,8):o=parseInt(a,10),this.finishToken(L.num,o)},oe.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},oe.readString=function(e){for(var t="",n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(n,this.pos),t+=this.readEscapedChar(!1),n=this.pos):(o(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(L.string,t)};var ce={};oe.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==ce)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},oe.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw ce;this.raise(e,t)},oe.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var n=this.input.charCodeAt(this.pos);if(96===n||36===n&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==L.template&&this.type!==L.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(L.template,e)):36===n?(this.pos+=2,this.finishToken(L.dollarBraceL)):(++this.pos,this.finishToken(L.backQuote));if(92===n)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(o(n)){switch(e+=this.input.slice(t,this.pos),++this.pos,n){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(n)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},oe.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var n=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],r=parseInt(n,8);return r>255&&(n=n.slice(0,-1),r=parseInt(n,8)),"0"!==n&&(this.strict||e)&&this.invalidStringToken(this.pos-2,"Octal literal in strict mode"),this.pos+=n.length-1,String.fromCharCode(r)}return String.fromCharCode(t)}},oe.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return null===n&&this.invalidStringToken(t,"Bad character escape sequence"),n},oe.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,i=this.pos,s=this.options.ecmaVersion>=6;this.pos=s)&&a[c](t,n,e),(null==r||t.start==r)&&(null==s||t.end==s)&&o(c,t))throw new i(t,n)}(n,u)}catch(e){if(e instanceof i)return e;throw e}},e.findNodeAround=function(n,r,s,o,a){s=t(s),o||(o=e.base);try{!function e(t,n,a){var u=a||t.type;if(!(t.start>r||t.end=r&&s(u,t))throw new i(t,n);o[u](t,n,e)}}(n,a)}catch(e){if(e instanceof i)return e;throw e}},e.findNodeBefore=function(n,r,s,o,a){s=t(s),o||(o=e.base);var u;return function e(t,n,a){if(!(t.start>r)){var c=a||t.type;t.end<=r&&(!u||u.node.end0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return o[e>>18&63]+o[e>>12&63]+o[e>>6&63]+o[63&e]}function s(e,t,n){for(var r,s=[],o=t;o0?c-4:c;var l=0;for(t=0;t>16&255,o[l++]=i>>8&255,o[l++]=255&i;return 2===s?(i=a[e.charCodeAt(t)]<<2|a[e.charCodeAt(t+1)]>>4,o[l++]=255&i):1===s&&(i=a[e.charCodeAt(t)]<<10|a[e.charCodeAt(t+1)]<<4|a[e.charCodeAt(t+2)]>>2,o[l++]=i>>8&255,o[l++]=255&i),o},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i="",a=[],u=0,c=n-r;uc?c:u+16383));return 1===r?(t=e[n-1],i+=o[t>>2],i+=o[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=o[t>>10],i+=o[t>>4&63],i+=o[t<<2&63],i+="="),a.push(i),a.join("")};for(var o=[],a=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0,p=c.length;lB)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return a(e)}return s(e,t,n)}function s(e,t,n){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return T(e)?function(e,t,n){if(t<0||e.byteLength=B)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+B.toString(16)+" bytes");return 0|e}function l(e,t){if(i.isBuffer(e))return e.length;if(N(e)||T(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return _(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(r)return _(e).length;t=(""+t).toLowerCase(),r=!0}}function p(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,n){var r=e.length;(!t||t<0)&&(t=0);(!n||n<0||n>r)&&(n=r);for(var i="",s=t;s2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,P(n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:d(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):d(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function d(e,t,n,r,i){function s(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}var o=1,a=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,u/=2,n/=2}var c;if(i){var l=-1;for(c=n;ca&&(n=a-u),c=n;c>=0;c--){for(var p=!0,h=0;hi&&(r=i):r=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function w(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i239?4:s>223?3:s>191?2:1;if(i+a<=n){var u,c,l,p;switch(a){case 1:s<128&&(o=s);break;case 2:128==(192&(u=e[i+1]))&&(p=(31&s)<<6|63&u)>127&&(o=p);break;case 3:u=e[i+1],c=e[i+2],128==(192&u)&&128==(192&c)&&(p=(15&s)<<12|(63&u)<<6|63&c)>2047&&(p<55296||p>57343)&&(o=p);break;case 4:u=e[i+1],c=e[i+2],l=e[i+3],128==(192&u)&&128==(192&c)&&128==(192&l)&&(p=(15&s)<<18|(63&u)<<12|(63&c)<<6|63&l)>65535&&p<1114112&&(o=p)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=a}return function(e){var t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);var n="",r=0;for(;rn)throw new RangeError("Trying to access beyond buffer length")}function S(e,t,n,r,s,o){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||te.length)throw new RangeError("Index out of range")}function k(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function A(e,t,n,r,i){return t=+t,n>>>=0,i||k(e,0,n,4),$.write(e,t,n,r,23,4),n+4}function C(e,t,n,r,i){return t=+t,n>>>=0,i||k(e,0,n,8),$.write(e,t,n,r,52,8),n+8}function _(e,t){t=t||1/0;for(var n,r=e.length,i=null,s=[],o=0;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function L(e){return F.toByteArray(function(e){if((e=e.trim().replace(I,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function O(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function T(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function N(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function P(e){return e!=e}var F=e("base64-js"),$=e("ieee754");n.Buffer=i,n.SlowBuffer=function(e){return+e!=e&&(e=0),i.alloc(+e)},n.INSPECT_MAX_BYTES=50;var B=2147483647;n.kMaxLength=B,(i.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}())||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return s(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return function(e,t,n){return o(e),e<=0?r(e):void 0!==t?"string"==typeof n?r(e).fill(t,n):r(e).fill(t):r(e)}(e,t,n)},i.allocUnsafe=function(e){return a(e)},i.allocUnsafeSlow=function(e){return a(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer},i.compare=function(e,t){if(!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,s=0,o=Math.min(n,r);s0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},i.prototype.compare=function(e,t,n,r,s){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,s>>>=0,this===e)return 0;for(var o=s-r,a=n-t,u=Math.min(o,a),c=this.slice(r,s),l=e.slice(t,n),p=0;p>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return m(this,e,t,n);case"ascii":return g(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return b(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;i.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t>>=0,t>>>=0,n||E(e,t,this.length);for(var r=this[e],i=1,s=0;++s>>=0,t>>>=0,n||E(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||E(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||E(e,t,this.length);for(var r=this[e],i=1,s=0;++s=i&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||E(e,t,this.length);for(var r=t,i=1,s=this[e+--r];r>0&&(i*=256);)s+=this[e+--r]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||E(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||E(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||E(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||E(e,4,this.length),$.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||E(e,4,this.length),$.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||E(e,8,this.length),$.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||E(e,8,this.length),$.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){S(this,e,t,n,Math.pow(2,8*n)-1,0)}var i=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,!r){S(this,e,t,n,Math.pow(2,8*n)-1,0)}var i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);S(this,e,t,n,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s>0)-a&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);S(this,e,t,n,i-1,-i)}var s=n-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o>>0)-a&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||S(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return A(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return A(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return C(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return C(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(s<1e3)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o>1,l=-7,p=n?i-1:0,h=n?-1:1,f=e[t+p];for(p+=h,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+p],p+=h,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=r;l>0;o=256*o+e[t+p],p+=h,l-=8);if(0===s)s=1-c;else{if(s===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=c}return(f?-1:1)*o*Math.pow(2,s-r)},n.write=function(e,t,n,r,i,s){var o,a,u,c=8*s-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,d=r?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),(t+=o+p>=1?h/u:h*Math.pow(2,1-p))*u>=2&&(o++,u/=2),o+p>=l?(a=0,o=l):o+p>=1?(a=(t*u-1)*Math.pow(2,i),o+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=d,a/=256,i-=8);for(o=o<0;e[n+f]=255&o,f+=d,o/=256,c-=8);e[n+f-d]|=128*y}},{}],10:[function(e,t,n){(function(n){function r(){}function i(e){this.covers={},this._ident=i.prototype.version+"_"+Math.random(),this.setOptions(e||{})}var s=e("./lib/parser"),o=e("./lib/arboriculture"),a=e("./lib/output");i.prototype.smCache={},i.prototype.setOptions=function(e){return this.log=!1===e.log?r:e.log||this.log,this.options=function(e){var t={};return e.forEach(function(e){if(e&&"object"==typeof e)for(var n in e)t[n]=e[n]}),t}([this.options,e]),delete this.options.log,this},i.prototype.version=e("./package.json").version,i.prototype.isThenable=function(e){return e&&e instanceof Object&&"function"==typeof e.then},i.prototype.compile=function(e,t,n,s){"object"==typeof n&&void 0===s&&(s=n),s=s||{};for(var o in i.initialCodeGenOpts)o in s||(s[o]=i.initialCodeGenOpts[o]);var a=this.parse(e,t,null,s);return this.asynchronize(a,null,s,this.log||r),this.prettyPrint(a,s),a},i.prototype.parse=function(e,t,n,r){"object"==typeof n&&void 0===r&&(r=n);var i={origCode:e.toString(),filename:t};try{return i.ast=s.parse(i.origCode,r&&r.parser),r.babelTree&&s.treeWalker(i.ast,function(e,t,n){"Literal"===e.type?n[0].replace(o.babelLiteralNode(e.value)):"Property"===e.type&&("ClassBody"===n[0].parent.type?e.type="ClassProperty":e.type="ObjectProperty"),t()}),i}catch(e){if(e instanceof SyntaxError){var a=i.origCode.substr(e.pos-e.loc.column);a=a.split("\n")[0],e.message+=" "+t+" (nodent)\n"+a+"\n"+a.replace(/[\S ]/g,"-").substring(0,e.loc.column)+"^",e.stack=""}throw e}},i.prototype.asynchronize=o.asynchronize,i.prototype.printNode=o.printNode,i.prototype.prettyPrint=function(t,r){var i=t.filename?t.filename.split("/"):["anonymous"],s=i.pop(),o=a(t.ast,r&&r.sourcemap?{map:{startLine:r.mapStartLine||0,file:s+"(original)",sourceMapRoot:i.join("/"),sourceContent:t.origCode}}:null,t.origCode);if(r&&r.sourcemap)try{var u="",c=o.map.toJSON();if(c){var l=e("source-map").SourceMapConsumer;t.sourcemap=c,this.smCache[t.filename]={map:c,smc:new l(c)},u="\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+function(e){return(e instanceof n?e:new n(e.toString(),"binary")).toString("base64")}(JSON.stringify(c))+"\n"}t.code=o.code+u}catch(e){t.code=o}else t.code=o;return t},i.prototype.getDefaultCompileOptions=void 0,Object.defineProperty(i.prototype,"Promise",{get:function(){return initOpts.log("Warning: nodent.Promise is deprecated. Use nodent.Thenable instead"),Thenable},enumerable:!1,configurable:!1}),i.initialCodeGenOpts={noRuntime:!1,lazyThenables:!1,es6target:!1,noUseDirective:!1,wrapAwait:null,mapStartLine:0,sourcemap:!0,engine:!1,parser:{sourceType:"script"},$return:"$return",$error:"$error",$arguments:"$args",$asyncspawn:"$asyncspawn",$asyncbind:"$asyncbind",generatedSymbolPrefix:"$",$makeThenable:"$makeThenable"},t.exports=i}).call(this,e("buffer").Buffer)},{"./lib/arboriculture":11,"./lib/output":12,"./lib/parser":13,"./package.json":25,buffer:8,"source-map":24}],11:[function(e,t,n){"use strict";function r(e){if(!e)return"";if(Array.isArray(e))return e.map(r).join("|\n");try{return m(e)}catch(t){return t.message+": "+(e&&e.type)}}function i(e){if(Array.isArray(e))return e.map(function(e){return i(e)});var t={};return Object.keys(e).forEach(function(n){t[n]=e[n]}),t}function s(e,t){e!==t&&(e.__proto__=Object.getPrototypeOf(t),Object.keys(e).forEach(function(t){t in g||delete e[t]}),Object.keys(t).forEach(function(n){n in e||(e[n]=t[n])}))}function o(){}function a(e){return e?(b.node=e,b):{}}function u(e,t,n){if(!e)return null;if(t&&"object"==typeof t){var r=Object.keys(t);return u(e,function(e){return r.every(function(n){return e[n]==t[n]})})}var i,s={};if(Array.isArray(e)){for(var o=0;o0){if(!o)return t(e);delete e.async}return void(!o&&i?t():(e.type="ReturnStatement",e.$mapped=!0,e.argument={type:"CallExpression",callee:k(s,[n]).$error,arguments:[e.argument]}))}return"TryStatement"===e.type?(i++,t(e),void i--):a(e).isFunction?(r++,t(e),void r--):void t(e)}if(r>0){if(!a(e).isAsync)return t(e);delete e.async}return e.$mapped=!0,void(a(e.argument).isUnaryExpression&&"void"===e.argument.operator?e.argument=e.argument.argument:e.argument={type:"CallExpression",callee:k(s,[n]).$return,arguments:e.argument?[e.argument]:[]})},t)}function P(e,t){return Array.isArray(e)?e.map(function(e){return P(e,t)}):(y.treeWalker(e,function(e,t,n){if(t(),"ConditionalExpression"===e.type&&(c(e.alternate)||c(e.consequent))){h(E("condOp"));s(e,_(y.part("if ($0) return $1 ; return $2",[e.test,e.consequent,e.alternate]).body))}},t),e)}function F(e,t){return Array.isArray(e)?e.map(function(e){return F(e,t)}):(y.treeWalker(e,function(e,t,n){if(t(),"LogicalExpression"===e.type&&c(e.right)){var r,i=h(E("logical"+("&&"===e.operator?"And":"Or")));if("||"===e.operator)r="var $0; if (!($0 = $1)) {$0 = $2} return $0";else{if("&&"!==e.operator)throw new Error(v(e)+"Illegal logical operator: "+e.operator);r="var $0; if ($0 = $1) {$0 = $2} return $0"}s(e,_(y.part(r,[i,e.left,e.right]).body))}},t),e)}function $(e,t,n){if("SwitchCase"!==e.type&&a(e).isBlockStatement)for(var r=0;r { $$setMapped: while (q) { if (q.then) "+(1===i?" return void q.then($idTrampoline, $exit); ":" return q.then($idTrampoline, $exit); ")+" try { if (q.pop) if (q.length) return q.pop() ? $idContinuation.call(this) : q; else q = $idStep; else q = q.call(this) } catch (_exception) { return $exit(_exception); } } }))($idIter)":"($idTrampoline = (function (q) { $$setMapped: while (q) { if (q.then) "+(1===i?" return void q.then($idTrampoline, $exit); ":" return q.then($idTrampoline, $exit); ")+" try { if (q.pop) if (q.length) return q.pop() ? $idContinuation.call(this) : q; else q = $idStep; else q = q.call(this) } catch (_exception) { return $exit(_exception); } } }).bind(this))($idIter)",{setMapped:function(e){return e.$mapped=!0,e},idTrampoline:w,exit:P,idIter:E,idContinuation:A,idStep:S}).expr:y.part("(Function.$0.trampoline(this,$1,$2,$3,$5)($4))",[pe.asyncbind,A,S,P,E,b(1===i)]).expr,o.push({type:"ReturnStatement",argument:N}),o.push({$label:e.$label,type:"FunctionDeclaration",id:E,params:[],body:{type:"BlockStatement",body:d}}),f&&o.push({type:"FunctionDeclaration",id:S,params:[],body:{type:"BlockStatement",body:[f,L]}}),!l||"VariableDeclaration"!==l.type||"let"!==l.kind&&"const"!==l.kind?(o.push(v),t[0].replace(o.map(r))):("const"===l.kind&&(l.kind="let"),t[0].replace([{type:"BlockStatement",body:o.map(r)},r(v)]))}}function G(e){if(!a(e).isFunction)throw new Error("Cannot examine non-Function node types for async exits");return u(e.body,function(e){return"Identifier"===e.type&&(e.name===n.$return||e.name===n.$error)||I(e)&&a(e).isAsync},function(e){return!(a(e).isFunction&&(e.$wasAsync||a(e).isAsync))})}function J(t){return y.treeWalker(t,function(t,r,i){var s=x(t);if(r(),s&&a(s).isAsync){if("set"==t.kind){var o=new SyntaxError(v(s)+"method 'async set' cannot be invoked",e.filename,t.start);throw o.pos=t.start,o.loc=t.loc.start,o}s.async=!1;var u=w(s);G(s)||0!==s.body.body.length&&"ReturnStatement"===s.body.body[s.body.body.length-1].type||s.body.body.push({type:"ReturnStatement"});var c=m(S({type:"FunctionExpression",params:[pe.return,pe.error],body:J(N(s.body,i)),$wasAsync:!0},n),n.promises||n.generators||n.engine?null:b(!n.lazyThenables||0));n.promises?s.body={type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"NewExpression",callee:h("Promise"),arguments:[c]}}]}:s.body={type:"BlockStatement",body:[{type:"ReturnStatement",argument:c}]},u&&D(s.body.body,[he])}})}function H(e){return y.treeWalker(e,function(e,t,r){if(t(),a(e).isAsync&&a(e).isFunction){var i;(i=x(r[0].parent))&&a(i).isAsync&&"get"===r[0].parent.kind&&X(r[0].parent.key),delete e.async;var s=w(e),o=S({type:"FunctionExpression",params:[pe.return,pe.error],$wasAsync:!0},n),u=[{self:o}].concat(r);return a(e.body).isBlockStatement?(G(e)||0!==e.body.body.length&&"ReturnStatement"===e.body.body[e.body.body.length-1].type||e.body.body.push({type:"ReturnStatement"}),o.body={type:"BlockStatement",body:e.body.body.map(function(e){return N(e,u)})}):(o.body={type:"BlockStatement",body:[N({type:"ReturnStatement",argument:e.body},u)]},e.expression=!1),o=m(o,n.promises||n.generators||n.engine?null:b(!n.lazyThenables||0)),n.promises&&(o={type:"NewExpression",callee:h("Promise"),arguments:[o]}),o={type:"BlockStatement",body:[{type:"ReturnStatement",loc:e.loc,argument:o}]},s&&D(o.body,[he]),void(e.body=o)}}),e}function Y(e){if(Array.isArray(e))return e.map(Y);var t=0;return y.treeWalker(e,function(e,n,r){if("ThrowStatement"!==e.type&&"ReturnStatement"!==e.type||e.$mapped){if(a(e).isFunction)return t++,n(e),void t--}else if(t>0&&a(e).isAsync)return delete e.async,e.argument={type:"CallExpression",callee:"ThrowStatement"===e.type?pe.error:pe.return,arguments:e.argument?[e.argument]:[]},void(e.type="ReturnStatement");n(e)})}function Z(e,t){if(n.noRuntime)throw new Error("Nodent: 'noRuntime' option only compatible with -promise and -engine modes");return y.part("{ return (function*($return,$error){ $:body }).$asyncspawn(Promise,this) }",{return:pe.return,error:pe.error,asyncspawn:pe.asyncspawn,body:Y(e).concat(t?[{type:"ReturnStatement",argument:pe.return}]:[])}).body[0]}function X(e){e.$asyncgetwarninig||(e.$asyncgetwarninig=!0,d(v(e)+"'async get "+r(e)+"(){...}' is non-standard. See https://github.com/MatAtBread/nodent#differences-from-the-es7-specification"))}function Q(e,t){function r(e,t){y.treeWalker(e,function(n,r,i){n!==e&&a(n).isFunction||(a(n).isAwait?t?(n.$hidden=!0,r()):(delete n.operator,n.delegate=!1,n.type="YieldExpression",r()):r())})}function o(e){var t=n.promises;n.promises=!0,A(e,!0),n.promises=t}function u(e){return"BlockStatement"!==e.body.type&&(e.body={type:"BlockStatement",body:[{type:"ReturnStatement",argument:e.body}]}),e}function c(e,n){n.$asyncexitwarninig||(n.$asyncexitwarninig=!0,d(v(e)+"'async "+{ReturnStatement:"return",ThrowStatement:"throw"}[e.type]+"' not possible in "+(t?"engine":"generator")+" mode. Using Promises for function at "+v(n)))}y.treeWalker(e,function(e,n,i){n();var l,p,h;if(a(e).isAsync&&a(e).isFunction){var f;(f=x(i[0].parent))&&a(f).isAsync&&"get"===i[0].parent.kind&&X(i[0].parent.key),(p=G(e))?(c(p,e.body),o(e)):t?"get"!==i[0].parent.kind&&r(e,!0):(delete(l=e).async,h=w(l),r(l,!1),(l=u(l)).body=Z(l.body.body,p),h&&D(l.body.body,[he]),l.id&&"ExpressionStatement"===i[0].parent.type?(l.type="FunctionDeclaration",i[1].replace(l)):i[0].replace(l))}else(l=x(e))&&a(l).isAsync&&((p=G(l))?(c(p,l),o(e)):t&&"get"!==e.kind||(t?o(e):(e.async=!1,h=w(l),r(l,!1),s(l,u(l)),l.body=Z(l.body.body,p)),h&&D(l.body.body,[he])))});var l=i(n);return n.engine=!1,n.generators=!1,ie(e),ne(e),j(e,l.engine),F(e),P(e),q(e,[M,W,B,R,$]),V(e,"warn"),n.engine=l.engine,n.generators=l.generators,e}function K(e,t,n){var r=[];return y.treeWalker(e,function(i,s,o){if(i===e)return s();t(i,o)?r.push([].concat(o)):n||a(i).isScope||s()}),r}function ee(e,t){var n=[],r={};if((e=e.filter(function(e){return"ExportNamedDeclaration"!==e[0].parent.type})).length){var s={};e.forEach(function(e){function t(e){e in s?r[e]=o.declarations[u]:s[e]=o.declarations[u]}for(var n=e[0],o=n.self,a=(o.kind,[]),u=0;u1?{type:"SequenceExpression",expressions:a}:a[0];"For"!==n.parent.type.slice(0,3)&&(p={type:"ExpressionStatement",expression:p}),n.replace(p)}});var o=Object.keys(s);o.length&&(o=o.map(function(e){return{type:"VariableDeclarator",id:h(e),loc:s[e].loc,start:s[e].start,end:s[e].end}}),n[0]&&"VariableDeclaration"===n[0].type?n[0].declarations=n[0].declarations.concat(o):n.unshift({type:"VariableDeclaration",kind:t,declarations:o}))}return{decls:n,duplicates:r}}function te(e){if(!e)return[];if(Array.isArray(e))return e.reduce(function(e,t){return e.concat(te(t.id))},[]);switch(e.type){case"Identifier":return[e.name];case"AssignmentPattern":return te(e.left);case"ArrayPattern":return e.elements.reduce(function(e,t){return e.concat(te(t))},[]);case"ObjectPattern":return e.properties.reduce(function(e,t){return e.concat(te(t))},[]);case"ObjectProperty":case"Property":return te(e.value);case"RestElement":case"RestProperty":return te(e.argument)}}function ne(e){function t(e){return u(e,function(e){return"AssignmentExpression"===e.type})}function n(e){return function(t,n){if("VariableDeclaration"===t.type&&(t.kind=t.kind||"var")&&e.indexOf(t.kind)>=0){var r=n[0];return("left"!=r.field||"ForInStatement"!==r.parent.type&&"ForOfStatement"!==r.parent.type)&&("init"!=r.field||"ForStatement"!==r.parent.type||"const"!==t.kind&&"let"!==t.kind)}}}function o(e,t){return!("FunctionDeclaration"!==e.type||!e.id)&&(a(e).isAsync||!e.$continuation)}var l={TemplateLiteral:function(e){return e.expressions},NewExpression:function(e){return e.arguments},CallExpression:function(e){return e.arguments},SequenceExpression:function(e){return e.expressions},ArrayExpression:function(e){return e.elements},ObjectExpression:function(e){return e.properties.map(function(e){return e.value})}};y.treeWalker(e,function(e,n,r){function o(e){h.length&&(e.argument={type:"SequenceExpression",expressions:h.map(function(e){var t=i(e);return s(e,e.left),t}).concat(e.argument)},h=[])}var u;if(n(),e.type in l&&!e.$hoisted){var p=l[e.type](e),h=[];for(u=0;u0;u--)if(e.declarations[u]&&e.declarations[u].init&&c(e.declarations[u].init)){var f={type:"VariableDeclaration",kind:e.kind,declarations:e.declarations.splice(u)},d=r[0];if(!("index"in d))throw new Error("VariableDeclaration not in a block");d.parent[d.field].splice(d.index+1,0,f)}}),function(e){function t(e){d(v(e)+"Possible assignment to 'const "+r(e)+"'")}function n(e){switch(e.type){case"Identifier":"const"===i[e.name]&&t(e);break;case"ArrayPattern":e.elements.forEach(function(e){"const"===i[e.name]&&t(e)});break;case"ObjectPattern":e.properties.forEach(function(e){"const"===i[e.key.name]&&t(e)})}}var i={};y.treeWalker(e,function(e,t,r){var s=a(e).isBlockStatement;if(s){i=Object.create(i);for(var o=0;o=0&&"ReturnStatement"===r[1].self.type){var s=e.$thisCallName,o=i(ce[s].def.body.body);ce[s].$inlined=!0,a(r[1].self).isJump||o.push({type:"ReturnStatement"}),r[1].replace(o)}});var n=Object.keys(ce).map(function(e){return ce[e].$inlined&&ce[e].def});y.treeWalker(e,function(e,t,r){t(),n.indexOf(e)>=0&&r[0].remove()})}if(!("Program"===e.type&&"module"===e.sourceType||u(e,function(e){return a(e).isES6},!0))){var r=oe(e);!function(e){y.treeWalker(e,function(e,t,n){if("Program"===e.type||"FunctionDeclaration"===e.type||"FunctionExpression"===e.type){var i=r;if(r=r||oe(e)){t();var s="Program"===e.type?e:e.body,o=K(s,function(e,t){if("FunctionDeclaration"===e.type)return t[0].parent!==s});o=o.map(function(e){return e[0].remove()}),[].push.apply(s.body,o)}else t();r=i}else t()})}(e)}return y.treeWalker(e,function(e,t,n){t(),Object.keys(e).filter(function(e){return"$"===e[0]}).forEach(function(t){delete e[t]})}),e}var ce={},le=1,pe={};Object.keys(n).filter(function(e){return"$"===e[0]}).forEach(function(e){pe[e.slice(1)]=h(n[e])});var he=y.part("var $0 = arguments",[pe.arguments]).body[0];return n.engine?(e.ast=re(e.ast,!0),e.ast=Q(e.ast,n.engine),e.ast=se(e.ast),ue(e.ast)):n.generators?(e.ast=re(e.ast),e.ast=Q(e.ast),e.ast=se(e.ast),ue(e.ast)):(e.ast=re(e.ast),A(e.ast)),n.babelTree&&y.treeWalker(e.ast,function(e,t,n){t(),"Literal"===e.type&&s(e,b(e.value))}),e}var y=e("./parser"),m=e("./output"),g={start:!0,end:!0,loc:!0,range:!0},v={getScope:function(){return"FunctionDeclaration"===this.node.type||"FunctionExpression"===this.node.type||"Function"===this.node.type||"ObjectMethod"===this.node.type||"ClassMethod"===this.node.type||"ArrowFunctionExpression"===this.node.type&&"BlockStatement"===this.node.body.type?this.node.body.body:"Program"===this.node.type?this.node.body:null},isScope:function(){return"FunctionDeclaration"===this.node.type||"FunctionExpression"===this.node.type||"Function"===this.node.type||"Program"===this.node.type||"ObjectMethod"===this.node.type||"ClassMethod"===this.node.type||"ArrowFunctionExpression"===this.node.type&&"BlockStatement"===this.node.body.type},isFunction:function(){return"FunctionDeclaration"===this.node.type||"FunctionExpression"===this.node.type||"Function"===this.node.type||"ObjectMethod"===this.node.type||"ClassMethod"===this.node.type||"ArrowFunctionExpression"===this.node.type},isClass:function(){return"ClassDeclaration"===this.node.type||"ClassExpression"===this.node.type},isBlockStatement:function(){return"ClassBody"===this.node.type||"Program"===this.node.type||"BlockStatement"===this.node.type?this.node.body:"SwitchCase"===this.node.type&&this.node.consequent},isExpressionStatement:function(){return"ExpressionStatement"===this.node.type},isLiteral:function(){return"Literal"===this.node.type||"BooleanLiteral"===this.node.type||"RegExpLiteral"===this.node.type||"NumericLiteral"===this.node.type||"StringLiteral"===this.node.type||"NullLiteral"===this.node.type},isDirective:function(){return"ExpressionStatement"===this.node.type&&("StringLiteral"===this.node.expression.type||"Literal"===this.node.expression.type&&"string"==typeof this.node.expression.value)},isUnaryExpression:function(){return"UnaryExpression"===this.node.type},isAwait:function(){return"AwaitExpression"===this.node.type&&!this.node.$hidden},isAsync:function(){return this.node.async},isStatement:function(){return null!==this.node.type.match(/[a-zA-Z]+Declaration/)||null!==this.node.type.match(/[a-zA-Z]+Statement/)},isExpression:function(){return null!==this.node.type.match(/[a-zA-Z]+Expression/)},isLoop:function(){return"ForStatement"===this.node.type||"WhileStatement"===this.node.type||"DoWhileStatement"===this.node.type},isJump:function(){return"ReturnStatement"===this.node.type||"ThrowStatement"===this.node.type||"BreakStatement"===this.node.type||"ContinueStatement"===this.node.type},isES6:function(){switch(this.node.type){case"ExportNamedDeclaration":case"ExportSpecifier":case"ExportDefaultDeclaration":case"ExportAllDeclaration":case"ImportDeclaration":case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ArrowFunctionExpression":case"ForOfStatement":case"YieldExpression":case"Super":case"RestElement":case"RestProperty":case"SpreadElement":case"TemplateLiteral":case"ClassDeclaration":case"ClassExpression":return!0;case"VariableDeclaration":return this.node.kind&&"var"!==this.node.kind;case"FunctionDeclaration":case"FunctionExpression":return!!this.node.generator}}},b={};Object.keys(v).forEach(function(e){Object.defineProperty(b,e,{get:v[e]})}),t.exports={printNode:r,babelLiteralNode:p,asynchronize:function(e,t,n,r){try{return d(e,0,n,r)}catch(t){if(t instanceof SyntaxError){var i=e.origCode.substr(t.pos-t.loc.column);i=i.split("\n")[0],t.message+=" (nodent)\n"+i+"\n"+i.replace(/[\S ]/g,"-").substring(0,t.loc.column)+"^",t.stack=""}throw t}}}},{"./output":12,"./parser":13}],12:[function(e,t,n){"use strict";function r(e){if("NewExpression"===e.type&&e.arguments&&e.arguments.length)return 19;var t=h[e.type]||h[e.type+e.operator]||h[e.type+e.operator+(e.prefix?"prefix":"")];return void 0!==t?t:20}var i,s,o,a,u,c,l=e("source-map").SourceMapGenerator;if("".repeat)c=function(e,t){return t&&e?e.repeat(t):""};else{var p={};c=function(e,t){if(!t||!e)return"";var n=""+e+t;if(!p[n]){for(var r=[];t--;)r.push(e);p[n]=r.join("")}return p[n]}}var h={ExpressionStatement:-1,Identifier:21,Literal:21,BooleanLiteral:21,RegExpLiteral:21,NumericLiteral:21,StringLiteral:21,NullLiteral:21,ThisExpression:21,SuperExpression:21,ObjectExpression:21,ClassExpression:21,MemberExpression:19,CallExpression:18,NewExpression:18,ArrayExpression:17.5,FunctionExpression:17.5,FunctionDeclaration:17.5,ArrowFunctionExpression:17.5,"UpdateExpression++":17,"UpdateExpression--":17,"UpdateExpression++prefix":16,"UpdateExpression--prefix":16,UnaryExpression:16,AwaitExpression:16,"BinaryExpression**":15,"BinaryExpression*":15,"BinaryExpression/":15,"BinaryExpression%":15,"BinaryExpression+":14,"BinaryExpression-":14,"BinaryExpression<<":13,"BinaryExpression>>":13,"BinaryExpression>>>":13,"BinaryExpression<":12,"BinaryExpression<=":12,"BinaryExpression>":12,"BinaryExpression>=":12,BinaryExpressionin:12,BinaryExpressioninstanceof:12,"BinaryExpression==":11,"BinaryExpression===":11,"BinaryExpression!=":11,"BinaryExpression!==":11,"BinaryExpression&":10,"BinaryExpression^":9,"BinaryExpression|":8,"LogicalExpression&&":7,"LogicalExpression||":6,ConditionalExpression:5,AssignmentPattern:4,AssignmentExpression:4,yield:3,YieldExpression:3,SpreadElement:2,"comma-separated-list":1.5,SequenceExpression:1},f={type:"comma-separated-list"},d={out:function(e,t,n){var r=this[n||e.type];r?r.call(this,e,t):t.write(e,"/*"+e.type+"?*/ "+t.sourceAt(e.start,e.end))},expr:function(e,t,n,i){2===i||r(n)0)for(var r=n.length,i=0;i0){this.out(e[0],t,e[0].type);for(var r=1,i=e.length;r0){t.write(null,s);for(var a=0,u=n.length;a0){this.out(n[0],t,"VariableDeclarator");for(var i=1;i0){for(var s=0;s0)for(var r=0;r ")):(this.formatParameters(e.params,t),t.write(e,"=> ")),"ObjectExpression"===e.body.type||"SequenceExpression"===e.body.type?(t.write(null,"("),this.out(e.body,t,e.body.type),t.write(null,")")):this.out(e.body,t,e.body.type)},ThisExpression:function(e,t){t.write(e,"this")},Super:function(e,t){t.write(e,"super")},RestElement:s=function(e,t){t.write(e,"..."),this.out(e.argument,t,e.argument.type)},SpreadElement:s,YieldExpression:function(e,t){t.write(e,e.delegate?"yield*":"yield"),e.argument&&(t.write(null," "),this.expr(t,e,e.argument))},AwaitExpression:function(e,t){t.write(e,"await "),this.expr(t,e,e.argument)},TemplateLiteral:function(e,t){var n,r=e.quasis,i=e.expressions;t.write(e,"`");for(var s=0,o=i.length;s0)for(var n=e.elements,r=n.length,i=0;;){var s=n[i];if(s&&this.expr(t,f,s),((i+=1)=r)break;t.lineLength()>t.wrapColumn&&t.write(null,t.lineEnd,c(t.indent,t.indentLevel+1))}t.write(null,"]")},ArrayPattern:a,ObjectExpression:function(e,t){var n,r=c(t.indent,t.indentLevel++),i=t.lineEnd,s=r+t.indent;if(t.write(e,"{"),e.properties.length>0){t.write(null,i);for(var o=e.properties,a=o.length,u=0;n=o[u],t.write(null,s),this.out(n,t,"Property"),++ut.wrapColumn&&t.write(null,t.lineEnd,c(t.indent,t.indentLevel+1));t.write(null,i,r,"}")}else t.write(null,"}");t.indentLevel--},Property:function(e,t){e.method||"get"===e.kind||"set"===e.kind?this.MethodDefinition(e,t):(e.shorthand||(e.computed?(t.write(null,"["),this.out(e.key,t,e.key.type),t.write(null,"]")):this.out(e.key,t,e.key.type),t.write(null,": ")),this.expr(t,f,e.value))},ObjectPattern:function(e,t){if(t.write(e,"{"),e.properties.length>0)for(var n=e.properties,r=n.length,i=0;this.out(n[i],t,"Property"),++i0)for(var i=r.length,s=0;s1&&t.write(e," "),this.expr(t,e,e.argument,!0)):(this.expr(t,e,e.argument),t.write(e,e.operator))},UpdateExpression:function(e,t){e.prefix?(t.write(e,e.operator),this.out(e.argument,t,e.argument.type)):(this.out(e.argument,t,e.argument.type),t.write(e,e.operator))},BinaryExpression:o=function(e,t){var n=e.operator;"in"===n&&t.inForInit&&t.write(null,"("),this.expr(t,e,e.left),t.write(e," ",n," "),this.expr(t,e,e.right,"ArrowFunctionExpression"===e.right.type?2:0),"in"===n&&t.inForInit&&t.write(null,")")},LogicalExpression:o,AssignmentExpression:function(e,t){"ObjectPattern"===e.left.type&&t.write(null,"("),this.BinaryExpression(e,t),"ObjectPattern"===e.left.type&&t.write(null,")")},AssignmentPattern:function(e,t){this.expr(t,e,e.left),t.write(e," = "),this.expr(t,e,e.right)},ConditionalExpression:function(e,t){this.expr(t,e,e.test,!0),t.write(e," ? "),this.expr(t,e,e.consequent),t.write(null," : "),this.expr(t,e,e.alternate)},NewExpression:function(e,t){t.write(e,"new "),this.expr(t,e,e.callee,"CallExpression"===e.callee.type||"ObjectExpression"===e.callee.type?2:0),this.argumentList(e,t)},CallExpression:function(e,t){this.expr(t,e,e.callee,"ObjectExpression"===e.callee.type?2:0),this.argumentList(e,t)},MemberExpression:function(e,t){!("ObjectExpression"===e.object.type||e.object.type.match(/Literal$/)&&e.object.raw&&e.object.raw.match(/^[0-9]/))&&("ArrayExpression"===e.object.type||"CallExpression"===e.object.type||"NewExpression"===e.object.type||r(e)<=r(e.object))?this.out(e.object,t,e.object.type):(t.write(null,"("),this.out(e.object,t,e.object.type),t.write(null,")")),e.computed?(t.write(e,"["),this.out(e.property,t,e.property.type),t.write(null,"]")):(t.write(e,"."),this.out(e.property,t,e.property.type))},Identifier:function(e,t){t.write(e,e.name)},Literal:function(e,t){t.write(e,e.raw)},NullLiteral:function(e,t){t.write(e,"null")},BooleanLiteral:function(e,t){t.write(e,JSON.stringify(e.value))},StringLiteral:function(e,t){t.write(e,JSON.stringify(e.value))},RegExpLiteral:function(e,t){t.write(e,e.extra.raw||"/"+e.pattern+"/"+e.flags)},NumericLiteral:function(e,t){t.write(e,JSON.stringify(e.value))}};t.exports=function(e,t,n){var r="",i=[],s=(t=t||{}).map&&new l(t.map);s&&t.map.sourceContent&&s.setSourceContent(t.map.file,t.map.sourceContent);var o="",a=[],u=[],p={inForInit:0,lineLength:function(){return r.length},sourceAt:function(e,t){return n?n.substring(e,t):"/* Omitted Non-standard node */"},write:function(e){o=arguments[arguments.length-1];for(var n=1;n=0&&r({self:i,parent:e,field:u[c],index:!0}):l instanceof Object&&i===l&&r({self:i,parent:e,field:u[c]})}})},n),e}function s(t,n){var r=[],s={ecmaVersion:8,allowHashBang:!0,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,locations:!0,onComment:r};if((!n||!n.noNodentExtensions||parseInt(o.version)<4)&&(c||(parseInt(o.version)<4&&console.warn("Nodent: Warning - noNodentExtensions option requires acorn >=v4.x. Extensions installed."),e("acorn-es7-plugin")(o),c=!0),s.plugins=s.plugins||{},s.plugins.asyncawait={asyncExits:!0,awaitAnywhere:!0}),n)for(var a in n)"noNodentExtensions"!==a&&(s[a]=n[a]);var u=o.parse(t,s);return i(u,function(e,t,n){for(t();r.length&&e.loc&&e.loc.start.line>=r[0].loc.start.line&&e.loc.end.line>=r[0].loc.end.line;)e.$comments=e.$comments||[],e.$comments.push(r.shift())}),u}var o=e("acorn"),a=e("acorn/dist/walk").make({AwaitExpression:function(e,t,n){n(e.argument,t,"Expression")},SwitchStatement:function(e,t,n){n(e.discriminant,t,"Expression");for(var r=0;r=0)return t}else{var n=i.toSetString(e);if(s.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')},r.prototype.at=function(e){if(e>=0&&e>>=5)>0&&(t|=32),n+=r.encode(t)}while(i>0);return n},n.decode=function(e,t,n){var i,s,o=e.length,a=0,u=0;do{if(t>=o)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(s=r.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));i=!!(32&s),a+=(s&=31)<>1;return 1==(1&e)?-t:t}(a),n.rest=t}},{"./base64":16}],16:[function(e,t,n){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");n.encode=function(e){if(0<=e&&e0?t-u>1?r(u,t,i,s,o,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,i,s,o,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,i,s){if(0===t.length)return-1;var o=r(-1,t.length,e,t,i,s||n.GREATEST_LOWER_BOUND);if(o<0)return-1;for(;o-1>=0&&0===i(t[o],t[o-1],!0);)--o;return o}},{}],18:[function(e,t,n){function r(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=e("./util");r.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},r.prototype.add=function(e){!function(e,t){var n=e.generatedLine,r=t.generatedLine,s=e.generatedColumn,o=t.generatedColumn;return r>n||r==n&&o>=s||i.compareByGeneratedPositionsInflated(e,t)<=0}(this._last,e)?(this._sorted=!1,this._array.push(e)):(this._last=e,this._array.push(e))},r.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=r},{"./util":23}],19:[function(e,t,n){function r(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function i(e,t,n,s){if(n=0){var s=this._originalMappings[i];if(void 0===e.column)for(var o=s.originalLine;s&&s.originalLine===o;)r.push({line:a.getArg(s,"generatedLine",null),column:a.getArg(s,"generatedColumn",null),lastColumn:a.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i];else for(var c=s.originalColumn;s&&s.originalLine===t&&s.originalColumn==c;)r.push({line:a.getArg(s,"generatedLine",null),column:a.getArg(s,"generatedColumn",null),lastColumn:a.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i]}return r},n.SourceMapConsumer=r,(i.prototype=Object.create(r.prototype)).consumer=r,i.fromSourceMap=function(e){var t=Object.create(i.prototype),n=t._names=c.fromArray(e._names.toArray(),!0),r=t._sources=c.fromArray(e._sources.toArray(),!0);t.sourceRoot=e._sourceRoot,t.sourcesContent=e._generateSourcesContent(t._sources.toArray(),t.sourceRoot),t.file=e._file;for(var o=e._mappings.toArray().slice(),u=t.__generatedMappings=[],l=t.__originalMappings=[],h=0,f=o.length;h1&&(n.source=y+i[1],y+=i[1],n.originalLine=f+i[2],f=n.originalLine,n.originalLine+=1,n.originalColumn=d+i[3],d=n.originalColumn,i.length>4&&(n.name=m+i[4],m+=i[4])),E.push(n),"number"==typeof n.originalLine&&w.push(n)}p(E,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=E,p(w,a.compareByOriginalPositions),this.__originalMappings=w},i.prototype._findMapping=function(e,t,n,r,i,s){if(e[n]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[n]);if(e[r]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[r]);return u.search(e,t,i,s)},i.prototype.computeColumnSpans=function(){for(var e=0;e=0){var i=this._generatedMappings[n];if(i.generatedLine===t.generatedLine){var s=a.getArg(i,"source",null);null!==s&&(s=this._sources.at(s),null!=this.sourceRoot&&(s=a.join(this.sourceRoot,s)));var o=a.getArg(i,"name",null);return null!==o&&(o=this._names.at(o)),{source:s,line:a.getArg(i,"originalLine",null),column:a.getArg(i,"originalColumn",null),name:o}}}return{source:null,line:null,column:null,name:null}},i.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},i.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=a.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var n;if(null!=this.sourceRoot&&(n=a.urlParse(this.sourceRoot))){var r=e.replace(/^file:\/\//,"");if("file"==n.scheme&&this._sources.has(r))return this.sourcesContent[this._sources.indexOf(r)];if((!n.path||"/"==n.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(t)return null;throw new Error('"'+e+'" is not in the SourceMap.')},i.prototype.generatedPositionFor=function(e){var t=a.getArg(e,"source");if(null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t)),!this._sources.has(t))return{line:null,column:null,lastColumn:null};var n={source:t=this._sources.indexOf(t),originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},i=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",r.GREATEST_LOWER_BOUND));if(i>=0){var s=this._originalMappings[i];if(s.source===n.source)return{line:a.getArg(s,"generatedLine",null),column:a.getArg(s,"generatedColumn",null),lastColumn:a.getArg(s,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=i,(o.prototype=Object.create(r.prototype)).constructor=r,o.prototype._version=3,Object.defineProperty(o.prototype,"sources",{get:function(){for(var e=[],t=0;t0&&e.column>=0)||t||n||r)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:t,name:r}))},r.prototype._serializeMappings=function(){for(var e,t,n,r,o=0,a=1,u=0,c=0,l=0,p=0,h="",f=this._mappings.toArray(),d=0,y=f.length;d0){if(!s.compareByGeneratedPositionsInflated(t,f[d-1]))continue;e+=","}e+=i.encode(t.generatedColumn-o),o=t.generatedColumn,null!=t.source&&(r=this._sources.indexOf(t.source),e+=i.encode(r-p),p=r,e+=i.encode(t.originalLine-1-c),c=t.originalLine-1,e+=i.encode(t.originalColumn-u),u=t.originalColumn,null!=t.name&&(n=this._names.indexOf(t.name),e+=i.encode(n-l),l=n)),h+=e}return h},r.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=s.relative(t,e));var n=s.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)},r.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},r.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=r},{"./array-set":14,"./base64-vlq":15,"./mapping-list":18,"./util":23}],22:[function(e,t,n){function r(e,t,n,r,i){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==t?null:t,this.source=null==n?null:n,this.name=null==i?null:i,this[a]=!0,null!=r&&this.add(r)}var i=e("./source-map-generator").SourceMapGenerator,s=e("./util"),o=/(\r?\n)/,a="$$$isSourceNode$$$";r.fromStringWithSourceMap=function(e,t,n){function i(e,t){if(null===e||void 0===e.source)a.add(t);else{var i=n?s.join(n,e.source):e.source;a.add(new r(e.originalLine,e.originalColumn,i,t,e.name))}}var a=new r,u=e.split(o),c=0,l=function(){function e(){return c=0;t--)this.prepend(e[t]);else{if(!e[a]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},r.prototype.walk=function(e){for(var t,n=0,r=this.children.length;n0){for(t=[],n=0;n=0;l--)"."===(o=u[l])?u.splice(l,1):".."===o?c++:c>0&&(""===o?(u.splice(l+1,c),c=0):(u.splice(l,2),c--));return""===(t=u.join("/"))&&(t=a?"/":"."),s?(s.path=t,i(s)):t}function o(e){return e}function a(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var n=t-10;n>=0;n--)if(36!==e.charCodeAt(n))return!1;return!0}function u(e,t){return e===t?0:e>t?1:-1}n.getArg=function(e,t,n){if(t in e)return e[t];if(3===arguments.length)return n;throw new Error('"'+t+'" is a required argument.')};var c=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,l=/^data:.+\,.+$/;n.urlParse=r,n.urlGenerate=i,n.normalize=s,n.join=function(e,t){""===e&&(e="."),""===t&&(t=".");var n=r(t),o=r(e);if(o&&(e=o.path||"/"),n&&!n.scheme)return o&&(n.scheme=o.scheme),i(n);if(n||t.match(l))return t;if(o&&!o.host&&!o.path)return o.host=t,i(o);var a="/"===t.charAt(0)?t:s(e.replace(/\/+$/,"")+"/"+t);return o?(o.path=a,i(o)):a},n.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(c)},n.relative=function(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var n=0;0!==t.indexOf(e+"/");){var r=e.lastIndexOf("/");if(r<0)return t;if((e=e.slice(0,r)).match(/^([^\/]+:\/)?\/*$/))return t;++n}return Array(n+1).join("../")+t.substr(e.length+1)};var p=!("__proto__"in Object.create(null));n.toSetString=p?o:function(e){return a(e)?"$"+e:e},n.fromSetString=p?o:function(e){return a(e)?e.slice(1):e},n.compareByOriginalPositions=function(e,t,n){var r=e.source-t.source;return 0!==r?r:0!=(r=e.originalLine-t.originalLine)?r:0!=(r=e.originalColumn-t.originalColumn)||n?r:0!=(r=e.generatedColumn-t.generatedColumn)?r:0!=(r=e.generatedLine-t.generatedLine)?r:e.name-t.name},n.compareByGeneratedPositionsDeflated=function(e,t,n){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!=(r=e.generatedColumn-t.generatedColumn)||n?r:0!=(r=e.source-t.source)?r:0!=(r=e.originalLine-t.originalLine)?r:0!=(r=e.originalColumn-t.originalColumn)?r:e.name-t.name},n.compareByGeneratedPositionsInflated=function(e,t){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!=(n=e.generatedColumn-t.generatedColumn)?n:0!==(n=u(e.source,t.source))?n:0!=(n=e.originalLine-t.originalLine)?n:0!=(n=e.originalColumn-t.originalColumn)?n:u(e.name,t.name)}},{}],24:[function(e,t,n){n.SourceMapGenerator=e("./lib/source-map-generator").SourceMapGenerator,n.SourceMapConsumer=e("./lib/source-map-consumer").SourceMapConsumer,n.SourceNode=e("./lib/source-node").SourceNode},{"./lib/source-map-consumer":20,"./lib/source-map-generator":21,"./lib/source-node":22}],25:[function(e,t,n){t.exports={_args:[[{raw:"nodent-compiler@>=3.1.3",scope:null,escapedName:"nodent-compiler",name:"nodent-compiler",rawSpec:">=3.1.3",spec:">=3.1.3",type:"range"},"/Users/evgenypoberezkin/Documents/JSON/ajv/node_modules/nodent"]],_from:"nodent-compiler@>=3.1.3",_id:"nodent-compiler@3.1.3",_inCache:!0,_location:"/nodent-compiler",_nodeVersion:"8.4.0",_npmOperationalInternal:{host:"s3://npm-registry-packages",tmp:"tmp/nodent-compiler-3.1.3.tgz_1504874988276_0.6329000329133123"},_npmUser:{name:"matatbread",email:"npm@mailed.me.uk"},_npmVersion:"5.3.0",_phantomChildren:{},_requested:{raw:"nodent-compiler@>=3.1.3",scope:null,escapedName:"nodent-compiler",name:"nodent-compiler",rawSpec:">=3.1.3",spec:">=3.1.3",type:"range"},_requiredBy:["/nodent"],_resolved:"https://registry.npmjs.org/nodent-compiler/-/nodent-compiler-3.1.3.tgz",_shasum:"6f0f1f8098db251ec773742bb4f33cd0266434b2",_shrinkwrap:null,_spec:"nodent-compiler@>=3.1.3",_where:"/Users/evgenypoberezkin/Documents/JSON/ajv/node_modules/nodent",author:{name:"Mat At Bread",email:"nodent@mailed.me.uk"},bugs:{url:"https://github.com/MatAtBread/nodent/issues"},dependencies:{acorn:">=2.5.2","acorn-es7-plugin":">=1.1.6","source-map":"^0.5.6"},description:"NoDent - Asynchronous Javascript language extensions",devDependencies:{},directories:{},dist:{integrity:"sha512-pcUC9gIgXXI3mbGjESZfVZO4Vgarw63xYZFRdkqxCDnygvvpiAwzwvvJ7rWqskp72Nk3cxWZY/rYxUIkPT14lw==",shasum:"6f0f1f8098db251ec773742bb4f33cd0266434b2",tarball:"https://registry.npmjs.org/nodent-compiler/-/nodent-compiler-3.1.3.tgz"},engines:"node >= 0.10.0",gitHead:"d72c5767ca302884c3215e6267d4910239add177",homepage:"https://github.com/MatAtBread/nodent-compiler#readme",keywords:["Javascript","ES7","async","await","language","extensions","Node","callback","generator","Promise","asynchronous"],license:"BSD-2-Clause",main:"compiler.js",maintainers:[{name:"matatbread",email:"npm@mailed.me.uk"}],name:"nodent-compiler",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/MatAtBread/nodent-compiler.git"},scripts:{test:"node tests/basic.js # Please install 'nodent' and test the compiler fully from there."},version:"3.1.3"}},{}],26:[function(e,t,n){"use strict";function r(e,t){if(Function.prototype.$asyncspawn||Object.defineProperty(Function.prototype,"$asyncspawn",{value:r,enumerable:!1,configurable:!0,writable:!0}),this instanceof Function){var n=this;return new e(function(e,r){function i(t,n){var o;try{if((o=t.call(s,n)).done){if(o.value!==e){if(o.value&&o.value===o.value.then)return o.value(e,r);e&&e(o.value),e=null}return}o.value.then?o.value.then(function(e){i(s.next,e)},function(e){i(s.throw,e)}):i(s.next,o.value)}catch(e){return r&&r(e),void(r=null)}}var s=n.call(t,e,r);i(s.next)})}}var i=function(e,t){for(var n=t.toString(),r="return "+n,i=n.match(/.*\(([^)]*)\)/)[1],s=/['"]!!!([^'"]*)['"]/g,o=[];;){var a=s.exec(r);if(!a)break;o.push(a)}return o.reverse().forEach(function(t){r=r.slice(0,t.index)+e[t[1]]+r.substr(t.index+t[0].length)}),r=r.replace(/\/\*[^*]*\*\//g," ").replace(/\s+/g," "),new Function(i,r)()}({zousan:e("./zousan").toString(),thenable:e("./thenableFactory").toString()},function e(t,n){function r(){return i.apply(t,arguments)}Function.prototype.$asyncbind||Object.defineProperty(Function.prototype,"$asyncbind",{value:e,enumerable:!1,configurable:!0,writable:!0}),e.trampoline||(e.trampoline=function(e,t,n,r,i){return function s(o){for(;o;){if(o.then)return o=o.then(s,r),i?void 0:o;try{if(o.pop){if(o.length)return o.pop()?t.call(e):o;o=n}else o=o.call(e)}catch(e){return r(e)}}}}),e.LazyThenable||(e.LazyThenable="!!!thenable"(),e.EagerThenable=e.Thenable=(e.EagerThenableFactory="!!!zousan")());var i=this;switch(n){case!0:return new e.Thenable(r);case 0:return new e.LazyThenable(r);case void 0:return r.then=r,r;default:return function(){try{return i.apply(t,arguments)}catch(e){return n(e)}}}});i(),r(),t.exports={$asyncbind:i,$asyncspawn:r}},{"./thenableFactory":27,"./zousan":28}],27:[function(e,t,n){t.exports=function(){function e(e){return e&&e instanceof Object&&"function"==typeof e.then}function t(n,r,i){try{var s=i?i(r):r;if(n===s)return n.reject(new TypeError("Promise resolution loop"));e(s)?s.then(function(e){t(n,e)},function(e){n.reject(e)}):n.resolve(s)}catch(e){n.reject(e)}}function n(){}function r(e){}function i(r,i){var s=new n;try{this._resolver(function(n){return e(n)?n.then(r,i):t(s,n,r)},function(e){t(s,e,i)})}catch(e){t(s,e,i)}return s}function s(e){this._resolver=e,this.then=i}return n.prototype={resolve:r,reject:r,then:function(e,t){this.resolve=e,this.reject=t}},s.resolve=function(e){return s.isThenable(e)?e:{then:function(t){return t(e)}}},s.isThenable=e,s}},{}],28:[function(e,t,n){(function(e){"use strict";t.exports=function(t){function n(e){if(e){var t=this;e(function(e){t.resolve(e)},function(e){t.reject(e)})}}function r(e,t){if("function"==typeof e.y)try{var n=e.y.call(void 0,t);e.p.resolve(n)}catch(t){e.p.reject(t)}else e.p.resolve(t)}function i(e,t){if("function"==typeof e.n)try{var n=e.n.call(void 0,t);e.p.resolve(n)}catch(t){e.p.reject(t)}else e.p.reject(t)}t=t||"object"==typeof e&&e.nextTick||"function"==typeof setImmediate&&setImmediate||function(e){setTimeout(e,0)};var s=function(){function e(){for(;n.length-r;){try{n[r]()}catch(e){}n[r++]=void 0,r===i&&(n.splice(0,i),r=0)}}var n=[],r=0,i=1024;return function(i){n.push(i),n.length-r==1&&t(e)}}();return n.prototype={resolve:function(e){if(void 0===this.state){if(e===this)return this.reject(new TypeError("Attempt to resolve promise with self"));var t=this;if(e&&("function"==typeof e||"object"==typeof e))try{var n=0,i=e.then;if("function"==typeof i)return void i.call(e,function(e){n++||t.resolve(e)},function(e){n++||t.reject(e)})}catch(e){return void(n||this.reject(e))}this.state=r,this.v=e,t.c&&s(function(){for(var n=0,i=t.c.length;n]*>)(.*)/i,/(.*)(<\/script>)(.*)/i],o=0,a=!0;t=t.split("\n");for(var u=0;u=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function r(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r=-1&&!i;s--){var o=s>=0?arguments[s]:e.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(n=o+"/"+n,i="/"===o.charAt(0))}return n=t(r(n.split("/"),function(e){return!!e}),!i).join("/"),(i?"/":"")+n||"."},n.normalize=function(e){var i=n.isAbsolute(e),s="/"===o(e,-1);return(e=t(r(e.split("/"),function(e){return!!e}),!i).join("/"))||i||(e="."),e&&s&&(e+="/"),(i?"/":"")+e},n.isAbsolute=function(e){return"/"===e.charAt(0)},n.join=function(){var e=Array.prototype.slice.call(arguments,0);return n.normalize(r(e,function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},n.relative=function(e,t){function r(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=n.resolve(e).substr(1),t=n.resolve(t).substr(1);for(var i=r(e.split("/")),s=r(t.split("/")),o=Math.min(i.length,s.length),a=o,u=0;u1)for(var n=1;n= 8.8",https:!0,_http_server:">= 0.11",_linklist:"< 8",module:!0,net:!0,os:!0,path:!0,perf_hooks:">= 8.5",process:">= 1",punycode:!0,querystring:!0,readline:!0,repl:!0,stream:!0,string_decoder:!0,sys:!0,timers:!0,tls:!0,tty:!0,url:!0,util:!0,v8:">= 1",vm:!0,zlib:!0}},{}],37:[function(e,t,n){(function(n){function r(e){if(!0===e)return!0;for(var t=e.split(" "),n=t[0],r=t[1].split("."),s=0;s<3;++s){var o=Number(i[s]||0),a=Number(r[s]||0);if(o!==a)return"<"===n?o="===n&&o>=a}return!1}var i=n.versions&&n.versions.node&&n.versions.node.split(".")||[],s=e("./core.json"),o={};for(var a in s)Object.prototype.hasOwnProperty.call(s,a)&&(o[a]=r(s[a]));t.exports=o}).call(this,e("_process"))},{"./core.json":36,_process:32}],38:[function(e,t,n){var r=e("path"),i=e("fs"),s=r.parse||e("path-parse");t.exports=function(e,t){var n=t&&t.moduleDirectory?[].concat(t.moduleDirectory):["node_modules"],o=r.resolve(e);if(t&&!1===t.preserveSymlinks)try{o=i.realpathSync(o)}catch(e){if("ENOENT"!==e.code)throw e}var a="/";/^([A-Za-z]:)/.test(o)?a="":/^\\\\/.test(o)&&(a="\\\\");for(var u=[o],c=s(o);c.dir!==u[u.length-1];)u.push(c.dir),c=s(c.dir);var l=u.reduce(function(e,t){return e.concat(n.map(function(e){return r.join(a,t,e)}))},[]);return t&&t.paths?l.concat(t.paths):l}},{fs:7,path:30,"path-parse":31}],39:[function(e,t,n){var r=e("./core"),i=e("fs"),s=e("path"),o=e("./caller.js"),a=e("./node-modules-paths.js");t.exports=function(e,t){function n(e){if(l(e))return e;for(var t=0;t"))}return Object.keys(hostOptions).forEach(function(k){"host"===parseOpts[k]&&(parseOpts[k]=function(){try{return eval(hostOptions[k]),!0}catch(e){return!1}}())}),parseOpts.promises||parseOpts.es7||parseOpts.generators||parseOpts.engine?((parseOpts.promises||parseOpts.es7)&&parseOpts.generators&&(log("No valid 'use nodent' directive, assumed -es7 mode"),parseOpts=optionSets.es7),(parseOpts.generators||parseOpts.engine)&&(parseOpts.promises=!0),parseOpts.promises&&(parseOpts.es7=!0),parseOpts):null}function stripBOM(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),"#!"===e.substring(0,2)&&(e="//"+e),e}function compileNodentedFile(e,t){return t=t||e.log,function(n,r,i){var s=stripBOM(fs.readFileSync(r,"utf8")),o=e.parse(s,r,i);i=i||parseCompilerOptions(o.ast,t,r),e.asynchronize(o,void 0,i,t),e.prettyPrint(o,i),n._compile(o.code,o.filename)}}function asyncify(e){return e=e||Thenable,function(t,n,r){if(Array.isArray(n)){var i=n;n=function(e,t){return i.indexOf(e)>=0}}else n=n||function(e,t){return!(e.match(/Sync$/)&&e.replace(/Sync$/,"")in t)};r||(r="");var s=Object.create(t);for(var o in s)!function(){var i=o;try{"function"!=typeof t[i]||s[i+r]&&s[i+r].isAsync||!n(i,s)||(s[i+r]=function(){var n=Array.prototype.slice.call(arguments);return new e(function(e,r){var s=function(t,n){if(t)return r(t);switch(arguments.length){case 0:return e();case 2:return e(n);default:return e(Array.prototype.slice.call(arguments,1))}};n.length>t[i].length?n.push(s):n[t[i].length-1]=s;t[i].apply(t,n)})},s[i+r].isAsync=!0)}catch(e){}}();return s.super=t,s}}function generateRequestHandler(e,t,n){var r={},i=this;t||(t=/\.njs$/),n?n.compiler||(n.compiler={}):n={compiler:{}};var s=copyObj([NodentCompiler.initialCodeGenOpts,n.compiler]);return function(o,a,u){function c(e){a.statusCode=500,a.write(e.toString()),a.end()}if(r[o.url])return a.setHeader("Content-Type",r[o.url].contentType),n.setHeaders&&n.setHeaders(a),a.write(r[o.url].output),void a.end();if(!(o.url.match(t)||n.htmlScriptRegex&&o.url.match(n.htmlScriptRegex)))return u&&u();var l=e+o.url;if(n.extensions&&!fs.existsSync(l))for(var p=0;p=0?this.covers[n]=require(e):this.covers[n]=require(__dirname+"/covers/"+e)),this.covers[n](this,t)}function prepareMappedStackTrace(e,t){return e+t.map(function(e){var t=e.getFileName();if(t&&NodentCompiler.prototype.smCache[t]){var n=NodentCompiler.prototype.smCache[t].smc.originalPositionFor({line:e.getLineNumber(),column:e.getColumnNumber()});if(n&&n.line){var r=e.toString();return"\n at "+r.substring(0,r.length-1)+" => …"+n.source+":"+n.line+":"+n.column+(e.getFunctionName()?")":"")}}return"\n at "+e}).join("")}function setGlobalEnvironment(e){var t={};t[defaultCodeGenOpts.$asyncbind]={value:$asyncbind,writable:!0,enumerable:!1,configurable:!0},t[defaultCodeGenOpts.$asyncspawn]={value:$asyncspawn,writable:!0,enumerable:!1,configurable:!0};try{Object.defineProperties(Function.prototype,t)}catch(t){e.log("Function prototypes already assigned: ",t.messsage)}defaultCodeGenOpts[defaultCodeGenOpts.$error]in global||(global[defaultCodeGenOpts[defaultCodeGenOpts.$error]]=globalErrorHandler),e.augmentObject&&Object.defineProperties(Object.prototype,{asyncify:{value:function(e,t,n){return asyncify(e)(this,t,n)},writable:!0,configurable:!0},isThenable:{value:function(){return Thenable.isThenable(this)},writable:!0,configurable:!0}}),Object[defaultCodeGenOpts.$makeThenable]=Thenable.resolve}function initialize(e){function t(n,r){if(!r.match(/nodent\/nodent\.js$/)){if(r.match(/node_modules\/nodent\/.*\.js$/))return stdJSLoader(n,r);for(var o=0;ot[n])return 1}return 0}(u.version,NodentCompiler.prototype.version)<0&&(u.originalNodentLoader=n.exports,n.exports=function(){var t=require.extensions[".js"],n=u.originalNodentLoader.apply(this,arguments);return u.jsCompiler=require.extensions[".js"],require.extensions[".js"]=t,setGlobalEnvironment(e),n},Object.keys(u.originalNodentLoader).forEach(function(e){n.exports[e]=u.originalNodentLoader[e]}),i.push(u),i=i.sort(function(e,t){return t.path.length-e.path.length})))}function n(t){if(Array.isArray(t))return t.forEach(n);if(require.extensions[t]){Object.keys(e).filter(function(t){return compiler[t]!=e[t]}).length&&e.log("File extension "+t+" already configured for async/await compilation.")}require.extensions[t]=compileNodentedFile(compiler,e.log)}if(e){for(var r in e)if("use"!==r&&!config.hasOwnProperty(r))throw new Error("NoDent: unknown option: "+r+"="+JSON.stringify(e[r]))}else e={};compiler?compiler.setOptions(e):(Object.keys(config).forEach(function(t){t in e||(e[t]=config[t])}),compiler=new NodentCompiler(e)),e.dontMapStackTraces||(Error.prepareStackTrace=prepareMappedStackTrace),setGlobalEnvironment(e);var i=[];if(!e.dontInstallRequireHook){if(!stdJSLoader){stdJSLoader=require.extensions[".js"];var s=compileNodentedFile(compiler,e.log);require.extensions[".js"]=t}e.extension&&n(e.extension)}return e.use&&(Array.isArray(e.use)?(e.log("Warning: nodent({use:[...]}) is deprecated. Use nodent.require(module,options)\n"+(new Error).stack.split("\n")[2]),e.use.length&&e.use.forEach(function(e){compiler[e]=compiler.require(e)})):(e.log("Warning: nodent({use:{...}}) is deprecated. Use nodent.require(module,options)\n"+(new Error).stack.split("\n")[2]),Object.keys(e.use).forEach(function(t){compiler[t]=compiler.require(t,e.use[t])}))),compiler}function runFromCLI(){function e(e,n){try{var s,o;if(r.fromast){if(e=JSON.parse(e),s={origCode:"",filename:t,ast:e},!(o=parseCompilerOptions(e,i.log))){var a=r.use?'"use nodent-'+r.use+'";':'"use nodent";';o=parseCompilerOptions(a,i.log),console.warn("/* "+t+": No 'use nodent*' directive, assumed "+a+" */")}}else(o=parseCompilerOptions(r.use?'"use nodent-'+r.use+'";':e,i.log))||(o=parseCompilerOptions('"use nodent";',i.log),r.dest||console.warn("/* "+t+": 'use nodent*' directive missing/ignored, assumed 'use nodent;' */")),s=i.parse(e,t,o);if(r.parseast||r.pretty||i.asynchronize(s,void 0,o,i.log),i.prettyPrint(s,o),r.out||r.pretty||r.dest){if(r.dest&&!n)throw new Error("Can't write unknown file to "+r.dest);var u="";r.runtime&&(u+="Function.prototype.$asyncbind = "+Function.prototype.$asyncbind.toString()+";\n",u+="global.$error = global.$error || "+global.$error.toString()+";\n"),u+=s.code,n&&r.dest?(fs.writeFileSync(r.dest+n,u),console.log("Compiled",r.dest+n)):console.log(u)}(r.minast||r.parseast)&&console.log(JSON.stringify(s.ast,function(e,t){return"$"===e[0]||e.match(/^(start|end|loc)$/)?void 0:t},2,null)),r.ast&&console.log(JSON.stringify(s.ast,function(e,t){return"$"===e[0]?void 0:t},0)),r.exec&&new Function(s.code)()}catch(e){console.error(e)}}var t,n=require("path"),r=(process.env.NODENT_OPTS&&JSON.parse(process.env.NODENT_OPTS),function(e){for(var t=[],n=e||2;n0",engine:"(async ()=>0)",noRuntime:"Promise"};NodentCompiler.prototype.Thenable=Thenable,NodentCompiler.prototype.EagerThenable=$asyncbind.EagerThenableFactory,NodentCompiler.prototype.asyncify=asyncify,NodentCompiler.prototype.require=requireCover,NodentCompiler.prototype.generateRequestHandler=generateRequestHandler,NodentCompiler.prototype.$asyncspawn=$asyncspawn,NodentCompiler.prototype.$asyncbind=$asyncbind,NodentCompiler.prototype.parseCompilerOptions=parseCompilerOptions,$asyncbind.call($asyncbind);var compiler;initialize.setDefaultCompileOptions=function(e,t){return e&&Object.keys(e).forEach(function(t){if(!(t in defaultCodeGenOpts))throw new Error("NoDent: unknown compiler option: "+t);defaultCodeGenOpts[t]=e[t]}),t&&Object.keys(t).forEach(function(e){if(!(e in t))throw new Error("NoDent: unknown configuration option: "+e);config[e]=t[e]}),initialize},initialize.setCompileOptions=function(e,t){return optionSet[e]=optionSet[e]||copyObj([defaultCodeGenOpts]),t&&Object.keys(t).forEach(function(n){if(!(n in defaultCodeGenOpts))throw new Error("NoDent: unknown compiler option: "+n);optionSet[e][n]=t[n]}),initialize},initialize.asyncify=asyncify,initialize.Thenable=$asyncbind.Thenable,initialize.EagerThenable=$asyncbind.EagerThenableFactory,module.exports=initialize,require.main===module&&process.argv.length>=3&&runFromCLI()}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},"/node_modules/nodent")},{"./htmlScriptParser":29,_process:32,fs:7,"nodent-compiler":10,"nodent-runtime":26,path:30,resolve:33}]},{},[]); \ No newline at end of file diff --git a/tools/eslint/node_modules/ajv/dist/regenerator.min.js b/tools/eslint/node_modules/ajv/dist/regenerator.min.js deleted file mode 100644 index 0b05fb9cf684d8..00000000000000 --- a/tools/eslint/node_modules/ajv/dist/regenerator.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/* regenerator 0.10.0: Source transformer enabling ECMAScript 6 generator functions (yield) in JavaScript-of-today (ES5) */ -require=function e(t,r,n){function i(a,o){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!o&&u)return u(a,!0);if(s)return s(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=r[a]={exports:{}};t[a][0].call(c.exports,function(e){var r=t[a][1][e];return i(r||e)},c,c.exports,e,t,r,n)}return r[a].exports}for(var s="function"==typeof require&&require,a=0;a=0;o--)if(u[o]!==l[o])return!1;for(o=u.length-1;o>=0;o--)if(a=u[o],!h(e[a],t[a],r,n))return!1;return!0}(e,t,r,o))}return r?e===t:e==t}function f(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function d(e,t,r){h(e,t,!0)&&c(e,t,r,"notDeepStrictEqual",d)}function m(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function y(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&c(i,r,"Missing expected exception"+n);var s="string"==typeof n,a=!e&&g.isError(i),o=!e&&i&&!r;if((a&&s&&m(i,r)||o)&&c(i,r,"Got unwanted exception"+n),e&&i&&r&&!m(i,r)||!e&&i)throw i}var g=e("util/"),b=Object.prototype.hasOwnProperty,v=Array.prototype.slice,x="foo"===function(){}.name,E=t.exports=p,A=/\s*function\s+([^\(\s]*)\s*/;E.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=function(e){return u(l(e.actual),128)+" "+e.operator+" "+u(l(e.expected),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||c;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var r=new Error;if(r.stack){var n=r.stack,i=o(t),s=n.indexOf("\n"+i);if(s>=0){var a=n.indexOf("\n",s+1);n=n.substring(a+1)}this.stack=n}}},g.inherits(E.AssertionError,Error),E.fail=c,E.ok=p,E.equal=function(e,t,r){e!=t&&c(e,t,r,"==",E.equal)},E.notEqual=function(e,t,r){e==t&&c(e,t,r,"!=",E.notEqual)},E.deepEqual=function(e,t,r){h(e,t,!1)||c(e,t,r,"deepEqual",E.deepEqual)},E.deepStrictEqual=function(e,t,r){h(e,t,!0)||c(e,t,r,"deepStrictEqual",E.deepStrictEqual)},E.notDeepEqual=function(e,t,r){h(e,t,!1)&&c(e,t,r,"notDeepEqual",E.notDeepEqual)},E.notDeepStrictEqual=d,E.strictEqual=function(e,t,r){e!==t&&c(e,t,r,"===",E.strictEqual)},E.notStrictEqual=function(e,t,r){e===t&&c(e,t,r,"!==",E.notStrictEqual)},E.throws=function(e,t,r){y(!0,e,t,r)},E.doesNotThrow=function(e,t,r){y(!1,e,t,r)},E.ifError=function(e){if(e)throw e};var D=Object.keys||function(e){var t=[];for(var r in e)b.call(e,r)&&t.push(r);return t}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":613}],2:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=t.use(e("../lib/shared")).defaults,i=r.Type.def,s=r.Type.or;i("Noop").bases("Node").build(),i("DoExpression").bases("Expression").build("body").field("body",[i("Statement")]),i("Super").bases("Expression").build(),i("BindExpression").bases("Expression").build("object","callee").field("object",s(i("Expression"),null)).field("callee",i("Expression")),i("Decorator").bases("Node").build("expression").field("expression",i("Expression")),i("Property").field("decorators",s([i("Decorator")],null),n.null),i("MethodDefinition").field("decorators",s([i("Decorator")],null),n.null),i("MetaProperty").bases("Expression").build("meta","property").field("meta",i("Identifier")).field("property",i("Identifier")),i("ParenthesizedExpression").bases("Expression").build("expression").field("expression",i("Expression")),i("ImportSpecifier").bases("ModuleSpecifier").build("imported","local").field("imported",i("Identifier")),i("ImportDefaultSpecifier").bases("ModuleSpecifier").build("local"),i("ImportNamespaceSpecifier").bases("ModuleSpecifier").build("local"),i("ExportDefaultDeclaration").bases("Declaration").build("declaration").field("declaration",s(i("Declaration"),i("Expression"))),i("ExportNamedDeclaration").bases("Declaration").build("declaration","specifiers","source").field("declaration",s(i("Declaration"),null)).field("specifiers",[i("ExportSpecifier")],n.emptyArray).field("source",s(i("Literal"),null),n.null),i("ExportSpecifier").bases("ModuleSpecifier").build("local","exported").field("exported",i("Identifier")),i("ExportNamespaceSpecifier").bases("Specifier").build("exported").field("exported",i("Identifier")),i("ExportDefaultSpecifier").bases("Specifier").build("exported").field("exported",i("Identifier")),i("ExportAllDeclaration").bases("Declaration").build("exported","source").field("exported",s(i("Identifier"),null)).field("source",i("Literal")),i("CommentBlock").bases("Comment").build("value","leading","trailing"),i("CommentLine").bases("Comment").build("value","leading","trailing")}},{"../lib/shared":18,"../lib/types":19,"./es7":7}],3:[function(e,t,r){t.exports=function(t){t.use(e("./babel")),t.use(e("./flow"));var r=t.use(e("../lib/types")),n=t.use(e("../lib/shared")).defaults,i=r.Type.def,s=r.Type.or;i("Directive").bases("Node").build("value").field("value",i("DirectiveLiteral")),i("DirectiveLiteral").bases("Node","Expression").build("value").field("value",String,n["use strict"]),i("BlockStatement").bases("Statement").build("body").field("body",[i("Statement")]).field("directives",[i("Directive")],n.emptyArray),i("Program").bases("Node").build("body").field("body",[i("Statement")]).field("directives",[i("Directive")],n.emptyArray),i("StringLiteral").bases("Literal").build("value").field("value",String),i("NumericLiteral").bases("Literal").build("value").field("value",Number),i("NullLiteral").bases("Literal").build(),i("BooleanLiteral").bases("Literal").build("value").field("value",Boolean),i("RegExpLiteral").bases("Literal").build("pattern","flags").field("pattern",String).field("flags",String);var a=s(i("Property"),i("ObjectMethod"),i("ObjectProperty"),i("SpreadProperty"));i("ObjectExpression").bases("Expression").build("properties").field("properties",[a]),i("ObjectMethod").bases("Node","Function").build("kind","key","params","body","computed").field("kind",s("method","get","set")).field("key",s(i("Literal"),i("Identifier"),i("Expression"))).field("params",[i("Pattern")]).field("body",i("BlockStatement")).field("computed",Boolean,n.false).field("generator",Boolean,n.false).field("async",Boolean,n.false).field("decorators",s([i("Decorator")],null),n.null),i("ObjectProperty").bases("Node").build("key","value").field("key",s(i("Literal"),i("Identifier"),i("Expression"))).field("value",s(i("Expression"),i("Pattern"))).field("computed",Boolean,n.false);var o=s(i("MethodDefinition"),i("VariableDeclarator"),i("ClassPropertyDefinition"),i("ClassProperty"),i("ClassMethod"));i("ClassBody").bases("Declaration").build("body").field("body",[o]),i("ClassMethod").bases("Declaration","Function").build("kind","key","params","body","computed","static").field("kind",s("get","set","method","constructor")).field("key",s(i("Literal"),i("Identifier"),i("Expression"))).field("params",[i("Pattern")]).field("body",i("BlockStatement")).field("computed",Boolean,n.false).field("static",Boolean,n.false).field("generator",Boolean,n.false).field("async",Boolean,n.false).field("decorators",s([i("Decorator")],null),n.null);var u=s(i("Property"),i("PropertyPattern"),i("SpreadPropertyPattern"),i("SpreadProperty"),i("ObjectProperty"),i("RestProperty"));i("ObjectPattern").bases("Pattern").build("properties").field("properties",[u]).field("decorators",s([i("Decorator")],null),n.null),i("SpreadProperty").bases("Node").build("argument").field("argument",i("Expression")),i("RestProperty").bases("Node").build("argument").field("argument",i("Expression")),i("ForAwaitStatement").bases("Statement").build("left","right","body").field("left",s(i("VariableDeclaration"),i("Expression"))).field("right",i("Expression")).field("body",i("Statement")),i("Import").bases("Expression").build()}},{"../lib/shared":18,"../lib/types":19,"./babel":2,"./flow":9}],4:[function(e,t,r){t.exports=function(t){var r=t.use(e("../lib/types")).Type,n=r.def,i=r.or,s=t.use(e("../lib/shared")),a=s.defaults,o=s.geq;n("Printable").field("loc",i(n("SourceLocation"),null),a.null,!0),n("Node").bases("Printable").field("type",String).field("comments",i([n("Comment")],null),a.null,!0),n("SourceLocation").build("start","end","source").field("start",n("Position")).field("end",n("Position")).field("source",i(String,null),a.null),n("Position").build("line","column").field("line",o(1)).field("column",o(0)),n("File").bases("Node").build("program","name").field("program",n("Program")).field("name",i(String,null),a.null),n("Program").bases("Node").build("body").field("body",[n("Statement")]),n("Function").bases("Node").field("id",i(n("Identifier"),null),a.null).field("params",[n("Pattern")]).field("body",n("BlockStatement")),n("Statement").bases("Node"),n("EmptyStatement").bases("Statement").build(),n("BlockStatement").bases("Statement").build("body").field("body",[n("Statement")]),n("ExpressionStatement").bases("Statement").build("expression").field("expression",n("Expression")),n("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",n("Expression")).field("consequent",n("Statement")).field("alternate",i(n("Statement"),null),a.null),n("LabeledStatement").bases("Statement").build("label","body").field("label",n("Identifier")).field("body",n("Statement")),n("BreakStatement").bases("Statement").build("label").field("label",i(n("Identifier"),null),a.null),n("ContinueStatement").bases("Statement").build("label").field("label",i(n("Identifier"),null),a.null),n("WithStatement").bases("Statement").build("object","body").field("object",n("Expression")).field("body",n("Statement")),n("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",n("Expression")).field("cases",[n("SwitchCase")]).field("lexical",Boolean,a.false),n("ReturnStatement").bases("Statement").build("argument").field("argument",i(n("Expression"),null)),n("ThrowStatement").bases("Statement").build("argument").field("argument",n("Expression")),n("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",n("BlockStatement")).field("handler",i(n("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[n("CatchClause")],function(){return this.handler?[this.handler]:[]},!0).field("guardedHandlers",[n("CatchClause")],a.emptyArray).field("finalizer",i(n("BlockStatement"),null),a.null),n("CatchClause").bases("Node").build("param","guard","body").field("param",n("Pattern")).field("guard",i(n("Expression"),null),a.null).field("body",n("BlockStatement")),n("WhileStatement").bases("Statement").build("test","body").field("test",n("Expression")).field("body",n("Statement")),n("DoWhileStatement").bases("Statement").build("body","test").field("body",n("Statement")).field("test",n("Expression")),n("ForStatement").bases("Statement").build("init","test","update","body").field("init",i(n("VariableDeclaration"),n("Expression"),null)).field("test",i(n("Expression"),null)).field("update",i(n("Expression"),null)).field("body",n("Statement")),n("ForInStatement").bases("Statement").build("left","right","body").field("left",i(n("VariableDeclaration"),n("Expression"))).field("right",n("Expression")).field("body",n("Statement")),n("DebuggerStatement").bases("Statement").build(),n("Declaration").bases("Statement"),n("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",n("Identifier")),n("FunctionExpression").bases("Function","Expression").build("id","params","body"),n("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",i("var","let","const")).field("declarations",[n("VariableDeclarator")]),n("VariableDeclarator").bases("Node").build("id","init").field("id",n("Pattern")).field("init",i(n("Expression"),null)),n("Expression").bases("Node","Pattern"),n("ThisExpression").bases("Expression").build(),n("ArrayExpression").bases("Expression").build("elements").field("elements",[i(n("Expression"),null)]),n("ObjectExpression").bases("Expression").build("properties").field("properties",[n("Property")]),n("Property").bases("Node").build("kind","key","value").field("kind",i("init","get","set")).field("key",i(n("Literal"),n("Identifier"))).field("value",n("Expression")),n("SequenceExpression").bases("Expression").build("expressions").field("expressions",[n("Expression")]);var u=i("-","+","!","~","typeof","void","delete");n("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",u).field("argument",n("Expression")).field("prefix",Boolean,a.true);var l=i("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");n("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",l).field("left",n("Expression")).field("right",n("Expression"));var c=i("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");n("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",c).field("left",n("Pattern")).field("right",n("Expression"));var p=i("++","--");n("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",p).field("argument",n("Expression")).field("prefix",Boolean);var h=i("||","&&");n("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",h).field("left",n("Expression")).field("right",n("Expression")),n("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",n("Expression")).field("consequent",n("Expression")).field("alternate",n("Expression")),n("NewExpression").bases("Expression").build("callee","arguments").field("callee",n("Expression")).field("arguments",[n("Expression")]),n("CallExpression").bases("Expression").build("callee","arguments").field("callee",n("Expression")).field("arguments",[n("Expression")]),n("MemberExpression").bases("Expression").build("object","property","computed").field("object",n("Expression")).field("property",i(n("Identifier"),n("Expression"))).field("computed",Boolean,function(){var e=this.property.type;return"Literal"===e||"MemberExpression"===e||"BinaryExpression"===e}),n("Pattern").bases("Node"),n("SwitchCase").bases("Node").build("test","consequent").field("test",i(n("Expression"),null)).field("consequent",[n("Statement")]),n("Identifier").bases("Node","Expression","Pattern").build("name").field("name",String),n("Literal").bases("Node","Expression").build("value").field("value",i(String,Boolean,null,Number,RegExp)).field("regex",i({pattern:String,flags:String},null),function(){if(this.value instanceof RegExp){var e="";return this.value.ignoreCase&&(e+="i"),this.value.multiline&&(e+="m"),this.value.global&&(e+="g"),{pattern:this.value.source,flags:e}}return null}),n("Comment").bases("Printable").field("value",String).field("leading",Boolean,a.true).field("trailing",Boolean,a.false)}},{"../lib/shared":18,"../lib/types":19}],5:[function(e,t,r){t.exports=function(t){t.use(e("./core"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or;n("XMLDefaultDeclaration").bases("Declaration").field("namespace",n("Expression")),n("XMLAnyName").bases("Expression"),n("XMLQualifiedIdentifier").bases("Expression").field("left",i(n("Identifier"),n("XMLAnyName"))).field("right",i(n("Identifier"),n("Expression"))).field("computed",Boolean),n("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",i(n("Identifier"),n("Expression"))).field("computed",Boolean),n("XMLAttributeSelector").bases("Expression").field("attribute",n("Expression")),n("XMLFilterExpression").bases("Expression").field("left",n("Expression")).field("right",n("Expression")),n("XMLElement").bases("XML","Expression").field("contents",[n("XML")]),n("XMLList").bases("XML","Expression").field("contents",[n("XML")]),n("XML").bases("Node"),n("XMLEscape").bases("XML").field("expression",n("Expression")),n("XMLText").bases("XML").field("text",String),n("XMLStartTag").bases("XML").field("contents",[n("XML")]),n("XMLEndTag").bases("XML").field("contents",[n("XML")]),n("XMLPointTag").bases("XML").field("contents",[n("XML")]),n("XMLName").bases("XML").field("contents",i(String,[n("XML")])),n("XMLAttribute").bases("XML").field("value",String),n("XMLCdata").bases("XML").field("contents",String),n("XMLComment").bases("XML").field("contents",String),n("XMLProcessingInstruction").bases("XML").field("target",String).field("contents",i(String,null))}},{"../lib/types":19,"./core":4}],6:[function(e,t,r){t.exports=function(t){t.use(e("./core"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")).defaults;n("Function").field("generator",Boolean,s.false).field("expression",Boolean,s.false).field("defaults",[i(n("Expression"),null)],s.emptyArray).field("rest",i(n("Identifier"),null),s.null),n("RestElement").bases("Pattern").build("argument").field("argument",n("Pattern")),n("SpreadElementPattern").bases("Pattern").build("argument").field("argument",n("Pattern")),n("FunctionDeclaration").build("id","params","body","generator","expression"),n("FunctionExpression").build("id","params","body","generator","expression"),n("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,s.null).field("body",i(n("BlockStatement"),n("Expression"))).field("generator",!1,s.false),n("YieldExpression").bases("Expression").build("argument","delegate").field("argument",i(n("Expression"),null)).field("delegate",Boolean,s.false),n("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",n("Expression")).field("blocks",[n("ComprehensionBlock")]).field("filter",i(n("Expression"),null)),n("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",n("Expression")).field("blocks",[n("ComprehensionBlock")]).field("filter",i(n("Expression"),null)),n("ComprehensionBlock").bases("Node").build("left","right","each").field("left",n("Pattern")).field("right",n("Expression")).field("each",Boolean),n("Property").field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("value",i(n("Expression"),n("Pattern"))).field("method",Boolean,s.false).field("shorthand",Boolean,s.false).field("computed",Boolean,s.false),n("PropertyPattern").bases("Pattern").build("key","pattern").field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("pattern",n("Pattern")).field("computed",Boolean,s.false),n("ObjectPattern").bases("Pattern").build("properties").field("properties",[i(n("PropertyPattern"),n("Property"))]),n("ArrayPattern").bases("Pattern").build("elements").field("elements",[i(n("Pattern"),null)]),n("MethodDefinition").bases("Declaration").build("kind","key","value","static").field("kind",i("constructor","method","get","set")).field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("value",n("Function")).field("computed",Boolean,s.false).field("static",Boolean,s.false),n("SpreadElement").bases("Node").build("argument").field("argument",n("Expression")),n("ArrayExpression").field("elements",[i(n("Expression"),n("SpreadElement"),n("RestElement"),null)]),n("NewExpression").field("arguments",[i(n("Expression"),n("SpreadElement"))]),n("CallExpression").field("arguments",[i(n("Expression"),n("SpreadElement"))]),n("AssignmentPattern").bases("Pattern").build("left","right").field("left",n("Pattern")).field("right",n("Expression"));var a=i(n("MethodDefinition"),n("VariableDeclarator"),n("ClassPropertyDefinition"),n("ClassProperty"));n("ClassProperty").bases("Declaration").build("key").field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("computed",Boolean,s.false),n("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",a),n("ClassBody").bases("Declaration").build("body").field("body",[a]),n("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",i(n("Identifier"),null)).field("body",n("ClassBody")).field("superClass",i(n("Expression"),null),s.null),n("ClassExpression").bases("Expression").build("id","body","superClass").field("id",i(n("Identifier"),null),s.null).field("body",n("ClassBody")).field("superClass",i(n("Expression"),null),s.null).field("implements",[n("ClassImplements")],s.emptyArray),n("ClassImplements").bases("Node").build("id").field("id",n("Identifier")).field("superClass",i(n("Expression"),null),s.null),n("Specifier").bases("Node"),n("ModuleSpecifier").bases("Specifier").field("local",i(n("Identifier"),null),s.null).field("id",i(n("Identifier"),null),s.null).field("name",i(n("Identifier"),null),s.null),n("TaggedTemplateExpression").bases("Expression").build("tag","quasi").field("tag",n("Expression")).field("quasi",n("TemplateLiteral")),n("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[n("TemplateElement")]).field("expressions",[n("Expression")]),n("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:String,raw:String}).field("tail",Boolean)}},{"../lib/shared":18,"../lib/types":19,"./core":4}],7:[function(e,t,r){t.exports=function(t){t.use(e("./es6"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=(r.builtInTypes,t.use(e("../lib/shared")).defaults);n("Function").field("async",Boolean,s.false),n("SpreadProperty").bases("Node").build("argument").field("argument",n("Expression")),n("ObjectExpression").field("properties",[i(n("Property"),n("SpreadProperty"))]),n("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",n("Pattern")),n("ObjectPattern").field("properties",[i(n("Property"),n("PropertyPattern"),n("SpreadPropertyPattern"))]),n("AwaitExpression").bases("Expression").build("argument","all").field("argument",i(n("Expression"),null)).field("all",Boolean,s.false)}},{"../lib/shared":18,"../lib/types":19,"./es6":6}],8:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=t.use(e("../lib/shared")).defaults,i=r.Type.def,s=r.Type.or;i("VariableDeclaration").field("declarations",[s(i("VariableDeclarator"),i("Identifier"))]),i("Property").field("value",s(i("Expression"),i("Pattern"))),i("ArrayPattern").field("elements",[s(i("Pattern"),i("SpreadElement"),null)]),i("ObjectPattern").field("properties",[s(i("Property"),i("PropertyPattern"),i("SpreadPropertyPattern"),i("SpreadProperty"))]),i("ExportSpecifier").bases("ModuleSpecifier").build("id","name"),i("ExportBatchSpecifier").bases("Specifier").build(),i("ImportSpecifier").bases("ModuleSpecifier").build("id","name"),i("ImportNamespaceSpecifier").bases("ModuleSpecifier").build("id"),i("ImportDefaultSpecifier").bases("ModuleSpecifier").build("id"),i("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",Boolean).field("declaration",s(i("Declaration"),i("Expression"),null)).field("specifiers",[s(i("ExportSpecifier"),i("ExportBatchSpecifier"))],n.emptyArray).field("source",s(i("Literal"),null),n.null),i("ImportDeclaration").bases("Declaration").build("specifiers","source","importKind").field("specifiers",[s(i("ImportSpecifier"),i("ImportNamespaceSpecifier"),i("ImportDefaultSpecifier"))],n.emptyArray).field("source",i("Literal")).field("importKind",s("value","type"),function(){return"value"}),i("Block").bases("Comment").build("value","leading","trailing"),i("Line").bases("Comment").build("value","leading","trailing")}},{"../lib/shared":18,"../lib/types":19,"./es7":7}],9:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")).defaults;n("Type").bases("Node"),n("AnyTypeAnnotation").bases("Type").build(),n("EmptyTypeAnnotation").bases("Type").build(),n("MixedTypeAnnotation").bases("Type").build(),n("VoidTypeAnnotation").bases("Type").build(),n("NumberTypeAnnotation").bases("Type").build(),n("NumberLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",Number).field("raw",String),n("NumericLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",Number).field("raw",String),n("StringTypeAnnotation").bases("Type").build(),n("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",String).field("raw",String),n("BooleanTypeAnnotation").bases("Type").build(),n("BooleanLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",Boolean).field("raw",String),n("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",n("Type")),n("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",n("Type")),n("NullLiteralTypeAnnotation").bases("Type").build(),n("NullTypeAnnotation").bases("Type").build(),n("ThisTypeAnnotation").bases("Type").build(),n("ExistsTypeAnnotation").bases("Type").build(),n("ExistentialTypeParam").bases("Type").build(),n("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[n("FunctionTypeParam")]).field("returnType",n("Type")).field("rest",i(n("FunctionTypeParam"),null)).field("typeParameters",i(n("TypeParameterDeclaration"),null)),n("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",n("Identifier")).field("typeAnnotation",n("Type")).field("optional",Boolean),n("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",n("Type")),n("ObjectTypeAnnotation").bases("Type").build("properties","indexers","callProperties").field("properties",[n("ObjectTypeProperty")]).field("indexers",[n("ObjectTypeIndexer")],s.emptyArray).field("callProperties",[n("ObjectTypeCallProperty")],s.emptyArray).field("exact",Boolean,s.false),n("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",i(n("Literal"),n("Identifier"))).field("value",n("Type")).field("optional",Boolean).field("variance",i("plus","minus",null),s.null),n("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",n("Identifier")).field("key",n("Type")).field("value",n("Type")).field("variance",i("plus","minus",null),s.null),n("ObjectTypeCallProperty").bases("Node").build("value").field("value",n("FunctionTypeAnnotation")).field("static",Boolean,s.false),n("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",i(n("Identifier"),n("QualifiedTypeIdentifier"))).field("id",n("Identifier")),n("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",i(n("Identifier"),n("QualifiedTypeIdentifier"))).field("typeParameters",i(n("TypeParameterInstantiation"),null)),n("MemberTypeAnnotation").bases("Type").build("object","property").field("object",n("Identifier")).field("property",i(n("MemberTypeAnnotation"),n("GenericTypeAnnotation"))),n("UnionTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",n("Type")),n("Identifier").field("typeAnnotation",i(n("TypeAnnotation"),null),s.null),n("TypeParameterDeclaration").bases("Node").build("params").field("params",[n("TypeParameter")]),n("TypeParameterInstantiation").bases("Node").build("params").field("params",[n("Type")]),n("TypeParameter").bases("Type").build("name","variance","bound").field("name",String).field("variance",i("plus","minus",null),s.null).field("bound",i(n("TypeAnnotation"),null),s.null),n("Function").field("returnType",i(n("TypeAnnotation"),null),s.null).field("typeParameters",i(n("TypeParameterDeclaration"),null),s.null),n("ClassProperty").build("key","value","typeAnnotation","static").field("value",i(n("Expression"),null)).field("typeAnnotation",i(n("TypeAnnotation"),null)).field("static",Boolean,s.false).field("variance",i("plus","minus",null),s.null),n("ClassImplements").field("typeParameters",i(n("TypeParameterInstantiation"),null),s.null),n("InterfaceDeclaration").bases("Declaration").build("id","body","extends").field("id",n("Identifier")).field("typeParameters",i(n("TypeParameterDeclaration"),null),s.null).field("body",n("ObjectTypeAnnotation")).field("extends",[n("InterfaceExtends")]),n("DeclareInterface").bases("InterfaceDeclaration").build("id","body","extends"),n("InterfaceExtends").bases("Node").build("id").field("id",n("Identifier")).field("typeParameters",i(n("TypeParameterInstantiation"),null)),n("TypeAlias").bases("Declaration").build("id","typeParameters","right").field("id",n("Identifier")).field("typeParameters",i(n("TypeParameterDeclaration"),null)).field("right",n("Type")),n("DeclareTypeAlias").bases("TypeAlias").build("id","typeParameters","right"),n("TypeCastExpression").bases("Expression").build("expression","typeAnnotation").field("expression",n("Expression")).field("typeAnnotation",n("TypeAnnotation")),n("TupleTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("DeclareVariable").bases("Statement").build("id").field("id",n("Identifier")),n("DeclareFunction").bases("Statement").build("id").field("id",n("Identifier")),n("DeclareClass").bases("InterfaceDeclaration").build("id"),n("DeclareModule").bases("Statement").build("id","body").field("id",i(n("Identifier"),n("Literal"))).field("body",n("BlockStatement")),n("DeclareModuleExports").bases("Statement").build("typeAnnotation").field("typeAnnotation",n("Type")),n("DeclareExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",Boolean).field("declaration",i(n("DeclareVariable"),n("DeclareFunction"),n("DeclareClass"),n("Type"),null)).field("specifiers",[i(n("ExportSpecifier"),n("ExportBatchSpecifier"))],s.emptyArray).field("source",i(n("Literal"),null),s.null),n("DeclareExportAllDeclaration").bases("Declaration").build("source").field("source",i(n("Literal"),null),s.null)}},{"../lib/shared":18,"../lib/types":19,"./es7":7}],10:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")).defaults;n("JSXAttribute").bases("Node").build("name","value").field("name",i(n("JSXIdentifier"),n("JSXNamespacedName"))).field("value",i(n("Literal"),n("JSXExpressionContainer"),null),s.null),n("JSXIdentifier").bases("Identifier").build("name").field("name",String),n("JSXNamespacedName").bases("Node").build("namespace","name").field("namespace",n("JSXIdentifier")).field("name",n("JSXIdentifier")),n("JSXMemberExpression").bases("MemberExpression").build("object","property").field("object",i(n("JSXIdentifier"),n("JSXMemberExpression"))).field("property",n("JSXIdentifier")).field("computed",Boolean,s.false);var a=i(n("JSXIdentifier"),n("JSXNamespacedName"),n("JSXMemberExpression"));n("JSXSpreadAttribute").bases("Node").build("argument").field("argument",n("Expression"));var o=[i(n("JSXAttribute"),n("JSXSpreadAttribute"))];n("JSXExpressionContainer").bases("Expression").build("expression").field("expression",n("Expression")),n("JSXElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",n("JSXOpeningElement")).field("closingElement",i(n("JSXClosingElement"),null),s.null).field("children",[i(n("JSXElement"),n("JSXExpressionContainer"),n("JSXText"),n("Literal"))],s.emptyArray).field("name",a,function(){return this.openingElement.name},!0).field("selfClosing",Boolean,function(){return this.openingElement.selfClosing},!0).field("attributes",o,function(){return this.openingElement.attributes},!0),n("JSXOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",a).field("attributes",o,s.emptyArray).field("selfClosing",Boolean,s.false),n("JSXClosingElement").bases("Node").build("name").field("name",a),n("JSXText").bases("Literal").build("value").field("value",String),n("JSXEmptyExpression").bases("Expression").build()}},{"../lib/shared":18,"../lib/types":19,"./es7":7}],11:[function(e,t,r){t.exports=function(t){t.use(e("./core"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")),a=s.geq,o=s.defaults;n("Function").field("body",i(n("BlockStatement"),n("Expression"))),n("ForInStatement").build("left","right","body","each").field("each",Boolean,o.false),n("ForOfStatement").bases("Statement").build("left","right","body").field("left",i(n("VariableDeclaration"),n("Expression"))).field("right",n("Expression")).field("body",n("Statement")),n("LetStatement").bases("Statement").build("head","body").field("head",[n("VariableDeclarator")]).field("body",n("Statement")),n("LetExpression").bases("Expression").build("head","body").field("head",[n("VariableDeclarator")]).field("body",n("Expression")),n("GraphExpression").bases("Expression").build("index","expression").field("index",a(0)).field("expression",n("Literal")),n("GraphIndexExpression").bases("Expression").build("index").field("index",a(0))}},{"../lib/shared":18,"../lib/types":19,"./core":4}],12:[function(e,t,r){t.exports=function(t){function r(e){var t=n.indexOf(e);return-1===t&&(t=n.length,n.push(e),i[t]=e(s)),i[t]}var n=[],i=[],s={};s.use=r;var a=r(e("./lib/types"));t.forEach(r),a.finalize();var o={Type:a.Type,builtInTypes:a.builtInTypes,namedTypes:a.namedTypes,builders:a.builders,defineMethod:a.defineMethod,getFieldNames:a.getFieldNames,getFieldValue:a.getFieldValue,eachField:a.eachField,someField:a.someField,getSupertypeNames:a.getSupertypeNames,astNodesAreEquivalent:r(e("./lib/equiv")),finalize:a.finalize,Path:r(e("./lib/path")),NodePath:r(e("./lib/node-path")),PathVisitor:r(e("./lib/path-visitor")),use:r};return o.visit=o.PathVisitor.visit,o}},{"./lib/equiv":13,"./lib/node-path":14,"./lib/path":16,"./lib/path-visitor":15,"./lib/types":19}],13:[function(e,t,r){t.exports=function(t){function r(e,t,r){return u.check(r)?r.length=0:r=null,i(e,t,r)}function n(e){return/[_$a-z][_$a-z0-9]*/i.test(e)?"."+e:"["+JSON.stringify(e)+"]"}function i(e,t,r){return e===t||(u.check(e)?function(e,t,r){u.assert(e);var n=e.length;if(!u.check(t)||t.length!==n)return r&&r.push("length"),!1;for(var s=0;su)return!0;if(s===u&&"right"===this.name){if(r.right!==t)throw new Error("Nodes must be equal");return!0}default:return!1}case"SequenceExpression":switch(r.type){case"ForStatement":return!1;case"ExpressionStatement":return"expression"!==this.name;default:return!0}case"YieldExpression":switch(r.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return!0;default:return!1}case"Literal":return"MemberExpression"===r.type&&l.check(t.value)&&"object"===this.name&&r.object===t;case"AssignmentExpression":case"ConditionalExpression":switch(r.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return!0;case"CallExpression":return"callee"===this.name&&r.callee===t;case"ConditionalExpression":return"test"===this.name&&r.test===t;case"MemberExpression":return"object"===this.name&&r.object===t;default:return!1}default:if("NewExpression"===r.type&&"callee"===this.name&&r.callee===t)return i(t)}return!(!0===e||this.canBeFirstInStatement()||!this.firstInStatement())};var d={};return[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,t){e.forEach(function(e){d[e]=t})}),f.canBeFirstInStatement=function(){var e=this.node;return!o.FunctionExpression.check(e)&&!o.ObjectExpression.check(e)},f.firstInStatement=function(){return function(e){for(var t,r;e.parent;e=e.parent){if(t=e.node,r=e.parent.node,o.BlockStatement.check(r)&&"body"===e.parent.name&&0===e.name){if(r.body[0]!==t)throw new Error("Nodes must be equal");return!0}if(o.ExpressionStatement.check(r)&&"expression"===e.name){if(r.expression!==t)throw new Error("Nodes must be equal");return!0}if(o.SequenceExpression.check(r)&&"expressions"===e.parent.name&&0===e.name){if(r.expressions[0]!==t)throw new Error("Nodes must be equal")}else if(o.CallExpression.check(r)&&"callee"===e.name){if(r.callee!==t)throw new Error("Nodes must be equal")}else if(o.MemberExpression.check(r)&&"object"===e.name){if(r.object!==t)throw new Error("Nodes must be equal")}else if(o.ConditionalExpression.check(r)&&"test"===e.name){if(r.test!==t)throw new Error("Nodes must be equal")}else if(n(r)&&"left"===e.name){if(r.left!==t)throw new Error("Nodes must be equal")}else{if(!o.UnaryExpression.check(r)||r.prefix||"argument"!==e.name)return!1;if(r.argument!==t)throw new Error("Nodes must be equal")}}return!0}(this)},r}},{"./path":16,"./scope":17,"./types":19}],15:[function(e,t,r){var n=Object.prototype.hasOwnProperty;t.exports=function(t){function r(){if(!(this instanceof r))throw new Error("PathVisitor constructor cannot be invoked without 'new'");this._reusableContextStack=[],this._methodNameTable=function(e){r=Object.create(null);for(var t in e)/^visit[A-Z]/.test(t)&&(r[t.slice("visit".length)]=!0);for(var r,n=a.computeSupertypeLookupTable(r),i=Object.create(null),s=(r=Object.keys(n)).length,o=0;o=0&&(s[e.name=a]=e)}else i[e.name]=e.value,s[e.name]=e;if(i[e.name]!==e.value)throw new Error("");if(e.parentPath.get(e.name)!==e)throw new Error("")}(this),l.check(i)){for(var u=i.length,c=o(this.parentPath,a-1,this.name+1),p=[this.name,1],h=0;h=e},a+" >= "+e)},r.defaults={null:function(){return null},emptyArray:function(){return[]},false:function(){return!1},true:function(){return!0},undefined:function(){}};var o=i.or(s.string,s.number,s.boolean,s.null,s.undefined);return r.isPrimitive=new i(function(e){if(null===e)return!0;var t=typeof e;return!("object"===t||"function"===t)},o.toString()),r}},{"../lib/types":19}],19:[function(e,t,r){var n=Array.prototype,i=n.slice,s=(n.map,n.forEach,Object.prototype),a=s.toString,o=a.call(function(){}),u=a.call(""),l=s.hasOwnProperty;t.exports=function(){function e(t,r){var n=this;if(!(n instanceof e))throw new Error("Type constructor cannot be invoked without 'new'");if(a.call(t)!==o)throw new Error(t+" is not a function");var i=a.call(r);if(i!==o&&i!==u)throw new Error(r+" is neither a function nor a string");Object.defineProperties(n,{name:{value:r},check:{value:function(e,r){var i=t.call(n,e,r);return!i&&r&&a.call(r)===o&&r(n,e),i}}})}function t(e){return C.check(e)?"{"+Object.keys(e).map(function(t){return t+": "+e[t]}).join(", ")+"}":D.check(e)?"["+e.map(t).join(", ")+"]":JSON.stringify(e)}function r(t,r){var n=a.call(t),i=new e(function(e){return a.call(e)===n},r);return x[r]=i,t&&"function"==typeof t.constructor&&(b.push(t.constructor),v.push(i)),i}function n(t,r){if(t instanceof e)return t;if(t instanceof c)return t.type;if(D.check(t))return e.fromArray(t);if(C.check(t))return e.fromObject(t);if(A.check(t)){var n=b.indexOf(t);return n>=0?v[n]:new e(t,r)}return new e(function(e){return e===t},_.check(r)?function(){return t+""}:r)}function s(e,t,r,i){if(!(this instanceof s))throw new Error("Field constructor cannot be invoked without 'new'");E.assert(e);var a={name:{value:e},type:{value:t=n(t)},hidden:{value:!!i}};A.check(r)&&(a.defaultFn={value:r}),Object.defineProperties(this,a)}function c(t){var r=this;if(!(r instanceof c))throw new Error("Def constructor cannot be invoked without 'new'");Object.defineProperties(r,{typeName:{value:t},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new e(function(e,t){return r.check(e,t)},t)}})}function p(e){return e.replace(/^[A-Z]+/,function(e){var t=e.length;switch(t){case 0:return"";case 1:return e.toLowerCase();default:return e.slice(0,t-1).toLowerCase()+e.charAt(t-1)}})}function h(e){return(e=p(e)).replace(/(Expression)?$/,"Statement")}function f(e){var t=c.fromValue(e);if(t)return t.fieldNames.slice(0);if("type"in e)throw new Error("did not recognize object of type "+JSON.stringify(e.type));return Object.keys(e)}function d(e,t){var r=c.fromValue(e);if(r){var n=r.allFields[t];if(n)return n.getValue(e)}return e&&e[t]}function m(e,t){return Object.keys(t).forEach(function(r){e[r]=t[r]}),e}var y={},g=e.prototype;y.Type=e,g.assert=function(e,r){if(!this.check(e,r)){var n=t(e);throw new Error(n+" does not match type "+this)}return!0},g.toString=function(){var e=this.name;return E.check(e)?e:A.check(e)?e.call(this)+"":e+" type"};var b=[],v=[],x={};y.builtInTypes=x;var E=r("truthy","string"),A=r(function(){},"function"),D=r([],"array"),C=r({},"object"),S=(r(/./,"RegExp"),r(new Date,"Date"),r(3,"number")),_=(r(!0,"boolean"),r(null,"null"),r(void 0,"undefined"));e.or=function(){for(var t=[],r=arguments.length,i=0;i=0&&function(e){var t=h(e);if(!T[t]){var r=T[p(e)];r&&(T[t]=function(){return T.expressionStatement(r.apply(T,arguments))})}}(e.typeName)}},y.finalize=function(){Object.keys(k).forEach(function(e){k[e].finalize()})},y}},{}],20:[function(e,t,r){t.exports=e("./fork")([e("./def/core"),e("./def/es6"),e("./def/es7"),e("./def/mozilla"),e("./def/e4x"),e("./def/jsx"),e("./def/flow"),e("./def/esprima"),e("./def/babel"),e("./def/babel6")])},{"./def/babel":2,"./def/babel6":3,"./def/core":4,"./def/e4x":5,"./def/es6":6,"./def/es7":7,"./def/esprima":8,"./def/flow":9,"./def/jsx":10,"./def/mozilla":11,"./fork":12}],21:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){return t.replace(a.default,function(){for(var t=arguments.length,r=Array(t),n=0;n3&&void 0!==arguments[3]?arguments[3]:{};r=Math.max(r,0);var s=n.highlightCode&&u.default.supportsColor||n.forceColor,a=u.default;n.forceColor&&(a=new u.default.constructor({enabled:!0}));var o=function(e,t){return s?e(t):t},c=function(e){return{keyword:e.cyan,capitalized:e.yellow,jsx_tag:e.yellow,punctuator:e.yellow,number:e.magenta,string:e.green,regex:e.magenta,comment:e.grey,invalid:e.white.bgRed.bold,gutter:e.grey,marker:e.red.bold}}(a);s&&(e=i(c,e));var p=n.linesAbove||2,h=n.linesBelow||3,f=e.split(l),d=Math.max(t-(p+1),0),m=Math.min(f.length,t+h);t||r||(d=0,m=f.length);var y=String(m).length,g=f.slice(d,m).map(function(e,n){var i=d+1+n,s=" "+(" "+i).slice(-y)+" | ";if(i===t){var a="";if(r){var u=e.slice(0,r-1).replace(/[^\t]/g," ");a=["\n ",o(c.gutter,s.replace(/\d/g," ")),u,o(c.marker,"^")].join("")}return[o(c.marker,">"),o(c.gutter,s),e,a].join("")}return" "+o(c.gutter,s)+e}).join("\n");return s?a.reset(g):g};var s=e("js-tokens"),a=n(s),o=n(e("esutils")),u=n(e("chalk")),l=/\r\n|[\n\r\u2028\u2029]/,c=/^[a-z][\w-]*$/i,p=/^[()\[\]{}]$/;t.exports=r.default},{chalk:24,esutils:28,"js-tokens":322}],22:[function(e,t,r){"use strict";t.exports=function(){return/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g}},{}],23:[function(e,t,r){"use strict";Object.defineProperty(t,"exports",{enumerable:!0,get:function(){var e={modifiers:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},colors:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39]},bgColors:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]}};return e.colors.grey=e.colors.gray,Object.keys(e).forEach(function(t){var r=e[t];Object.keys(r).forEach(function(t){var n=r[t];e[t]=r[t]={open:"["+n[0]+"m",close:"["+n[1]+"m"}}),Object.defineProperty(e,t,{value:r,enumerable:!1})}),e}})},{}],24:[function(e,t,r){(function(r){"use strict";function n(e){this.enabled=e&&void 0!==e.enabled?e.enabled:l}function i(e){var t=function(){return function(){var e=arguments,t=e.length,r=0!==t&&String(arguments[0]);if(t>1)for(var n=1;n=97&&o<=122||o>=65&&o<=90||36===o||95===o;for(a=new Array(128),o=0;o<128;++o)a[o]=o>=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||36===o||95===o;t.exports={isDecimalDigit:function(e){return 48<=e&&e<=57},isHexDigit:function(e){return 48<=e&&e<=57||97<=e&&e<=102||65<=e&&e<=70},isOctalDigit:function(e){return e>=48&&e<=55},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&i.indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStartES5:function(t){return t<128?s[t]:n.NonAsciiIdentifierStart.test(e(t))},isIdentifierPartES5:function(t){return t<128?a[t]:n.NonAsciiIdentifierPart.test(e(t))},isIdentifierStartES6:function(t){return t<128?s[t]:r.NonAsciiIdentifierStart.test(e(t))},isIdentifierPartES6:function(t){return t<128?a[t]:r.NonAsciiIdentifierPart.test(e(t))}}}()},{}],27:[function(e,t,r){!function(){"use strict";function r(e,t){return!(!t&&"yield"===e)&&n(e,t)}function n(e,t){if(t&&function(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return!0;default:return!1}}(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function i(e,t){return"null"===e||"true"===e||"false"===e||r(e,t)}function s(e,t){return"null"===e||"true"===e||"false"===e||n(e,t)}function a(e){var t,r,n;if(0===e.length)return!1;if(n=e.charCodeAt(0),!l.isIdentifierStartES5(n))return!1;for(t=1,r=e.length;t=r)return!1;if(!(56320<=(i=e.charCodeAt(t))&&i<=57343))return!1;n=o(n,i)}if(!s(n))return!1;s=l.isIdentifierPartES6}return!0}var l=e("./code");t.exports={isKeywordES5:r,isKeywordES6:n,isReservedWordES5:i,isReservedWordES6:s,isRestrictedWord:function(e){return"eval"===e||"arguments"===e},isIdentifierNameES5:a,isIdentifierNameES6:u,isIdentifierES5:function(e,t){return a(e)&&!i(e,t)},isIdentifierES6:function(e,t){return u(e)&&!s(e,t)}}}()},{"./code":26}],28:[function(e,t,r){!function(){"use strict";r.ast=e("./ast"),r.code=e("./code"),r.keyword=e("./keyword")}()},{"./ast":25,"./code":26,"./keyword":27}],29:[function(e,t,r){"use strict";var n=e("ansi-regex")();t.exports=function(e){return"string"==typeof e?e.replace(n,""):e}},{"ansi-regex":22}],30:[function(e,t,r){(function(e){"use strict";var r=e.argv,n=r.indexOf("--"),i=function(e){e="--"+e;var t=r.indexOf(e);return-1!==t&&(-1===n||t1&&void 0!==arguments[1]?arguments[1]:{};return t.filename=e,x(h.default.readFileSync(e,"utf8"),t)};var h=i(e("fs")),f=n(e("../util")),d=n(e("babel-messages")),m=n(e("babel-types")),y=i(e("babel-traverse")),g=i(e("../transformation/file/options/option-manager")),b=i(e("../transformation/pipeline"));r.util=f,r.messages=d,r.types=m,r.traverse=y.default,r.OptionManager=g.default,r.Pipeline=b.default;var v=new b.default,x=(r.analyse=v.analyse.bind(v),r.transform=v.transform.bind(v));r.transformFromAst=v.transformFromAst.bind(v)},{"../../package":73,"../helpers/resolve-plugin":38,"../helpers/resolve-preset":39,"../tools/build-external-helpers":42,"../transformation/file":43,"../transformation/file/options/config":47,"../transformation/file/options/option-manager":49,"../transformation/pipeline":54,"../util":57,"babel-messages":110,"babel-template":139,"babel-traverse":143,"babel-types":178,fs:191}],33:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e){return["babel-plugin-"+e,e]},t.exports=r.default},{}],34:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e){var t=["babel-preset-"+e,e],r=e.match(/^(@[^/]+)\/(.+)$/);if(r){var n=r[1],i=r[2];t.push(n+"/babel-preset-"+i)}return t},t.exports=r.default},{}],35:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.default=function(e,t){if(e&&t)return(0,s.default)(e,t,function(e,t){if(t&&Array.isArray(e)){for(var r=t.slice(0),n=e,s=Array.isArray(n),a=0,n=s?n:(0,i.default)(n);;){var o;if(s){if(a>=n.length)break;o=n[a++]}else{if((a=n.next()).done)break;o=a.value}var u=o;r.indexOf(u)<0&&r.push(u)}return r}})};var s=n(e("lodash/mergeWith"));t.exports=r.default},{"babel-runtime/core-js/get-iterator":120,"lodash/mergeWith":527}],36:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t,r){if(e){if("Program"===e.type)return n.file(e,t||[],r||[]);if("File"===e.type)return e}throw new Error("Not a valid ast?")};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));t.exports=r.default},{"babel-types":178}],37:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t){return e.reduce(function(e,r){return e||(0,n.default)(r,t)},null)};var n=function(e){return e&&e.__esModule?e:{default:e}}(e("./resolve"));t.exports=r.default},{"./resolve":40}],38:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0,r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();return(0,s.default)((0,a.default)(e),t)};var s=i(e("./resolve-from-possible-names")),a=i(e("./get-possible-plugin-names"));t.exports=r.default}).call(this,e("_process"))},{"./get-possible-plugin-names":33,"./resolve-from-possible-names":37,_process:550}],39:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0,r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();return(0,s.default)((0,a.default)(e),t)};var s=i(e("./resolve-from-possible-names")),a=i(e("./get-possible-preset-names"));t.exports=r.default}).call(this,e("_process"))},{"./get-possible-preset-names":34,"./resolve-from-possible-names":37,_process:550}],40:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var s=i(e("babel-runtime/helpers/typeof"));r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();if("object"===(void 0===a.default?"undefined":(0,s.default)(a.default)))return null;var r=u[t];if(!r){r=new a.default;var i=o.default.join(t,".babelrc");r.id=i,r.filename=i,r.paths=a.default._nodeModulePaths(t),u[t]=r}try{return a.default._resolveFilename(e,r)}catch(e){return null}};var a=i(e("module")),o=i(e("path")),u={};t.exports=r.default}).call(this,e("_process"))},{_process:550,"babel-runtime/helpers/typeof":138,module:191,path:546}],41:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/map")),s=n(e("babel-runtime/helpers/classCallCheck")),a=n(e("babel-runtime/helpers/possibleConstructorReturn")),o=n(e("babel-runtime/helpers/inherits")),u=function(e){function t(){(0,s.default)(this,t);var r=(0,a.default)(this,e.call(this));return r.dynamicData={},r}return(0,o.default)(t,e),t.prototype.setDynamic=function(e,t){this.dynamicData[e]=t},t.prototype.get=function(t){if(this.has(t))return e.prototype.get.call(this,t);if(Object.prototype.hasOwnProperty.call(this.dynamicData,t)){var r=this.dynamicData[t]();return this.set(t,r),r}},t}(i.default);r.default=u,t.exports=r.default},{"babel-runtime/core-js/map":122,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137}],42:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function s(e,t){var r=[],n=h.functionExpression(null,[h.identifier("global")],h.blockStatement(r)),i=h.program([h.expressionStatement(h.callExpression(n,[u.get("selfGlobal")]))]);return r.push(h.variableDeclaration("var",[h.variableDeclarator(e,h.assignmentExpression("=",h.memberExpression(h.identifier("global"),e),h.objectExpression([])))])),t(r),i}function a(e,t){var r=[];return r.push(h.variableDeclaration("var",[h.variableDeclarator(e,h.identifier("global"))])),t(r),h.program([f({FACTORY_PARAMETERS:h.identifier("global"),BROWSER_ARGUMENTS:h.assignmentExpression("=",h.memberExpression(h.identifier("root"),e),h.objectExpression([])),COMMON_ARGUMENTS:h.identifier("exports"),AMD_ARGUMENTS:h.arrayExpression([h.stringLiteral("exports")]),FACTORY_BODY:r,UMD_ROOT:h.identifier("this")})])}function o(e,t){var r=[];return r.push(h.variableDeclaration("var",[h.variableDeclarator(e,h.objectExpression([]))])),t(r),r.push(h.expressionStatement(e)),h.program(r)}r.__esModule=!0,r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"global",r=h.identifier("babelHelpers"),n=void 0,i={global:s,umd:a,var:o}[t];if(!i)throw new Error(c.get("unsupportedOutputType",t));return n=i(r,function(t){return function(e,t,r){u.list.forEach(function(n){if(!(r&&r.indexOf(n)<0)){var i=h.identifier(n);e.push(h.expressionStatement(h.assignmentExpression("=",h.memberExpression(t,i),u.get(n))))}})}(t,r,e)}),(0,l.default)(n).code};var u=i(e("babel-helpers")),l=n(e("babel-generator")),c=i(e("babel-messages")),p=n(e("babel-template")),h=i(e("babel-types")),f=(0,p.default)('\n (function (root, factory) {\n if (typeof define === "function" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === "object") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n');t.exports=r.default},{"babel-generator":85,"babel-helpers":109,"babel-messages":110,"babel-template":139,"babel-types":178}],43:[function(e,t,r){(function(t){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0,r.File=void 0;var s=i(e("babel-runtime/core-js/get-iterator")),a=i(e("babel-runtime/core-js/object/create")),o=i(e("babel-runtime/core-js/object/assign")),u=i(e("babel-runtime/helpers/classCallCheck")),l=i(e("babel-runtime/helpers/possibleConstructorReturn")),c=i(e("babel-runtime/helpers/inherits")),p=i(e("babel-helpers")),h=n(e("./metadata")),f=i(e("convert-source-map")),d=i(e("./options/option-manager")),m=i(e("../plugin-pass")),y=e("babel-traverse"),g=i(y),b=i(e("source-map")),v=i(e("babel-generator")),x=i(e("babel-code-frame")),E=i(e("lodash/defaults")),A=i(e("./logger")),D=i(e("../../store")),C=e("babylon"),S=n(e("../../util")),_=i(e("path")),w=n(e("babel-types")),k=i(e("../../helpers/resolve")),F=i(e("../internal-plugins/block-hoist")),T=i(e("../internal-plugins/shadow-functions")),P=/^#!.*/,B=[[F.default],[T.default]],O={enter:function(e,t){var r=e.node.loc;r&&(t.loc=r,e.stop())}},j=function(r){function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];(0,u.default)(this,n);var i=(0,l.default)(this,r.call(this));return i.pipeline=t,i.log=new A.default(i,e.filename||"unknown"),i.opts=i.initOptions(e),i.parserOpts={sourceType:i.opts.sourceType,sourceFileName:i.opts.filename,plugins:[]},i.pluginVisitors=[],i.pluginPasses=[],i.buildPluginsForOptions(i.opts),i.opts.passPerPreset&&(i.perPresetOpts=[],i.opts.presets.forEach(function(e){var t=(0,o.default)((0,a.default)(i.opts),e);i.perPresetOpts.push(t),i.buildPluginsForOptions(t)})),i.metadata={usedHelpers:[],marked:[],modules:{imports:[],exports:{exported:[],specifiers:[]}}},i.dynamicImportTypes={},i.dynamicImportIds={},i.dynamicImports=[],i.declarations={},i.usedHelpers={},i.path=null,i.ast={},i.code="",i.shebang="",i.hub=new y.Hub(i),i}return(0,c.default)(n,r),n.prototype.getMetadata=function(){for(var e=!1,t=this.ast.program.body,r=Array.isArray(t),n=0,t=r?t:(0,s.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var a=i;if(w.isModuleDeclaration(a)){e=!0;break}}e&&this.path.traverse(h,this)},n.prototype.initOptions=function(e){(e=new d.default(this.log,this.pipeline).init(e)).inputSourceMap&&(e.sourceMaps=!0),e.moduleId&&(e.moduleIds=!0),e.basename=_.default.basename(e.filename,_.default.extname(e.filename)),e.ignore=S.arrayify(e.ignore,S.regexify),e.only&&(e.only=S.arrayify(e.only,S.regexify)),(0,E.default)(e,{moduleRoot:e.sourceRoot}),(0,E.default)(e,{sourceRoot:e.moduleRoot}),(0,E.default)(e,{filenameRelative:e.filename});var t=_.default.basename(e.filenameRelative);return(0,E.default)(e,{sourceFileName:t,sourceMapTarget:t}),e},n.prototype.buildPluginsForOptions=function(e){if(Array.isArray(e.plugins)){for(var t=[],r=[],n=e.plugins.concat(B),i=Array.isArray(n),a=0,n=i?n:(0,s.default)(n);;){var o;if(i){if(a>=n.length)break;o=n[a++]}else{if((a=n.next()).done)break;o=a.value}var u=o,l=u[0],c=u[1];t.push(l.visitor),r.push(new m.default(this,l,c)),l.manipulateOptions&&l.manipulateOptions(e,this.parserOpts,this)}this.pluginVisitors.push(t),this.pluginPasses.push(r)}},n.prototype.getModuleName=function(){var e=this.opts;if(!e.moduleIds)return null;if(null!=e.moduleId&&!e.getModuleId)return e.moduleId;var t=e.filenameRelative,r="";if(null!=e.moduleRoot&&(r=e.moduleRoot+"/"),!e.filenameRelative)return r+e.filename.replace(/^\//,"");if(null!=e.sourceRoot){var n=new RegExp("^"+e.sourceRoot+"/?");t=t.replace(n,"")}return t=t.replace(/\.(\w*?)$/,""),r+=t,r=r.replace(/\\/g,"/"),e.getModuleId?e.getModuleId(r)||r:r},n.prototype.resolveModuleSource=function(e){var t=this.opts.resolveModuleSource;return t&&(e=t(e,this.opts.filename)),e},n.prototype.addImport=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,n=e+":"+t,i=this.dynamicImportIds[n];if(!i){e=this.resolveModuleSource(e),i=this.dynamicImportIds[n]=this.scope.generateUidIdentifier(r);var s=[];"*"===t?s.push(w.importNamespaceSpecifier(i)):"default"===t?s.push(w.importDefaultSpecifier(i)):s.push(w.importSpecifier(i,w.identifier(t)));var a=w.importDeclaration(s,w.stringLiteral(e));a._blockHoist=3,this.path.unshiftContainer("body",a)}return i},n.prototype.addHelper=function(e){var t=this.declarations[e];if(t)return t;this.usedHelpers[e]||(this.metadata.usedHelpers.push(e),this.usedHelpers[e]=!0);var r=this.get("helperGenerator"),n=this.get("helpersNamespace");if(r){var i=r(e);if(i)return i}else if(n)return w.memberExpression(n,w.identifier(e));var s=(0,p.default)(e),a=this.declarations[e]=this.scope.generateUidIdentifier(e);return w.isFunctionExpression(s)&&!s.id?(s.body._compact=!0,s._generated=!0,s.id=a,s.type="FunctionDeclaration",this.path.unshiftContainer("body",s)):(s._compact=!0,this.scope.push({id:a,init:s,unique:!0})),a},n.prototype.addTemplateObject=function(e,t,r){var n=r.elements.map(function(e){return e.value}),i=e+"_"+r.elements.length+"_"+n.join(","),s=this.declarations[i];if(s)return s;var a=this.declarations[i]=this.scope.generateUidIdentifier("templateObject"),o=this.addHelper(e),u=w.callExpression(o,[t,r]);return u._compact=!0,this.scope.push({id:a,init:u,_blockHoist:1.9}),a},n.prototype.buildCodeFrameError=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:SyntaxError,n=e&&(e.loc||e._loc),i=new r(t);return n?i.loc=n.start:((0,g.default)(e,O,this.scope,i),i.message+=" (This is an error on an internal node. Probably an internal error",i.loc&&(i.message+=". Location has been estimated."),i.message+=")"),i},n.prototype.mergeSourceMap=function(e){var t=this.opts.inputSourceMap;if(t){var r=new b.default.SourceMapConsumer(t),n=new b.default.SourceMapConsumer(e),i=new b.default.SourceMapGenerator({file:r.file,sourceRoot:r.sourceRoot}),s=n.sources[0];r.eachMapping(function(e){var t=n.generatedPositionFor({line:e.generatedLine,column:e.generatedColumn,source:s});null!=t.column&&i.addMapping({source:e.source,original:null==e.source?null:{line:e.originalLine,column:e.originalColumn},generated:t})});var a=i.toJSON();return t.mappings=a.mappings,t}return e},n.prototype.parse=function(r){var n=C.parse,i=this.opts.parserOpts;if(i&&(i=(0,o.default)({},this.parserOpts,i)).parser){if("string"==typeof i.parser){var s=_.default.dirname(this.opts.filename)||t.cwd(),a=(0,k.default)(i.parser,s);if(!a)throw new Error("Couldn't find parser "+i.parser+' with "parse" method relative to directory '+s);n=e(a).parse}else n=i.parser;i.parser={parse:function(e){return(0,C.parse)(e,i)}}}this.log.debug("Parse start");var u=n(r,i||this.parserOpts);return this.log.debug("Parse stop"),u},n.prototype._addAst=function(e){this.path=y.NodePath.get({hub:this.hub,parentPath:null,parent:e,container:e,key:"program"}).setContext(),this.scope=this.path.scope,this.ast=e,this.getMetadata()},n.prototype.addAst=function(e){this.log.debug("Start set AST"),this._addAst(e),this.log.debug("End set AST")},n.prototype.transform=function(){for(var e=0;e=r.length)break;a=r[i++]}else{if((i=r.next()).done)break;a=i.value}var o=a,u=o.plugin[e];u&&u.call(o,this)}},n.prototype.parseInputSourceMap=function(e){var t=this.opts;if(!1!==t.inputSourceMap){var r=f.default.fromSource(e);r&&(t.inputSourceMap=r.toObject(),e=f.default.removeComments(e))}return e},n.prototype.parseShebang=function(){var e=P.exec(this.code);e&&(this.shebang=e[0],this.code=this.code.replace(P,""))},n.prototype.makeResult=function(e){var t=e.code,r=e.map,n=e.ast,i=e.ignored,s={metadata:null,options:this.opts,ignored:!!i,code:null,ast:null,map:r||null};return this.opts.code&&(s.code=t),this.opts.ast&&(s.ast=n),this.opts.metadata&&(s.metadata=this.metadata),s},n.prototype.generate=function(){var r=this.opts,n=this.ast,i={ast:n};if(!r.code)return this.makeResult(i);var s=v.default;if(r.generatorOpts.generator&&"string"==typeof(s=r.generatorOpts.generator)){var a=_.default.dirname(this.opts.filename)||t.cwd(),u=(0,k.default)(s,a);if(!u)throw new Error("Couldn't find generator "+s+' with "print" method relative to directory '+a);s=e(u).print}this.log.debug("Generation start");var l=s(n,r.generatorOpts?(0,o.default)(r,r.generatorOpts):r,this.code);return i.code=l.code,i.map=l.map,this.log.debug("Generation end"),this.shebang&&(i.code=this.shebang+"\n"+i.code),i.map&&(i.map=this.mergeSourceMap(i.map)),"inline"!==r.sourceMaps&&"both"!==r.sourceMaps||(i.code+="\n"+f.default.fromObject(i.map).toComment()),"inline"===r.sourceMaps&&(i.map=null),this.makeResult(i)},n}(D.default);r.default=j,r.File=j}).call(this,e("_process"))},{"../../helpers/resolve":40,"../../store":41,"../../util":57,"../internal-plugins/block-hoist":52,"../internal-plugins/shadow-functions":53,"../plugin-pass":55,"./logger":44,"./metadata":45,"./options/option-manager":49,_process:550,"babel-code-frame":21,"babel-generator":85,"babel-helpers":109,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/object/assign":124,"babel-runtime/core-js/object/create":125,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137,"babel-traverse":143,"babel-types":178,babylon:186,"convert-source-map":58,"lodash/defaults":495,path:546,"source-map":72}],44:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=n(e("debug/node")),a=(0,s.default)("babel:verbose"),o=(0,s.default)("babel"),u=[],l=function(){function e(t,r){(0,i.default)(this,e),this.filename=r,this.file=t}return e.prototype._buildMessage=function(e){var t="[BABEL] "+this.filename;return e&&(t+=": "+e),t},e.prototype.warn=function(e){console.warn(this._buildMessage(e))},e.prototype.error=function(e){throw new(arguments.length>1&&void 0!==arguments[1]?arguments[1]:Error)(this._buildMessage(e))},e.prototype.deprecate=function(e){this.file.opts&&this.file.opts.suppressDeprecationMessages||(e=this._buildMessage(e),u.indexOf(e)>=0||(u.push(e),console.error(e)))},e.prototype.verbose=function(e){a.enabled&&a(this._buildMessage(e))},e.prototype.debug=function(e){o.enabled&&o(this._buildMessage(e))},e.prototype.deopt=function(e,t){this.debug(t)},e}();r.default=l,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134,"debug/node":59}],45:[function(e,t,r){"use strict";r.__esModule=!0,r.ImportDeclaration=r.ModuleDeclaration=void 0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.ExportDeclaration=function(e,t){var r=e.node,s=r.source?r.source.value:null,a=t.metadata.modules.exports,o=e.get("declaration");if(o.isStatement()){var u=o.getBindingIdentifiers();for(var l in u)a.exported.push(l),a.specifiers.push({kind:"local",local:l,exported:e.isExportDefaultDeclaration()?"default":l})}if(e.isExportNamedDeclaration()&&r.specifiers)for(var c=r.specifiers,p=Array.isArray(c),h=0,c=p?c:(0,n.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if((h=c.next()).done)break;f=h.value}var d=f,m=d.exported.name;a.exported.push(m),i.isExportDefaultSpecifier(d)&&a.specifiers.push({kind:"external",local:m,exported:m,source:s}),i.isExportNamespaceSpecifier(d)&&a.specifiers.push({kind:"external-namespace",exported:m,source:s});var y=d.local;y&&(s&&a.specifiers.push({kind:"external",local:y.name,exported:m,source:s}),s||a.specifiers.push({kind:"local",local:y.name,exported:m}))}e.isExportAllDeclaration()&&a.specifiers.push({kind:"external-all",source:s})},r.Scope=function(e){e.skip()};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));r.ModuleDeclaration={enter:function(e,t){var r=e.node;r.source&&(r.source.value=t.resolveModuleSource(r.source.value))}},r.ImportDeclaration={exit:function(e,t){var r=e.node,i=[],s=[];t.metadata.modules.imports.push({source:r.source.value,imported:s,specifiers:i});for(var a=e.get("specifiers"),o=Array.isArray(a),u=0,a=o?a:(0,n.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var c=l,p=c.node.local.name;if(c.isImportDefaultSpecifier()&&(s.push("default"),i.push({kind:"named",imported:"default",local:p})),c.isImportSpecifier()){var h=c.node.imported.name;s.push(h),i.push({kind:"named",imported:h,local:p})}c.isImportNamespaceSpecifier()&&(s.push("*"),i.push({kind:"namespace",local:p}))}}}},{"babel-runtime/core-js/get-iterator":120,"babel-types":178}],46:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e){var t=f[e];return null==t?f[e]=h.default.existsSync(e):t}r.__esModule=!0;var a=i(e("babel-runtime/core-js/object/assign")),o=i(e("babel-runtime/helpers/classCallCheck"));r.default=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],r=e.filename,n=new m(t);return!1!==e.babelrc&&n.findConfigs(r),n.mergeConfig({options:e,alias:"base",dirname:r&&p.default.dirname(r)}),n.configs};var u=i(e("../../../helpers/resolve")),l=i(e("json5")),c=i(e("path-is-absolute")),p=i(e("path")),h=i(e("fs")),f={},d={},m=function(){function e(t){(0,o.default)(this,e),this.resolvedConfigs=[],this.configs=[],this.log=t}return e.prototype.findConfigs=function(e){if(e){(0,c.default)(e)||(e=p.default.join(n.cwd(),e));for(var t=!1,r=!1;e!==(e=p.default.dirname(e));){if(!t){var i=p.default.join(e,".babelrc");s(i)&&(this.addConfig(i),t=!0);var a=p.default.join(e,"package.json");!t&&s(a)&&(t=this.addConfig(a,"babel",JSON))}if(!r){var o=p.default.join(e,".babelignore");s(o)&&(this.addIgnoreConfig(o),r=!0)}if(r&&t)return}}},e.prototype.addIgnoreConfig=function(e){var t=h.default.readFileSync(e,"utf8").split("\n");(t=t.map(function(e){return e.replace(/#(.*?)$/,"").trim()}).filter(function(e){return!!e})).length&&this.mergeConfig({options:{ignore:t},alias:e,dirname:p.default.dirname(e)})},e.prototype.addConfig=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:l.default;if(this.resolvedConfigs.indexOf(e)>=0)return!1;this.resolvedConfigs.push(e);var n=h.default.readFileSync(e,"utf8"),i=void 0;try{i=d[n]=d[n]||r.parse(n),t&&(i=i[t])}catch(t){throw t.message=e+": Error while parsing JSON - "+t.message,t}return this.mergeConfig({options:i,alias:e,dirname:p.default.dirname(e)}),!!i},e.prototype.mergeConfig=function(e){var t=e.options,r=e.alias,i=e.loc,s=e.dirname;if(!t)return!1;if(t=(0,a.default)({},t),s=s||n.cwd(),i=i||r,t.extends){var o=(0,u.default)(t.extends,s);o?this.addConfig(o):this.log&&this.log.error("Couldn't resolve extends clause of "+t.extends+" in "+r),delete t.extends}this.configs.push({options:t,alias:r,loc:i,dirname:s});var l=void 0,c=n.env.BABEL_ENV||n.env.NODE_ENV||"development";t.env&&(l=t.env[c],delete t.env),this.mergeConfig({options:l,alias:r+".env."+c,dirname:s})},e}();t.exports=r.default}).call(this,e("_process"))},{"../../../helpers/resolve":40,_process:550,"babel-runtime/core-js/object/assign":124,"babel-runtime/helpers/classCallCheck":134,fs:191,json5:324,path:546,"path-is-absolute":547}],47:[function(e,t,r){"use strict";t.exports={filename:{type:"filename",description:"filename to use when reading from stdin - this will be used in source-maps, errors etc",default:"unknown",shorthand:"f"},filenameRelative:{hidden:!0,type:"string"},inputSourceMap:{hidden:!0},env:{hidden:!0,default:{}},mode:{description:"",hidden:!0},retainLines:{type:"boolean",default:!1,description:"retain line numbers - will result in really ugly code"},highlightCode:{description:"enable/disable ANSI syntax highlighting of code frames (on by default)",type:"boolean",default:!0},suppressDeprecationMessages:{type:"boolean",default:!1,hidden:!0},presets:{type:"list",description:"",default:[]},plugins:{type:"list",default:[],description:""},ignore:{type:"list",description:"list of glob paths to **not** compile",default:[]},only:{type:"list",description:"list of glob paths to **only** compile"},code:{hidden:!0,default:!0,type:"boolean"},metadata:{hidden:!0,default:!0,type:"boolean"},ast:{hidden:!0,default:!0,type:"boolean"},extends:{type:"string",hidden:!0},comments:{type:"boolean",default:!0,description:"write comments to generated output (true by default)"},shouldPrintComment:{hidden:!0,description:"optional callback to control whether a comment should be inserted, when this is used the comments option is ignored"},wrapPluginVisitorMethod:{hidden:!0,description:"optional callback to wrap all visitor methods"},compact:{type:"booleanString",default:"auto",description:"do not include superfluous whitespace characters and line terminators [true|false|auto]"},minified:{type:"boolean",default:!1,description:"save as much bytes when printing [true|false]"},sourceMap:{alias:"sourceMaps",hidden:!0},sourceMaps:{type:"booleanString",description:"[true|false|inline]",default:!1,shorthand:"s"},sourceMapTarget:{type:"string",description:"set `file` on returned source map"},sourceFileName:{type:"string",description:"set `sources[0]` on returned source map"},sourceRoot:{type:"filename",description:"the root from which all sources are relative"},babelrc:{description:"Whether or not to look up .babelrc and .babelignore files",type:"boolean",default:!0},sourceType:{description:"",default:"module"},auxiliaryCommentBefore:{type:"string",description:"print a comment before any injected non-user code"},auxiliaryCommentAfter:{type:"string",description:"print a comment after any injected non-user code"},resolveModuleSource:{hidden:!0},getModuleId:{hidden:!0},moduleRoot:{type:"filename",description:"optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"},moduleIds:{type:"boolean",default:!1,shorthand:"M",description:"insert an explicit id for modules"},moduleId:{description:"specify a custom name for module ids",type:"string"},passPerPreset:{description:"Whether to spawn a traversal pass per a preset. By default all presets are merged.",type:"boolean",default:!1,hidden:!0},parserOpts:{description:"Options to pass into the parser, or to change parsers (parserOpts.parser)",default:!1},generatorOpts:{description:"Options to pass into the generator, or to change generators (generatorOpts.generator)",default:!1}}},{}],48:[function(e,t,r){"use strict";r.__esModule=!0,r.config=void 0,r.normaliseOptions=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e){var r=e[t];if(null!=r){var s=i.default[t];if(s&&s.alias&&(s=i.default[s.alias]),s){var a=n[s.type];a&&(r=a(r)),e[t]=r}}}return e};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./parsers")),i=function(e){return e&&e.__esModule?e:{default:e}}(e("./config"));r.config=i.default},{"./config":47,"./parsers":50}],49:[function(e,t,r){(function(n){"use strict";function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function s(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var a=s(e("babel-runtime/helpers/objectWithoutProperties")),o=s(e("babel-runtime/core-js/json/stringify")),u=s(e("babel-runtime/core-js/object/assign")),l=s(e("babel-runtime/core-js/get-iterator")),c=s(e("babel-runtime/helpers/typeof")),p=s(e("babel-runtime/helpers/classCallCheck")),h=i(e("../../../api/node")),f=s(e("../../plugin")),d=i(e("babel-messages")),m=e("./index"),y=s(e("../../../helpers/resolve-plugin")),g=s(e("../../../helpers/resolve-preset")),b=s(e("lodash/cloneDeepWith")),v=s(e("lodash/clone")),x=s(e("../../../helpers/merge")),E=s(e("./config")),A=s(e("./removed")),D=s(e("./build-config-chain")),C=s(e("path")),S=function(){function t(e){(0,p.default)(this,t),this.resolvedConfigs=[],this.options=t.createBareOptions(),this.log=e}return t.memoisePluginContainer=function(e,r,n,i){for(var s=t.memoisedPlugins,a=Array.isArray(s),o=0,s=a?s:(0,l.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var p=u;if(p.container===e)return p.plugin}var m=void 0;if("object"===(void 0===(m="function"==typeof e?e(h):e)?"undefined":(0,c.default)(m))){var y=new f.default(m,i);return t.memoisedPlugins.push({container:e,plugin:y}),y}throw new TypeError(d.get("pluginNotObject",r,n,void 0===m?"undefined":(0,c.default)(m))+r+n)},t.createBareOptions=function(){var e={};for(var t in E.default){var r=E.default[t];e[t]=(0,v.default)(r.default)}return e},t.normalisePlugin=function(e,r,n,i){if(!((e=e.__esModule?e.default:e)instanceof f.default)){if("function"!=typeof e&&"object"!==(void 0===e?"undefined":(0,c.default)(e)))throw new TypeError(d.get("pluginNotFunction",r,n,void 0===e?"undefined":(0,c.default)(e)));e=t.memoisePluginContainer(e,r,n,i)}return e.init(r,n),e},t.normalisePlugins=function(r,n,i){return i.map(function(i,s){var a=void 0,o=void 0;if(!i)throw new TypeError("Falsy value found in plugins");Array.isArray(i)?(a=i[0],o=i[1]):a=i;var u="string"==typeof a?a:r+"$"+s;if("string"==typeof a){var l=(0,y.default)(a,n);if(!l)throw new ReferenceError(d.get("pluginUnknown",a,r,s,n));a=e(l)}return a=t.normalisePlugin(a,r,s,u),[a,o]})},t.prototype.mergeOptions=function(e){var r=this,i=e.options,s=e.extending,a=e.alias,o=e.loc,l=e.dirname;if(a=a||"foreign",i){("object"!==(void 0===i?"undefined":(0,c.default)(i))||Array.isArray(i))&&this.log.error("Invalid options type for "+a,TypeError);var p=(0,b.default)(i,function(e){if(e instanceof f.default)return e});l=l||n.cwd(),o=o||a;for(var h in p){if(!E.default[h]&&this.log)if(A.default[h])this.log.error("Using removed Babel 5 option: "+a+"."+h+" - "+A.default[h].message,ReferenceError);else{var d="Unknown option: "+a+"."+h+". Check out http://babeljs.io/docs/usage/options/ for more information about options.";this.log.error(d+"\n\nA common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options.",ReferenceError)}}(0,m.normaliseOptions)(p),p.plugins&&(p.plugins=t.normalisePlugins(o,l,p.plugins)),p.presets&&(p.passPerPreset?p.presets=this.resolvePresets(p.presets,l,function(e,t){r.mergeOptions({options:e,extending:e,alias:t,loc:t,dirname:l})}):(this.mergePresets(p.presets,l),delete p.presets)),i===s?(0,u.default)(s,p):(0,x.default)(s||this.options,p)}},t.prototype.mergePresets=function(e,t){var r=this;this.resolvePresets(e,t,function(e,t){r.mergeOptions({options:e,alias:t,loc:t,dirname:C.default.dirname(t||"")})})},t.prototype.resolvePresets=function(t,r,n){return t.map(function(t){var i=void 0;if(Array.isArray(t)){if(t.length>2)throw new Error("Unexpected extra options "+(0,o.default)(t.slice(2))+" passed to preset.");var s=t;t=s[0],i=s[1]}var u=void 0;try{if("string"==typeof t){if(!(u=(0,g.default)(t,r)))throw new Error("Couldn't find preset "+(0,o.default)(t)+" relative to directory "+(0,o.default)(r));t=e(u)}if("object"===(void 0===t?"undefined":(0,c.default)(t))&&t.__esModule)if(t.default)t=t.default;else{var l=t;l.__esModule;t=(0,a.default)(l,["__esModule"])}if("object"===(void 0===t?"undefined":(0,c.default)(t))&&t.buildPreset&&(t=t.buildPreset),"function"!=typeof t&&void 0!==i)throw new Error("Options "+(0,o.default)(i)+" passed to "+(u||"a preset")+" which does not accept options.");if("function"==typeof t&&(t=t(h,i,{dirname:r})),"object"!==(void 0===t?"undefined":(0,c.default)(t)))throw new Error("Unsupported preset format: "+t+".");n&&n(t,u)}catch(e){throw u&&(e.message+=" (While processing preset: "+(0,o.default)(u)+")"),e}return t})},t.prototype.normaliseOptions=function(){var e=this.options;for(var t in E.default){var r=E.default[t],n=e[t];!n&&r.optional||(r.alias?e[r.alias]=e[r.alias]||n:e[t]=n)}},t.prototype.init=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=(0,D.default)(e,this.log),r=Array.isArray(t),n=0,t=r?t:(0,l.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;this.mergeOptions(s)}return this.normaliseOptions(e),this.options},t}();r.default=S,S.memoisedPlugins=[],t.exports=r.default}).call(this,e("_process"))},{"../../../api/node":32,"../../../helpers/merge":35,"../../../helpers/resolve-plugin":38,"../../../helpers/resolve-preset":39,"../../plugin":56,"./build-config-chain":46,"./config":47,"./index":48,"./removed":51,_process:550,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/core-js/object/assign":124,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/objectWithoutProperties":136,"babel-runtime/helpers/typeof":138,"lodash/clone":491,"lodash/cloneDeepWith":493,path:546}],50:[function(e,t,r){"use strict";r.__esModule=!0,r.filename=void 0,r.boolean=function(e){return!!e},r.booleanString=function(e){return i.booleanify(e)},r.list=function(e){return i.list(e)};var n=function(e){return e&&e.__esModule?e:{default:e}}(e("slash")),i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../../../util"));r.filename=n.default},{"../../../util":57,slash:603}],51:[function(e,t,r){"use strict";t.exports={auxiliaryComment:{message:"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"},blacklist:{message:"Put the specific transforms you want in the `plugins` option"},breakConfig:{message:"This is not a necessary option in Babel 6"},experimental:{message:"Put the specific transforms you want in the `plugins` option"},externalHelpers:{message:"Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/"},extra:{message:""},jsxPragma:{message:"use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/"},loose:{message:"Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option."},metadataUsedHelpers:{message:"Not required anymore as this is enabled by default"},modules:{message:"Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules"},nonStandard:{message:"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"},optional:{message:"Put the specific transforms you want in the `plugins` option"},sourceMapName:{message:"Use the `sourceMapTarget` option"},stage:{message:"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"},whitelist:{message:"Put the specific transforms you want in the `plugins` option"}}},{}],52:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("../plugin")),s=n(e("lodash/sortBy"));r.default=new i.default({name:"internal.blockHoist",visitor:{Block:{exit:function(e){for(var t=e.node,r=!1,n=0;n1&&void 0!==arguments[1]?arguments[1]:{};return t.code=!1,t.mode="lint",this.transform(e,t)},e.prototype.pretransform=function(e,t){var r=new o.default(t,this);return r.wrap(e,function(){return r.addCode(e),r.parseCode(e),r})},e.prototype.transform=function(e,t){var r=new o.default(t,this);return r.wrap(e,function(){return r.addCode(e),r.parseCode(e),r.transform()})},e.prototype.analyse=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments[2];return t.code=!1,r&&(t.plugins=t.plugins||[],t.plugins.push(new a.default({visitor:r}))),this.transform(e,t).metadata},e.prototype.transformFromAst=function(e,t,r){e=(0,s.default)(e);var n=new o.default(r,this);return n.wrap(t,function(){return n.addCode(t),n.addAst(e),n.transform()})},e}();r.default=u,t.exports=r.default},{"../helpers/normalize-ast":36,"./file":43,"./plugin":56,"babel-runtime/helpers/classCallCheck":134}],55:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=n(e("babel-runtime/helpers/possibleConstructorReturn")),a=n(e("babel-runtime/helpers/inherits")),o=n(e("../store")),u=(n(e("./file")),function(e){function t(r,n){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};(0,i.default)(this,t);var o=(0,s.default)(this,e.call(this));return o.plugin=n,o.key=n.key,o.file=r,o.opts=a,o}return(0,a.default)(t,e),t.prototype.addHelper=function(){var e;return(e=this.file).addHelper.apply(e,arguments)},t.prototype.addImport=function(){var e;return(e=this.file).addImport.apply(e,arguments)},t.prototype.getModuleName=function(){var e;return(e=this.file).getModuleName.apply(e,arguments)},t.prototype.buildCodeFrameError=function(){var e;return(e=this.file).buildCodeFrameError.apply(e,arguments)},t}(o.default));r.default=u,t.exports=r.default},{"../store":41,"./file":43,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137}],56:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator")),s=n(e("babel-runtime/helpers/classCallCheck")),a=n(e("babel-runtime/helpers/possibleConstructorReturn")),o=n(e("babel-runtime/helpers/inherits")),u=n(e("./file/options/option-manager")),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-messages")),c=n(e("../store")),p=n(e("babel-traverse")),h=n(e("lodash/assign")),f=n(e("lodash/clone")),d=["enter","exit"],m=function(e){function t(r,n){(0,s.default)(this,t);var i=(0,a.default)(this,e.call(this));return i.initialized=!1,i.raw=(0,h.default)({},r),i.key=i.take("name")||n,i.manipulateOptions=i.take("manipulateOptions"),i.post=i.take("post"),i.pre=i.take("pre"),i.visitor=i.normaliseVisitor((0,f.default)(i.take("visitor"))||{}),i}return(0,o.default)(t,e),t.prototype.take=function(e){var t=this.raw[e];return delete this.raw[e],t},t.prototype.chain=function(e,t){if(!e[t])return this[t];if(!this[t])return e[t];var r=[e[t],this[t]];return function(){for(var e=void 0,t=arguments.length,n=Array(t),s=0;s=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}if(l){var c=l.apply(this,n);null!=c&&(e=c)}}return e}},t.prototype.maybeInherit=function(e){var t=this.take("inherits");t&&(t=u.default.normalisePlugin(t,e,"inherits"),this.manipulateOptions=this.chain(t,"manipulateOptions"),this.post=this.chain(t,"post"),this.pre=this.chain(t,"pre"),this.visitor=p.default.visitors.merge([t.visitor,this.visitor]))},t.prototype.init=function(e,t){if(!this.initialized){this.initialized=!0,this.maybeInherit(e);for(var r in this.raw)throw new Error(l.get("pluginInvalidProperty",e,t,r))}},t.prototype.normaliseVisitor=function(e){for(var t=d,r=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}if(e[s])throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.")}return p.default.explode(e),e},t}(c.default);r.default=m,t.exports=r.default},{"../store":41,"./file/options/option-manager":49,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137,"babel-traverse":143,"lodash/assign":488,"lodash/clone":491}],57:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r=t||i.EXTENSIONS,n=m.default.extname(e);return(0,f.default)(r,n)}function s(e){return e?Array.isArray(e)?e:"string"==typeof e?e.split(","):[e]:[]}function a(e,t){return e?"boolean"==typeof e?a([e],t):"string"==typeof e?a(s(e),t):Array.isArray(e)?(t&&(e=e.map(t)),e):[e]:[]}function o(e,t){return"function"==typeof e?e(t):e.test(t)}r.__esModule=!0,r.inspect=r.inherits=void 0;var u=n(e("babel-runtime/core-js/get-iterator")),l=e("util");Object.defineProperty(r,"inherits",{enumerable:!0,get:function(){return l.inherits}}),Object.defineProperty(r,"inspect",{enumerable:!0,get:function(){return l.inspect}}),r.canCompile=i,r.list=s,r.regexify=function(e){if(!e)return new RegExp(/.^/);if(Array.isArray(e)&&(e=new RegExp(e.map(c.default).join("|"),"i")),"string"==typeof e){e=(0,y.default)(e),((0,p.default)(e,"./")||(0,p.default)(e,"*/"))&&(e=e.slice(2)),(0,p.default)(e,"**/")&&(e=e.slice(3));var t=h.default.makeRe(e,{nocase:!0});return new RegExp(t.source.slice(1,-1),"i")}if((0,d.default)(e))return e;throw new TypeError("illegal type for regexify")},r.arrayify=a,r.booleanify=function(e){return"true"===e||1==e||!("false"===e||0==e||!e)&&e},r.shouldIgnore=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments[2];if(e=e.replace(/\\/g,"/"),r){for(var n=r,i=Array.isArray(n),s=0,n=i?n:(0,u.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}if(o(a,e))return!1}return!0}if(t.length)for(var l=t,c=Array.isArray(l),p=0,l=c?l:(0,u.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if((p=l.next()).done)break;h=p.value}if(o(h,e))return!0}return!1};var c=n(e("lodash/escapeRegExp")),p=n(e("lodash/startsWith")),h=n(e("minimatch")),f=n(e("lodash/includes")),d=n(e("lodash/isRegExp")),m=n(e("path")),y=n(e("slash"));i.EXTENSIONS=[".js",".jsx",".es6",".es"]},{"babel-runtime/core-js/get-iterator":120,"lodash/escapeRegExp":497,"lodash/includes":507,"lodash/isRegExp":519,"lodash/startsWith":532,minimatch:542,path:546,slash:603,util:613}],58:[function(e,t,r){(function(t){"use strict";function n(e,n){(n=n||{}).isFileComment&&(e=function(e,t){var n=r.mapFileCommentRegex.exec(e),a=n[1]||n[2],o=s.resolve(t,a);try{return i.readFileSync(o,"utf8")}catch(e){throw new Error("An error occurred while trying to read the map file at "+o+"\n"+e)}}(e,n.commentFileDir)),n.hasComment&&(e=function(e){return e.split(",").pop()}(e)),n.isEncoded&&(e=function(e){return new t(e,"base64").toString()}(e)),(n.isJSON||n.isEncoded)&&(e=JSON.parse(e)),this.sourcemap=e}var i=e("fs"),s=e("path");Object.defineProperty(r,"commentRegex",{get:function(){return/^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/gm}}),Object.defineProperty(r,"mapFileCommentRegex",{get:function(){return/(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/gm}}),n.prototype.toJSON=function(e){return JSON.stringify(this.sourcemap,null,e)},n.prototype.toBase64=function(){var e=this.toJSON();return new t(e).toString("base64")},n.prototype.toComment=function(e){var t="sourceMappingURL=data:application/json;charset=utf-8;base64,"+this.toBase64();return e&&e.multiline?"/*# "+t+" */":"//# "+t},n.prototype.toObject=function(){return JSON.parse(this.toJSON())},n.prototype.addProperty=function(e,t){if(this.sourcemap.hasOwnProperty(e))throw new Error("property %s already exists on the sourcemap, use set property instead");return this.setProperty(e,t)},n.prototype.setProperty=function(e,t){return this.sourcemap[e]=t,this},n.prototype.getProperty=function(e){return this.sourcemap[e]},r.fromObject=function(e){return new n(e)},r.fromJSON=function(e){return new n(e,{isJSON:!0})},r.fromBase64=function(e){return new n(e,{isEncoded:!0})},r.fromComment=function(e){return e=e.replace(/^\/\*/g,"//").replace(/\*\/$/g,""),new n(e,{isEncoded:!0,hasComment:!0})},r.fromMapFileComment=function(e,t){return new n(e,{commentFileDir:t,isFileComment:!0,isJSON:!0})},r.fromSource=function(e){var t=e.match(r.commentRegex);return t?r.fromComment(t.pop()):null},r.fromMapFileSource=function(e,t){var n=e.match(r.mapFileCommentRegex);return n?r.fromMapFileComment(n.pop(),t):null},r.removeComments=function(e){return e.replace(r.commentRegex,"")},r.removeMapFileComments=function(e){return e.replace(r.mapFileCommentRegex,"")},r.generateMapFileComment=function(e,t){var r="sourceMappingURL="+e;return t&&t.multiline?"/*# "+r+" */":"//# "+r}}).call(this,e("buffer").Buffer)},{buffer:192,fs:191,path:546}],59:[function(e,t,r){t.exports=e("./src/node")},{"./src/node":61}],60:[function(e,t,r){function n(e){function t(){if(t.enabled){var e=t,n=+new Date,s=n-(i||n);e.diff=s,e.prev=i,e.curr=n,i=n;for(var a=new Array(arguments.length),o=0;o=0)return t}else{var r=i.toSetString(e);if(s.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},n.prototype.at=function(e){if(e>=0&&e>>=5)>0&&(t|=32),r+=n.encode(t)}while(i>0);return r},r.decode=function(e,t,r){var i,s,a=e.length,o=0,u=0;do{if(t>=a)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(s=n.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));i=!!(32&s),o+=(s&=31)<>1;return 1==(1&e)?-t:t}(o),r.rest=t}},{"./base64":64}],64:[function(e,t,r){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");r.encode=function(e){if(0<=e&&e0?t-u>1?n(u,t,i,s,a,o):o==r.LEAST_UPPER_BOUND?t1?n(e,u,i,s,a,o):o==r.LEAST_UPPER_BOUND?u:e<0?-1:e}r.GREATEST_LOWER_BOUND=1,r.LEAST_UPPER_BOUND=2,r.search=function(e,t,i,s){if(0===t.length)return-1;var a=n(-1,t.length,e,t,i,s||r.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&0===i(t[a],t[a-1],!0);)--a;return a}},{}],66:[function(e,t,r){function n(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=e("./util");n.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},n.prototype.add=function(e){!function(e,t){var r=e.generatedLine,n=t.generatedLine,s=e.generatedColumn,a=t.generatedColumn;return n>r||n==r&&a>=s||i.compareByGeneratedPositionsInflated(e,t)<=0}(this._last,e)?(this._sorted=!1,this._array.push(e)):(this._last=e,this._array.push(e))},n.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},r.MappingList=n},{"./util":71}],67:[function(e,t,r){function n(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function i(e,t,r,s){if(r=0){var s=this._originalMappings[i];if(void 0===e.column)for(var a=s.originalLine;s&&s.originalLine===a;)n.push({line:o.getArg(s,"generatedLine",null),column:o.getArg(s,"generatedColumn",null),lastColumn:o.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i];else for(var l=s.originalColumn;s&&s.originalLine===t&&s.originalColumn==l;)n.push({line:o.getArg(s,"generatedLine",null),column:o.getArg(s,"generatedColumn",null),lastColumn:o.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i]}return n},r.SourceMapConsumer=n,(i.prototype=Object.create(n.prototype)).consumer=n,i.fromSourceMap=function(e){var t=Object.create(i.prototype),r=t._names=l.fromArray(e._names.toArray(),!0),n=t._sources=l.fromArray(e._sources.toArray(),!0);t.sourceRoot=e._sourceRoot,t.sourcesContent=e._generateSourcesContent(t._sources.toArray(),t.sourceRoot),t.file=e._file;for(var a=e._mappings.toArray().slice(),u=t.__generatedMappings=[],c=t.__originalMappings=[],h=0,f=a.length;h1&&(r.source=m+i[1],m+=i[1],r.originalLine=f+i[2],f=r.originalLine,r.originalLine+=1,r.originalColumn=d+i[3],d=r.originalColumn,i.length>4&&(r.name=y+i[4],y+=i[4])),A.push(r),"number"==typeof r.originalLine&&E.push(r)}p(A,o.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,p(E,o.compareByOriginalPositions),this.__originalMappings=E},i.prototype._findMapping=function(e,t,r,n,i,s){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[n]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[n]);return u.search(e,t,i,s)},i.prototype.computeColumnSpans=function(){for(var e=0;e=0){var i=this._generatedMappings[r];if(i.generatedLine===t.generatedLine){var s=o.getArg(i,"source",null);null!==s&&(s=this._sources.at(s),null!=this.sourceRoot&&(s=o.join(this.sourceRoot,s)));var a=o.getArg(i,"name",null);return null!==a&&(a=this._names.at(a)),{source:s,line:o.getArg(i,"originalLine",null),column:o.getArg(i,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}},i.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},i.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=o.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var r;if(null!=this.sourceRoot&&(r=o.urlParse(this.sourceRoot))){var n=e.replace(/^file:\/\//,"");if("file"==r.scheme&&this._sources.has(n))return this.sourcesContent[this._sources.indexOf(n)];if((!r.path||"/"==r.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(t)return null;throw new Error('"'+e+'" is not in the SourceMap.')},i.prototype.generatedPositionFor=function(e){var t=o.getArg(e,"source");if(null!=this.sourceRoot&&(t=o.relative(this.sourceRoot,t)),!this._sources.has(t))return{line:null,column:null,lastColumn:null};var r={source:t=this._sources.indexOf(t),originalLine:o.getArg(e,"line"),originalColumn:o.getArg(e,"column")},i=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",o.compareByOriginalPositions,o.getArg(e,"bias",n.GREATEST_LOWER_BOUND));if(i>=0){var s=this._originalMappings[i];if(s.source===r.source)return{line:o.getArg(s,"generatedLine",null),column:o.getArg(s,"generatedColumn",null),lastColumn:o.getArg(s,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},r.BasicSourceMapConsumer=i,(a.prototype=Object.create(n.prototype)).constructor=n,a.prototype._version=3,Object.defineProperty(a.prototype,"sources",{get:function(){for(var e=[],t=0;t0&&e.column>=0)||t||r||n)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:n}))},n.prototype._serializeMappings=function(){for(var e,t,r,n,a=0,o=1,u=0,l=0,c=0,p=0,h="",f=this._mappings.toArray(),d=0,m=f.length;d0){if(!s.compareByGeneratedPositionsInflated(t,f[d-1]))continue;e+=","}e+=i.encode(t.generatedColumn-a),a=t.generatedColumn,null!=t.source&&(n=this._sources.indexOf(t.source),e+=i.encode(n-p),p=n,e+=i.encode(t.originalLine-1-l),l=t.originalLine-1,e+=i.encode(t.originalColumn-u),u=t.originalColumn,null!=t.name&&(r=this._names.indexOf(t.name),e+=i.encode(r-c),c=r)),h+=e}return h},n.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=s.relative(t,e));var r=s.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},n.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},n.prototype.toString=function(){return JSON.stringify(this.toJSON())},r.SourceMapGenerator=n},{"./array-set":62,"./base64-vlq":63,"./mapping-list":66,"./util":71}],70:[function(e,t,r){function n(e,t,r,n,i){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==t?null:t,this.source=null==r?null:r,this.name=null==i?null:i,this[o]=!0,null!=n&&this.add(n)}var i=e("./source-map-generator").SourceMapGenerator,s=e("./util"),a=/(\r?\n)/,o="$$$isSourceNode$$$";n.fromStringWithSourceMap=function(e,t,r){function i(e,t){if(null===e||void 0===e.source)o.add(t);else{var i=r?s.join(r,e.source):e.source;o.add(new n(e.originalLine,e.originalColumn,i,t,e.name))}}var o=new n,u=e.split(a),l=0,c=function(){function e(){return l=0;t--)this.prepend(e[t]);else{if(!e[o]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},n.prototype.walk=function(e){for(var t,r=0,n=this.children.length;r0){for(t=[],r=0;r=0;c--)"."===(a=u[c])?u.splice(c,1):".."===a?l++:l>0&&(""===a?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return""===(t=u.join("/"))&&(t=o?"/":"."),s?(s.path=t,i(s)):t}function a(e){return e}function o(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var r=t-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function u(e,t){return e===t?0:e>t?1:-1}r.getArg=function(e,t,r){if(t in e)return e[t];if(3===arguments.length)return r;throw new Error('"'+t+'" is a required argument.')};var l=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,c=/^data:.+\,.+$/;r.urlParse=n,r.urlGenerate=i,r.normalize=s,r.join=function(e,t){""===e&&(e="."),""===t&&(t=".");var r=n(t),a=n(e);if(a&&(e=a.path||"/"),r&&!r.scheme)return a&&(r.scheme=a.scheme),i(r);if(r||t.match(c))return t;if(a&&!a.host&&!a.path)return a.host=t,i(a);var o="/"===t.charAt(0)?t:s(e.replace(/\/+$/,"")+"/"+t);return a?(a.path=o,i(a)):o},r.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(l)},r.relative=function(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==t.indexOf(e+"/");){var n=e.lastIndexOf("/");if(n<0)return t;if((e=e.slice(0,n)).match(/^([^\/]+:\/)?\/*$/))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)};var p=!("__proto__"in Object.create(null));r.toSetString=p?a:function(e){return o(e)?"$"+e:e},r.fromSetString=p?a:function(e){return o(e)?e.slice(1):e},r.compareByOriginalPositions=function(e,t,r){var n=e.source-t.source;return 0!==n?n:0!=(n=e.originalLine-t.originalLine)?n:0!=(n=e.originalColumn-t.originalColumn)||r?n:0!=(n=e.generatedColumn-t.generatedColumn)?n:0!=(n=e.generatedLine-t.generatedLine)?n:e.name-t.name},r.compareByGeneratedPositionsDeflated=function(e,t,r){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!=(n=e.generatedColumn-t.generatedColumn)||r?n:0!=(n=e.source-t.source)?n:0!=(n=e.originalLine-t.originalLine)?n:0!=(n=e.originalColumn-t.originalColumn)?n:e.name-t.name},r.compareByGeneratedPositionsInflated=function(e,t){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!=(r=e.generatedColumn-t.generatedColumn)?r:0!==(r=u(e.source,t.source))?r:0!=(r=e.originalLine-t.originalLine)?r:0!=(r=e.originalColumn-t.originalColumn)?r:u(e.name,t.name)}},{}],72:[function(e,t,r){r.SourceMapGenerator=e("./lib/source-map-generator").SourceMapGenerator,r.SourceMapConsumer=e("./lib/source-map-consumer").SourceMapConsumer,r.SourceNode=e("./lib/source-node").SourceNode},{"./lib/source-map-consumer":68,"./lib/source-map-generator":69,"./lib/source-node":70}],73:[function(e,t,r){t.exports={_args:[[{raw:"babel-core@^6.18.2",scope:null,escapedName:"babel-core",name:"babel-core",rawSpec:"^6.18.2",spec:">=6.18.2 <7.0.0",type:"range"},"/Users/evgenypoberezkin/Documents/JSON/ajv/node_modules/regenerator"]],_from:"babel-core@>=6.18.2 <7.0.0",_id:"babel-core@6.26.0",_inCache:!0,_location:"/babel-core",_nodeVersion:"6.9.0",_npmOperationalInternal:{host:"s3://npm-registry-packages",tmp:"tmp/babel-core-6.26.0.tgz_1502898861183_0.43529116874560714"},_npmUser:{name:"hzoo",email:"hi@henryzoo.com"},_npmVersion:"4.6.1",_phantomChildren:{ms:"2.0.0"},_requested:{raw:"babel-core@^6.18.2",scope:null,escapedName:"babel-core",name:"babel-core",rawSpec:"^6.18.2",spec:">=6.18.2 <7.0.0",type:"range"},_requiredBy:["/babel-register","/regenerator"],_resolved:"https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz",_shasum:"af32f78b31a6fcef119c87b0fd8d9753f03a0bb8",_shrinkwrap:null,_spec:"babel-core@^6.18.2",_where:"/Users/evgenypoberezkin/Documents/JSON/ajv/node_modules/regenerator",author:{name:"Sebastian McKenzie",email:"sebmck@gmail.com"},dependencies:{"babel-code-frame":"^6.26.0","babel-generator":"^6.26.0","babel-helpers":"^6.24.1","babel-messages":"^6.23.0","babel-register":"^6.26.0","babel-runtime":"^6.26.0","babel-template":"^6.26.0","babel-traverse":"^6.26.0","babel-types":"^6.26.0",babylon:"^6.18.0","convert-source-map":"^1.5.0",debug:"^2.6.8",json5:"^0.5.1",lodash:"^4.17.4",minimatch:"^3.0.4","path-is-absolute":"^1.0.1",private:"^0.1.7",slash:"^1.0.0","source-map":"^0.5.6"},description:"Babel compiler core.",devDependencies:{"babel-helper-fixtures":"^6.26.0","babel-helper-transform-fixture-test-runner":"^6.26.0","babel-polyfill":"^6.26.0"},directories:{},dist:{shasum:"af32f78b31a6fcef119c87b0fd8d9753f03a0bb8",tarball:"https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz"},homepage:"https://babeljs.io/",keywords:["6to5","babel","classes","const","es6","harmony","let","modules","transpile","transpiler","var","babel-core","compiler"],license:"MIT",maintainers:[{name:"thejameskyle",email:"me@thejameskyle.com"},{name:"sebmck",email:"sebmck@gmail.com"},{name:"danez",email:"daniel@tschinder.de"},{name:"hzoo",email:"hi@henryzoo.com"},{name:"loganfsmyth",email:"loganfsmyth@gmail.com"}],name:"babel-core",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"https://github.com/babel/babel/tree/master/packages/babel-core"},scripts:{bench:"make bench",test:"make test"},version:"6.26.0"}},{}],74:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=n(e("trim-right")),a=/^[ \t]+$/,o=function(){function e(t){(0,i.default)(this,e),this._map=null,this._buf=[],this._last="",this._queue=[],this._position={line:1,column:0},this._sourcePosition={identifierName:null,line:null,column:null,filename:null},this._map=t}return e.prototype.get=function(){this._flush();var e=this._map,t={code:(0,s.default)(this._buf.join("")),map:null,rawMappings:e&&e.getRawMappings()};return e&&Object.defineProperty(t,"map",{configurable:!0,enumerable:!0,get:function(){return this.map=e.get()},set:function(e){Object.defineProperty(this,"map",{value:e,writable:!0})}}),t},e.prototype.append=function(e){this._flush();var t=this._sourcePosition,r=t.line,n=t.column,i=t.filename,s=t.identifierName;this._append(e,r,n,s,i)},e.prototype.queue=function(e){if("\n"===e)for(;this._queue.length>0&&a.test(this._queue[0][0]);)this._queue.shift();var t=this._sourcePosition,r=t.line,n=t.column,i=t.filename,s=t.identifierName;this._queue.unshift([e,r,n,s,i])},e.prototype._flush=function(){for(var e=void 0;e=this._queue.pop();)this._append.apply(this,e)},e.prototype._append=function(e,t,r,n,i){this._map&&"\n"!==e[0]&&this._map.mark(this._position.line,this._position.column,t,r,n,i),this._buf.push(e),this._last=e[e.length-1];for(var s=0;s0&&"\n"===this._queue[0][0]&&this._queue.shift()},e.prototype.removeLastSemicolon=function(){this._queue.length>0&&";"===this._queue[0][0]&&this._queue.shift()},e.prototype.endsWith=function(e){if(1===e.length){var t=void 0;if(this._queue.length>0){var r=this._queue[0][0];t=r[r.length-1]}else t=this._last;return t===e}var n=this._last+this._queue.reduce(function(e,t){return t[0]+e},"");return e.length<=n.length&&n.slice(-e.length)===e},e.prototype.hasContent=function(){return this._queue.length>0||!!this._last},e.prototype.source=function(e,t){if(!e||t){var r=t?t[e]:null;this._sourcePosition.identifierName=t&&t.identifierName||null,this._sourcePosition.line=r?r.line:null,this._sourcePosition.column=r?r.column:null,this._sourcePosition.filename=t&&t.filename||null}},e.prototype.withSource=function(e,t,r){if(!this._map)return r();var n=this._sourcePosition.line,i=this._sourcePosition.column,s=this._sourcePosition.filename,a=this._sourcePosition.identifierName;this.source(e,t),r(),this._sourcePosition.line=n,this._sourcePosition.column=i,this._sourcePosition.filename=s,this._sourcePosition.identifierName=a},e.prototype.getCurrentColumn=function(){var e=this._queue.reduce(function(e,t){return t[0]+e},""),t=e.lastIndexOf("\n");return-1===t?this._position.column+e.length:e.length-1-t},e.prototype.getCurrentLine=function(){for(var e=this._queue.reduce(function(e,t){return t[0]+e},""),t=0,r=0;r")}function a(){this.space(),this.token("|"),this.space()}r.__esModule=!0,r.TypeParameterDeclaration=r.StringLiteralTypeAnnotation=r.NumericLiteralTypeAnnotation=r.GenericTypeAnnotation=r.ClassImplements=void 0,r.AnyTypeAnnotation=function(){this.word("any")},r.ArrayTypeAnnotation=function(e){this.print(e.elementType,e),this.token("["),this.token("]")},r.BooleanTypeAnnotation=function(){this.word("boolean")},r.BooleanLiteralTypeAnnotation=function(e){this.word(e.value?"true":"false")},r.NullLiteralTypeAnnotation=function(){this.word("null")},r.DeclareClass=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.word("class"),this.space(),this._interfaceish(e)},r.DeclareFunction=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.word("function"),this.space(),this.print(e.id,e),this.print(e.id.typeAnnotation.typeAnnotation,e),this.semicolon()},r.DeclareInterface=function(e){this.word("declare"),this.space(),this.InterfaceDeclaration(e)},r.DeclareModule=function(e){this.word("declare"),this.space(),this.word("module"),this.space(),this.print(e.id,e),this.space(),this.print(e.body,e)},r.DeclareModuleExports=function(e){this.word("declare"),this.space(),this.word("module"),this.token("."),this.word("exports"),this.print(e.typeAnnotation,e)},r.DeclareTypeAlias=function(e){this.word("declare"),this.space(),this.TypeAlias(e)},r.DeclareOpaqueType=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.OpaqueType(e)},r.DeclareVariable=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.word("var"),this.space(),this.print(e.id,e),this.print(e.id.typeAnnotation,e),this.semicolon()},r.DeclareExportDeclaration=function(e){this.word("declare"),this.space(),this.word("export"),this.space(),e.default&&(this.word("default"),this.space()),function(e){if(e.declaration){var t=e.declaration;this.print(t,e),u.isStatement(t)||this.semicolon()}else this.token("{"),e.specifiers.length&&(this.space(),this.printList(e.specifiers,e),this.space()),this.token("}"),e.source&&(this.space(),this.word("from"),this.space(),this.print(e.source,e)),this.semicolon()}.apply(this,arguments)},r.ExistentialTypeParam=function(){this.token("*")},r.FunctionTypeAnnotation=function(e,t){this.print(e.typeParameters,e),this.token("("),this.printList(e.params,e),e.rest&&(e.params.length&&(this.token(","),this.space()),this.token("..."),this.print(e.rest,e)),this.token(")"),"ObjectTypeCallProperty"===t.type||"DeclareFunction"===t.type?this.token(":"):(this.space(),this.token("=>")),this.space(),this.print(e.returnType,e)},r.FunctionTypeParam=function(e){this.print(e.name,e),e.optional&&this.token("?"),this.token(":"),this.space(),this.print(e.typeAnnotation,e)},r.InterfaceExtends=n,r._interfaceish=function(e){this.print(e.id,e),this.print(e.typeParameters,e),e.extends.length&&(this.space(),this.word("extends"),this.space(),this.printList(e.extends,e)),e.mixins&&e.mixins.length&&(this.space(),this.word("mixins"),this.space(),this.printList(e.mixins,e)),this.space(),this.print(e.body,e)},r._variance=function(e){"plus"===e.variance?this.token("+"):"minus"===e.variance&&this.token("-")},r.InterfaceDeclaration=function(e){this.word("interface"),this.space(),this._interfaceish(e)},r.IntersectionTypeAnnotation=function(e){this.printJoin(e.types,e,{separator:i})},r.MixedTypeAnnotation=function(){this.word("mixed")},r.EmptyTypeAnnotation=function(){this.word("empty")},r.NullableTypeAnnotation=function(e){this.token("?"),this.print(e.typeAnnotation,e)};var o=e("./types");Object.defineProperty(r,"NumericLiteralTypeAnnotation",{enumerable:!0,get:function(){return o.NumericLiteral}}),Object.defineProperty(r,"StringLiteralTypeAnnotation",{enumerable:!0,get:function(){return o.StringLiteral}}),r.NumberTypeAnnotation=function(){this.word("number")},r.StringTypeAnnotation=function(){this.word("string")},r.ThisTypeAnnotation=function(){this.word("this")},r.TupleTypeAnnotation=function(e){this.token("["),this.printList(e.types,e),this.token("]")},r.TypeofTypeAnnotation=function(e){this.word("typeof"),this.space(),this.print(e.argument,e)},r.TypeAlias=function(e){this.word("type"),this.space(),this.print(e.id,e),this.print(e.typeParameters,e),this.space(),this.token("="),this.space(),this.print(e.right,e),this.semicolon()},r.OpaqueType=function(e){this.word("opaque"),this.space(),this.word("type"),this.space(),this.print(e.id,e),this.print(e.typeParameters,e),e.supertype&&(this.token(":"),this.space(),this.print(e.supertype,e)),e.impltype&&(this.space(),this.token("="),this.space(),this.print(e.impltype,e)),this.semicolon()},r.TypeAnnotation=function(e){this.token(":"),this.space(),e.optional&&this.token("?"),this.print(e.typeAnnotation,e)},r.TypeParameter=function(e){this._variance(e),this.word(e.name),e.bound&&this.print(e.bound,e),e.default&&(this.space(),this.token("="),this.space(),this.print(e.default,e))},r.TypeParameterInstantiation=s,r.ObjectTypeAnnotation=function(e){var t=this;e.exact?this.token("{|"):this.token("{");var r=e.properties.concat(e.callProperties,e.indexers);r.length&&(this.space(),this.printJoin(r,e,{addNewlines:function(e){if(e&&!r[0])return 1},indent:!0,statement:!0,iterator:function(){1!==r.length&&(t.format.flowCommaSeparator?t.token(","):t.semicolon(),t.space())}}),this.space()),e.exact?this.token("|}"):this.token("}")},r.ObjectTypeCallProperty=function(e){e.static&&(this.word("static"),this.space()),this.print(e.value,e)},r.ObjectTypeIndexer=function(e){e.static&&(this.word("static"),this.space()),this._variance(e),this.token("["),this.print(e.id,e),this.token(":"),this.space(),this.print(e.key,e),this.token("]"),this.token(":"),this.space(),this.print(e.value,e)},r.ObjectTypeProperty=function(e){e.static&&(this.word("static"),this.space()),this._variance(e),this.print(e.key,e),e.optional&&this.token("?"),this.token(":"),this.space(),this.print(e.value,e)},r.ObjectTypeSpreadProperty=function(e){this.token("..."),this.print(e.argument,e)},r.QualifiedTypeIdentifier=function(e){this.print(e.qualification,e),this.token("."),this.print(e.id,e)},r.UnionTypeAnnotation=function(e){this.printJoin(e.types,e,{separator:a})},r.TypeCastExpression=function(e){this.token("("),this.print(e.expression,e),this.print(e.typeAnnotation,e),this.token(")")},r.VoidTypeAnnotation=function(){this.word("void")};var u=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));r.ClassImplements=n,r.GenericTypeAnnotation=n,r.TypeParameterDeclaration=s},{"./types":84,"babel-types":178}],79:[function(e,t,r){"use strict";function n(){this.space()}r.__esModule=!0;var i=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.JSXAttribute=function(e){this.print(e.name,e),e.value&&(this.token("="),this.print(e.value,e))},r.JSXIdentifier=function(e){this.word(e.name)},r.JSXNamespacedName=function(e){this.print(e.namespace,e),this.token(":"),this.print(e.name,e)},r.JSXMemberExpression=function(e){this.print(e.object,e),this.token("."),this.print(e.property,e)},r.JSXSpreadAttribute=function(e){this.token("{"),this.token("..."),this.print(e.argument,e),this.token("}")},r.JSXExpressionContainer=function(e){this.token("{"),this.print(e.expression,e),this.token("}")},r.JSXSpreadChild=function(e){this.token("{"),this.token("..."),this.print(e.expression,e),this.token("}")},r.JSXText=function(e){this.token(e.value)},r.JSXElement=function(e){var t=e.openingElement;if(this.print(t,e),!t.selfClosing){this.indent();for(var r=e.children,n=Array.isArray(r),s=0,r=n?r:(0,i.default)(r);;){var a;if(n){if(s>=r.length)break;a=r[s++]}else{if((s=r.next()).done)break;a=s.value}var o=a;this.print(o,e)}this.dedent(),this.print(e.closingElement,e)}},r.JSXOpeningElement=function(e){this.token("<"),this.print(e.name,e),e.attributes.length>0&&(this.space(),this.printJoin(e.attributes,e,{separator:n})),e.selfClosing?(this.space(),this.token("/>")):this.token(">")},r.JSXClosingElement=function(e){this.token("")},r.JSXEmptyExpression=function(){}},{"babel-runtime/core-js/get-iterator":120}],80:[function(e,t,r){"use strict";function n(e){e.async&&(this.word("async"),this.space()),this.word("function"),e.generator&&this.token("*"),e.id?(this.space(),this.print(e.id,e)):this.space(),this._params(e),this.space(),this.print(e.body,e)}r.__esModule=!0,r.FunctionDeclaration=void 0,r._params=function(e){var t=this;this.print(e.typeParameters,e),this.token("("),this.printList(e.params,e,{iterator:function(e){e.optional&&t.token("?"),t.print(e.typeAnnotation,e)}}),this.token(")"),e.returnType&&this.print(e.returnType,e)},r._method=function(e){var t=e.kind,r=e.key;"method"!==t&&"init"!==t||e.generator&&this.token("*"),"get"!==t&&"set"!==t||(this.word(t),this.space()),e.async&&(this.word("async"),this.space()),e.computed?(this.token("["),this.print(r,e),this.token("]")):this.print(r,e),this._params(e),this.space(),this.print(e.body,e)},r.FunctionExpression=n,r.ArrowFunctionExpression=function(e){e.async&&(this.word("async"),this.space());var t=e.params[0];1===e.params.length&&i.isIdentifier(t)&&!function(e,t){return e.typeParameters||e.returnType||t.typeAnnotation||t.optional||t.trailingComments}(e,t)?this.print(t,e):this._params(e),this.space(),this.token("=>"),this.space(),this.print(e.body,e)};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));r.FunctionDeclaration=n},{"babel-types":178}],81:[function(e,t,r){"use strict";function n(e){if(e.declaration){var t=e.declaration;this.print(t,e),i.isStatement(t)||this.semicolon()}else{"type"===e.exportKind&&(this.word("type"),this.space());for(var r=e.specifiers.slice(0),n=!1;;){var s=r[0];if(!i.isExportDefaultSpecifier(s)&&!i.isExportNamespaceSpecifier(s))break;n=!0,this.print(r.shift(),e),r.length&&(this.token(","),this.space())}(r.length||!r.length&&!n)&&(this.token("{"),r.length&&(this.space(),this.printList(r,e),this.space()),this.token("}")),e.source&&(this.space(),this.word("from"),this.space(),this.print(e.source,e)),this.semicolon()}}r.__esModule=!0,r.ImportSpecifier=function(e){"type"!==e.importKind&&"typeof"!==e.importKind||(this.word(e.importKind),this.space()),this.print(e.imported,e),e.local&&e.local.name!==e.imported.name&&(this.space(),this.word("as"),this.space(),this.print(e.local,e))},r.ImportDefaultSpecifier=function(e){this.print(e.local,e)},r.ExportDefaultSpecifier=function(e){this.print(e.exported,e)},r.ExportSpecifier=function(e){this.print(e.local,e),e.exported&&e.local.name!==e.exported.name&&(this.space(),this.word("as"),this.space(),this.print(e.exported,e))},r.ExportNamespaceSpecifier=function(e){this.token("*"),this.space(),this.word("as"),this.space(),this.print(e.exported,e)},r.ExportAllDeclaration=function(e){this.word("export"),this.space(),this.token("*"),this.space(),this.word("from"),this.space(),this.print(e.source,e),this.semicolon()},r.ExportNamedDeclaration=function(){this.word("export"),this.space(),n.apply(this,arguments)},r.ExportDefaultDeclaration=function(){this.word("export"),this.space(),this.word("default"),this.space(),n.apply(this,arguments)},r.ImportDeclaration=function(e){this.word("import"),this.space(),"type"!==e.importKind&&"typeof"!==e.importKind||(this.word(e.importKind),this.space());var t=e.specifiers.slice(0);if(t&&t.length){for(;;){var r=t[0];if(!i.isImportDefaultSpecifier(r)&&!i.isImportNamespaceSpecifier(r))break;this.print(t.shift(),e),t.length&&(this.token(","),this.space())}t.length&&(this.token("{"),this.space(),this.printList(t,e),this.space(),this.token("}")),this.space(),this.word("from"),this.space()}this.print(e.source,e),this.semicolon()},r.ImportNamespaceSpecifier=function(e){this.token("*"),this.space(),this.word("as"),this.space(),this.print(e.local,e)};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"))},{"babel-types":178}],82:[function(e,t,r){"use strict";function n(e){return a.isStatement(e.body)?n(e.body):e}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"label";return function(r){this.word(e);var n=r[t];if(n){this.space();var i=this.startTerminatorless();this.print(n,r),this.endTerminatorless(i)}this.semicolon()}}r.__esModule=!0,r.ThrowStatement=r.BreakStatement=r.ReturnStatement=r.ContinueStatement=r.ForAwaitStatement=r.ForOfStatement=r.ForInStatement=void 0;var s=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.WithStatement=function(e){this.word("with"),this.space(),this.token("("),this.print(e.object,e),this.token(")"),this.printBlock(e)},r.IfStatement=function(e){this.word("if"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.space();var t=e.alternate&&a.isIfStatement(n(e.consequent));t&&(this.token("{"),this.newline(),this.indent()),this.printAndIndentOnComments(e.consequent,e),t&&(this.dedent(),this.newline(),this.token("}")),e.alternate&&(this.endsWith("}")&&this.space(),this.word("else"),this.space(),this.printAndIndentOnComments(e.alternate,e))},r.ForStatement=function(e){this.word("for"),this.space(),this.token("("),this.inForStatementInitCounter++,this.print(e.init,e),this.inForStatementInitCounter--,this.token(";"),e.test&&(this.space(),this.print(e.test,e)),this.token(";"),e.update&&(this.space(),this.print(e.update,e)),this.token(")"),this.printBlock(e)},r.WhileStatement=function(e){this.word("while"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.printBlock(e)},r.DoWhileStatement=function(e){this.word("do"),this.space(),this.print(e.body,e),this.space(),this.word("while"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.semicolon()},r.LabeledStatement=function(e){this.print(e.label,e),this.token(":"),this.space(),this.print(e.body,e)},r.TryStatement=function(e){this.word("try"),this.space(),this.print(e.block,e),this.space(),e.handlers?this.print(e.handlers[0],e):this.print(e.handler,e),e.finalizer&&(this.space(),this.word("finally"),this.space(),this.print(e.finalizer,e))},r.CatchClause=function(e){this.word("catch"),this.space(),this.token("("),this.print(e.param,e),this.token(")"),this.space(),this.print(e.body,e)},r.SwitchStatement=function(e){this.word("switch"),this.space(),this.token("("),this.print(e.discriminant,e),this.token(")"),this.space(),this.token("{"),this.printSequence(e.cases,e,{indent:!0,addNewlines:function(t,r){if(!t&&e.cases[e.cases.length-1]===r)return-1}}),this.token("}")},r.SwitchCase=function(e){e.test?(this.word("case"),this.space(),this.print(e.test,e),this.token(":")):(this.word("default"),this.token(":")),e.consequent.length&&(this.newline(),this.printSequence(e.consequent,e,{indent:!0}))},r.DebuggerStatement=function(){this.word("debugger"),this.semicolon()},r.VariableDeclaration=function(e,t){this.word(e.kind),this.space();var r=!1;if(!a.isFor(t))for(var n=e.declarations,i=Array.isArray(n),o=0,n=i?n:(0,s.default)(n);;){var u;if(i){if(o>=n.length)break;u=n[o++]}else{if((o=n.next()).done)break;u=o.value}u.init&&(r=!0)}var l=void 0;r&&(l="const"===e.kind?function(){if(this.token(","),this.newline(),this.endsWith("\n"))for(var e=0;e<6;e++)this.space(!0)}:function(){if(this.token(","),this.newline(),this.endsWith("\n"))for(var e=0;e<4;e++)this.space(!0)}),this.printList(e.declarations,e,{separator:l}),(!a.isFor(t)||t.left!==e&&t.init!==e)&&this.semicolon()},r.VariableDeclarator=function(e){this.print(e.id,e),this.print(e.id.typeAnnotation,e),e.init&&(this.space(),this.token("="),this.space(),this.print(e.init,e))};var a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types")),o=function(e){return function(t){this.word("for"),this.space(),"await"===e&&(this.word("await"),this.space()),this.token("("),this.print(t.left,t),this.space(),this.word("await"===e?"of":e),this.space(),this.print(t.right,t),this.token(")"),this.printBlock(t)}};r.ForInStatement=o("in"),r.ForOfStatement=o("of"),r.ForAwaitStatement=o("await"),r.ContinueStatement=i("continue"),r.ReturnStatement=i("return","argument"),r.BreakStatement=i("break"),r.ThrowStatement=i("throw","argument")},{"babel-runtime/core-js/get-iterator":120,"babel-types":178}],83:[function(e,t,r){"use strict";r.__esModule=!0,r.TaggedTemplateExpression=function(e){this.print(e.tag,e),this.print(e.quasi,e)},r.TemplateElement=function(e,t){var r=t.quasis[0]===e,n=t.quasis[t.quasis.length-1]===e,i=(r?"`":"}")+e.value.raw+(n?"`":"${");this.token(i)},r.TemplateLiteral=function(e){for(var t=e.quasis,r=0;r0&&this.space(),this.print(i,e),n1&&void 0!==arguments[1]?arguments[1]:{},a=arguments[2];(0,i.default)(this,t);var c=r.tokens||[],p=function(e,t,r){var n=" ";if(e&&"string"==typeof e){var i=(0,o.default)(e).indent;i&&" "!==i&&(n=i)}var s={auxiliaryCommentBefore:t.auxiliaryCommentBefore,auxiliaryCommentAfter:t.auxiliaryCommentAfter,shouldPrintComment:t.shouldPrintComment,retainLines:t.retainLines,retainFunctionParens:t.retainFunctionParens,comments:null==t.comments||t.comments,compact:t.compact,minified:t.minified,concise:t.concise,quotes:t.quotes||function(e,t){if(!e)return"double";for(var r={single:0,double:0},n=0,i=0;i=3))break}return r.single>r.double?"single":"double"}(e,r),jsonCompatibleStrings:t.jsonCompatibleStrings,indent:{adjustMultilineComment:!0,style:n,base:0},flowCommaSeparator:t.flowCommaSeparator};return s.minified?(s.compact=!0,s.shouldPrintComment=s.shouldPrintComment||function(){return s.comments}):s.shouldPrintComment=s.shouldPrintComment||function(e){return s.comments||e.indexOf("@license")>=0||e.indexOf("@preserve")>=0},"auto"===s.compact&&(s.compact=e.length>5e5,s.compact&&console.error("[BABEL] "+l.get("codeGeneratorDeopt",t.filename,"500KB"))),s.compact&&(s.indent.adjustMultilineComment=!1),s}(a,n,c),h=n.sourceMaps?new u.default(n,a):null,f=(0,s.default)(this,e.call(this,p,h,c));return f.ast=r,f}return(0,a.default)(t,e),t.prototype.generate=function(){return e.prototype.generate.call(this,this.ast)},t}(n(e("./printer")).default);r.CodeGenerator=function(){function e(t,r,n){(0,i.default)(this,e),this._generator=new c(t,r,n)}return e.prototype.generate=function(){return this._generator.generate()},e}()},{"./printer":89,"./source-map":90,"babel-messages":110,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137,"detect-indent":309}],86:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e){function t(e,t){var n=r[e];r[e]=n?function(e,r,i){var s=n(e,r,i);return null==s?t(e,r,i):s}:t}for(var r={},n=(0,c.default)(e),i=Array.isArray(n),s=0,n=i?n:(0,l.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a,u=f.FLIPPED_ALIAS_KEYS[o];if(u)for(var p=u,h=Array.isArray(p),d=0,p=h?p:(0,l.default)(p);;){var m;if(h){if(d>=p.length)break;m=p[d++]}else{if((d=p.next()).done)break;m=d.value}t(m,e[o])}else t(o,e[o])}return r}function a(e,t,r,n){var i=e[t.type];return i?i(t,r,n):null}function o(e){return!!f.isCallExpression(e)||!!f.isMemberExpression(e)&&(o(e.object)||!e.computed&&o(e.property))}function u(e,t,r){if(!e)return 0;f.isExpressionStatement(e)&&(e=e.expression);var n=a(m,e,t);if(!n){var i=a(y,e,t);if(i)for(var s=0;s1&&void 0!==arguments[1]?arguments[1]:{},r=t.considerArrow,n=void 0!==r&&r,i=t.considerDefaultExports,s=void 0!==i&&i,a=e.length-1,o=e[a],l=e[--a];a>0;){if(u.isExpressionStatement(l,{expression:o})||u.isTaggedTemplateExpression(l)||s&&u.isExportDefaultDeclaration(l,{declaration:o})||n&&u.isArrowFunctionExpression(l,{body:o}))return!0;if(!(u.isCallExpression(l,{callee:o})||u.isSequenceExpression(l)&&l.expressions[0]===o||u.isMemberExpression(l,{object:o})||u.isConditional(l,{test:o})||u.isBinary(l,{left:o})||u.isAssignmentExpression(l,{left:o})))return!1;o=l,l=e[--a]}return!1}r.__esModule=!0,r.AwaitExpression=r.FunctionTypeAnnotation=void 0,r.NullableTypeAnnotation=n,r.UpdateExpression=function(e,t){return u.isMemberExpression(t)&&t.object===e},r.ObjectExpression=function(e,t,r){return o(r,{considerArrow:!0})},r.DoExpression=function(e,t,r){return o(r)},r.Binary=function(e,t){if((u.isCallExpression(t)||u.isNewExpression(t))&&t.callee===e||u.isUnaryLike(t)||u.isMemberExpression(t)&&t.object===e||u.isAwaitExpression(t))return!0;if(u.isBinary(t)){var r=t.operator,n=l[r],i=e.operator,s=l[i];if(n===s&&t.right===e&&!u.isLogicalExpression(t)||n>s)return!0}return!1},r.BinaryExpression=function(e,t){return"in"===e.operator&&(u.isVariableDeclarator(t)||u.isFor(t))},r.SequenceExpression=function(e,t){return!(u.isForStatement(t)||u.isThrowStatement(t)||u.isReturnStatement(t)||u.isIfStatement(t)&&t.test===e||u.isWhileStatement(t)&&t.test===e||u.isForInStatement(t)&&t.right===e||u.isSwitchStatement(t)&&t.discriminant===e||u.isExpressionStatement(t)&&t.expression===e)},r.YieldExpression=i,r.ClassExpression=function(e,t,r){return o(r,{considerDefaultExports:!0})},r.UnaryLike=s,r.FunctionExpression=function(e,t,r){return o(r,{considerDefaultExports:!0})},r.ArrowFunctionExpression=function(e,t){return!!(u.isExportDeclaration(t)||u.isBinaryExpression(t)||u.isLogicalExpression(t)||u.isUnaryExpression(t)||u.isTaggedTemplateExpression(t))||s(e,t)},r.ConditionalExpression=a,r.AssignmentExpression=function(e){return!!u.isObjectPattern(e.left)||a.apply(void 0,arguments)};var u=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types")),l={"||":0,"&&":1,"|":2,"^":3,"&":4,"==":5,"===":5,"!=":5,"!==":5,"<":6,">":6,"<=":6,">=":6,in:6,instanceof:6,">>":7,"<<":7,">>>":7,"+":8,"-":8,"*":9,"/":9,"%":9,"**":10};r.FunctionTypeAnnotation=n,r.AwaitExpression=i},{"babel-types":178}],88:[function(e,t,r){"use strict";function n(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return o.isMemberExpression(e)?(n(e.object,t),e.computed&&n(e.property,t)):o.isBinary(e)||o.isAssignmentExpression(e)?(n(e.left,t),n(e.right,t)):o.isCallExpression(e)?(t.hasCall=!0,n(e.callee,t)):o.isFunction(e)?t.hasFunction=!0:o.isIdentifier(e)&&(t.hasHelper=t.hasHelper||i(e.callee)),t}function i(e){return o.isMemberExpression(e)?i(e.object)||i(e.property):o.isIdentifier(e)?"require"===e.name||"_"===e.name[0]:o.isCallExpression(e)?i(e.callee):!(!o.isBinary(e)&&!o.isAssignmentExpression(e))&&(o.isIdentifier(e.left)&&i(e.left)||i(e.right))}function s(e){return o.isLiteral(e)||o.isObjectExpression(e)||o.isArrayExpression(e)||o.isIdentifier(e)||o.isMemberExpression(e)}var a=function(e){return e&&e.__esModule?e:{default:e}}(e("lodash/map")),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));r.nodes={AssignmentExpression:function(e){var t=n(e.right);if(t.hasCall&&t.hasHelper||t.hasFunction)return{before:t.hasFunction,after:!0}},SwitchCase:function(e,t){return{before:e.consequent.length||t.cases[0]===e}},LogicalExpression:function(e){if(o.isFunction(e.left)||o.isFunction(e.right))return{after:!0}},Literal:function(e){if("use strict"===e.value)return{after:!0}},CallExpression:function(e){if(o.isFunction(e.callee)||i(e))return{before:!0,after:!0}},VariableDeclaration:function(e){for(var t=0;t0?new g.default(n):null}return e.prototype.generate=function(e){return this.print(e),this._maybeAddAuxComment(),this._buf.get()},e.prototype.indent=function(){this.format.compact||this.format.concise||this._indent++},e.prototype.dedent=function(){this.format.compact||this.format.concise||this._indent--},e.prototype.semicolon=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._maybeAddAuxComment(),this._append(";",!e)},e.prototype.rightBrace=function(){this.format.minified&&this._buf.removeLastSemicolon(),this.token("}")},e.prototype.space=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.format.compact||(this._buf.hasContent()&&!this.endsWith(" ")&&!this.endsWith("\n")||e)&&this._space()},e.prototype.word=function(e){this._endsWithWord&&this._space(),this._maybeAddAuxComment(),this._append(e),this._endsWithWord=!0},e.prototype.number=function(e){this.word(e),this._endsWithInteger=(0,f.default)(+e)&&!E.test(e)&&!v.test(e)&&!x.test(e)&&"."!==e[e.length-1]},e.prototype.token=function(e){("--"===e&&this.endsWith("!")||"+"===e[0]&&this.endsWith("+")||"-"===e[0]&&this.endsWith("-")||"."===e[0]&&this._endsWithInteger)&&this._space(),this._maybeAddAuxComment(),this._append(e)},e.prototype.newline=function(e){if(!this.format.retainLines&&!this.format.compact)if(this.format.concise)this.space();else if(!(this.endsWith("\n\n")||("number"!=typeof e&&(e=1),e=Math.min(2,e),(this.endsWith("{\n")||this.endsWith(":\n"))&&e--,e<=0)))for(var t=0;t1&&void 0!==arguments[1]&&arguments[1];this._maybeAddParen(e),this._maybeIndent(e),t?this._buf.queue(e):this._buf.append(e),this._endsWithWord=!1,this._endsWithInteger=!1},e.prototype._maybeIndent=function(e){this._indent&&this.endsWith("\n")&&"\n"!==e[0]&&this._buf.queue(this._getIndent())},e.prototype._maybeAddParen=function(e){var t=this._parenPushNewlineState;if(t){this._parenPushNewlineState=null;var r=void 0;for(r=0;r2&&void 0!==arguments[2]?arguments[2]:{};if(e&&e.length){r.indent&&this.indent();for(var n={addNewlines:r.addNewlines},i=0;i1&&void 0!==arguments[1])||arguments[1];e.innerComments&&(t&&this.indent(),this._printComments(e.innerComments),t&&this.dedent())},e.prototype.printSequence=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.statement=!0,this.printJoin(e,t,r)},e.prototype.printList=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return null==r.separator&&(r.separator=s),this.printJoin(e,t,r)},e.prototype._printNewline=function(e,t,r,n){var i=this;if(!this.format.retainLines&&!this.format.compact)if(this.format.concise)this.space();else{var s=0;if(null!=t.start&&!t._ignoreUserWhitespace&&this._whitespace)if(e){var a=t.leadingComments,o=a&&(0,p.default)(a,function(e){return!!e.loc&&i.format.shouldPrintComment(e.value)});s=this._whitespace.getNewlinesBefore(o||t)}else{var u=t.trailingComments,l=u&&(0,h.default)(u,function(e){return!!e.loc&&i.format.shouldPrintComment(e.value)});s=this._whitespace.getNewlinesAfter(l||t)}else{e||s++,n.addNewlines&&(s+=n.addNewlines(e,t)||0);var c=y.needsWhitespaceAfter;e&&(c=y.needsWhitespaceBefore),c(t,r)&&s++,this._buf.hasContent()||(s=0)}this.newline(s)}},e.prototype._getComments=function(e,t){return t&&(e?t.leadingComments:t.trailingComments)||[]},e.prototype._printComment=function(e){var t=this;if(this.format.shouldPrintComment(e.value)&&!e.ignore&&!this._printedComments.has(e)){if(this._printedComments.add(e),null!=e.start){if(this._printedCommentStarts[e.start])return;this._printedCommentStarts[e.start]=!0}this.newline(this._whitespace?this._whitespace.getNewlinesBefore(e):0),this.endsWith("[")||this.endsWith("{")||this.space();var r="CommentLine"===e.type?"//"+e.value+"\n":"/*"+e.value+"*/";if("CommentBlock"===e.type&&this.format.indent.adjustMultilineComment){var n=e.loc&&e.loc.start.column;if(n){var i=new RegExp("\\n\\s{1,"+n+"}","g");r=r.replace(i,"\n")}var s=Math.max(this._getIndent().length,this._buf.getCurrentColumn());r=r.replace(/\n(?!$)/g,"\n"+(0,d.default)(" ",s))}this.withSource("start",e.loc,function(){t._append(r)}),this.newline((this._whitespace?this._whitespace.getNewlinesAfter(e):0)+("CommentLine"===e.type?-1:0))}},e.prototype._printComments=function(e){if(e&&e.length)for(var t=e,r=Array.isArray(t),n=0,t=r?t:(0,o.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;this._printComment(s)}},e}();r.default=A;for(var D=[e("./generators/template-literals"),e("./generators/expressions"),e("./generators/statements"),e("./generators/classes"),e("./generators/methods"),e("./generators/modules"),e("./generators/types"),e("./generators/flow"),e("./generators/base"),e("./generators/jsx")],C=0;C=0){for(;i&&e.start===n[i-1].start;)--i;t=n[i-1],r=n[i]}return this._getNewlinesBetween(t,r)},e.prototype.getNewlinesAfter=function(e){var t=void 0,r=void 0,n=this.tokens,i=this._findToken(function(t){return t.end-e.end},0,n.length);if(i>=0){for(;i&&e.end===n[i-1].end;)--i;t=n[i],","===(r=n[i+1]).type.label&&(r=n[i+2])}return r&&"eof"===r.type.label?1:this._getNewlinesBetween(t,r)},e.prototype._getNewlinesBetween=function(e,t){if(!t||!t.loc)return 0;for(var r=e?e.loc.end.line:1,n=t.loc.start.line,i=0,s=r;s=r)return-1;var n=t+r>>>1,i=e(this.tokens[n]);return i<0?this._findToken(e,n+1,r):i>0?this._findToken(e,t,n):0===i?n:-1},e}();r.default=i,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134}],92:[function(e,t,r){arguments[4][62][0].apply(r,arguments)},{"./util":101,dup:62}],93:[function(e,t,r){arguments[4][63][0].apply(r,arguments)},{"./base64":94,dup:63}],94:[function(e,t,r){arguments[4][64][0].apply(r,arguments)},{dup:64}],95:[function(e,t,r){arguments[4][65][0].apply(r,arguments)},{dup:65}],96:[function(e,t,r){arguments[4][66][0].apply(r,arguments)},{"./util":101,dup:66}],97:[function(e,t,r){arguments[4][67][0].apply(r,arguments)},{dup:67}],98:[function(e,t,r){arguments[4][68][0].apply(r,arguments)},{"./array-set":92,"./base64-vlq":93,"./binary-search":95,"./quick-sort":97,"./util":101,dup:68}],99:[function(e,t,r){arguments[4][69][0].apply(r,arguments)},{"./array-set":92,"./base64-vlq":93,"./mapping-list":96,"./util":101,dup:69}],100:[function(e,t,r){arguments[4][70][0].apply(r,arguments)},{"./source-map-generator":99,"./util":101,dup:70}],101:[function(e,t,r){arguments[4][71][0].apply(r,arguments)},{dup:71}],102:[function(e,t,r){arguments[4][72][0].apply(r,arguments)},{"./lib/source-map-consumer":98,"./lib/source-map-generator":99,"./lib/source-node":100,dup:72}],103:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=u.objectExpression([]);return(0,s.default)(e).forEach(function(r){var n=e[r],i=u.objectExpression([]),a=u.objectProperty(n._key,i,n._computed);(0,s.default)(n).forEach(function(e){var t=n[e];if("_"!==e[0]){var r=t;(u.isClassMethod(t)||u.isClassProperty(t))&&(t=t.value);var s=u.objectProperty(u.identifier(e),t);u.inheritsComments(s,r),u.removeComments(r),i.properties.push(s)}}),t.properties.push(a)}),t}r.__esModule=!0;var s=n(e("babel-runtime/core-js/object/keys"));r.push=function(e,t,r,n,i){var s=u.toKeyAlias(t),l={};if((0,o.default)(e,s)&&(l=e[s]),e[s]=l,l._inherits=l._inherits||[],l._inherits.push(t),l._key=t.key,t.computed&&(l._computed=!0),t.decorators){var c=l.decorators=l.decorators||u.arrayExpression([]);c.elements=c.elements.concat(t.decorators.map(function(e){return e.expression}).reverse())}if(l.value||l.initializer)throw n.buildCodeFrameError(t,"Key conflict with sibling node");var p=void 0,h=void 0;(u.isObjectProperty(t)||u.isObjectMethod(t)||u.isClassMethod(t))&&(p=u.toComputedKey(t,t.key)),u.isObjectProperty(t)||u.isClassProperty(t)?h=t.value:(u.isObjectMethod(t)||u.isClassMethod(t))&&((h=u.functionExpression(null,t.params,t.body,t.generator,t.async)).returnType=t.returnType);var f=function(e){return!u.isClassMethod(e)&&!u.isObjectMethod(e)||"get"!==e.kind&&"set"!==e.kind?"value":e.kind}(t);return r&&"value"===f||(r=f),i&&u.isStringLiteral(p)&&("value"===r||"initializer"===r)&&u.isFunctionExpression(h)&&(h=(0,a.default)({id:p,node:h,scope:i})),h&&(u.inheritsComments(h,t),l[r]=h),l},r.hasComputed=function(e){for(var t in e)if(e[t]._computed)return!0;return!1},r.toComputedObjectFromClass=function(e){for(var t=u.arrayExpression([]),r=0;r1&&void 0!==arguments[1]&&arguments[1];(0,o.default)(this,e),this.forceSuperMemoisation=t.forceSuperMemoisation,this.methodPath=t.methodPath,this.methodNode=t.methodNode,this.superRef=t.superRef,this.isStatic=t.isStatic,this.hasSuper=!1,this.inClass=r,this.isLoose=t.isLoose,this.scope=this.methodPath.scope,this.file=t.file,this.opts=t,this.bareSupers=[],this.returns=[],this.thises=[]}return e.prototype.getObjectRef=function(){return this.opts.objectRef||this.opts.getObjectRef()},e.prototype.setSuperProperty=function(e,t,r){return p.callExpression(this.file.addHelper("set"),[a(this.getObjectRef(),this.isStatic),r?e:p.stringLiteral(e.name),t,p.thisExpression()])},e.prototype.getSuperProperty=function(e,t){return p.callExpression(this.file.addHelper("get"),[a(this.getObjectRef(),this.isStatic),t?e:p.stringLiteral(e.name),p.thisExpression()])},e.prototype.replace=function(){this.methodPath.traverse(f,this)},e.prototype.getLooseSuperProperty=function(e,t){var r=this.methodNode,n=this.superRef||p.identifier("Function");return t.property===e?void 0:p.isCallExpression(t,{callee:e})?void 0:p.isMemberExpression(t)&&!r.static?p.memberExpression(n,p.identifier("prototype")):n},e.prototype.looseHandle=function(e){var t=e.node;if(e.isSuper())return this.getLooseSuperProperty(t,e.parent);if(e.isCallExpression()){var r=t.callee;if(!p.isMemberExpression(r))return;if(!p.isSuper(r.object))return;return p.appendToMemberExpression(r,p.identifier("call")),t.arguments.unshift(p.thisExpression()),!0}},e.prototype.specHandleAssignmentExpression=function(e,t,r){return"="===r.operator?this.setSuperProperty(r.left.property,r.right,r.left.computed):(e=e||t.scope.generateUidIdentifier("ref"),[p.variableDeclaration("var",[p.variableDeclarator(e,r.left)]),p.expressionStatement(p.assignmentExpression("=",r.left,p.binaryExpression(r.operator[0],e,r.right)))])},e.prototype.specHandle=function(e){var t=void 0,r=void 0,n=void 0,i=e.parent,a=e.node;if(function(e,t){return!!p.isSuper(e)&&!p.isMemberExpression(t,{computed:!1})&&!p.isCallExpression(t,{callee:e})}(a,i))throw e.buildCodeFrameError(c.get("classesIllegalBareSuper"));if(p.isCallExpression(a)){var o=a.callee;if(p.isSuper(o))return;s(o)&&(t=o.property,r=o.computed,n=a.arguments)}else if(p.isMemberExpression(a)&&p.isSuper(a.object))t=a.property,r=a.computed;else{if(p.isUpdateExpression(a)&&s(a.argument)){var u=p.binaryExpression(a.operator[0],a.argument,p.numericLiteral(1));if(a.prefix)return this.specHandleAssignmentExpression(null,e,u);var l=e.scope.generateUidIdentifier("ref");return this.specHandleAssignmentExpression(l,e,u).concat(p.expressionStatement(l))}if(p.isAssignmentExpression(a)&&s(a.left))return this.specHandleAssignmentExpression(null,e,a)}if(t){var h=this.getSuperProperty(t,r);return n?this.optimiseCall(h,n):h}},e.prototype.optimiseCall=function(e,t){var r=p.thisExpression();return r[h]=!0,(0,l.default)(e,r,t)},e}();r.default=d,t.exports=r.default},{"babel-helper-optimise-call-expression":106,"babel-messages":110,"babel-runtime/core-js/symbol":129,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],108:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-template")),i={};r.default=i,i.typeof=(0,n.default)('\n (typeof Symbol === "function" && typeof Symbol.iterator === "symbol")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? "symbol"\n : typeof obj;\n };\n'),i.jsx=(0,n.default)('\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === "function" && Symbol.for && Symbol.for("react.element")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we\'re going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : \'\' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n'),i.asyncIterator=(0,n.default)('\n (function (iterable) {\n if (typeof Symbol === "function") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError("Object is not async iterable");\n })\n'),i.asyncGenerator=(0,n.default)('\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume("next", arg); },\n function (arg) { resume("throw", arg); });\n } else {\n settle(result.done ? "return" : "normal", result.value);\n }\n } catch (err) {\n settle("throw", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case "return":\n front.resolve({ value: value, done: true });\n break;\n case "throw":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide "return" method if generator return is not supported\n if (typeof gen.return !== "function") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === "function" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n'),i.asyncGeneratorDelegate=(0,n.default)('\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === "function" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump("next", value);\n };\n\n if (typeof inner.throw === "function") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump("throw", value);\n };\n }\n\n if (typeof inner.return === "function") {\n iter.return = function (value) {\n return pump("return", value);\n };\n }\n\n return iter;\n })\n'),i.asyncToGenerator=(0,n.default)('\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n step("next", value);\n }, function (err) {\n step("throw", err);\n });\n }\n }\n\n return step("next");\n });\n };\n })\n'),i.classCallCheck=(0,n.default)('\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError("Cannot call a class as a function");\n }\n });\n'),i.createClass=(0,n.default)('\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if ("value" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n'),i.defineEnumerableProperties=(0,n.default)('\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if ("value" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n'),i.defaults=(0,n.default)("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n"),i.defineProperty=(0,n.default)("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n"),i.extends=(0,n.default)("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n"),i.get=(0,n.default)('\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if ("value" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n'),i.inherits=(0,n.default)('\n (function (subClass, superClass) {\n if (typeof superClass !== "function" && superClass !== null) {\n throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n'),i.instanceof=(0,n.default)('\n (function (left, right) {\n if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n'),i.interopRequireDefault=(0,n.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"),i.interopRequireWildcard=(0,n.default)("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n"),i.newArrowCheck=(0,n.default)('\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError("Cannot instantiate an arrow function");\n }\n });\n'),i.objectDestructuringEmpty=(0,n.default)('\n (function (obj) {\n if (obj == null) throw new TypeError("Cannot destructure undefined");\n });\n'),i.objectWithoutProperties=(0,n.default)("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n"),i.possibleConstructorReturn=(0,n.default)('\n (function (self, call) {\n if (!self) {\n throw new ReferenceError("this hasn\'t been initialised - super() hasn\'t been called");\n }\n return call && (typeof call === "object" || typeof call === "function") ? call : self;\n });\n'),i.selfGlobal=(0,n.default)('\n typeof global === "undefined" ? self : global\n'),i.set=(0,n.default)('\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if ("value" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n'),i.slicedToArray=(0,n.default)('\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i["return"]) _i["return"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError("Invalid attempt to destructure non-iterable instance");\n }\n };\n })();\n'),i.slicedToArrayLoose=(0,n.default)('\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError("Invalid attempt to destructure non-iterable instance");\n }\n });\n'),i.taggedTemplateLiteral=(0,n.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"),i.taggedTemplateLiteralLoose=(0,n.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"),i.temporalRef=(0,n.default)('\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + " is not defined - temporal dead zone");\n } else {\n return val;\n }\n })\n'),i.temporalUndefined=(0,n.default)("\n ({})\n"),i.toArray=(0,n.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"),i.toConsumableArray=(0,n.default)("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n"),t.exports=r.default},{"babel-template":139}],109:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=a.default[e];if(!t)throw new ReferenceError("Unknown helper "+e);return t().expression}r.__esModule=!0,r.list=void 0;var s=n(e("babel-runtime/core-js/object/keys"));r.get=i;var a=n(e("./helpers"));r.list=(0,s.default)(a.default).map(function(e){return e.replace(/^_/,"")}).filter(function(e){return"__esModule"!==e});r.default=i},{"./helpers":108,"babel-runtime/core-js/object/keys":127}],110:[function(e,t,r){"use strict";function n(e){return e.map(function(e){if(null!=e&&e.inspect)return e.inspect();try{return(0,i.default)(e)||e+""}catch(t){return s.inspect(e)}})}r.__esModule=!0,r.MESSAGES=void 0;var i=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/json/stringify"));r.get=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),s=1;s4&&void 0!==arguments[4]&&arguments[4];if(t||(t=e.node),!h.isFor(r))for(var s=0;s0&&e.traverse(g,t),e.skip()}},p.visitor]),g=c.default.visitors.merge([{ReferencedIdentifier:function(e,t){var r=t.letReferences[e.node.name];if(r){var n=e.scope.getBindingIdentifier(e.node.name);n&&n!==r||(t.closurify=!0)}}},p.visitor]),b={enter:function(e,t){var r=e.node;e.parent;if(e.isForStatement()){if(a(r.init)){var n=t.pushDeclar(r.init);1===n.length?r.init=n[0]:r.init=h.sequenceExpression(n)}}else if(e.isFor())a(r.left)&&(t.pushDeclar(r.left),r.left=r.left.declarations[0].id);else if(a(r))e.replaceWithMultiple(t.pushDeclar(r).map(function(e){return h.expressionStatement(e)}));else if(e.isFunction())return e.skip()}},v={LabeledStatement:function(e,t){var r=e.node;t.innerLabels.push(r.label.name)}},x={enter:function(e,t){if(e.isAssignmentExpression()||e.isUpdateExpression()){var r=e.getBindingIdentifiers();for(var n in r)t.outsideReferences[n]===e.scope.getBindingIdentifier(n)&&(t.reassignments[n]=!0)}}},E={Loop:function(e,t){var r=t.ignoreLabeless;t.ignoreLabeless=!0,e.traverse(E,t),t.ignoreLabeless=r,e.skip()},Function:function(e){e.skip()},SwitchCase:function(e,t){var r=t.inSwitchCase;t.inSwitchCase=!0,e.traverse(E,t),t.inSwitchCase=r,e.skip()},"BreakStatement|ContinueStatement|ReturnStatement":function(e,t){var r=e.node,n=e.parent,i=e.scope;if(!r[this.LOOP_IGNORE]){var s=void 0,a=function(e){return h.isBreakStatement(e)?"break":h.isContinueStatement(e)?"continue":void 0}(r);if(a){if(r.label){if(t.innerLabels.indexOf(r.label.name)>=0)return;a=a+"|"+r.label.name}else{if(t.ignoreLabeless)return;if(t.inSwitchCase)return;if(h.isBreakStatement(r)&&h.isSwitchCase(n))return}t.hasBreakContinue=!0,t.map[a]=r,s=h.stringLiteral(a)}e.isReturnStatement()&&(t.hasReturn=!0,s=h.objectExpression([h.objectProperty(h.identifier("v"),r.argument||i.buildUndefinedNode())])),s&&((s=h.returnStatement(s))[this.LOOP_IGNORE]=!0,e.skip(),e.replaceWith(h.inherits(s,r)))}}},A=function(){function e(t,r,n,i,s){(0,l.default)(this,e),this.parent=n,this.scope=i,this.file=s,this.blockPath=r,this.block=r.node,this.outsideLetReferences=(0,u.default)(null),this.hasLetReferences=!1,this.letReferences=(0,u.default)(null),this.body=[],t&&(this.loopParent=t.parent,this.loopLabel=h.isLabeledStatement(this.loopParent)&&this.loopParent.label,this.loopPath=t,this.loop=t.node)}return e.prototype.run=function(){var e=this.block;if(!e._letDone){e._letDone=!0;var t=this.getLetReferences();if(h.isFunction(this.parent)||h.isProgram(this.block))this.updateScopeInfo();else if(this.hasLetReferences)return t?this.wrapClosure():this.remap(),this.updateScopeInfo(t),this.loopLabel&&!h.isLabeledStatement(this.loopParent)?h.labeledStatement(this.loopLabel,this.loop):void 0}},e.prototype.updateScopeInfo=function(e){var t=this.scope,r=t.getFunctionParent(),n=this.letReferences;for(var i in n){var s=n[i],a=t.getBinding(s.name);a&&("let"!==a.kind&&"const"!==a.kind||(a.kind="var",e?t.removeBinding(s.name):t.moveBindingTo(s.name,r)))}},e.prototype.remap=function(){var e=this.letReferences,t=this.scope;for(var r in e){var n=e[r];(t.parentHasBinding(r)||t.hasGlobal(r))&&(t.hasOwnBinding(r)&&t.rename(n.name),this.blockPath.scope.hasOwnBinding(r)&&this.blockPath.scope.rename(n.name))}},e.prototype.wrapClosure=function(){if(this.file.opts.throwIfClosureRequired)throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure (throwIfClosureRequired).");var e=this.block,t=this.outsideLetReferences;if(this.loop)for(var r in t){var n=t[r];(this.scope.hasGlobal(n.name)||this.scope.parentHasBinding(n.name))&&(delete t[n.name],delete this.letReferences[n.name],this.scope.rename(n.name),this.letReferences[n.name]=n,t[n.name]=n)}this.has=this.checkLoop(),this.hoistVarDeclarations();var i=(0,f.default)(t),s=(0,f.default)(t),a=this.blockPath.isSwitchStatement(),o=h.functionExpression(null,i,h.blockStatement(a?[e]:e.body));o.shadow=!0,this.addContinuations(o);var u=o;this.loop&&(u=this.scope.generateUidIdentifier("loop"),this.loopPath.insertBefore(h.variableDeclaration("var",[h.variableDeclarator(u,o)])));var l=h.callExpression(u,s),p=this.scope.generateUidIdentifier("ret");c.default.hasType(o.body,this.scope,"YieldExpression",h.FUNCTION_TYPES)&&(o.generator=!0,l=h.yieldExpression(l,!0));c.default.hasType(o.body,this.scope,"AwaitExpression",h.FUNCTION_TYPES)&&(o.async=!0,l=h.awaitExpression(l)),this.buildClosure(p,l),a?this.blockPath.replaceWithMultiple(this.body):e.body=this.body},e.prototype.buildClosure=function(e,t){var r=this.has;r.hasReturn||r.hasBreakContinue?this.buildHas(e,t):this.body.push(h.expressionStatement(t))},e.prototype.addContinuations=function(e){var t={reassignments:{},outsideReferences:this.outsideLetReferences};this.scope.traverse(e,x,t);for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"value",n=arguments[3],i=void 0;e.static?(this.hasStaticDescriptors=!0,i=this.staticMutatorMap):(this.hasInstanceDescriptors=!0,i=this.instanceMutatorMap);var s=c.push(i,e,r,this.file,n);return t&&(s.enumerable=h.booleanLiteral(!0)),s},e.prototype.constructorMeMaybe=function(){for(var e=!1,t=this.path.get("body.body"),r=Array.isArray(t),n=0,t=r?t:(0,s.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}if(e=i.equals("kind","constructor"))break}if(!e){var a=void 0,o=void 0;if(this.isDerived){var u=f().expression;a=u.params,o=u.body}else a=[],o=h.blockStatement([]);this.path.get("body").unshiftContainer("body",h.classMethod("constructor",h.identifier("constructor"),a,o))}},e.prototype.buildBody=function(){if(this.constructorMeMaybe(),this.pushBody(),this.verifyConstructor(),this.userConstructor){var e=this.constructorBody;e.body=e.body.concat(this.userConstructor.body.body),h.inherits(this.constructor,this.userConstructor),h.inherits(e,this.userConstructor.body)}this.pushDescriptors()},e.prototype.pushBody=function(){for(var e=this.path.get("body.body"),t=Array.isArray(e),r=0,e=t?e:(0,s.default)(e);;){var n;if(t){if(r>=e.length)break;n=e[r++]}else{if((r=e.next()).done)break;n=r.value}var i=n,a=i.node;if(i.isClassProperty())throw i.buildCodeFrameError("Missing class properties transform.");if(a.decorators)throw i.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");if(h.isClassMethod(a)){var o="constructor"===a.kind;if(o&&(i.traverse(m,this),!this.hasBareSuper&&this.isDerived))throw i.buildCodeFrameError("missing super() call in constructor");var l=new u.default({forceSuperMemoisation:o,methodPath:i,methodNode:a,objectRef:this.classRef,superRef:this.superName,isStatic:a.static,isLoose:this.isLoose,scope:this.scope,file:this.file},!0);l.replace(),o?this.pushConstructor(l,a,i):this.pushMethod(a,i)}}},e.prototype.clearDescriptors=function(){this.hasInstanceDescriptors=!1,this.hasStaticDescriptors=!1,this.instanceMutatorMap={},this.staticMutatorMap={}},e.prototype.pushDescriptors=function(){this.pushInherits();var e=this.body,t=void 0,r=void 0;if(this.hasInstanceDescriptors&&(t=c.toClassObject(this.instanceMutatorMap)),this.hasStaticDescriptors&&(r=c.toClassObject(this.staticMutatorMap)),t||r){t&&(t=c.toComputedObjectFromClass(t)),r&&(r=c.toComputedObjectFromClass(r));var n=h.nullLiteral(),i=[this.classRef,n,n,n,n];t&&(i[1]=t),r&&(i[2]=r),this.instanceInitializersId&&(i[3]=this.instanceInitializersId,e.unshift(this.buildObjectAssignment(this.instanceInitializersId))),this.staticInitializersId&&(i[4]=this.staticInitializersId,e.unshift(this.buildObjectAssignment(this.staticInitializersId)));for(var s=0,a=0;a=o.length)break;c=o[l++]}else{if((l=o.next()).done)break;c=l.value}var p=c;this.wrapSuperCall(p,i,a,r),n&&p.find(function(e){return e===t||(e.isLoop()||e.isConditional()?(n=!1,!0):void 0)})}for(var f=this.superThises,d=Array.isArray(f),m=0,f=d?f:(0,s.default)(f);;){var g;if(d){if(m>=f.length)break;g=f[m++]}else{if((m=f.next()).done)break;g=m.value}g.replaceWith(a)}var b=function(t){return h.callExpression(e.file.addHelper("possibleConstructorReturn"),[a].concat(t||[]))},v=r.get("body");v.length&&!v.pop().isReturnStatement()&&r.pushContainer("body",h.returnStatement(n?a:b()));for(var x=this.superReturns,E=Array.isArray(x),A=0,x=E?x:(0,s.default)(x);;){var D;if(E){if(A>=x.length)break;D=x[A++]}else{if((A=x.next()).done)break;D=A.value}var C=D;if(C.node.argument){var S=C.scope.generateDeclaredUidIdentifier("ret");C.get("argument").replaceWithMultiple([h.assignmentExpression("=",S,C.node.argument),b(S)])}else C.get("argument").replaceWith(b())}}},e.prototype.pushMethod=function(e,t){var r=t?t.scope:this.scope;"method"===e.kind&&this._processMethod(e,r)||this.pushToMap(e,!1,null,r)},e.prototype._processMethod=function(){return!1},e.prototype.pushConstructor=function(e,t,r){this.bareSupers=e.bareSupers,this.superReturns=e.returns,r.scope.hasOwnBinding(this.classRef.name)&&r.scope.rename(this.classRef.name);var n=this.constructor;this.userConstructorPath=r,this.userConstructor=t,this.hasConstructor=!0,h.inheritsComments(n,t),n._ignoreUserWhitespace=!0,n.params=t.params,h.inherits(n.body,t.body),n.body.directives=t.body.directives,this._pushConstructor()},e.prototype._pushConstructor=function(){this.pushedConstructor||(this.pushedConstructor=!0,(this.hasInstanceDescriptors||this.hasStaticDescriptors)&&this.pushDescriptors(),this.body.push(this.constructor),this.pushInherits())},e.prototype.pushInherits=function(){this.isDerived&&!this.pushedInherits&&(this.pushedInherits=!0,this.body.unshift(h.expressionStatement(h.callExpression(this.file.addHelper("inherits"),[this.classRef,this.superName]))))},e}();r.default=g,t.exports=r.default},{"babel-helper-define-map":103,"babel-helper-optimise-call-expression":106,"babel-helper-replace-supers":107,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-template":139,"babel-traverse":143,"babel-types":178}],119:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e){function t(e){var t=e.node,r=e.scope,n=[],i=t.right;if(!a.isIdentifier(i)||!r.hasBinding(i.name)){var s=r.generateUidIdentifier("arr");n.push(a.variableDeclaration("var",[a.variableDeclarator(s,i)])),i=s}var u=r.generateUidIdentifier("i"),l=o({BODY:t.body,KEY:u,ARR:i});a.inherits(l,t),a.ensureBlock(l);var c=a.memberExpression(i,u,!0),p=t.left;return a.isVariableDeclaration(p)?(p.declarations[0].init=c,l.body.body.unshift(p)):l.body.body.unshift(a.expressionStatement(a.assignmentExpression("=",p,c))),e.parentPath.isLabeledStatement()&&(l=a.labeledStatement(e.parentPath.node.label,l)),n.push(l),n}function r(e,t){var r=e.node,n=e.scope,s=e.parent,o=r.left,l=void 0,c=void 0;if(a.isIdentifier(o)||a.isPattern(o)||a.isMemberExpression(o))c=o;else{if(!a.isVariableDeclaration(o))throw t.buildCodeFrameError(o,i.get("unknownForHead",o.type));c=n.generateUidIdentifier("ref"),l=a.variableDeclaration(o.kind,[a.variableDeclarator(o.declarations[0].id,c)])}var p=n.generateUidIdentifier("iterator"),h=n.generateUidIdentifier("isArray"),f=u({LOOP_OBJECT:p,IS_ARRAY:h,OBJECT:r.right,INDEX:n.generateUidIdentifier("i"),ID:c});l||f.body.body.shift();var d=a.isLabeledStatement(s),m=void 0;return d&&(m=a.labeledStatement(s.label,f)),{replaceParent:d,declar:l,node:m||f,loop:f}}function n(e,t){var r=e.node,n=e.scope,s=e.parent,o=r.left,u=void 0,c=n.generateUidIdentifier("step"),p=a.memberExpression(c,a.identifier("value"));if(a.isIdentifier(o)||a.isPattern(o)||a.isMemberExpression(o))u=a.expressionStatement(a.assignmentExpression("=",o,p));else{if(!a.isVariableDeclaration(o))throw t.buildCodeFrameError(o,i.get("unknownForHead",o.type));u=a.variableDeclaration(o.kind,[a.variableDeclarator(o.declarations[0].id,p)])}var h=n.generateUidIdentifier("iterator"),f=l({ITERATOR_HAD_ERROR_KEY:n.generateUidIdentifier("didIteratorError"),ITERATOR_COMPLETION:n.generateUidIdentifier("iteratorNormalCompletion"),ITERATOR_ERROR_KEY:n.generateUidIdentifier("iteratorError"),ITERATOR_KEY:h,STEP_KEY:c,OBJECT:r.right,BODY:null}),d=a.isLabeledStatement(s),m=f[3].block.body,y=m[0];return d&&(m[0]=a.labeledStatement(s.label,y)),{replaceParent:d,declar:u,loop:y,node:f}}var i=e.messages,s=e.template,a=e.types,o=s("\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "),u=s("\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "),l=s("\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n ");return{visitor:{ForOfStatement:function(e,i){if(e.get("right").isArrayExpression())return e.parentPath.isLabeledStatement()?e.parentPath.replaceWithMultiple(t(e)):e.replaceWithMultiple(t(e));var s=n;i.opts.loose&&(s=r);var o=e.node,u=s(e,i),l=u.declar,c=u.loop,p=c.body;e.ensureBlock(),l&&p.body.push(l),p.body=p.body.concat(o.body.body),a.inherits(c,o),a.inherits(c.body,o.body),u.replaceParent?(e.parentPath.replaceWithMultiple(u.node),e.remove()):e.replaceWithMultiple(u.node)}}}},t.exports=r.default},{}],120:[function(e,t,r){t.exports={default:e("core-js/library/fn/get-iterator"),__esModule:!0}},{"core-js/library/fn/get-iterator":194}],121:[function(e,t,r){t.exports={default:e("core-js/library/fn/json/stringify"),__esModule:!0}},{"core-js/library/fn/json/stringify":195}],122:[function(e,t,r){t.exports={default:e("core-js/library/fn/map"),__esModule:!0}},{"core-js/library/fn/map":196}],123:[function(e,t,r){t.exports={default:e("core-js/library/fn/number/max-safe-integer"),__esModule:!0}},{"core-js/library/fn/number/max-safe-integer":197}],124:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/assign"),__esModule:!0}},{"core-js/library/fn/object/assign":198}],125:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/create"),__esModule:!0}},{"core-js/library/fn/object/create":199}],126:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/get-own-property-symbols"),__esModule:!0}},{"core-js/library/fn/object/get-own-property-symbols":200}],127:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/keys"),__esModule:!0}},{"core-js/library/fn/object/keys":201}],128:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/set-prototype-of"),__esModule:!0}},{"core-js/library/fn/object/set-prototype-of":202}],129:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol"),__esModule:!0}},{"core-js/library/fn/symbol":204}],130:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol/for"),__esModule:!0}},{"core-js/library/fn/symbol/for":203}],131:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol/iterator"),__esModule:!0}},{"core-js/library/fn/symbol/iterator":205}],132:[function(e,t,r){t.exports={default:e("core-js/library/fn/weak-map"),__esModule:!0}},{"core-js/library/fn/weak-map":206}],133:[function(e,t,r){t.exports={default:e("core-js/library/fn/weak-set"),__esModule:!0}},{"core-js/library/fn/weak-set":207}],134:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},{}],135:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("../core-js/object/set-prototype-of")),s=n(e("../core-js/object/create")),a=n(e("../helpers/typeof"));r.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,a.default)(t)));e.prototype=(0,s.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i.default?(0,i.default)(e,t):e.__proto__=t)}},{"../core-js/object/create":125,"../core-js/object/set-prototype-of":128,"../helpers/typeof":138}],136:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}},{}],137:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("../helpers/typeof"));r.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,n.default)(t))&&"function"!=typeof t?e:t}},{"../helpers/typeof":138}],138:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("../core-js/symbol/iterator")),s=n(e("../core-js/symbol")),a="function"==typeof s.default&&"symbol"==typeof i.default?function(e){return typeof e}:function(e){return e&&"function"==typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":typeof e};r.default="function"==typeof s.default&&"symbol"===a(i.default)?function(e){return void 0===e?"undefined":a(e)}:function(e){return e&&"function"==typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":void 0===e?"undefined":a(e)}},{"../core-js/symbol":129,"../core-js/symbol/iterator":131}],139:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var s=i(e("babel-runtime/core-js/symbol"));r.default=function(e,t){var r=void 0;try{throw new Error}catch(e){e.stack&&(r=e.stack.split("\n").slice(1).join("\n"))}t=(0,o.default)({allowReturnOutsideFunction:!0,allowSuperOutsideMethod:!0,preserveComments:!1},t);var n=function(){var i=void 0;try{i=c.parse(e,t),i=l.default.removeProperties(i,{preserveComments:t.preserveComments}),l.default.cheap(i,function(e){e[h]=!0})}catch(e){throw e.stack=e.stack+"from\n"+r,e}return n=function(){return i},i};return function(){for(var e=arguments.length,t=Array(e),r=0;r1?r.body:r.body[0]}(n(),t)}};var a=i(e("lodash/cloneDeep")),o=i(e("lodash/assign")),u=i(e("lodash/has")),l=i(e("babel-traverse")),c=n(e("babylon")),p=n(e("babel-types")),h="_fromTemplate",f=(0,s.default)(),d={noScope:!0,enter:function(e,t){var r=e.node;if(r[f])return e.skip();p.isExpressionStatement(r)&&(r=r.expression);var n=void 0;if(p.isIdentifier(r)&&r[h])if((0,u.default)(t[0],r.name))n=t[0][r.name];else if("$"===r.name[0]){var i=+r.name.slice(1);t[i]&&(n=t[i])}null===n&&e.remove(),n&&(n[f]=!0,e.replaceInline(n))},exit:function(e){var t=e.node;t.loc||l.default.clearNode(t)}};t.exports=r.default},{"babel-runtime/core-js/symbol":129,"babel-traverse":143,"babel-types":178,babylon:186,"lodash/assign":488,"lodash/cloneDeep":492,"lodash/has":504}],140:[function(e,t,r){"use strict";function n(){r.path=a=new s.default}function i(){r.scope=o=new s.default}r.__esModule=!0,r.scope=r.path=void 0;var s=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/weak-map"));r.clear=function(){n(),i()},r.clearPath=n,r.clearScope=i;var a=r.path=new s.default,o=r.scope=new s.default},{"babel-runtime/core-js/weak-map":132}],141:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var s=i(e("babel-runtime/core-js/get-iterator")),a=i(e("babel-runtime/helpers/classCallCheck")),o=i(e("./path")),u=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types")),l="test"===n.env.NODE_ENV,c=function(){function e(t,r,n,i){(0,a.default)(this,e),this.queue=null,this.parentPath=i,this.scope=t,this.state=n,this.opts=r}return e.prototype.shouldVisit=function(e){var t=this.opts;if(t.enter||t.exit)return!0;if(t[e.type])return!0;var r=u.VISITOR_KEYS[e.type];if(!r||!r.length)return!1;for(var n=r,i=Array.isArray(n),a=0,n=i?n:(0,s.default)(n);;){var o;if(i){if(a>=n.length)break;o=n[a++]}else{if((a=n.next()).done)break;o=a.value}if(e[o])return!0}return!1},e.prototype.create=function(e,t,r,n){return o.default.get({parentPath:this.parentPath,parent:e,container:t,key:r,listKey:n})},e.prototype.maybeQueue=function(e,t){if(this.trap)throw new Error("Infinite cycle detected");this.queue&&(t?this.queue.push(e):this.priorityQueue.push(e))},e.prototype.visitMultiple=function(e,t,r){if(0===e.length)return!1;for(var n=[],i=0;i=n.length)break;o=n[a++]}else{if((a=n.next()).done)break;o=a.value}var u=o;if(u.resync(),0!==u.contexts.length&&u.contexts[u.contexts.length-1]===this||u.pushContext(this),null!==u.key&&(l&&e.length>=1e4&&(this.trap=!0),!(t.indexOf(u.node)>=0))){if(t.push(u.node),u.visit()){r=!0;break}if(this.priorityQueue.length&&(r=this.visitQueue(this.priorityQueue),this.priorityQueue=[],this.queue=e,r))break}}for(var c=e,p=Array.isArray(c),h=0,c=p?c:(0,s.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if((h=c.next()).done)break;f=h.value}f.popContext()}return this.queue=null,r},e.prototype.visit=function(e,t){var r=e[t];return!!r&&(Array.isArray(r)?this.visitMultiple(r,e,t):this.visitSingle(e,t))},e}();r.default=c,t.exports=r.default}).call(this,e("_process"))},{"./path":150,_process:550,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],142:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/helpers/classCallCheck"));r.default=function e(t,r){(0,n.default)(this,e),this.file=t,this.options=r},t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134}],143:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r,n,i){if(e){if(t||(t={}),!t.noScope&&!r&&"Program"!==e.type&&"File"!==e.type)throw new Error(f.get("traverseNeedsParent",e.type));h.explode(t),s.node(e,t,r,n,i)}}function a(e,t){e.node.type===t.type&&(t.has=!0,e.stop())}r.__esModule=!0,r.visitors=r.Hub=r.Scope=r.NodePath=void 0;var o=i(e("babel-runtime/core-js/get-iterator")),u=e("./path");Object.defineProperty(r,"NodePath",{enumerable:!0,get:function(){return i(u).default}});var l=e("./scope");Object.defineProperty(r,"Scope",{enumerable:!0,get:function(){return i(l).default}});var c=e("./hub");Object.defineProperty(r,"Hub",{enumerable:!0,get:function(){return i(c).default}}),r.default=s;var p=i(e("./context")),h=n(e("./visitors")),f=n(e("babel-messages")),d=i(e("lodash/includes")),m=n(e("babel-types")),y=n(e("./cache"));r.visitors=h,s.visitors=h,s.verify=h.verify,s.explode=h.explode,s.NodePath=e("./path"),s.Scope=e("./scope"),s.Hub=e("./hub"),s.cheap=function(e,t){return m.traverseFast(e,t)},s.node=function(e,t,r,n,i,s){var a=m.VISITOR_KEYS[e.type];if(a)for(var u=new p.default(r,t,n,i),l=a,c=Array.isArray(l),h=0,l=c?l:(0,o.default)(l);;){var f;if(c){if(h>=l.length)break;f=l[h++]}else{if((h=l.next()).done)break;f=h.value}var d=f;if((!s||!s[d])&&u.visit(e,d))return}},s.clearNode=function(e,t){m.removeProperties(e,t),y.path.delete(e)},s.removeProperties=function(e,t){return m.traverseFast(e,s.clearNode,t),e},s.hasType=function(e,t,r,n){if((0,d.default)(n,e.type))return!1;if(e.type===r)return!0;var i={has:!1,type:r};return s(e,{blacklist:n,enter:a},t,i),i.has},(s.clearCache=function(){y.clear()}).clearPath=y.clearPath,s.clearCache.clearScope=y.clearScope,s.copyCache=function(e,t){y.path.has(e)&&y.path.set(t,y.path.get(e))}},{"./cache":140,"./context":141,"./hub":142,"./path":150,"./scope":162,"./visitors":164,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-types":178,"lodash/includes":507}],144:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.findParent=function(e){for(var t=this;t=t.parentPath;)if(e(t))return t;return null},r.find=function(e){var t=this;do{if(e(t))return t}while(t=t.parentPath);return null},r.getFunctionParent=function(){return this.findParent(function(e){return e.isFunction()||e.isProgram()})},r.getStatementParent=function(){var e=this;do{if(Array.isArray(e.container))return e}while(e=e.parentPath)},r.getEarliestCommonAncestorFrom=function(e){return this.getDeepestCommonAncestorFrom(e,function(e,t,r){for(var n=void 0,a=s.VISITOR_KEYS[e.type],o=r,u=Array.isArray(o),l=0,o=u?o:(0,i.default)(o);;){var c;if(u){if(l>=o.length)break;c=o[l++]}else{if((l=o.next()).done)break;c=l.value}var p=c[t+1];n?p.listKey&&n.listKey===p.listKey&&p.keya.indexOf(p.parentKey)&&(n=p):n=p}return n})},r.getDeepestCommonAncestorFrom=function(e,t){var r=this;if(!e.length)return this;if(1===e.length)return e[0];var n=1/0,s=void 0,a=void 0,o=e.map(function(e){var t=[];do{t.unshift(e)}while((e=e.parentPath)&&e!==r);return t.length=p.length)break;d=p[f++]}else{if((f=p.next()).done)break;d=f.value}if(d[l]!==c)break e}s=l,a=c}if(a)return t?t(a,s,o):a;throw new Error("Couldn't find intersection")},r.getAncestry=function(){var e=this,t=[];do{t.push(e)}while(e=e.parentPath);return t},r.isAncestor=function(e){return e.isDescendant(this)},r.isDescendant=function(e){return!!this.findParent(function(t){return t===e})},r.inType=function(){for(var e=this;e;){for(var t=arguments,r=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}var a=s;if(e.node.type===a)return!0}e=e.parentPath}return!1},r.inShadow=function(e){var t=this.isFunction()?this:this.findParent(function(e){return e.isFunction()});if(t){if(t.isFunctionExpression()||t.isFunctionDeclaration()){var r=t.node.shadow;if(r&&(!e||!1!==r[e]))return t}else if(t.isArrowFunctionExpression())return t;return null}};var s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));n(e("./index"))},{"./index":150,"babel-runtime/core-js/get-iterator":120,"babel-types":178}],145:[function(e,t,r){"use strict";r.__esModule=!0,r.shareCommentsWithSiblings=function(){if("string"!=typeof this.key){var e=this.node;if(e){var t=e.trailingComments,r=e.leadingComments;if(t||r){var n=this.getSibling(this.key-1),i=this.getSibling(this.key+1);n.node||(n=i),i.node||(i=n),n.addComments("trailing",r),i.addComments("leading",t)}}}},r.addComment=function(e,t,r){this.addComments(e,[{type:r?"CommentLine":"CommentBlock",value:t}])},r.addComments=function(e,t){if(t){var r=this.node;if(r){var n=e+"Comments";r[n]?r[n]=r[n].concat(t):r[n]=t}}}},{}],146:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.call=function(e){var t=this.opts;return this.debug(function(){return e}),!(!this.node||!this._call(t[e]))||!!this.node&&this._call(t[this.node.type]&&t[this.node.type][e])},r._call=function(e){if(!e)return!1;for(var t=e,r=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}var a=s;if(a){var o=this.node;if(!o)return!0;if(a.call(this.state,this,this.state))throw new Error("Unexpected return value from visitor method "+a);if(this.node!==o)return!0;if(this.shouldStop||this.shouldSkip||this.removed)return!0}}return!1},r.isBlacklisted=function(){var e=this.opts.blacklist;return e&&e.indexOf(this.node.type)>-1},r.visit=function(){return!!this.node&&!this.isBlacklisted()&&(!this.opts.shouldSkip||!this.opts.shouldSkip(this))&&(this.call("enter")||this.shouldSkip?(this.debug(function(){return"Skip..."}),this.shouldStop):(this.debug(function(){return"Recursing into..."}),s.default.node(this.node,this.opts,this.scope,this.state,this,this.skipKeys),this.call("exit"),this.shouldStop))},r.skip=function(){this.shouldSkip=!0},r.skipKey=function(e){this.skipKeys[e]=!0},r.stop=function(){this.shouldStop=!0,this.shouldSkip=!0},r.setScope=function(){if(!this.opts||!this.opts.noScope){var e=this.context&&this.context.scope;if(!e)for(var t=this.parentPath;t&&!e;){if(t.opts&&t.opts.noScope)return;e=t.scope,t=t.parentPath}this.scope=this.getScope(e),this.scope&&this.scope.init()}},r.setContext=function(e){return this.shouldSkip=!1,this.shouldStop=!1,this.removed=!1,this.skipKeys={},e&&(this.context=e,this.state=e.state,this.opts=e.opts),this.setScope(),this},r.resync=function(){this.removed||(this._resyncParent(),this._resyncList(),this._resyncKey())},r._resyncParent=function(){this.parentPath&&(this.parent=this.parentPath.node)},r._resyncKey=function(){if(this.container&&this.node!==this.container[this.key]){if(Array.isArray(this.container)){for(var e=0;e0&&void 0!==arguments[0]?arguments[0]:this;if(!e.removed)for(var t=this.contexts,r=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}s.maybeQueue(e)}},r._getQueueContexts=function(){for(var e=this,t=this.contexts;!t.length;)t=(e=e.parentPath).contexts;return t};var s=n(e("../index"))},{"../index":143,"babel-runtime/core-js/get-iterator":120}],147:[function(e,t,r){"use strict";r.__esModule=!0,r.toComputedKey=function(){var e=this.node,t=void 0;if(this.isMemberExpression())t=e.property;else{if(!this.isProperty()&&!this.isMethod())throw new ReferenceError("todo");t=e.key}return e.computed||n.isIdentifier(t)&&(t=n.stringLiteral(t.name)),t},r.ensureBlock=function(){return n.ensureBlock(this.node)},r.arrowFunctionToShadowed=function(){if(this.isArrowFunctionExpression()){this.ensureBlock();var e=this.node;e.expression=!1,e.type="FunctionExpression",e.shadow=e.shadow||!0}};var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"))},{"babel-types":178}],148:[function(e,t,r){(function(t){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/typeof")),s=n(e("babel-runtime/core-js/get-iterator")),a=n(e("babel-runtime/core-js/map"));r.evaluateTruthy=function(){var e=this.evaluate();if(e.confident)return!!e.value},r.evaluate=function(){function e(e){n&&(l=e,n=!1)}function r(a){var l=a.node;if(c.has(l)){var p=c.get(l);return p.resolved?p.value:void e(a)}var h={resolved:!1};c.set(l,h);var f=function(a){if(n){var l=a.node;if(a.isSequenceExpression()){var c=a.get("expressions");return r(c[c.length-1])}if(a.isStringLiteral()||a.isNumericLiteral()||a.isBooleanLiteral())return l.value;if(a.isNullLiteral())return null;if(a.isTemplateLiteral()){for(var p="",h=0,f=a.get("expressions"),d=l.quasis,m=Array.isArray(d),y=0,d=m?d:(0,s.default)(d);;){var g;if(m){if(y>=d.length)break;g=d[y++]}else{if((y=d.next()).done)break;g=y.value}if(!n)break;p+=g.value.cooked;var b=f[h++];b&&(p+=String(r(b)))}if(!n)return;return p}if(a.isConditionalExpression()){var v=r(a.get("test"));if(!n)return;return r(v?a.get("consequent"):a.get("alternate"))}if(a.isExpressionWrapper())return r(a.get("expression"));if(a.isMemberExpression()&&!a.parentPath.isCallExpression({callee:l})){var x=a.get("property"),E=a.get("object");if(E.isLiteral()&&x.isIdentifier()){var A=E.node.value,D=void 0===A?"undefined":(0,i.default)(A);if("number"===D||"string"===D)return A[x.node.name]}}if(a.isReferencedIdentifier()){var C=a.scope.getBinding(l.name);if(C&&C.constantViolations.length>0)return e(C.path);if(C&&a.node.start=F.length)break;B=F[P++]}else{if((P=F.next()).done)break;B=P.value}var O=B;if(!(O=O.evaluate()).confident)return e(O);k.push(O.value)}return k}if(a.isObjectExpression()){for(var j={},N=a.get("properties"),I=Array.isArray(N),L=0,N=I?N:(0,s.default)(N);;){var M;if(I){if(L>=N.length)break;M=N[L++]}else{if((L=N.next()).done)break;M=L.value}var R=M;if(R.isObjectMethod()||R.isSpreadProperty())return e(R);var V=R.get("key"),U=V;if(R.node.computed){if(!(U=U.evaluate()).confident)return e(V);U=U.value}else U=U.isIdentifier()?U.node.name:U.node.value;var q=R.get("value"),G=q.evaluate();if(!G.confident)return e(q);G=G.value,j[U]=G}return j}if(a.isLogicalExpression()){var X=n,W=r(a.get("left")),J=n;n=X;var K=r(a.get("right")),z=n;switch(n=J&&z,l.operator){case"||":if(W&&J)return n=!0,W;if(!n)return;return W||K;case"&&":if((!W&&J||!K&&z)&&(n=!0),!n)return;return W&&K}}if(a.isBinaryExpression()){var Y=r(a.get("left"));if(!n)return;var H=r(a.get("right"));if(!n)return;switch(l.operator){case"-":return Y-H;case"+":return Y+H;case"/":return Y/H;case"*":return Y*H;case"%":return Y%H;case"**":return Math.pow(Y,H);case"<":return Y":return Y>H;case"<=":return Y<=H;case">=":return Y>=H;case"==":return Y==H;case"!=":return Y!=H;case"===":return Y===H;case"!==":return Y!==H;case"|":return Y|H;case"&":return Y&H;case"^":return Y^H;case"<<":return Y<>":return Y>>H;case">>>":return Y>>>H}}if(a.isCallExpression()){var $=a.get("callee"),Q=void 0,Z=void 0;if($.isIdentifier()&&!a.scope.getBinding($.node.name,!0)&&o.indexOf($.node.name)>=0&&(Z=t[l.callee.name]),$.isMemberExpression()){var ee=$.get("object"),te=$.get("property");if(ee.isIdentifier()&&te.isIdentifier()&&o.indexOf(ee.node.name)>=0&&u.indexOf(te.node.name)<0&&(Q=t[ee.node.name],Z=Q[te.node.name]),ee.isLiteral()&&te.isIdentifier()){var re=(0,i.default)(ee.node.value);"string"!==re&&"number"!==re||(Q=ee.node.value,Z=Q[te.node.name])}}if(Z){var ne=a.get("arguments").map(r);if(!n)return;return Z.apply(Q,ne)}}e(a)}}(a);return n&&(h.resolved=!0,h.value=f),f}var n=!0,l=void 0,c=new a.default,p=r(this);return n||(p=void 0),{confident:n,deopt:l,value:p}};var o=["String","Number","Math"],u=["random"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/map":122,"babel-runtime/helpers/typeof":138}],149:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/object/create")),s=n(e("babel-runtime/core-js/get-iterator"));r.getStatementParent=function(){var e=this;do{if(!e.parentPath||Array.isArray(e.container)&&e.isStatement())break;e=e.parentPath}while(e);if(e&&(e.isProgram()||e.isFile()))throw new Error("File/Program node, we can't possibly find a statement parent to this");return e},r.getOpposite=function(){return"left"===this.key?this.getSibling("right"):"right"===this.key?this.getSibling("left"):void 0},r.getCompletionRecords=function(){var e=[],t=function(t){t&&(e=e.concat(t.getCompletionRecords()))};if(this.isIfStatement())t(this.get("consequent")),t(this.get("alternate"));else if(this.isDoExpression()||this.isFor()||this.isWhile())t(this.get("body"));else if(this.isProgram()||this.isBlockStatement())t(this.get("body").pop());else{if(this.isFunction())return this.get("body").getCompletionRecords();this.isTryStatement()?(t(this.get("block")),t(this.get("handler")),t(this.get("finalizer"))):e.push(this)}return e},r.getSibling=function(e){return a.default.get({parentPath:this.parentPath,parent:this.parent,container:this.container,listKey:this.listKey,key:e})},r.getPrevSibling=function(){return this.getSibling(this.key-1)},r.getNextSibling=function(){return this.getSibling(this.key+1)},r.getAllNextSiblings=function(){for(var e=this.key,t=this.getSibling(++e),r=[];t.node;)r.push(t),t=this.getSibling(++e);return r},r.getAllPrevSiblings=function(){for(var e=this.key,t=this.getSibling(--e),r=[];t.node;)r.push(t),t=this.getSibling(--e);return r},r.get=function(e,t){!0===t&&(t=this.context);var r=e.split(".");return 1===r.length?this._getKey(e,t):this._getPattern(r,t)},r._getKey=function(e,t){var r=this,n=this.node,i=n[e];return Array.isArray(i)?i.map(function(s,o){return a.default.get({listKey:e,parentPath:r,parent:n,container:i,key:o}).setContext(t)}):a.default.get({parentPath:this,parent:n,container:n,key:e}).setContext(t)},r._getPattern=function(e,t){for(var r=this,n=e,i=Array.isArray(n),a=0,n=i?n:(0,s.default)(n);;){var o;if(i){if(a>=n.length)break;o=n[a++]}else{if((a=n.next()).done)break;o=a.value}var u=o;r="."===u?r.parentPath:Array.isArray(r)?r[u]:r.get(u,t)}return r},r.getBindingIdentifiers=function(e){return o.getBindingIdentifiers(this.node,e)},r.getOuterBindingIdentifiers=function(e){return o.getOuterBindingIdentifiers(this.node,e)},r.getBindingIdentifierPaths=function(){for(var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=[].concat(this),n=(0,i.default)(null);r.length;){var s=r.shift();if(s&&s.node){var a=o.getBindingIdentifiers.keys[s.node.type];if(s.isIdentifier())e?(n[s.node.name]=n[s.node.name]||[]).push(s):n[s.node.name]=s;else if(s.isExportDeclaration()){var u=s.get("declaration");u.isDeclaration()&&r.push(u)}else{if(t){if(s.isFunctionDeclaration()){r.push(s.get("id"));continue}if(s.isFunctionExpression())continue}if(a)for(var l=0;l1&&void 0!==arguments[1]?arguments[1]:SyntaxError;return this.hub.file.buildCodeFrameError(this.node,e,t)},e.prototype.traverse=function(e,t){(0,c.default)(this.node,e,this.scope,t,this)},e.prototype.mark=function(e,t){this.hub.file.metadata.marked.push({type:e,message:t,loc:this.node.loc})},e.prototype.set=function(e,t){f.validate(this.node,e,t),this.node[e]=t},e.prototype.getPathLocation=function(){var e=[],t=this;do{var r=t.key;t.inList&&(r=t.listKey+"["+r+"]"),e.unshift(r)}while(t=t.parentPath);return e.join(".")},e.prototype.debug=function(e){m.enabled&&m(this.getPathLocation()+" "+this.type+": "+e())},e}();r.default=y,(0,p.default)(y.prototype,e("./ancestry")),(0,p.default)(y.prototype,e("./inference")),(0,p.default)(y.prototype,e("./replacement")),(0,p.default)(y.prototype,e("./evaluation")),(0,p.default)(y.prototype,e("./conversion")),(0,p.default)(y.prototype,e("./introspection")),(0,p.default)(y.prototype,e("./context")),(0,p.default)(y.prototype,e("./removal")),(0,p.default)(y.prototype,e("./modification")),(0,p.default)(y.prototype,e("./family")),(0,p.default)(y.prototype,e("./comments"));for(var g=function(){if(v){if(x>=b.length)return"break";E=b[x++]}else{if((x=b.next()).done)return"break";E=x.value}var e=E,t="is"+e;y.prototype[t]=function(e){return f[t](this.node,e)},y.prototype["assert"+e]=function(r){if(!this[t](r))throw new TypeError("Expected node path of type "+e)}},b=f.TYPES,v=Array.isArray(b),x=0,b=v?b:(0,s.default)(b);;){var E;if("break"===g())break}var A=function(e){if("_"===e[0])return"continue";f.TYPES.indexOf(e)<0&&f.TYPES.push(e);var t=o[e];y.prototype["is"+e]=function(e){return t.checkPath(this,e)}};for(var D in o){A(D)}t.exports=r.default},{"../cache":140,"../index":143,"../scope":162,"./ancestry":144,"./comments":145,"./context":146,"./conversion":147,"./evaluation":148,"./family":149,"./inference":151,"./introspection":154,"./lib/virtual-types":157,"./modification":158,"./removal":159,"./replacement":160,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-types":178,debug:165,invariant:318,"lodash/assign":488}],151:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e,t,r){if("string"===e)return o.isStringTypeAnnotation(t);if("number"===e)return o.isNumberTypeAnnotation(t);if("boolean"===e)return o.isBooleanTypeAnnotation(t);if("any"===e)return o.isAnyTypeAnnotation(t);if("mixed"===e)return o.isMixedTypeAnnotation(t);if("empty"===e)return o.isEmptyTypeAnnotation(t);if("void"===e)return o.isVoidTypeAnnotation(t);if(r)return!1;throw new Error("Unknown base type "+e)}r.__esModule=!0;var s=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.getTypeAnnotation=function(){if(this.typeAnnotation)return this.typeAnnotation;var e=this._getTypeAnnotation()||o.anyTypeAnnotation();return o.isTypeAnnotation(e)&&(e=e.typeAnnotation),this.typeAnnotation=e},r._getTypeAnnotation=function(){var e=this.node;if(e){if(e.typeAnnotation)return e.typeAnnotation;var t=a[e.type];return t?t.call(this,e):(t=a[this.parentPath.type])&&t.validParent?this.parentPath.getTypeAnnotation():void 0}if("init"===this.key&&this.parentPath.isVariableDeclarator()){var r=this.parentPath.parentPath,n=r.parentPath;return"left"===r.key&&n.isForInStatement()?o.stringTypeAnnotation():"left"===r.key&&n.isForOfStatement()?o.anyTypeAnnotation():o.voidTypeAnnotation()}},r.isBaseType=function(e,t){return i(e,this.getTypeAnnotation(),t)},r.couldBeBaseType=function(e){var t=this.getTypeAnnotation();if(o.isAnyTypeAnnotation(t))return!0;if(o.isUnionTypeAnnotation(t)){for(var r=t.types,n=Array.isArray(r),a=0,r=n?r:(0,s.default)(r);;){var u;if(n){if(a>=r.length)break;u=r[a++]}else{if((a=r.next()).done)break;u=a.value}var l=u;if(o.isAnyTypeAnnotation(l)||i(e,l,!0))return!0}return!1}return i(e,t,!0)},r.baseTypeStrictlyMatches=function(e){var t=this.getTypeAnnotation();if(e=e.getTypeAnnotation(),!o.isAnyTypeAnnotation(t)&&o.isFlowBaseAnnotation(t))return e.type===t.type},r.isGenericType=function(e){var t=this.getTypeAnnotation();return o.isGenericTypeAnnotation(t)&&o.isIdentifier(t.id,{name:e})};var a=n(e("./inferers")),o=n(e("babel-types"))},{"./inferers":153,"babel-runtime/core-js/get-iterator":120,"babel-types":178}],152:[function(e,t,r){"use strict";function n(e,t,r){var n=e.constantViolations.slice();return n.unshift(e.path),n.filter(function(e){var n=(e=e.resolve())._guessExecutionStatusRelativeTo(t);return r&&"function"===n&&r.push(e),"before"===n})}function i(e,t){var r=t.node.operator,n=t.get("right").resolve(),i=t.get("left").resolve(),s=void 0;if(i.isIdentifier({name:e})?s=n:n.isIdentifier({name:e})&&(s=i),s)return"==="===r?s.getTypeAnnotation():o.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(r)>=0?o.numberTypeAnnotation():void 0;if("==="===r){var a=void 0,u=void 0;if(i.isUnaryExpression({operator:"typeof"})?(a=i,u=n):n.isUnaryExpression({operator:"typeof"})&&(a=n,u=i),(u||a)&&(u=u.resolve()).isLiteral()){if("string"==typeof u.node.value&&a.get("argument").isIdentifier({name:e}))return o.createTypeAnnotationBasedOnTypeof(u.node.value)}}}function s(e,t){var r=function(e){for(var t=void 0;t=e.parentPath;){if(t.isIfStatement()||t.isConditionalExpression())return"test"===e.key?void 0:t;e=t}}(e);if(r){var n=[r.get("test")],a=[];do{var u=n.shift().resolve();if(u.isLogicalExpression()&&(n.push(u.get("left")),n.push(u.get("right"))),u.isBinaryExpression()){var l=i(t,u);l&&a.push(l)}}while(n.length);return a.length?{typeAnnotation:o.createUnionTypeAnnotation(a),ifStatement:r}:s(r,t)}}r.__esModule=!0;var a=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.default=function(e){if(this.isReferenced()){var t=this.scope.getBinding(e.name);return t?t.identifier.typeAnnotation?t.identifier.typeAnnotation:function(e,t){var r=e.scope.getBinding(t),i=[];e.typeAnnotation=o.unionTypeAnnotation(i);var u=[],l=n(r,e,u),c=s(e,t);if(c){var p=n(r,c.ifStatement);l=l.filter(function(e){return p.indexOf(e)<0}),i.push(c.typeAnnotation)}if(l.length)for(var h=l=l.concat(u),f=Array.isArray(h),d=0,h=f?h:(0,a.default)(h);;){var m;if(f){if(d>=h.length)break;m=h[d++]}else{if((d=h.next()).done)break;m=d.value}var y=m;i.push(y.getTypeAnnotation())}if(i.length)return o.createUnionTypeAnnotation(i)}(this,e.name):"undefined"===e.name?o.voidTypeAnnotation():"NaN"===e.name||"Infinity"===e.name?o.numberTypeAnnotation():void e.name}};var o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));t.exports=r.default},{"babel-runtime/core-js/get-iterator":120,"babel-types":178}],153:[function(e,t,r){"use strict";function n(e){return e.typeAnnotation}function i(){return l.genericTypeAnnotation(l.identifier("Array"))}function s(){return i()}function a(){return l.genericTypeAnnotation(l.identifier("Function"))}function o(e){if((e=e.resolve()).isFunction()){if(e.is("async"))return e.is("generator")?l.genericTypeAnnotation(l.identifier("AsyncIterator")):l.genericTypeAnnotation(l.identifier("Promise"));if(e.node.returnType)return e.node.returnType}}r.__esModule=!0,r.ClassDeclaration=r.ClassExpression=r.FunctionDeclaration=r.ArrowFunctionExpression=r.FunctionExpression=r.Identifier=void 0;var u=e("./inferer-reference");Object.defineProperty(r,"Identifier",{enumerable:!0,get:function(){return function(e){return e&&e.__esModule?e:{default:e}}(u).default}}),r.VariableDeclarator=function(){return this.get("id").isIdentifier()?this.get("init").getTypeAnnotation():void 0},r.TypeCastExpression=n,r.NewExpression=function(e){if(this.get("callee").isIdentifier())return l.genericTypeAnnotation(e.callee)},r.TemplateLiteral=function(){return l.stringTypeAnnotation()},r.UnaryExpression=function(e){var t=e.operator;return"void"===t?l.voidTypeAnnotation():l.NUMBER_UNARY_OPERATORS.indexOf(t)>=0?l.numberTypeAnnotation():l.STRING_UNARY_OPERATORS.indexOf(t)>=0?l.stringTypeAnnotation():l.BOOLEAN_UNARY_OPERATORS.indexOf(t)>=0?l.booleanTypeAnnotation():void 0},r.BinaryExpression=function(e){var t=e.operator;if(l.NUMBER_BINARY_OPERATORS.indexOf(t)>=0)return l.numberTypeAnnotation();if(l.BOOLEAN_BINARY_OPERATORS.indexOf(t)>=0)return l.booleanTypeAnnotation();if("+"===t){var r=this.get("right"),n=this.get("left");return n.isBaseType("number")&&r.isBaseType("number")?l.numberTypeAnnotation():n.isBaseType("string")||r.isBaseType("string")?l.stringTypeAnnotation():l.unionTypeAnnotation([l.stringTypeAnnotation(),l.numberTypeAnnotation()])}},r.LogicalExpression=function(){return l.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(),this.get("right").getTypeAnnotation()])},r.ConditionalExpression=function(){return l.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(),this.get("alternate").getTypeAnnotation()])},r.SequenceExpression=function(){return this.get("expressions").pop().getTypeAnnotation()},r.AssignmentExpression=function(){return this.get("right").getTypeAnnotation()},r.UpdateExpression=function(e){var t=e.operator;if("++"===t||"--"===t)return l.numberTypeAnnotation()},r.StringLiteral=function(){return l.stringTypeAnnotation()},r.NumericLiteral=function(){return l.numberTypeAnnotation()},r.BooleanLiteral=function(){return l.booleanTypeAnnotation()},r.NullLiteral=function(){return l.nullLiteralTypeAnnotation()},r.RegExpLiteral=function(){return l.genericTypeAnnotation(l.identifier("RegExp"))},r.ObjectExpression=function(){return l.genericTypeAnnotation(l.identifier("Object"))},r.ArrayExpression=i,r.RestElement=s,r.CallExpression=function(){return o(this.get("callee"))},r.TaggedTemplateExpression=function(){return o(this.get("tag"))};var l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));n.validParent=!0,s.validParent=!0,r.FunctionExpression=a,r.ArrowFunctionExpression=a,r.FunctionDeclaration=a,r.ClassExpression=a,r.ClassDeclaration=a},{"./inferer-reference":152,"babel-types":178}],154:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=this.node&&this.node[e];return t&&Array.isArray(t)?!!t.length:!!t}r.__esModule=!0,r.is=void 0;var s=n(e("babel-runtime/core-js/get-iterator"));r.matchesPattern=function(e,t){function r(e){var t=n[s];return"*"===t||e===t}if(!this.isMemberExpression())return!1;for(var n=e.split("."),i=[this.node],s=0;i.length;){var a=i.shift();if(t&&s===n.length)return!0;if(o.isIdentifier(a)){if(!r(a.name))return!1}else if(o.isLiteral(a)){if(!r(a.value))return!1}else{if(o.isMemberExpression(a)){if(a.computed&&!o.isLiteral(a.property))return!1;i.unshift(a.property),i.unshift(a.object);continue}if(!o.isThisExpression(a))return!1;if(!r("this"))return!1}if(++s>n.length)return!1}return s===n.length},r.has=i,r.isStatic=function(){return this.scope.isStatic(this.node)},r.isnt=function(e){return!this.has(e)},r.equals=function(e,t){return this.node[e]===t},r.isNodeType=function(e){return o.isType(this.type,e)},r.canHaveVariableDeclarationOrExpression=function(){return("init"===this.key||"left"===this.key)&&this.parentPath.isFor()},r.canSwapBetweenExpressionAndStatement=function(e){return!("body"!==this.key||!this.parentPath.isArrowFunctionExpression())&&(this.isExpression()?o.isBlockStatement(e):!!this.isBlockStatement()&&o.isExpression(e))},r.isCompletionRecord=function(e){var t=this,r=!0;do{var n=t.container;if(t.isFunction()&&!r)return!!e;if(r=!1,Array.isArray(n)&&t.key!==n.length-1)return!1}while((t=t.parentPath)&&!t.isProgram());return!0},r.isStatementOrBlock=function(){return!this.parentPath.isLabeledStatement()&&!o.isBlockStatement(this.container)&&(0,a.default)(o.STATEMENT_OR_BLOCK_KEYS,this.key)},r.referencesImport=function(e,t){if(!this.isReferencedIdentifier())return!1;var r=this.scope.getBinding(this.node.name);if(!r||"module"!==r.kind)return!1;var n=r.path,i=n.parentPath;return!(!i.isImportDeclaration()||i.node.source.value!==e||t&&(!n.isImportDefaultSpecifier()||"default"!==t)&&(!n.isImportNamespaceSpecifier()||"*"!==t)&&(!n.isImportSpecifier()||n.node.imported.name!==t))},r.getSource=function(){var e=this.node;return e.end?this.hub.file.code.slice(e.start,e.end):""},r.willIMaybeExecuteBefore=function(e){return"after"!==this._guessExecutionStatusRelativeTo(e)},r._guessExecutionStatusRelativeTo=function(e){var t=e.scope.getFunctionParent(),r=this.scope.getFunctionParent();if(t.node!==r.node){var n=this._guessExecutionStatusRelativeToDifferentFunctions(t);if(n)return n;e=t.path}var i=e.getAncestry();if(i.indexOf(this)>=0)return"after";var s=this.getAncestry(),a=void 0,u=void 0,l=void 0;for(l=0;l=0){a=c;break}}if(!a)return"before";var p=i[u-1],h=s[l-1];return p&&h?p.listKey&&p.container===h.container?p.key>h.key?"before":"after":o.VISITOR_KEYS[p.type].indexOf(p.key)>o.VISITOR_KEYS[h.type].indexOf(h.key)?"before":"after":"before"},r._guessExecutionStatusRelativeToDifferentFunctions=function(e){var t=e.path;if(t.isFunctionDeclaration()){var r=t.scope.getBinding(t.node.id.name);if(!r.references)return"before";for(var n=r.referencePaths,i=n,a=Array.isArray(i),o=0,i=a?i:(0,s.default)(i);;){var u;if(a){if(o>=i.length)break;u=i[o++]}else{if((o=i.next()).done)break;u=o.value}var l=u;if("callee"!==l.key||!l.parentPath.isCallExpression())return}for(var c=void 0,p=n,h=Array.isArray(p),f=0,p=h?p:(0,s.default)(p);;){var d;if(h){if(f>=p.length)break;d=p[f++]}else{if((f=p.next()).done)break;d=f.value}var m=d;if(!m.find(function(e){return e.node===t.node})){var y=this._guessExecutionStatusRelativeTo(m);if(c){if(c!==y)return}else c=y}}return c}},r.resolve=function(e,t){return this._resolve(e,t)||this},r._resolve=function(e,t){if(!(t&&t.indexOf(this)>=0))if((t=t||[]).push(this),this.isVariableDeclarator()){if(this.get("id").isIdentifier())return this.get("init").resolve(e,t)}else if(this.isReferencedIdentifier()){var r=this.scope.getBinding(this.node.name);if(!r)return;if(!r.constant)return;if("module"===r.kind)return;if(r.path!==this){var n=r.path.resolve(e,t);if(this.find(function(e){return e.node===n.node}))return;return n}}else{if(this.isTypeCastExpression())return this.get("expression").resolve(e,t);if(e&&this.isMemberExpression()){var i=this.toComputedKey();if(!o.isLiteral(i))return;var a=i.value,u=this.get("object").resolve(e,t);if(u.isObjectExpression())for(var l=u.get("properties"),c=Array.isArray(l),p=0,l=c?l:(0,s.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if((p=l.next()).done)break;h=p.value}var f=h;if(f.isProperty()){var d=f.get("key"),m=f.isnt("computed")&&d.isIdentifier({name:a});if(m=m||d.isLiteral({value:a}))return f.get("value").resolve(e,t)}}else if(u.isArrayExpression()&&!isNaN(+a)){var y=u.get("elements")[a];if(y)return y.resolve(e,t)}}}};var a=n(e("lodash/includes")),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"));r.is=i},{"babel-runtime/core-js/get-iterator":120,"babel-types":178,"lodash/includes":507}],155:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator")),s=n(e("babel-runtime/helpers/classCallCheck")),a=e("babel-types"),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(a),u={ReferencedIdentifier:function(e,t){if(!e.isJSXIdentifier()||!a.react.isCompatTag(e.node.name)||e.parentPath.isJSXMemberExpression()){if("this"===e.node.name){var r=e.scope;do{if(r.path.isFunction()&&!r.path.isArrowFunctionExpression())break}while(r=r.parent);r&&t.breakOnScopePaths.push(r.path)}var n=e.scope.getBinding(e.node.name);n&&n===t.scope.getBinding(e.node.name)&&(t.bindings[e.node.name]=n)}}},l=function(){function e(t,r){(0,s.default)(this,e),this.breakOnScopePaths=[],this.bindings={},this.scopes=[],this.scope=r,this.path=t,this.attachAfter=!1}return e.prototype.isCompatibleScope=function(e){for(var t in this.bindings){var r=this.bindings[t];if(!e.bindingIdentifierEquals(t,r.identifier))return!1}return!0},e.prototype.getCompatibleScopes=function(){var e=this.path.scope;do{if(!this.isCompatibleScope(e))break;if(this.scopes.push(e),this.breakOnScopePaths.indexOf(e.path)>=0)break}while(e=e.parent)},e.prototype.getAttachmentPath=function(){var e=this._getAttachmentPath();if(e){var t=e.scope;if(t.path===e&&(t=e.scope.parent),t.path.isProgram()||t.path.isFunction())for(var r in this.bindings)if(t.hasOwnBinding(r)){var n=this.bindings[r];if("param"!==n.kind&&this.getAttachmentParentForPath(n.path).key>e.key){this.attachAfter=!0,e=n.path;for(var s=n.constantViolations,a=Array.isArray(s),o=0,s=a?s:(0,i.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var l=u;this.getAttachmentParentForPath(l).key>e.key&&(e=l)}}}return e.parentPath.isExportDeclaration()&&(e=e.parentPath),e}},e.prototype._getAttachmentPath=function(){var e=this.scopes.pop();if(e){if(e.path.isFunction()){if(this.hasOwnParamBindings(e)){if(this.scope===e)return;return e.path.get("body").get("body")[0]}return this.getNextScopeAttachmentParent()}return e.path.isProgram()?this.getNextScopeAttachmentParent():void 0}},e.prototype.getNextScopeAttachmentParent=function(){var e=this.scopes.pop();if(e)return this.getAttachmentParentForPath(e.path)},e.prototype.getAttachmentParentForPath=function(e){do{if(!e.parentPath||Array.isArray(e.container)&&e.isStatement()||e.isVariableDeclarator()&&null!==e.parentPath.node&&e.parentPath.node.declarations.length>1)return e}while(e=e.parentPath)},e.prototype.hasOwnParamBindings=function(e){for(var t in this.bindings)if(e.hasOwnBinding(t)){var r=this.bindings[t];if("param"===r.kind&&r.constant)return!0}return!1},e.prototype.run=function(){var e=this.path.node;if(!e._hoisted){e._hoisted=!0,this.path.traverse(u,this),this.getCompatibleScopes();var t=this.getAttachmentPath();if(t&&t.getFunctionParent()!==this.path.getFunctionParent()){var r=t.scope.generateUidIdentifier("ref"),n=o.variableDeclarator(r,this.path.node);t[this.attachAfter?"insertAfter":"insertBefore"]([t.isVariableDeclarator()?n:o.variableDeclaration("var",[n])]);var i=this.path.parentPath;i.isJSXElement()&&this.path.container===i.node.children&&(r=o.JSXExpressionContainer(r)),this.path.replaceWith(r)}}},e}();r.default=l,t.exports=r.default},{"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],156:[function(e,t,r){"use strict";r.__esModule=!0;r.hooks=[function(e,t){if("test"===e.key&&(t.isWhile()||t.isSwitchCase())||"declaration"===e.key&&t.isExportDeclaration()||"body"===e.key&&t.isLabeledStatement()||"declarations"===e.listKey&&t.isVariableDeclaration()&&1===t.node.declarations.length||"expression"===e.key&&t.isExpressionStatement())return t.remove(),!0},function(e,t){if(t.isSequenceExpression()&&1===t.node.expressions.length)return t.replaceWith(t.node.expressions[0]),!0},function(e,t){if(t.isBinary())return"left"===e.key?t.replaceWith(t.node.right):t.replaceWith(t.node.left),!0},function(e,t){if(t.isIfStatement()&&("consequent"===e.key||"alternate"===e.key)||"body"===e.key&&(t.isLoop()||t.isArrowFunctionExpression()))return e.replaceWith({type:"BlockStatement",body:[]}),!0}]},{}],157:[function(e,t,r){"use strict";r.__esModule=!0,r.Flow=r.Pure=r.Generated=r.User=r.Var=r.BlockScoped=r.Referenced=r.Scope=r.Expression=r.Statement=r.BindingIdentifier=r.ReferencedMemberExpression=r.ReferencedIdentifier=void 0;var n=e("babel-types"),i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(n);r.ReferencedIdentifier={types:["Identifier","JSXIdentifier"],checkPath:function(e,t){var r=e.node,s=e.parent;if(!i.isIdentifier(r,t)&&!i.isJSXMemberExpression(s,t)){if(!i.isJSXIdentifier(r,t))return!1;if(n.react.isCompatTag(r.name))return!1}return i.isReferenced(r,s)}},r.ReferencedMemberExpression={types:["MemberExpression"],checkPath:function(e){var t=e.node,r=e.parent;return i.isMemberExpression(t)&&i.isReferenced(t,r)}},r.BindingIdentifier={types:["Identifier"],checkPath:function(e){var t=e.node,r=e.parent;return i.isIdentifier(t)&&i.isBinding(t,r)}},r.Statement={types:["Statement"],checkPath:function(e){var t=e.node,r=e.parent;if(i.isStatement(t)){if(i.isVariableDeclaration(t)){if(i.isForXStatement(r,{left:t}))return!1;if(i.isForStatement(r,{init:t}))return!1}return!0}return!1}},r.Expression={types:["Expression"],checkPath:function(e){return e.isIdentifier()?e.isReferencedIdentifier():i.isExpression(e.node)}},r.Scope={types:["Scopable"],checkPath:function(e){return i.isScope(e.node,e.parent)}},r.Referenced={checkPath:function(e){return i.isReferenced(e.node,e.parent)}},r.BlockScoped={checkPath:function(e){return i.isBlockScoped(e.node)}},r.Var={types:["VariableDeclaration"],checkPath:function(e){return i.isVar(e.node)}},r.User={checkPath:function(e){return e.node&&!!e.node.loc}},r.Generated={checkPath:function(e){return!e.isUser()}},r.Pure={checkPath:function(e,t){return e.scope.isPure(e.node,t)}},r.Flow={types:["Flow","ImportDeclaration","ExportDeclaration","ImportSpecifier"],checkPath:function(e){var t=e.node;return!!i.isFlow(t)||(i.isImportDeclaration(t)?"type"===t.importKind||"typeof"===t.importKind:i.isExportDeclaration(t)?"type"===t.exportKind:!!i.isImportSpecifier(t)&&("type"===t.importKind||"typeof"===t.importKind))}}},{"babel-types":178}],158:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/typeof")),s=n(e("babel-runtime/core-js/get-iterator"));r.insertBefore=function(e){if(this._assertUnremoved(),e=this._verifyNodeList(e),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertBefore(e);if(this.isNodeType("Expression")||this.parentPath.isForStatement()&&"init"===this.key)this.node&&e.push(this.node),this.replaceExpressionWithStatements(e);else{if(this._maybePopFromStatements(e),Array.isArray(this.container))return this._containerInsertBefore(e);if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&e.push(this.node),this._replaceWith(l.blockStatement(e))}return[this]},r._containerInsert=function(e,t){this.updateSiblingKeys(e,t.length);for(var r=[],n=0;n=c.length)break;f=c[h++]}else{if((h=c.next()).done)break;f=h.value}var d=f;d.setScope(),d.debug(function(){return"Inserted."});for(var m=l,y=Array.isArray(m),g=0,m=y?m:(0,s.default)(m);;){var b;if(y){if(g>=m.length)break;b=m[g++]}else{if((g=m.next()).done)break;b=g.value}b.maybeQueue(d,!0)}}return r},r._containerInsertBefore=function(e){return this._containerInsert(this.key,e)},r._containerInsertAfter=function(e){return this._containerInsert(this.key+1,e)},r._maybePopFromStatements=function(e){var t=e[e.length-1];(l.isIdentifier(t)||l.isExpressionStatement(t)&&l.isIdentifier(t.expression))&&!this.isCompletionRecord()&&e.pop()},r.insertAfter=function(e){if(this._assertUnremoved(),e=this._verifyNodeList(e),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertAfter(e);if(this.isNodeType("Expression")||this.parentPath.isForStatement()&&"init"===this.key){if(this.node){var t=this.scope.generateDeclaredUidIdentifier();e.unshift(l.expressionStatement(l.assignmentExpression("=",t,this.node))),e.push(l.expressionStatement(t))}this.replaceExpressionWithStatements(e)}else{if(this._maybePopFromStatements(e),Array.isArray(this.container))return this._containerInsertAfter(e);if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&e.unshift(this.node),this._replaceWith(l.blockStatement(e))}return[this]},r.updateSiblingKeys=function(e,t){if(this.parent)for(var r=a.path.get(this.parent),n=0;n=e&&(i.key+=t)}},r._verifyNodeList=function(e){if(!e)return[];e.constructor!==Array&&(e=[e]);for(var t=0;t0&&void 0!==arguments[0]?arguments[0]:this.scope;return new o.default(this,e).run()};var a=e("../cache"),o=n(e("./lib/hoister")),u=n(e("./index")),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"))},{"../cache":140,"./index":150,"./lib/hoister":155,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/typeof":138,"babel-types":178}],159:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.remove=function(){this._assertUnremoved(),this.resync(),this._callRemovalHooks()?this._markRemoved():(this.shareCommentsWithSiblings(),this._remove(),this._markRemoved())},r._callRemovalHooks=function(){for(var e=i.hooks,t=Array.isArray(e),r=0,e=t?e:(0,n.default)(e);;){var s;if(t){if(r>=e.length)break;s=e[r++]}else{if((r=e.next()).done)break;s=r.value}if(s(this,this.parentPath))return!0}},r._remove=function(){Array.isArray(this.container)?(this.container.splice(this.key,1),this.updateSiblingKeys(this.key,-1)):this._replaceWith(null)},r._markRemoved=function(){this.shouldSkip=!0,this.removed=!0,this.node=null},r._assertUnremoved=function(){if(this.removed)throw this.buildCodeFrameError("NodePath has been removed so is read-only.")};var i=e("./lib/removal-hooks")},{"./lib/removal-hooks":156,"babel-runtime/core-js/get-iterator":120}],160:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.replaceWithMultiple=function(e){this.resync(),e=this._verifyNodeList(e),l.inheritLeadingComments(e[0],this.node),l.inheritTrailingComments(e[e.length-1],this.node),this.node=this.container[this.key]=null,this.insertAfter(e),this.node?this.requeue():this.remove()},r.replaceWithSourceString=function(e){this.resync();try{e="("+e+")",e=(0,u.parse)(e)}catch(r){var t=r.loc;throw t&&(r.message+=" - make sure this is an expression.",r.message+="\n"+(0,s.default)(e,t.line,t.column+1)),r}return e=e.program.body[0].expression,a.default.removeProperties(e),this.replaceWith(e)},r.replaceWith=function(e){if(this.resync(),this.removed)throw new Error("You can't replace this node, we've already removed it");if(e instanceof o.default&&(e=e.node),!e)throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");if(this.node!==e){if(this.isProgram()&&!l.isProgram(e))throw new Error("You can only replace a Program root node with another Program node");if(Array.isArray(e))throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");if("string"==typeof e)throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");if(this.isNodeType("Statement")&&l.isExpression(e)&&(this.canHaveVariableDeclarationOrExpression()||this.canSwapBetweenExpressionAndStatement(e)||this.parentPath.isExportDefaultDeclaration()||(e=l.expressionStatement(e))),this.isNodeType("Expression")&&l.isStatement(e)&&!this.canHaveVariableDeclarationOrExpression()&&!this.canSwapBetweenExpressionAndStatement(e))return this.replaceExpressionWithStatements([e]);var t=this.node;t&&(l.inheritsComments(e,t),l.removeComments(t)),this._replaceWith(e),this.type=e.type,this.setScope(),this.requeue()}},r._replaceWith=function(e){if(!this.container)throw new ReferenceError("Container is falsy");this.inList?l.validate(this.parent,this.key,[e]):l.validate(this.parent,this.key,e),this.debug(function(){return"Replace with "+(e&&e.type)}),this.node=this.container[this.key]=e},r.replaceExpressionWithStatements=function(e){this.resync();var t=l.toSequenceExpression(e,this.scope);if(l.isSequenceExpression(t)){var r=t.expressions;r.length>=2&&this.parentPath.isExpressionStatement()&&this._maybePopFromStatements(r),1===r.length?this.replaceWith(r[0]):this.replaceWith(t)}else{if(!t){var n=l.functionExpression(null,[],l.blockStatement(e));n.shadow=!0,this.replaceWith(l.callExpression(n,[])),this.traverse(c);for(var s=this.get("callee").getCompletionRecords(),a=Array.isArray(s),o=0,s=a?s:(0,i.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var p=u;if(p.isExpressionStatement()){var h=p.findParent(function(e){return e.isLoop()});if(h){var f=h.getData("expressionReplacementReturnUid");if(f)f=l.identifier(f.name);else{var d=this.get("callee");f=d.scope.generateDeclaredUidIdentifier("ret"),d.get("body").pushContainer("body",l.returnStatement(f)),h.setData("expressionReplacementReturnUid",f)}p.get("expression").replaceWith(l.assignmentExpression("=",f,p.node.expression))}else p.replaceWith(l.returnStatement(p.node.expression))}}return this.node}this.replaceWith(t)}},r.replaceInline=function(e){return this.resync(),Array.isArray(e)?Array.isArray(this.container)?(e=this._verifyNodeList(e),this._containerInsertAfter(e),this.remove()):this.replaceWithMultiple(e):this.replaceWith(e)};var s=n(e("babel-code-frame")),a=n(e("../index")),o=n(e("./index")),u=e("babylon"),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types")),c={Function:function(e){e.skip()},VariableDeclaration:function(e){if("var"===e.node.kind){var t=e.getBindingIdentifiers();for(var r in t)e.scope.push({id:t[r]});for(var n=[],s=e.node.declarations,a=Array.isArray(s),o=0,s=a?s:(0,i.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var c=u;c.init&&n.push(l.expressionStatement(l.assignmentExpression("=",c.id,c.init)))}e.replaceWithMultiple(n)}}}},{"../index":143,"./index":150,"babel-code-frame":21,"babel-runtime/core-js/get-iterator":120,"babel-types":178,babylon:186}],161:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/helpers/classCallCheck")),i=function(){function e(t){var r=t.existing,i=t.identifier,s=t.scope,a=t.path,o=t.kind;(0,n.default)(this,e),this.identifier=i,this.scope=s,this.path=a,this.kind=o,this.constantViolations=[],this.constant=!0,this.referencePaths=[],this.referenced=!1,this.references=0,this.clearValue(),r&&(this.constantViolations=[].concat(r.path,r.constantViolations,this.constantViolations))}return e.prototype.deoptValue=function(){this.clearValue(),this.hasDeoptedValue=!0},e.prototype.setValue=function(e){this.hasDeoptedValue||(this.hasValue=!0,this.value=e)},e.prototype.clearValue=function(){this.hasDeoptedValue=!1,this.hasValue=!1,this.value=null},e.prototype.reassign=function(e){this.constant=!1,-1===this.constantViolations.indexOf(e)&&this.constantViolations.push(e)},e.prototype.reference=function(e){-1===this.referencePaths.indexOf(e)&&(this.referenced=!0,this.references++,this.referencePaths.push(e))},e.prototype.dereference=function(){this.references--,this.referenced=!!this.references},e}();r.default=i,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134}],162:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t){if(v.isModuleDeclaration(e))if(e.source)s(e.source,t);else if(e.specifiers&&e.specifiers.length)for(var r=e.specifiers,n=Array.isArray(r),i=0,r=n?r:(0,c.default)(r);;){var a;if(n){if(i>=r.length)break;a=r[i++]}else{if((i=r.next()).done)break;a=i.value}s(a,t)}else e.declaration&&s(e.declaration,t);else if(v.isModuleSpecifier(e))s(e.local,t);else if(v.isMemberExpression(e))s(e.object,t),s(e.property,t);else if(v.isIdentifier(e))t.push(e.name);else if(v.isLiteral(e))t.push(e.value);else if(v.isCallExpression(e))s(e.callee,t);else if(v.isObjectExpression(e)||v.isObjectPattern(e))for(var o=e.properties,u=Array.isArray(o),l=0,o=u?o:(0,c.default)(o);;){var p;if(u){if(l>=o.length)break;p=o[l++]}else{if((l=o.next()).done)break;p=l.value}var h=p;s(h.key||h.argument,t)}}r.__esModule=!0;var a=i(e("babel-runtime/core-js/object/keys")),o=i(e("babel-runtime/core-js/object/create")),u=i(e("babel-runtime/core-js/map")),l=i(e("babel-runtime/helpers/classCallCheck")),c=i(e("babel-runtime/core-js/get-iterator")),p=i(e("lodash/includes")),h=i(e("lodash/repeat")),f=i(e("./lib/renamer")),d=i(e("../index")),m=i(e("lodash/defaults")),y=n(e("babel-messages")),g=i(e("./binding")),b=i(e("globals")),v=n(e("babel-types")),x=e("../cache"),E=0,A={For:function(e){for(var t=v.FOR_INIT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i,a=e.get(s);a.isVar()&&e.scope.getFunctionParent().registerBinding("var",a)}},Declaration:function(e){e.isBlockScoped()||e.isExportDeclaration()&&e.get("declaration").isDeclaration()||e.scope.getFunctionParent().registerDeclaration(e)},ReferencedIdentifier:function(e,t){t.references.push(e)},ForXStatement:function(e,t){var r=e.get("left");(r.isPattern()||r.isIdentifier())&&t.constantViolations.push(r)},ExportDeclaration:{exit:function(e){var t=e.node,r=e.scope,n=t.declaration;if(v.isClassDeclaration(n)||v.isFunctionDeclaration(n)){var i=n.id;if(!i)return;var s=r.getBinding(i.name);s&&s.reference(e)}else if(v.isVariableDeclaration(n))for(var a=n.declarations,o=Array.isArray(a),u=0,a=o?a:(0,c.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var p=l,h=v.getBindingIdentifiers(p);for(var f in h){var d=r.getBinding(f);d&&d.reference(e)}}}},LabeledStatement:function(e){e.scope.getProgramParent().addGlobal(e.node),e.scope.getBlockParent().registerDeclaration(e)},AssignmentExpression:function(e,t){t.assignments.push(e)},UpdateExpression:function(e,t){t.constantViolations.push(e.get("argument"))},UnaryExpression:function(e,t){"delete"===e.node.operator&&t.constantViolations.push(e.get("argument"))},BlockScoped:function(e){var t=e.scope;t.path===e&&(t=t.parent),t.getBlockParent().registerDeclaration(e)},ClassDeclaration:function(e){var t=e.node.id;if(t){var r=t.name;e.scope.bindings[r]=e.scope.getBinding(r)}},Block:function(e){for(var t=e.get("body"),r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;s.isFunctionDeclaration()&&e.scope.getBlockParent().registerDeclaration(s)}}},D=0,C=function(){function e(t,r){if((0,l.default)(this,e),r&&r.block===t.node)return r;var n=function(e,t,r){for(var n=x.scope.get(e.node)||[],i=n,s=Array.isArray(i),a=0,i=s?i:(0,c.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if((a=i.next()).done)break;o=a.value}var u=o;if(u.parent===t&&u.path===e)return u}n.push(r),x.scope.has(e.node)||x.scope.set(e.node,n)}(t,r,this);if(n)return n;this.uid=D++,this.parent=r,this.hub=t.hub,this.parentBlock=t.parent,this.block=t.node,this.path=t,this.labels=new u.default}return e.prototype.traverse=function(e,t,r){(0,d.default)(e,t,this,r,this.path)},e.prototype.generateDeclaredUidIdentifier=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"temp",t=this.generateUidIdentifier(e);return this.push({id:t}),t},e.prototype.generateUidIdentifier=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"temp";return v.identifier(this.generateUid(e))},e.prototype.generateUid=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"temp";e=v.toIdentifier(e).replace(/^_+/,"").replace(/[0-9]+$/g,"");var t=void 0,r=0;do{t=this._generateUid(e,r),r++}while(this.hasLabel(t)||this.hasBinding(t)||this.hasGlobal(t)||this.hasReference(t));var n=this.getProgramParent();return n.references[t]=!0,n.uids[t]=!0,t},e.prototype._generateUid=function(e,t){var r=e;return t>1&&(r+=t),"_"+r},e.prototype.generateUidIdentifierBasedOnNode=function(e,t){var r=e;v.isAssignmentExpression(e)?r=e.left:v.isVariableDeclarator(e)?r=e.id:(v.isObjectProperty(r)||v.isObjectMethod(r))&&(r=r.key);var n=[];s(r,n);var i=n.join("$");return i=i.replace(/^_/,"")||t||"ref",this.generateUidIdentifier(i.slice(0,20))},e.prototype.isStatic=function(e){if(v.isThisExpression(e)||v.isSuper(e))return!0;if(v.isIdentifier(e)){var t=this.getBinding(e.name);return t?t.constant:this.hasBinding(e.name)}return!1},e.prototype.maybeGenerateMemoised=function(e,t){if(this.isStatic(e))return null;var r=this.generateUidIdentifierBasedOnNode(e);return t||this.push({id:r}),r},e.prototype.checkBlockScopedCollisions=function(e,t,r,n){if("param"!==t&&("hoisted"!==t||"let"!==e.kind)){if("let"===t||"let"===e.kind||"const"===e.kind||"module"===e.kind||"param"===e.kind&&("let"===t||"const"===t))throw this.hub.file.buildCodeFrameError(n,y.get("scopeDuplicateDeclaration",r),TypeError)}},e.prototype.rename=function(e,t,r){var n=this.getBinding(e);if(n)return t=t||this.generateUidIdentifier(e).name,new f.default(n,e,t).rename(r)},e.prototype._renameFromMap=function(e,t,r,n){e[t]&&(e[r]=n,e[t]=null)},e.prototype.dump=function(){var e=(0,h.default)("-",60);console.log(e);var t=this;do{console.log("#",t.block.type);for(var r in t.bindings){var n=t.bindings[r];console.log(" -",r,{constant:n.constant,references:n.references,violations:n.constantViolations.length,kind:n.kind})}}while(t=t.parent);console.log(e)},e.prototype.toArray=function(e,t){var r=this.hub.file;if(v.isIdentifier(e)){var n=this.getBinding(e.name);if(n&&n.constant&&n.path.isGenericType("Array"))return e}if(v.isArrayExpression(e))return e;if(v.isIdentifier(e,{name:"arguments"}))return v.callExpression(v.memberExpression(v.memberExpression(v.memberExpression(v.identifier("Array"),v.identifier("prototype")),v.identifier("slice")),v.identifier("call")),[e]);var i="toArray",s=[e];return!0===t?i="toConsumableArray":t&&(s.push(v.numericLiteral(t)),i="slicedToArray"),v.callExpression(r.addHelper(i),s)},e.prototype.hasLabel=function(e){return!!this.getLabel(e)},e.prototype.getLabel=function(e){return this.labels.get(e)},e.prototype.registerLabel=function(e){this.labels.set(e.node.label.name,e)},e.prototype.registerDeclaration=function(e){if(e.isLabeledStatement())this.registerLabel(e);else if(e.isFunctionDeclaration())this.registerBinding("hoisted",e.get("id"),e);else if(e.isVariableDeclaration())for(var t=e.get("declarations"),r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;this.registerBinding(e.node.kind,s)}else if(e.isClassDeclaration())this.registerBinding("let",e);else if(e.isImportDeclaration())for(var a=e.get("specifiers"),o=Array.isArray(a),u=0,a=o?a:(0,c.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var p=l;this.registerBinding("module",p)}else if(e.isExportDeclaration()){var h=e.get("declaration");(h.isClassDeclaration()||h.isFunctionDeclaration()||h.isVariableDeclaration())&&this.registerDeclaration(h)}else this.registerBinding("unknown",e)},e.prototype.buildUndefinedNode=function(){return this.hasBinding("undefined")?v.unaryExpression("void",v.numericLiteral(0),!0):v.identifier("undefined")},e.prototype.registerConstantViolation=function(e){var t=e.getBindingIdentifiers();for(var r in t){var n=this.getBinding(r);n&&n.reassign(e)}},e.prototype.registerBinding=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(!e)throw new ReferenceError("no `kind`");if(t.isVariableDeclaration())for(var n=t.get("declarations"),i=Array.isArray(n),s=0,n=i?n:(0,c.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a;this.registerBinding(e,o)}else{var u=this.getProgramParent(),l=t.getBindingIdentifiers(!0);for(var p in l)for(var h=l[p],f=Array.isArray(h),d=0,h=f?h:(0,c.default)(h);;){var m;if(f){if(d>=h.length)break;m=h[d++]}else{if((d=h.next()).done)break;m=d.value}var y=m,b=this.getOwnBinding(p);if(b){if(b.identifier===y)continue;this.checkBlockScopedCollisions(b,e,p,y)}b&&b.path.isFlow()&&(b=null),u.references[p]=!0,this.bindings[p]=new g.default({identifier:y,existing:b,scope:this,path:r,kind:e})}}},e.prototype.addGlobal=function(e){this.globals[e.name]=e},e.prototype.hasUid=function(e){var t=this;do{if(t.uids[e])return!0}while(t=t.parent);return!1},e.prototype.hasGlobal=function(e){var t=this;do{if(t.globals[e])return!0}while(t=t.parent);return!1},e.prototype.hasReference=function(e){var t=this;do{if(t.references[e])return!0}while(t=t.parent);return!1},e.prototype.isPure=function(e,t){if(v.isIdentifier(e)){var r=this.getBinding(e.name);return!!r&&(!t||r.constant)}if(v.isClass(e))return!(e.superClass&&!this.isPure(e.superClass,t))&&this.isPure(e.body,t);if(v.isClassBody(e)){for(var n=e.body,i=Array.isArray(n),s=0,n=i?n:(0,c.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a;if(!this.isPure(o,t))return!1}return!0}if(v.isBinary(e))return this.isPure(e.left,t)&&this.isPure(e.right,t);if(v.isArrayExpression(e)){for(var u=e.elements,l=Array.isArray(u),p=0,u=l?u:(0,c.default)(u);;){var h;if(l){if(p>=u.length)break;h=u[p++]}else{if((p=u.next()).done)break;h=p.value}var f=h;if(!this.isPure(f,t))return!1}return!0}if(v.isObjectExpression(e)){for(var d=e.properties,m=Array.isArray(d),y=0,d=m?d:(0,c.default)(d);;){var g;if(m){if(y>=d.length)break;g=d[y++]}else{if((y=d.next()).done)break;g=y.value}var b=g;if(!this.isPure(b,t))return!1}return!0}return v.isClassMethod(e)?!(e.computed&&!this.isPure(e.key,t))&&("get"!==e.kind&&"set"!==e.kind):v.isClassProperty(e)||v.isObjectProperty(e)?!(e.computed&&!this.isPure(e.key,t))&&this.isPure(e.value,t):v.isUnaryExpression(e)?this.isPure(e.argument,t):v.isPureish(e)},e.prototype.setData=function(e,t){return this.data[e]=t},e.prototype.getData=function(e){var t=this;do{var r=t.data[e];if(null!=r)return r}while(t=t.parent)},e.prototype.removeData=function(e){var t=this;do{null!=t.data[e]&&(t.data[e]=null)}while(t=t.parent)},e.prototype.init=function(){this.references||this.crawl()},e.prototype.crawl=function(){E++,this._crawl(),E--},e.prototype._crawl=function(){var e=this.path;if(this.references=(0,o.default)(null),this.bindings=(0,o.default)(null),this.globals=(0,o.default)(null),this.uids=(0,o.default)(null),this.data=(0,o.default)(null),e.isLoop())for(var t=v.FOR_INIT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i,a=e.get(s);a.isBlockScoped()&&this.registerBinding(a.node.kind,a)}if(e.isFunctionExpression()&&e.has("id")&&(e.get("id").node[v.NOT_LOCAL_BINDING]||this.registerBinding("local",e.get("id"),e)),e.isClassExpression()&&e.has("id")&&(e.get("id").node[v.NOT_LOCAL_BINDING]||this.registerBinding("local",e)),e.isFunction())for(var u=e.get("params"),l=Array.isArray(u),p=0,u=l?u:(0,c.default)(u);;){var h;if(l){if(p>=u.length)break;h=u[p++]}else{if((p=u.next()).done)break;h=p.value}var f=h;this.registerBinding("param",f)}e.isCatchClause()&&this.registerBinding("let",e);if(!this.getProgramParent().crawling){var d={references:[],constantViolations:[],assignments:[]};this.crawling=!0,e.traverse(A,d),this.crawling=!1;for(var m=d.assignments,y=Array.isArray(m),g=0,m=y?m:(0,c.default)(m);;){var b;if(y){if(g>=m.length)break;b=m[g++]}else{if((g=m.next()).done)break;b=g.value}var x=b,E=x.getBindingIdentifiers(),D=void 0;for(var C in E)x.scope.getBinding(C)||(D=D||x.scope.getProgramParent()).addGlobal(E[C]);x.scope.registerConstantViolation(x)}for(var S=d.references,_=Array.isArray(S),w=0,S=_?S:(0,c.default)(S);;){var k;if(_){if(w>=S.length)break;k=S[w++]}else{if((w=S.next()).done)break;k=w.value}var F=k,T=F.scope.getBinding(F.node.name);T?T.reference(F):F.scope.getProgramParent().addGlobal(F.node)}for(var P=d.constantViolations,B=Array.isArray(P),O=0,P=B?P:(0,c.default)(P);;){var j;if(B){if(O>=P.length)break;j=P[O++]}else{if((O=P.next()).done)break;j=O.value}var N=j;N.scope.registerConstantViolation(N)}}},e.prototype.push=function(e){var t=this.path;t.isBlockStatement()||t.isProgram()||(t=this.getBlockParent().path),t.isSwitchStatement()&&(t=this.getFunctionParent().path),(t.isLoop()||t.isCatchClause()||t.isFunction())&&(v.ensureBlock(t.node),t=t.get("body"));var r=e.unique,n=e.kind||"var",i=null==e._blockHoist?2:e._blockHoist,s="declaration:"+n+":"+i,a=!r&&t.getData(s);if(!a){var o=v.variableDeclaration(n,[]);o._generated=!0,o._blockHoist=i;a=t.unshiftContainer("body",[o])[0],r||t.setData(s,a)}var u=v.variableDeclarator(e.id,e.init);a.node.declarations.push(u),this.registerBinding(n,a.get("declarations").pop())},e.prototype.getProgramParent=function(){var e=this;do{if(e.path.isProgram())return e}while(e=e.parent);throw new Error("We couldn't find a Function or Program...")},e.prototype.getFunctionParent=function(){var e=this;do{if(e.path.isFunctionParent())return e}while(e=e.parent);throw new Error("We couldn't find a Function or Program...")},e.prototype.getBlockParent=function(){var e=this;do{if(e.path.isBlockParent())return e}while(e=e.parent);throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...")},e.prototype.getAllBindings=function(){var e=(0,o.default)(null),t=this;do{(0,m.default)(e,t.bindings),t=t.parent}while(t);return e},e.prototype.getAllBindingsOfKind=function(){for(var e=(0,o.default)(null),t=arguments,r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i,a=this;do{for(var u in a.bindings){var l=a.bindings[u];l.kind===s&&(e[u]=l)}a=a.parent}while(a)}return e},e.prototype.bindingIdentifierEquals=function(e,t){return this.getBindingIdentifier(e)===t},e.prototype.warnOnFlowBinding=function(e){return 0===E&&e&&e.path.isFlow()&&console.warn("\n You or one of the Babel plugins you are using are using Flow declarations as bindings.\n Support for this will be removed in version 7. To find out the caller, grep for this\n message and change it to a `console.trace()`.\n "),e},e.prototype.getBinding=function(e){var t=this;do{var r=t.getOwnBinding(e);if(r)return this.warnOnFlowBinding(r)}while(t=t.parent)},e.prototype.getOwnBinding=function(e){return this.warnOnFlowBinding(this.bindings[e])},e.prototype.getBindingIdentifier=function(e){var t=this.getBinding(e);return t&&t.identifier},e.prototype.getOwnBindingIdentifier=function(e){var t=this.bindings[e];return t&&t.identifier},e.prototype.hasOwnBinding=function(e){return!!this.getOwnBinding(e)},e.prototype.hasBinding=function(t,r){return!!t&&(!!this.hasOwnBinding(t)||(!!this.parentHasBinding(t,r)||(!!this.hasUid(t)||(!(r||!(0,p.default)(e.globals,t))||!(r||!(0,p.default)(e.contextVariables,t))))))},e.prototype.parentHasBinding=function(e,t){return this.parent&&this.parent.hasBinding(e,t)},e.prototype.moveBindingTo=function(e,t){var r=this.getBinding(e);r&&(r.scope.removeOwnBinding(e),r.scope=t,t.bindings[e]=r)},e.prototype.removeOwnBinding=function(e){delete this.bindings[e]},e.prototype.removeBinding=function(e){var t=this.getBinding(e);t&&t.scope.removeOwnBinding(e);var r=this;do{r.uids[e]&&(r.uids[e]=!1)}while(r=r.parent)},e}();C.globals=(0,a.default)(b.default.builtin),C.contextVariables=["arguments","undefined","Infinity","NaN"],r.default=C,t.exports=r.default},{"../cache":140,"../index":143,"./binding":161,"./lib/renamer":163,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/map":122,"babel-runtime/core-js/object/create":125,"babel-runtime/core-js/object/keys":127,"babel-runtime/helpers/classCallCheck":134,"babel-types":178,globals:313,"lodash/defaults":495,"lodash/includes":507,"lodash/repeat":530}],163:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=(n(e("../binding")),function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("babel-types"))),a={ReferencedIdentifier:function(e,t){var r=e.node;r.name===t.oldName&&(r.name=t.newName)},Scope:function(e,t){e.scope.bindingIdentifierEquals(t.oldName,t.binding.identifier)||e.skip()},"AssignmentExpression|Declaration":function(e,t){var r=e.getOuterBindingIdentifiers();for(var n in r)n===t.oldName&&(r[n].name=t.newName)}},o=function(){function e(t,r,n){(0,i.default)(this,e),this.newName=n,this.oldName=r,this.binding=t}return e.prototype.maybeConvertFromExportDeclaration=function(e){var t=e.parentPath.isExportDeclaration()&&e.parentPath;if(t){var r=t.isExportDefaultDeclaration();r&&(e.isFunctionDeclaration()||e.isClassDeclaration())&&!e.node.id&&(e.node.id=e.scope.generateUidIdentifier("default"));var n=e.getOuterBindingIdentifiers(),i=[];for(var a in n){var o=a===this.oldName?this.newName:a,u=r?"default":a;i.push(s.exportSpecifier(s.identifier(o),s.identifier(u)))}if(i.length){var l=s.exportNamedDeclaration(null,i);e.isFunctionDeclaration()&&(l._blockHoist=3),t.insertAfter(l),t.replaceWith(e.node)}}},e.prototype.rename=function(e){var t=this.binding,r=this.oldName,n=this.newName,i=t.scope,s=t.path.find(function(e){return e.isDeclaration()||e.isFunctionExpression()});s&&this.maybeConvertFromExportDeclaration(s),i.traverse(e||i.block,a,this),e||(i.removeOwnBinding(r),i.bindings[n]=t,this.binding.identifier.name=n),t.type},e}();r.default=o,t.exports=r.default},{"../binding":161,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],164:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e){if(e._exploded)return e;e._exploded=!0;for(var t in e)if(!l(t)){var r=t.split("|");if(1!==r.length){var n=e[t];delete e[t];for(var i=r,s=Array.isArray(i),o=0,i=s?i:(0,f.default)(i);;){var p;if(s){if(o>=i.length)break;p=i[o++]}else{if((o=i.next()).done)break;p=o.value}e[p]=n}}}a(e),delete e.__esModule,function(e){for(var t in e)if(!l(t)){var r=e[t];"function"==typeof r&&(e[t]={enter:r})}}(e),u(e);for(var m=(0,h.default)(e),b=Array.isArray(m),v=0,m=b?m:(0,f.default)(m);;){var x;if(b){if(v>=m.length)break;x=m[v++]}else{if((v=m.next()).done)break;x=v.value}var E=x;if(!l(E)){var A=d[E];if(A){var D=e[E];for(var C in D)D[C]=function(e,t){var r=function(r){if(e.checkPath(r))return t.apply(this,arguments)};return r.toString=function(){return t.toString()},r}(A,D[C]);if(delete e[E],A.types)for(var S=A.types,_=Array.isArray(S),w=0,S=_?S:(0,f.default)(S);;){var k;if(_){if(w>=S.length)break;k=S[w++]}else{if((w=S.next()).done)break;k=w.value}var F=k;e[F]?c(e[F],D):e[F]=D}else c(e,D)}}}for(var T in e)if(!l(T)){var P=e[T],B=y.FLIPPED_ALIAS_KEYS[T],O=y.DEPRECATED_KEYS[T];if(O&&(console.trace("Visitor defined for "+T+" but it has been renamed to "+O),B=[O]),B){delete e[T];for(var j=B,N=Array.isArray(j),I=0,j=N?j:(0,f.default)(j);;){var L;if(N){if(I>=j.length)break;L=j[I++]}else{if((I=j.next()).done)break;L=I.value}var M=L,R=e[M];R?c(R,P):e[M]=(0,g.default)(P)}}}for(var V in e)l(V)||u(e[V]);return e}function a(e){if(!e._verified){if("function"==typeof e)throw new Error(m.get("traverseVerifyRootFunction"));for(var t in e)if("enter"!==t&&"exit"!==t||o(t,e[t]),!l(t)){if(y.TYPES.indexOf(t)<0)throw new Error(m.get("traverseVerifyNodeType",t));var r=e[t];if("object"===(void 0===r?"undefined":(0,p.default)(r)))for(var n in r){if("enter"!==n&&"exit"!==n)throw new Error(m.get("traverseVerifyVisitorProperty",t,n));o(t+"."+n,r[n])}}e._verified=!0}}function o(e,t){for(var r=[].concat(t),n=Array.isArray(r),i=0,r=n?r:(0,f.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}var a=s;if("function"!=typeof a)throw new TypeError("Non-function found defined in "+e+" with type "+(void 0===a?"undefined":(0,p.default)(a)))}}function u(e){e.enter&&!Array.isArray(e.enter)&&(e.enter=[e.enter]),e.exit&&!Array.isArray(e.exit)&&(e.exit=[e.exit])}function l(e){return"_"===e[0]||("enter"===e||"exit"===e||"shouldSkip"===e||("blacklist"===e||"noScope"===e||"skipKeys"===e))}function c(e,t){for(var r in t)e[r]=[].concat(e[r]||[],t[r])}r.__esModule=!0;var p=i(e("babel-runtime/helpers/typeof")),h=i(e("babel-runtime/core-js/object/keys")),f=i(e("babel-runtime/core-js/get-iterator"));r.explode=s,r.verify=a,r.merge=function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments[2],n={},i=0;i=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},r.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],r.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},r.enable(i())}).call(this,e("_process"))},{"./debug":166,_process:550}],166:[function(e,t,r){arguments[4][60][0].apply(r,arguments)},{dup:60,ms:543}],167:[function(e,t,r){"use strict";r.__esModule=!0,r.NOT_LOCAL_BINDING=r.BLOCK_SCOPED_SYMBOL=r.INHERIT_KEYS=r.UNARY_OPERATORS=r.STRING_UNARY_OPERATORS=r.NUMBER_UNARY_OPERATORS=r.BOOLEAN_UNARY_OPERATORS=r.BINARY_OPERATORS=r.NUMBER_BINARY_OPERATORS=r.BOOLEAN_BINARY_OPERATORS=r.COMPARISON_BINARY_OPERATORS=r.EQUALITY_BINARY_OPERATORS=r.BOOLEAN_NUMBER_BINARY_OPERATORS=r.UPDATE_OPERATORS=r.LOGICAL_OPERATORS=r.COMMENT_KEYS=r.FOR_INIT_KEYS=r.FLATTENABLE_KEYS=r.STATEMENT_OR_BLOCK_KEYS=void 0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/symbol/for")),i=(r.STATEMENT_OR_BLOCK_KEYS=["consequent","body","alternate"],r.FLATTENABLE_KEYS=["body","expressions"],r.FOR_INIT_KEYS=["left","init"],r.COMMENT_KEYS=["leadingComments","trailingComments","innerComments"],r.LOGICAL_OPERATORS=["||","&&"],r.UPDATE_OPERATORS=["++","--"],r.BOOLEAN_NUMBER_BINARY_OPERATORS=[">","<",">=","<="]),s=r.EQUALITY_BINARY_OPERATORS=["==","===","!=","!=="],a=r.COMPARISON_BINARY_OPERATORS=[].concat(s,["in","instanceof"]),o=r.BOOLEAN_BINARY_OPERATORS=[].concat(a,i),u=r.NUMBER_BINARY_OPERATORS=["-","/","%","*","**","&","|",">>",">>>","<<","^"],l=(r.BINARY_OPERATORS=["+"].concat(u,o),r.BOOLEAN_UNARY_OPERATORS=["delete","!"]),c=r.NUMBER_UNARY_OPERATORS=["+","-","++","--","~"],p=r.STRING_UNARY_OPERATORS=["typeof"];r.UNARY_OPERATORS=["void"].concat(l,c,p),r.INHERIT_KEYS={optional:["typeAnnotation","typeParameters","returnType"],force:["start","loc","end"]},r.BLOCK_SCOPED_SYMBOL=(0,n.default)("var used to be block scoped"),r.NOT_LOCAL_BINDING=(0,n.default)("should not be considered a local binding")},{"babel-runtime/core-js/symbol/for":130}],168:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t,r){for(var n=[],s=!0,a=e,o=Array.isArray(a),u=0,a=o?a:(0,l.default)(a);;){var c;if(o){if(u>=a.length)break;c=a[u++]}else{if((u=a.next()).done)break;c=u.value}var p=c;if(s=!1,h.isExpression(p))n.push(p);else if(h.isExpressionStatement(p))n.push(p.expression);else if(h.isVariableDeclaration(p)){if("var"!==p.kind)return;for(var f=p.declarations,d=Array.isArray(f),m=0,f=d?f:(0,l.default)(f);;){var y;if(d){if(m>=f.length)break;y=f[m++]}else{if((m=f.next()).done)break;y=m.value}var g=y,b=h.getBindingIdentifiers(g);for(var v in b)r.push({kind:p.kind,id:b[v]});g.init&&n.push(h.assignmentExpression("=",g.id,g.init))}s=!0}else if(h.isIfStatement(p)){var x=p.consequent?i([p.consequent],t,r):t.buildUndefinedNode(),E=p.alternate?i([p.alternate],t,r):t.buildUndefinedNode();if(!x||!E)return;n.push(h.conditionalExpression(p.test,x,E))}else if(h.isBlockStatement(p)){var A=i(p.body,t,r);if(!A)return;n.push(A)}else{if(!h.isEmptyStatement(p))return;s=!0}}return s&&n.push(t.buildUndefinedNode()),1===n.length?n[0]:h.sequenceExpression(n)}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.key,r=void 0;return"method"===e.kind?s.increment()+"":(r=h.isIdentifier(t)?t.name:h.isStringLiteral(t)?(0,u.default)(t.value):(0,u.default)(h.removePropertiesDeep(h.cloneDeep(t))),e.computed&&(r="["+r+"]"),e.static&&(r="static:"+r),r)}function a(e){return e+="",e=e.replace(/[^a-zA-Z0-9$_]/g,"-"),e=e.replace(/^[-0-9]+/,""),e=e.replace(/[-\s]+(.)?/g,function(e,t){return t?t.toUpperCase():""}),h.isValidIdentifier(e)||(e="_"+e),e||"_"}r.__esModule=!0;var o=n(e("babel-runtime/core-js/number/max-safe-integer")),u=n(e("babel-runtime/core-js/json/stringify")),l=n(e("babel-runtime/core-js/get-iterator"));r.toComputedKey=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.key||e.property;return e.computed||h.isIdentifier(t)&&(t=h.stringLiteral(t.name)),t},r.toSequenceExpression=function(e,t){if(e&&e.length){var r=[],n=i(e,t,r);if(n){for(var s=r,a=Array.isArray(s),o=0,s=a?s:(0,l.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var c=u;t.push(c)}return n}}},r.toKeyAlias=s,r.toIdentifier=a,r.toBindingIdentifierName=function(e){return"eval"!==(e=a(e))&&"arguments"!==e||(e="_"+e),e},r.toStatement=function(e,t){if(h.isStatement(e))return e;var r=!1,n=void 0;if(h.isClass(e))r=!0,n="ClassDeclaration";else if(h.isFunction(e))r=!0,n="FunctionDeclaration";else if(h.isAssignmentExpression(e))return h.expressionStatement(e);if(r&&!e.id&&(n=!1),!n){if(t)return!1;throw new Error("cannot turn "+e.type+" to a statement")}return e.type=n,e},r.toExpression=function(e){if(h.isExpressionStatement(e)&&(e=e.expression),h.isExpression(e))return e;if(h.isClass(e)?e.type="ClassExpression":h.isFunction(e)&&(e.type="FunctionExpression"),!h.isExpression(e))throw new Error("cannot turn "+e.type+" to an expression");return e},r.toBlock=function(e,t){return h.isBlockStatement(e)?e:(h.isEmptyStatement(e)&&(e=[]),Array.isArray(e)||(h.isStatement(e)||(e=h.isFunction(t)?h.returnStatement(e):h.expressionStatement(e)),e=[e]),h.blockStatement(e))},r.valueToNode=function(e){if(void 0===e)return h.identifier("undefined");if(!0===e||!1===e)return h.booleanLiteral(e);if(null===e)return h.nullLiteral();if("string"==typeof e)return h.stringLiteral(e);if("number"==typeof e)return h.numericLiteral(e);if((0,p.default)(e)){var t=e.source,r=e.toString().match(/\/([a-z]+|)$/)[1];return h.regExpLiteral(t,r)}if(Array.isArray(e))return h.arrayExpression(e.map(h.valueToNode));if((0,c.default)(e)){var n=[];for(var i in e){var s=void 0;s=h.isValidIdentifier(i)?h.identifier(i):h.stringLiteral(i),n.push(h.objectProperty(s,h.valueToNode(e[i])))}return h.objectExpression(n)}throw new Error("don't know how to turn this value into a node")};var c=n(e("lodash/isPlainObject")),p=n(e("lodash/isRegExp")),h=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./index"));s.uid=0,s.increment=function(){return s.uid>=o.default?s.uid=0:s.uid++}},{"./index":178,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/core-js/number/max-safe-integer":123,"lodash/isPlainObject":518,"lodash/isRegExp":519}],169:[function(e,t,r){"use strict";var n=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../index")),i=e("../constants"),s=e("./index"),a=function(e){return e&&e.__esModule?e:{default:e}}(s);(0,a.default)("ArrayExpression",{fields:{elements:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeOrValueType)("null","Expression","SpreadElement"))),default:[]}},visitor:["elements"],aliases:["Expression"]}),(0,a.default)("AssignmentExpression",{fields:{operator:{validate:(0,s.assertValueType)("string")},left:{validate:(0,s.assertNodeType)("LVal")},right:{validate:(0,s.assertNodeType)("Expression")}},builder:["operator","left","right"],visitor:["left","right"],aliases:["Expression"]}),(0,a.default)("BinaryExpression",{builder:["operator","left","right"],fields:{operator:{validate:s.assertOneOf.apply(void 0,i.BINARY_OPERATORS)},left:{validate:(0,s.assertNodeType)("Expression")},right:{validate:(0,s.assertNodeType)("Expression")}},visitor:["left","right"],aliases:["Binary","Expression"]}),(0,a.default)("Directive",{visitor:["value"],fields:{value:{validate:(0,s.assertNodeType)("DirectiveLiteral")}}}),(0,a.default)("DirectiveLiteral",{builder:["value"],fields:{value:{validate:(0,s.assertValueType)("string")}}}),(0,a.default)("BlockStatement",{builder:["body","directives"],visitor:["directives","body"],fields:{directives:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Directive"))),default:[]},body:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Statement")))}},aliases:["Scopable","BlockParent","Block","Statement"]}),(0,a.default)("BreakStatement",{visitor:["label"],fields:{label:{validate:(0,s.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),(0,a.default)("CallExpression",{visitor:["callee","arguments"],fields:{callee:{validate:(0,s.assertNodeType)("Expression")},arguments:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Expression","SpreadElement")))}},aliases:["Expression"]}),(0,a.default)("CatchClause",{visitor:["param","body"],fields:{param:{validate:(0,s.assertNodeType)("Identifier")},body:{validate:(0,s.assertNodeType)("BlockStatement")}},aliases:["Scopable"]}),(0,a.default)("ConditionalExpression",{visitor:["test","consequent","alternate"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},consequent:{validate:(0,s.assertNodeType)("Expression")},alternate:{validate:(0,s.assertNodeType)("Expression")}},aliases:["Expression","Conditional"]}),(0,a.default)("ContinueStatement",{visitor:["label"],fields:{label:{validate:(0,s.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),(0,a.default)("DebuggerStatement",{aliases:["Statement"]}),(0,a.default)("DoWhileStatement",{visitor:["test","body"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("Statement")}},aliases:["Statement","BlockParent","Loop","While","Scopable"]}),(0,a.default)("EmptyStatement",{aliases:["Statement"]}),(0,a.default)("ExpressionStatement",{visitor:["expression"],fields:{expression:{validate:(0,s.assertNodeType)("Expression")}},aliases:["Statement","ExpressionWrapper"]}),(0,a.default)("File",{builder:["program","comments","tokens"],visitor:["program"],fields:{program:{validate:(0,s.assertNodeType)("Program")}}}),(0,a.default)("ForInStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(0,s.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("ForStatement",{visitor:["init","test","update","body"],aliases:["Scopable","Statement","For","BlockParent","Loop"],fields:{init:{validate:(0,s.assertNodeType)("VariableDeclaration","Expression"),optional:!0},test:{validate:(0,s.assertNodeType)("Expression"),optional:!0},update:{validate:(0,s.assertNodeType)("Expression"),optional:!0},body:{validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("FunctionDeclaration",{builder:["id","params","body","generator","async"],visitor:["id","params","body","returnType","typeParameters"],fields:{id:{validate:(0,s.assertNodeType)("Identifier")},params:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("LVal")))},body:{validate:(0,s.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,s.assertValueType)("boolean")},async:{default:!1,validate:(0,s.assertValueType)("boolean")}},aliases:["Scopable","Function","BlockParent","FunctionParent","Statement","Pureish","Declaration"]}),(0,a.default)("FunctionExpression",{inherits:"FunctionDeclaration",aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{id:{validate:(0,s.assertNodeType)("Identifier"),optional:!0},params:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("LVal")))},body:{validate:(0,s.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,s.assertValueType)("boolean")},async:{default:!1,validate:(0,s.assertValueType)("boolean")}}}),(0,a.default)("Identifier",{builder:["name"],visitor:["typeAnnotation"],aliases:["Expression","LVal"],fields:{name:{validate:function(e,t,r){n.isValidIdentifier(r)}},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator")))}}}),(0,a.default)("IfStatement",{visitor:["test","consequent","alternate"],aliases:["Statement","Conditional"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},consequent:{validate:(0,s.assertNodeType)("Statement")},alternate:{optional:!0,validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("LabeledStatement",{visitor:["label","body"],aliases:["Statement"],fields:{label:{validate:(0,s.assertNodeType)("Identifier")},body:{validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("StringLiteral",{builder:["value"],fields:{value:{validate:(0,s.assertValueType)("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("NumericLiteral",{builder:["value"],deprecatedAlias:"NumberLiteral",fields:{value:{validate:(0,s.assertValueType)("number")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("NullLiteral",{aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("BooleanLiteral",{builder:["value"],fields:{value:{validate:(0,s.assertValueType)("boolean")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("RegExpLiteral",{builder:["pattern","flags"],deprecatedAlias:"RegexLiteral",aliases:["Expression","Literal"],fields:{pattern:{validate:(0,s.assertValueType)("string")},flags:{validate:(0,s.assertValueType)("string"),default:""}}}),(0,a.default)("LogicalExpression",{builder:["operator","left","right"],visitor:["left","right"],aliases:["Binary","Expression"],fields:{operator:{validate:s.assertOneOf.apply(void 0,i.LOGICAL_OPERATORS)},left:{validate:(0,s.assertNodeType)("Expression")},right:{validate:(0,s.assertNodeType)("Expression")}}}),(0,a.default)("MemberExpression",{builder:["object","property","computed"],visitor:["object","property"],aliases:["Expression","LVal"],fields:{object:{validate:(0,s.assertNodeType)("Expression")},property:{validate:function(e,t,r){var n=e.computed?"Expression":"Identifier";(0,s.assertNodeType)(n)(e,t,r)}},computed:{default:!1}}}),(0,a.default)("NewExpression",{visitor:["callee","arguments"],aliases:["Expression"],fields:{callee:{validate:(0,s.assertNodeType)("Expression")},arguments:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Expression","SpreadElement")))}}}),(0,a.default)("Program",{visitor:["directives","body"],builder:["body","directives"],fields:{directives:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Directive"))),default:[]},body:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Statement")))}},aliases:["Scopable","BlockParent","Block","FunctionParent"]}),(0,a.default)("ObjectExpression",{visitor:["properties"],aliases:["Expression"],fields:{properties:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("ObjectMethod","ObjectProperty","SpreadProperty")))}}}),(0,a.default)("ObjectMethod",{builder:["kind","key","params","body","computed"],fields:{kind:{validate:(0,s.chain)((0,s.assertValueType)("string"),(0,s.assertOneOf)("method","get","set")),default:"method"},computed:{validate:(0,s.assertValueType)("boolean"),default:!1},key:{validate:function(e,t,r){var n=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];s.assertNodeType.apply(void 0,n)(e,t,r)}},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator")))},body:{validate:(0,s.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,s.assertValueType)("boolean")},async:{default:!1,validate:(0,s.assertValueType)("boolean")}},visitor:["key","params","body","decorators","returnType","typeParameters"],aliases:["UserWhitespacable","Function","Scopable","BlockParent","FunctionParent","Method","ObjectMember"]}),(0,a.default)("ObjectProperty",{builder:["key","value","computed","shorthand","decorators"],fields:{computed:{validate:(0,s.assertValueType)("boolean"),default:!1},key:{validate:function(e,t,r){var n=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];s.assertNodeType.apply(void 0,n)(e,t,r)}},value:{validate:(0,s.assertNodeType)("Expression","Pattern","RestElement")},shorthand:{validate:(0,s.assertValueType)("boolean"),default:!1},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator"))),optional:!0}},visitor:["key","value","decorators"],aliases:["UserWhitespacable","Property","ObjectMember"]}),(0,a.default)("RestElement",{visitor:["argument","typeAnnotation"],aliases:["LVal"],fields:{argument:{validate:(0,s.assertNodeType)("LVal")},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator")))}}}),(0,a.default)("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,s.assertNodeType)("Expression"),optional:!0}}}),(0,a.default)("SequenceExpression",{visitor:["expressions"],fields:{expressions:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Expression")))}},aliases:["Expression"]}),(0,a.default)("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:(0,s.assertNodeType)("Expression"),optional:!0},consequent:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Statement")))}}}),(0,a.default)("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:(0,s.assertNodeType)("Expression")},cases:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("SwitchCase")))}}}),(0,a.default)("ThisExpression",{aliases:["Expression"]}),(0,a.default)("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,s.assertNodeType)("Expression")}}}),(0,a.default)("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{body:{validate:(0,s.assertNodeType)("BlockStatement")},handler:{optional:!0,handler:(0,s.assertNodeType)("BlockStatement")},finalizer:{optional:!0,validate:(0,s.assertNodeType)("BlockStatement")}}}),(0,a.default)("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!0},argument:{validate:(0,s.assertNodeType)("Expression")},operator:{validate:s.assertOneOf.apply(void 0,i.UNARY_OPERATORS)}},visitor:["argument"],aliases:["UnaryLike","Expression"]}),(0,a.default)("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!1},argument:{validate:(0,s.assertNodeType)("Expression")},operator:{validate:s.assertOneOf.apply(void 0,i.UPDATE_OPERATORS)}},visitor:["argument"],aliases:["Expression"]}),(0,a.default)("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{kind:{validate:(0,s.chain)((0,s.assertValueType)("string"),(0,s.assertOneOf)("var","let","const"))},declarations:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("VariableDeclarator")))}}}),(0,a.default)("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:(0,s.assertNodeType)("LVal")},init:{optional:!0,validate:(0,s.assertNodeType)("Expression")}}}),(0,a.default)("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("BlockStatement","Statement")}}}),(0,a.default)("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{object:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("BlockStatement","Statement")}}})},{"../constants":167,"../index":178,"./index":173}],170:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("AssignmentPattern",{visitor:["left","right"],aliases:["Pattern","LVal"],fields:{left:{validate:(0,n.assertNodeType)("Identifier")},right:{validate:(0,n.assertNodeType)("Expression")},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ArrayPattern",{visitor:["elements","typeAnnotation"],aliases:["Pattern","LVal"],fields:{elements:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Identifier","Pattern","RestElement")))},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ArrowFunctionExpression",{builder:["params","body","async"],visitor:["params","body","returnType","typeParameters"],aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{params:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("LVal")))},body:{validate:(0,n.assertNodeType)("BlockStatement","Expression")},async:{validate:(0,n.assertValueType)("boolean"),default:!1}}}),(0,i.default)("ClassBody",{visitor:["body"],fields:{body:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("ClassMethod","ClassProperty")))}}}),(0,i.default)("ClassDeclaration",{builder:["id","superClass","body","decorators"],visitor:["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators"],aliases:["Scopable","Class","Statement","Declaration","Pureish"],fields:{id:{validate:(0,n.assertNodeType)("Identifier")},body:{validate:(0,n.assertNodeType)("ClassBody")},superClass:{optional:!0,validate:(0,n.assertNodeType)("Expression")},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ClassExpression",{inherits:"ClassDeclaration",aliases:["Scopable","Class","Expression","Pureish"],fields:{id:{optional:!0,validate:(0,n.assertNodeType)("Identifier")},body:{validate:(0,n.assertNodeType)("ClassBody")},superClass:{optional:!0,validate:(0,n.assertNodeType)("Expression")},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ExportAllDeclaration",{visitor:["source"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{source:{validate:(0,n.assertNodeType)("StringLiteral")}}}),(0,i.default)("ExportDefaultDeclaration",{visitor:["declaration"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{declaration:{validate:(0,n.assertNodeType)("FunctionDeclaration","ClassDeclaration","Expression")}}}),(0,i.default)("ExportNamedDeclaration",{visitor:["declaration","specifiers","source"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{declaration:{validate:(0,n.assertNodeType)("Declaration"),optional:!0},specifiers:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("ExportSpecifier")))},source:{validate:(0,n.assertNodeType)("StringLiteral"),optional:!0}}}),(0,i.default)("ExportSpecifier",{visitor:["local","exported"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")},exported:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ForOfStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(0,n.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,n.assertNodeType)("Expression")},body:{validate:(0,n.assertNodeType)("Statement")}}}),(0,i.default)("ImportDeclaration",{visitor:["specifiers","source"],aliases:["Statement","Declaration","ModuleDeclaration"],fields:{specifiers:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier")))},source:{validate:(0,n.assertNodeType)("StringLiteral")}}}),(0,i.default)("ImportDefaultSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ImportNamespaceSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ImportSpecifier",{visitor:["local","imported"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")},imported:{validate:(0,n.assertNodeType)("Identifier")},importKind:{validate:(0,n.assertOneOf)(null,"type","typeof")}}}),(0,i.default)("MetaProperty",{visitor:["meta","property"],aliases:["Expression"],fields:{meta:{validate:(0,n.assertValueType)("string")},property:{validate:(0,n.assertValueType)("string")}}}),(0,i.default)("ClassMethod",{aliases:["Function","Scopable","BlockParent","FunctionParent","Method"],builder:["kind","key","params","body","computed","static"],visitor:["key","params","body","decorators","returnType","typeParameters"],fields:{kind:{validate:(0,n.chain)((0,n.assertValueType)("string"),(0,n.assertOneOf)("get","set","method","constructor")),default:"method"},computed:{default:!1,validate:(0,n.assertValueType)("boolean")},static:{default:!1,validate:(0,n.assertValueType)("boolean")},key:{validate:function(e,t,r){var i=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];n.assertNodeType.apply(void 0,i)(e,t,r)}},params:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("LVal")))},body:{validate:(0,n.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,n.assertValueType)("boolean")},async:{default:!1,validate:(0,n.assertValueType)("boolean")}}}),(0,i.default)("ObjectPattern",{visitor:["properties","typeAnnotation"],aliases:["Pattern","LVal"],fields:{properties:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("RestProperty","Property")))},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("SpreadElement",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("Super",{aliases:["Expression"]}),(0,i.default)("TaggedTemplateExpression",{visitor:["tag","quasi"],aliases:["Expression"],fields:{tag:{validate:(0,n.assertNodeType)("Expression")},quasi:{validate:(0,n.assertNodeType)("TemplateLiteral")}}}),(0,i.default)("TemplateElement",{builder:["value","tail"],fields:{value:{},tail:{validate:(0,n.assertValueType)("boolean"),default:!1}}}),(0,i.default)("TemplateLiteral",{visitor:["quasis","expressions"],aliases:["Expression","Literal"],fields:{quasis:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("TemplateElement")))},expressions:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Expression")))}}}),(0,i.default)("YieldExpression",{builder:["argument","delegate"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{delegate:{validate:(0,n.assertValueType)("boolean"),default:!1},argument:{optional:!0,validate:(0,n.assertNodeType)("Expression")}}})},{"./index":173}],171:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("AwaitExpression",{builder:["argument"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("ForAwaitStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(0,n.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,n.assertNodeType)("Expression")},body:{validate:(0,n.assertNodeType)("Statement")}}}),(0,i.default)("BindExpression",{visitor:["object","callee"],aliases:["Expression"],fields:{}}),(0,i.default)("Import",{aliases:["Expression"]}),(0,i.default)("Decorator",{visitor:["expression"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("DoExpression",{visitor:["body"],aliases:["Expression"],fields:{body:{validate:(0,n.assertNodeType)("BlockStatement")}}}),(0,i.default)("ExportDefaultSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ExportNamespaceSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("RestProperty",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:(0,n.assertNodeType)("LVal")}}}),(0,i.default)("SpreadProperty",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}})},{"./index":173}],172:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("AnyTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("ArrayTypeAnnotation",{visitor:["elementType"],aliases:["Flow"],fields:{}}),(0,i.default)("BooleanTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("BooleanLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),(0,i.default)("NullLiteralTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("ClassImplements",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),(0,i.default)("ClassProperty",{visitor:["key","value","typeAnnotation","decorators"],builder:["key","value","typeAnnotation","decorators","computed"],aliases:["Property"],fields:{computed:{validate:(0,n.assertValueType)("boolean"),default:!1}}}),(0,i.default)("DeclareClass",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareFunction",{visitor:["id"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareInterface",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareModule",{visitor:["id","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareModuleExports",{visitor:["typeAnnotation"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareTypeAlias",{visitor:["id","typeParameters","right"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareOpaqueType",{visitor:["id","typeParameters","supertype"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareVariable",{visitor:["id"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareExportDeclaration",{visitor:["declaration","specifiers","source"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("ExistentialTypeParam",{aliases:["Flow"]}),(0,i.default)("FunctionTypeAnnotation",{visitor:["typeParameters","params","rest","returnType"],aliases:["Flow"],fields:{}}),(0,i.default)("FunctionTypeParam",{visitor:["name","typeAnnotation"],aliases:["Flow"],fields:{}}),(0,i.default)("GenericTypeAnnotation",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),(0,i.default)("InterfaceExtends",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),(0,i.default)("InterfaceDeclaration",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("IntersectionTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),(0,i.default)("MixedTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"]}),(0,i.default)("EmptyTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"]}),(0,i.default)("NullableTypeAnnotation",{visitor:["typeAnnotation"],aliases:["Flow"],fields:{}}),(0,i.default)("NumericLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),(0,i.default)("NumberTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("StringLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),(0,i.default)("StringTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("ThisTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("TupleTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeofTypeAnnotation",{visitor:["argument"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeAlias",{visitor:["id","typeParameters","right"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("OpaqueType",{visitor:["id","typeParameters","impltype","supertype"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("TypeAnnotation",{visitor:["typeAnnotation"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeCastExpression",{visitor:["expression","typeAnnotation"],aliases:["Flow","ExpressionWrapper","Expression"],fields:{}}),(0,i.default)("TypeParameter",{visitor:["bound"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeParameterDeclaration",{visitor:["params"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeParameterInstantiation",{visitor:["params"],aliases:["Flow"],fields:{}}),(0,i.default)("ObjectTypeAnnotation",{visitor:["properties","indexers","callProperties"],aliases:["Flow"],fields:{}}),(0,i.default)("ObjectTypeCallProperty",{visitor:["value"],aliases:["Flow","UserWhitespacable"],fields:{}}),(0,i.default)("ObjectTypeIndexer",{visitor:["id","key","value"],aliases:["Flow","UserWhitespacable"],fields:{}}),(0,i.default)("ObjectTypeProperty",{visitor:["key","value"],aliases:["Flow","UserWhitespacable"],fields:{}}),(0,i.default)("ObjectTypeSpreadProperty",{visitor:["argument"],aliases:["Flow","UserWhitespacable"],fields:{}}),(0,i.default)("QualifiedTypeIdentifier",{visitor:["id","qualification"],aliases:["Flow"],fields:{}}),(0,i.default)("UnionTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),(0,i.default)("VoidTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}})},{"./index":173}],173:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){return Array.isArray(e)?"array":null===e?"null":void 0===e?"undefined":void 0===e?"undefined":(0,u.default)(e)}function s(e){function t(t,r,n){if(!(i(n)===e))throw new TypeError("Property "+r+" expected type of "+e+" but got "+i(n))}return t.type=e,t}r.__esModule=!0,r.DEPRECATED_KEYS=r.BUILDER_KEYS=r.NODE_FIELDS=r.ALIAS_KEYS=r.VISITOR_KEYS=void 0;var a=n(e("babel-runtime/core-js/get-iterator")),o=n(e("babel-runtime/core-js/json/stringify")),u=n(e("babel-runtime/helpers/typeof"));r.assertEach=function(e){function t(t,r,n){if(Array.isArray(n))for(var i=0;i=s.length)break;p=s[c++]}else{if((c=s.next()).done)break;p=c.value}var h=p;if(l.is(h,n)){i=!0;break}}if(!i)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,o.default)(r)+" but instead got "+(0,o.default)(n&&n.type))}for(var t=arguments.length,r=Array(t),n=0;n=u.length)break;h=u[p++]}else{if((p=u.next()).done)break;h=p.value}var f=h;if(i(n)===f||l.is(f,n)){s=!0;break}}if(!s)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,o.default)(r)+" but instead got "+(0,o.default)(n&&n.type))}for(var t=arguments.length,r=Array(t),n=0;n=e.length)break;i=e[n++]}else{if((n=e.next()).done)break;i=n.value}i.apply(void 0,arguments)}}for(var t=arguments.length,r=Array(t),n=0;n1&&void 0!==arguments[1]?arguments[1]:{},r=t.inherits&&m[t.inherits]||{};t.fields=t.fields||r.fields||{},t.visitor=t.visitor||r.visitor||[],t.aliases=t.aliases||r.aliases||[],t.builder=t.builder||r.builder||t.visitor||[],t.deprecatedAlias&&(d[t.deprecatedAlias]=e);for(var n=t.visitor.concat(t.builder),o=Array.isArray(n),u=0,n=o?n:(0,a.default)(n);;){var l;if(o){if(u>=n.length)break;l=n[u++]}else{if((u=n.next()).done)break;l=u.value}var y=l;t.fields[y]=t.fields[y]||{}}for(var g in t.fields){var b=t.fields[g];-1===t.builder.indexOf(g)&&(b.optional=!0),void 0===b.default?b.default=null:b.validate||(b.validate=s(i(b.default)))}c[e]=t.visitor,f[e]=t.builder,h[e]=t.fields,p[e]=t.aliases,m[e]=t};var l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("../index")),c=r.VISITOR_KEYS={},p=r.ALIAS_KEYS={},h=r.NODE_FIELDS={},f=r.BUILDER_KEYS={},d=r.DEPRECATED_KEYS={},m={}},{"../index":178,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/helpers/typeof":138}],174:[function(e,t,r){"use strict";e("./index"),e("./core"),e("./es2015"),e("./flow"),e("./jsx"),e("./misc"),e("./experimental")},{"./core":169,"./es2015":170,"./experimental":171,"./flow":172,"./index":173,"./jsx":175,"./misc":176}],175:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("JSXAttribute",{visitor:["name","value"],aliases:["JSX","Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXNamespacedName")},value:{optional:!0,validate:(0,n.assertNodeType)("JSXElement","StringLiteral","JSXExpressionContainer")}}}),(0,i.default)("JSXClosingElement",{visitor:["name"],aliases:["JSX","Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXMemberExpression")}}}),(0,i.default)("JSXElement",{builder:["openingElement","closingElement","children","selfClosing"],visitor:["openingElement","children","closingElement"],aliases:["JSX","Immutable","Expression"],fields:{openingElement:{validate:(0,n.assertNodeType)("JSXOpeningElement")},closingElement:{optional:!0,validate:(0,n.assertNodeType)("JSXClosingElement")},children:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement")))}}}),(0,i.default)("JSXEmptyExpression",{aliases:["JSX","Expression"]}),(0,i.default)("JSXExpressionContainer",{visitor:["expression"],aliases:["JSX","Immutable"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("JSXSpreadChild",{visitor:["expression"],aliases:["JSX","Immutable"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("JSXIdentifier",{builder:["name"],aliases:["JSX","Expression"],fields:{name:{validate:(0,n.assertValueType)("string")}}}),(0,i.default)("JSXMemberExpression",{visitor:["object","property"],aliases:["JSX","Expression"],fields:{object:{validate:(0,n.assertNodeType)("JSXMemberExpression","JSXIdentifier")},property:{validate:(0,n.assertNodeType)("JSXIdentifier")}}}),(0,i.default)("JSXNamespacedName",{visitor:["namespace","name"],aliases:["JSX"],fields:{namespace:{validate:(0,n.assertNodeType)("JSXIdentifier")},name:{validate:(0,n.assertNodeType)("JSXIdentifier")}}}),(0,i.default)("JSXOpeningElement",{builder:["name","attributes","selfClosing"],visitor:["name","attributes"],aliases:["JSX","Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXMemberExpression")},selfClosing:{default:!1,validate:(0,n.assertValueType)("boolean")},attributes:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("JSXAttribute","JSXSpreadAttribute")))}}}),(0,i.default)("JSXSpreadAttribute",{visitor:["argument"],aliases:["JSX"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("JSXText",{aliases:["JSX","Immutable"],builder:["value"],fields:{value:{validate:(0,n.assertValueType)("string")}}})},{"./index":173}],176:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("Noop",{visitor:[]}),(0,i.default)("ParenthesizedExpression",{visitor:["expression"],aliases:["Expression","ExpressionWrapper"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}})},{"./index":173}],177:[function(e,t,r){"use strict";function n(e){for(var t={},r={},s=[],a=[],o=0;o=0)){if(i.isAnyTypeAnnotation(u))return[u];if(i.isFlowBaseAnnotation(u))r[u.type]=u;else if(i.isUnionTypeAnnotation(u))s.indexOf(u.types)<0&&(e=e.concat(u.types),s.push(u.types));else if(i.isGenericTypeAnnotation(u)){var l=u.id.name;if(t[l]){var c=t[l];c.typeParameters?u.typeParameters&&(c.typeParameters.params=n(c.typeParameters.params.concat(u.typeParameters.params))):c=u.typeParameters}else t[l]=u}else a.push(u)}}for(var p in r)a.push(r[p]);for(var h in t)a.push(t[h]);return a}r.__esModule=!0,r.createUnionTypeAnnotation=function(e){var t=n(e);return 1===t.length?t[0]:i.unionTypeAnnotation(t)},r.removeTypeDuplicates=n,r.createTypeAnnotationBasedOnTypeof=function(e){if("string"===e)return i.stringTypeAnnotation();if("number"===e)return i.numberTypeAnnotation();if("undefined"===e)return i.voidTypeAnnotation();if("boolean"===e)return i.booleanTypeAnnotation();if("function"===e)return i.genericTypeAnnotation(i.identifier("Function"));if("object"===e)return i.genericTypeAnnotation(i.identifier("Object"));if("symbol"===e)return i.genericTypeAnnotation(i.identifier("Symbol"));throw new Error("Invalid typeof value")};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./index"))},{"./index":178}],178:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=F["is"+e];t||(t=F["is"+e]=function(t,r){return F.is(e,t,r)}),F["assert"+e]=function(r,n){if(n=n||{},!t(r,n))throw new Error("Expected type "+(0,b.default)(e)+" with option "+(0,b.default)(n))}}function s(e,t){if(e===t)return!0;if(F.ALIAS_KEYS[t])return!1;var r=F.FLIPPED_ALIAS_KEYS[t];if(r){if(r[0]===e)return!0;for(var n=r,i=Array.isArray(n),s=0,n=i?n:(0,y.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}if(e===a)return!0}}return!1}function a(e,t,r){if(e){var n=F.NODE_FIELDS[e.type];if(n){var i=n[t];i&&i.validate&&(i.optional&&null==r||i.validate(e,t,r))}}}function o(e){if(!e)return e;var t={};for(var r in e)"_"!==r[0]&&(t[r]=e[r]);return t}function u(e,t){p("trailingComments",e,t)}function l(e,t){p("leadingComments",e,t)}function c(e,t){p("innerComments",e,t)}function p(e,t,r){t&&r&&(t[e]=(0,_.default)([].concat(t[e],r[e]).filter(Boolean)))}function h(e){return!(!e||!w.VISITOR_KEYS[e.type])}function f(e,t,r){if(e){var n=F.VISITOR_KEYS[e.type];if(n){t(e,r=r||{});for(var i=n,s=Array.isArray(i),a=0,i=s?i:(0,y.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if((a=i.next()).done)break;o=a.value}var u=e[o];if(Array.isArray(u))for(var l=u,c=Array.isArray(l),p=0,l=c?l:(0,y.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if((p=l.next()).done)break;h=p.value}f(h,t,r)}else f(u,t,r)}}}}function d(e,t){for(var r=(t=t||{}).preserveComments?O:j,n=Array.isArray(r),i=0,r=n?r:(0,y.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}var a=s;null!=e[a]&&(e[a]=void 0)}for(var o in e)"_"===o[0]&&null!=e[o]&&(e[o]=void 0);for(var u=(0,m.default)(e),l=Array.isArray(u),c=0,u=l?u:(0,y.default)(u);;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if((c=u.next()).done)break;p=c.value}e[p]=null}}r.__esModule=!0,r.createTypeAnnotationBasedOnTypeof=r.removeTypeDuplicates=r.createUnionTypeAnnotation=r.valueToNode=r.toBlock=r.toExpression=r.toStatement=r.toBindingIdentifierName=r.toIdentifier=r.toKeyAlias=r.toSequenceExpression=r.toComputedKey=r.isNodesEquivalent=r.isImmutable=r.isScope=r.isSpecifierDefault=r.isVar=r.isBlockScoped=r.isLet=r.isValidIdentifier=r.isReferenced=r.isBinding=r.getOuterBindingIdentifiers=r.getBindingIdentifiers=r.TYPES=r.react=r.DEPRECATED_KEYS=r.BUILDER_KEYS=r.NODE_FIELDS=r.ALIAS_KEYS=r.VISITOR_KEYS=r.NOT_LOCAL_BINDING=r.BLOCK_SCOPED_SYMBOL=r.INHERIT_KEYS=r.UNARY_OPERATORS=r.STRING_UNARY_OPERATORS=r.NUMBER_UNARY_OPERATORS=r.BOOLEAN_UNARY_OPERATORS=r.BINARY_OPERATORS=r.NUMBER_BINARY_OPERATORS=r.BOOLEAN_BINARY_OPERATORS=r.COMPARISON_BINARY_OPERATORS=r.EQUALITY_BINARY_OPERATORS=r.BOOLEAN_NUMBER_BINARY_OPERATORS=r.UPDATE_OPERATORS=r.LOGICAL_OPERATORS=r.COMMENT_KEYS=r.FOR_INIT_KEYS=r.FLATTENABLE_KEYS=r.STATEMENT_OR_BLOCK_KEYS=void 0;var m=n(e("babel-runtime/core-js/object/get-own-property-symbols")),y=n(e("babel-runtime/core-js/get-iterator")),g=n(e("babel-runtime/core-js/object/keys")),b=n(e("babel-runtime/core-js/json/stringify")),v=e("./constants");Object.defineProperty(r,"STATEMENT_OR_BLOCK_KEYS",{enumerable:!0,get:function(){return v.STATEMENT_OR_BLOCK_KEYS}}),Object.defineProperty(r,"FLATTENABLE_KEYS",{enumerable:!0,get:function(){return v.FLATTENABLE_KEYS}}),Object.defineProperty(r,"FOR_INIT_KEYS",{enumerable:!0,get:function(){return v.FOR_INIT_KEYS}}),Object.defineProperty(r,"COMMENT_KEYS",{enumerable:!0,get:function(){return v.COMMENT_KEYS}}),Object.defineProperty(r,"LOGICAL_OPERATORS",{enumerable:!0,get:function(){return v.LOGICAL_OPERATORS}}),Object.defineProperty(r,"UPDATE_OPERATORS",{enumerable:!0,get:function(){return v.UPDATE_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.BOOLEAN_NUMBER_BINARY_OPERATORS}}),Object.defineProperty(r,"EQUALITY_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.EQUALITY_BINARY_OPERATORS}}),Object.defineProperty(r,"COMPARISON_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.COMPARISON_BINARY_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.BOOLEAN_BINARY_OPERATORS}}),Object.defineProperty(r,"NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.NUMBER_BINARY_OPERATORS}}),Object.defineProperty(r,"BINARY_OPERATORS",{enumerable:!0,get:function(){return v.BINARY_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_UNARY_OPERATORS",{enumerable:!0,get:function(){return v.BOOLEAN_UNARY_OPERATORS}}),Object.defineProperty(r,"NUMBER_UNARY_OPERATORS",{enumerable:!0,get:function(){return v.NUMBER_UNARY_OPERATORS}}),Object.defineProperty(r,"STRING_UNARY_OPERATORS",{enumerable:!0,get:function(){return v.STRING_UNARY_OPERATORS}}),Object.defineProperty(r,"UNARY_OPERATORS",{enumerable:!0,get:function(){return v.UNARY_OPERATORS}}),Object.defineProperty(r,"INHERIT_KEYS",{enumerable:!0,get:function(){return v.INHERIT_KEYS}}),Object.defineProperty(r,"BLOCK_SCOPED_SYMBOL",{enumerable:!0,get:function(){return v.BLOCK_SCOPED_SYMBOL}}),Object.defineProperty(r,"NOT_LOCAL_BINDING",{enumerable:!0,get:function(){return v.NOT_LOCAL_BINDING}}),r.is=function(e,t,r){return!!t&&!!s(t.type,e)&&(void 0===r||F.shallowEqual(t,r))},r.isType=s,r.validate=a,r.shallowEqual=function(e,t){for(var r=(0,g.default)(t),n=Array.isArray(r),i=0,r=n?r:(0,y.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}var a=s;if(e[a]!==t[a])return!1}return!0},r.appendToMemberExpression=function(e,t,r){return e.object=F.memberExpression(e.object,e.property,e.computed),e.property=t,e.computed=!!r,e},r.prependToMemberExpression=function(e,t){return e.object=F.memberExpression(t,e.object),e},r.ensureBlock=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"body";return e[t]=F.toBlock(e[t],e)},r.clone=o,r.cloneWithoutLoc=function(e){var t=o(e);return delete t.loc,t},r.cloneDeep=function(e){if(!e)return e;var t={};for(var r in e)if("_"!==r[0]){var n=e[r];n&&(n.type?n=F.cloneDeep(n):Array.isArray(n)&&(n=n.map(F.cloneDeep))),t[r]=n}return t},r.buildMatchMemberExpression=function(e,t){var r=e.split(".");return function(e){if(!F.isMemberExpression(e))return!1;for(var n=[e],i=0;n.length;){var s=n.shift();if(t&&i===r.length)return!0;if(F.isIdentifier(s)){if(r[i]!==s.name)return!1}else{if(!F.isStringLiteral(s)){if(F.isMemberExpression(s)){if(s.computed&&!F.isStringLiteral(s.property))return!1;n.push(s.object),n.push(s.property);continue}return!1}if(r[i]!==s.value)return!1}if(++i>r.length)return!1}return!0}},r.removeComments=function(e){for(var t=F.COMMENT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,y.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}delete e[i]}return e},r.inheritsComments=function(e,t){return u(e,t),l(e,t),c(e,t),e},r.inheritTrailingComments=u,r.inheritLeadingComments=l,r.inheritInnerComments=c,r.inherits=function(e,t){if(!e||!t)return e;for(var r=F.INHERIT_KEYS.optional,n=Array.isArray(r),i=0,r=n?r:(0,y.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}var a=s;null==e[a]&&(e[a]=t[a])}for(var o in t)"_"===o[0]&&(e[o]=t[o]);for(var u=F.INHERIT_KEYS.force,l=Array.isArray(u),c=0,u=l?u:(0,y.default)(u);;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if((c=u.next()).done)break;p=c.value}var h=p;e[h]=t[h]}return F.inheritsComments(e,t),e},r.assertNode=function(e){if(!h(e))throw new TypeError("Not a valid node "+(e&&e.type))},r.isNode=h,r.traverseFast=f,r.removeProperties=d,r.removePropertiesDeep=function(e,t){return f(e,d,t),e};var x=e("./retrievers");Object.defineProperty(r,"getBindingIdentifiers",{enumerable:!0,get:function(){return x.getBindingIdentifiers}}),Object.defineProperty(r,"getOuterBindingIdentifiers",{enumerable:!0,get:function(){return x.getOuterBindingIdentifiers}});var E=e("./validators");Object.defineProperty(r,"isBinding",{enumerable:!0,get:function(){return E.isBinding}}),Object.defineProperty(r,"isReferenced",{enumerable:!0,get:function(){return E.isReferenced}}),Object.defineProperty(r,"isValidIdentifier",{enumerable:!0,get:function(){return E.isValidIdentifier}}),Object.defineProperty(r,"isLet",{enumerable:!0,get:function(){return E.isLet}}),Object.defineProperty(r,"isBlockScoped",{enumerable:!0,get:function(){return E.isBlockScoped}}),Object.defineProperty(r,"isVar",{enumerable:!0,get:function(){return E.isVar}}),Object.defineProperty(r,"isSpecifierDefault",{enumerable:!0,get:function(){return E.isSpecifierDefault}}),Object.defineProperty(r,"isScope",{enumerable:!0,get:function(){return E.isScope}}),Object.defineProperty(r,"isImmutable",{enumerable:!0,get:function(){return E.isImmutable}}),Object.defineProperty(r,"isNodesEquivalent",{enumerable:!0,get:function(){return E.isNodesEquivalent}});var A=e("./converters");Object.defineProperty(r,"toComputedKey",{enumerable:!0,get:function(){return A.toComputedKey}}),Object.defineProperty(r,"toSequenceExpression",{enumerable:!0,get:function(){return A.toSequenceExpression}}),Object.defineProperty(r,"toKeyAlias",{enumerable:!0,get:function(){return A.toKeyAlias}}),Object.defineProperty(r,"toIdentifier",{enumerable:!0,get:function(){return A.toIdentifier}}),Object.defineProperty(r,"toBindingIdentifierName",{enumerable:!0,get:function(){return A.toBindingIdentifierName}}),Object.defineProperty(r,"toStatement",{enumerable:!0,get:function(){return A.toStatement}}),Object.defineProperty(r,"toExpression",{enumerable:!0,get:function(){return A.toExpression}}),Object.defineProperty(r,"toBlock",{enumerable:!0,get:function(){return A.toBlock}}),Object.defineProperty(r,"valueToNode",{enumerable:!0,get:function(){return A.valueToNode}});var D=e("./flow");Object.defineProperty(r,"createUnionTypeAnnotation",{enumerable:!0,get:function(){return D.createUnionTypeAnnotation}}),Object.defineProperty(r,"removeTypeDuplicates",{enumerable:!0,get:function(){return D.removeTypeDuplicates}}),Object.defineProperty(r,"createTypeAnnotationBasedOnTypeof",{enumerable:!0,get:function(){return D.createTypeAnnotationBasedOnTypeof}});var C=n(e("to-fast-properties")),S=n(e("lodash/clone")),_=n(e("lodash/uniq"));e("./definitions/init");var w=e("./definitions"),k=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./react")),F=r;r.VISITOR_KEYS=w.VISITOR_KEYS,r.ALIAS_KEYS=w.ALIAS_KEYS,r.NODE_FIELDS=w.NODE_FIELDS,r.BUILDER_KEYS=w.BUILDER_KEYS,r.DEPRECATED_KEYS=w.DEPRECATED_KEYS,r.react=k;for(var T in F.VISITOR_KEYS)i(T);F.FLIPPED_ALIAS_KEYS={},(0,g.default)(F.ALIAS_KEYS).forEach(function(e){F.ALIAS_KEYS[e].forEach(function(t){(F.FLIPPED_ALIAS_KEYS[t]=F.FLIPPED_ALIAS_KEYS[t]||[]).push(e)})}),(0,g.default)(F.FLIPPED_ALIAS_KEYS).forEach(function(e){F[e.toUpperCase()+"_TYPES"]=F.FLIPPED_ALIAS_KEYS[e],i(e)});r.TYPES=(0,g.default)(F.VISITOR_KEYS).concat((0,g.default)(F.FLIPPED_ALIAS_KEYS)).concat((0,g.default)(F.DEPRECATED_KEYS));(0,g.default)(F.BUILDER_KEYS).forEach(function(e){function t(){if(arguments.length>r.length)throw new Error("t."+e+": Too many arguments passed. Received "+arguments.length+" but can receive no more than "+r.length);var t={};t.type=e;for(var n=0,i=r,s=Array.isArray(i),o=0,i=s?i:(0,y.default)(i);;){var u;if(s){if(o>=i.length)break;u=i[o++]}else{if((o=i.next()).done)break;u=o.value}var l=u,c=F.NODE_FIELDS[e][l],p=arguments[n++];void 0===p&&(p=(0,S.default)(c.default)),t[l]=p}for(var h in t)a(t,h,t[h]);return t}var r=F.BUILDER_KEYS[e];F[e]=t,F[e[0].toLowerCase()+e.slice(1)]=t});var P=function(e){function t(t){return function(){return console.trace("The node type "+e+" has been renamed to "+r),t.apply(this,arguments)}}var r=F.DEPRECATED_KEYS[e];F[e]=F[e[0].toLowerCase()+e.slice(1)]=t(F[r]),F["is"+e]=t(F["is"+r]),F["assert"+e]=t(F["assert"+r])};for(var B in F.DEPRECATED_KEYS)P(B);(0,C.default)(F),(0,C.default)(F.VISITOR_KEYS);var O=["tokens","start","end","loc","raw","rawValue"],j=F.COMMENT_KEYS.concat(["comments"]).concat(O)},{"./constants":167,"./converters":168,"./definitions":173,"./definitions/init":174,"./flow":177,"./react":179,"./retrievers":180,"./validators":181,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/core-js/object/get-own-property-symbols":126,"babel-runtime/core-js/object/keys":127,"lodash/clone":491,"lodash/uniq":540,"to-fast-properties":607}],179:[function(e,t,r){"use strict";function n(e,t){for(var r=e.value.split(/\r\n|\n|\r/),n=0,s=0;s=r.length)break;l=r[u++]}else{if((u=r.next()).done)break;l=u.value}var p=l;if((0,a.default)(e[p])!==(0,a.default)(t[p]))return!1;if(Array.isArray(e[p])){if(!Array.isArray(t[p]))return!1;if(e[p].length!==t[p].length)return!1;for(var h=0;h=0)return!0}else if(i===e)return!0}return!1},r.isReferenced=function(e,t){switch(t.type){case"BindExpression":return t.object===e||t.callee===e;case"MemberExpression":case"JSXMemberExpression":return!(t.property!==e||!t.computed)||t.object===e;case"MetaProperty":return!1;case"ObjectProperty":if(t.key===e)return t.computed;case"VariableDeclarator":return t.id!==e;case"ArrowFunctionExpression":case"FunctionDeclaration":case"FunctionExpression":for(var r=t.params,n=Array.isArray(r),i=0,r=n?r:(0,o.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}if(s===e)return!1}return t.id!==e;case"ExportSpecifier":return!t.source&&t.local===e;case"ExportNamespaceSpecifier":case"ExportDefaultSpecifier":return!1;case"JSXAttribute":return t.name!==e;case"ClassProperty":return t.key===e?t.computed:t.value===e;case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ImportSpecifier":return!1;case"ClassDeclaration":case"ClassExpression":return t.id!==e;case"ClassMethod":case"ObjectMethod":return t.key===e&&t.computed;case"LabeledStatement":return!1;case"CatchClause":return t.param!==e;case"RestElement":return!1;case"AssignmentExpression":case"AssignmentPattern":return t.right===e;case"ObjectPattern":case"ArrayPattern":return!1}return!0},r.isValidIdentifier=function(e){return"string"==typeof e&&!l.default.keyword.isReservedWordES6(e,!0)&&"await"!==e&&l.default.keyword.isIdentifierNameES6(e)},r.isLet=function(e){return c.isVariableDeclaration(e)&&("var"!==e.kind||e[p.BLOCK_SCOPED_SYMBOL])},r.isBlockScoped=function(e){return c.isFunctionDeclaration(e)||c.isClassDeclaration(e)||c.isLet(e)},r.isVar=function(e){return c.isVariableDeclaration(e,{kind:"var"})&&!e[p.BLOCK_SCOPED_SYMBOL]},r.isSpecifierDefault=function(e){return c.isImportDefaultSpecifier(e)||c.isIdentifier(e.imported||e.exported,{name:"default"})},r.isScope=function(e,t){return(!c.isBlockStatement(e)||!c.isFunction(t,{body:e}))&&c.isScopable(e)},r.isImmutable=function(e){return!!c.isType(e.type,"Immutable")||!!c.isIdentifier(e)&&"undefined"===e.name},r.isNodesEquivalent=i;var u=e("./retrievers"),l=n(e("esutils")),c=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(e("./index")),p=e("./constants")},{"./constants":167,"./index":178,"./retrievers":180,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/object/keys":127,"babel-runtime/helpers/typeof":138,esutils:185}],182:[function(e,t,r){arguments[4][25][0].apply(r,arguments)},{dup:25}],183:[function(e,t,r){arguments[4][26][0].apply(r,arguments)},{dup:26}],184:[function(e,t,r){arguments[4][27][0].apply(r,arguments)},{"./code":183,dup:27}],185:[function(e,t,r){arguments[4][28][0].apply(r,arguments)},{"./ast":182,"./code":183,"./keyword":184,dup:28}],186:[function(e,t,r){"use strict";function n(e){return e=e.split(" "),function(t){return e.indexOf(t)>=0}}function i(e,t){for(var r=65536,n=0;ne)return!1;if((r+=t[n+1])>=e)return!0}}function s(e){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&g.test(String.fromCharCode(e)):i(e,v)))}function a(e){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&b.test(String.fromCharCode(e)):i(e,v)||i(e,x))))}function o(e){return 10===e||13===e||8232===e||8233===e}function u(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10),56320+(e-65536&1023))}function l(e,t,r,n){return e.type=t,e.end=r,e.loc.end=n,this.processComment(e),e}function c(e){return e[e.length-1]}function p(e){return e&&"Property"===e.type&&"init"===e.kind&&!1===e.method}function h(e){return"JSXIdentifier"===e.type?e.name:"JSXNamespacedName"===e.type?e.namespace.name+":"+e.name.name:"JSXMemberExpression"===e.type?h(e.object)+"."+h(e.property):void 0}Object.defineProperty(r,"__esModule",{value:!0});var f={6:n("enum await"),strict:n("implements interface let package private protected public static yield"),strictBind:n("eval arguments")},d=n("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 let const class extends export import yield super"),m="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿕ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",y="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",g=new RegExp("["+m+"]"),b=new RegExp("["+m+y+"]");m=y=null;var v=[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],x=[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],E={sourceType:"script",sourceFilename:void 0,startLine:1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,plugins:[],strictMode:null},A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},D=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},C=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},S=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},_=!0,w=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};D(this,e),this.label=t,this.keyword=r.keyword,this.beforeExpr=!!r.beforeExpr,this.startsExpr=!!r.startsExpr,this.rightAssociative=!!r.rightAssociative,this.isLoop=!!r.isLoop,this.isAssign=!!r.isAssign,this.prefix=!!r.prefix,this.postfix=!!r.postfix,this.binop=r.binop||null,this.updateContext=null},k=function(e){function t(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return D(this,t),n.keyword=r,S(this,e.call(this,r,n))}return C(t,e),t}(w),F=function(e){function t(r,n){return D(this,t),S(this,e.call(this,r,{beforeExpr:_,binop:n}))}return C(t,e),t}(w),T={num:new w("num",{startsExpr:!0}),regexp:new w("regexp",{startsExpr:!0}),string:new w("string",{startsExpr:!0}),name:new w("name",{startsExpr:!0}),eof:new w("eof"),bracketL:new w("[",{beforeExpr:_,startsExpr:!0}),bracketR:new w("]"),braceL:new w("{",{beforeExpr:_,startsExpr:!0}),braceBarL:new w("{|",{beforeExpr:_,startsExpr:!0}),braceR:new w("}"),braceBarR:new w("|}"),parenL:new w("(",{beforeExpr:_,startsExpr:!0}),parenR:new w(")"),comma:new w(",",{beforeExpr:_}),semi:new w(";",{beforeExpr:_}),colon:new w(":",{beforeExpr:_}),doubleColon:new w("::",{beforeExpr:_}),dot:new w("."),question:new w("?",{beforeExpr:_}),arrow:new w("=>",{beforeExpr:_}),template:new w("template"),ellipsis:new w("...",{beforeExpr:_}),backQuote:new w("`",{startsExpr:!0}),dollarBraceL:new w("${",{beforeExpr:_,startsExpr:!0}),at:new w("@"),eq:new w("=",{beforeExpr:_,isAssign:!0}),assign:new w("_=",{beforeExpr:_,isAssign:!0}),incDec:new w("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new w("prefix",{beforeExpr:_,prefix:!0,startsExpr:!0}),logicalOR:new F("||",1),logicalAND:new F("&&",2),bitwiseOR:new F("|",3),bitwiseXOR:new F("^",4),bitwiseAND:new F("&",5),equality:new F("==/!=",6),relational:new F("",7),bitShift:new F("<>",8),plusMin:new w("+/-",{beforeExpr:_,binop:9,prefix:!0,startsExpr:!0}),modulo:new F("%",10),star:new F("*",10),slash:new F("/",10),exponent:new w("**",{beforeExpr:_,binop:11,rightAssociative:!0})},P={break:new k("break"),case:new k("case",{beforeExpr:_}),catch:new k("catch"),continue:new k("continue"),debugger:new k("debugger"),default:new k("default",{beforeExpr:_}),do:new k("do",{isLoop:!0,beforeExpr:_}),else:new k("else",{beforeExpr:_}),finally:new k("finally"),for:new k("for",{isLoop:!0}),function:new k("function",{startsExpr:!0}),if:new k("if"),return:new k("return",{beforeExpr:_}),switch:new k("switch"),throw:new k("throw",{beforeExpr:_}),try:new k("try"),var:new k("var"),let:new k("let"),const:new k("const"),while:new k("while",{isLoop:!0}),with:new k("with"),new:new k("new",{beforeExpr:_,startsExpr:!0}),this:new k("this",{startsExpr:!0}),super:new k("super",{startsExpr:!0}),class:new k("class"),extends:new k("extends",{beforeExpr:_}),export:new k("export"),import:new k("import",{startsExpr:!0}),yield:new k("yield",{beforeExpr:_,startsExpr:!0}),null:new k("null",{startsExpr:!0}),true:new k("true",{startsExpr:!0}),false:new k("false",{startsExpr:!0}),in:new k("in",{beforeExpr:_,binop:7}),instanceof:new k("instanceof",{beforeExpr:_,binop:7}),typeof:new k("typeof",{beforeExpr:_,prefix:!0,startsExpr:!0}),void:new k("void",{beforeExpr:_,prefix:!0,startsExpr:!0}),delete:new k("delete",{beforeExpr:_,prefix:!0,startsExpr:!0})};Object.keys(P).forEach(function(e){T["_"+e]=P[e]});var B=/\r\n?|\n|\u2028|\u2029/,O=new RegExp(B.source,"g"),j=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,N=function e(t,r,n,i){D(this,e),this.token=t,this.isExpr=!!r,this.preserveSpace=!!n,this.override=i},I={braceStatement:new N("{",!1),braceExpression:new N("{",!0),templateQuasi:new N("${",!0),parenStatement:new N("(",!1),parenExpression:new N("(",!0),template:new N("`",!0,!0,function(e){return e.readTmplToken()}),functionExpression:new N("function",!0)};T.parenR.updateContext=T.braceR.updateContext=function(){if(1!==this.state.context.length){var e=this.state.context.pop();e===I.braceStatement&&this.curContext()===I.functionExpression?(this.state.context.pop(),this.state.exprAllowed=!1):e===I.templateQuasi?this.state.exprAllowed=!0:this.state.exprAllowed=!e.isExpr}else this.state.exprAllowed=!0},T.name.updateContext=function(e){this.state.exprAllowed=!1,e!==T._let&&e!==T._const&&e!==T._var||B.test(this.input.slice(this.state.end))&&(this.state.exprAllowed=!0)},T.braceL.updateContext=function(e){this.state.context.push(this.braceIsBlock(e)?I.braceStatement:I.braceExpression),this.state.exprAllowed=!0},T.dollarBraceL.updateContext=function(){this.state.context.push(I.templateQuasi),this.state.exprAllowed=!0},T.parenL.updateContext=function(e){var t=e===T._if||e===T._for||e===T._with||e===T._while;this.state.context.push(t?I.parenStatement:I.parenExpression),this.state.exprAllowed=!0},T.incDec.updateContext=function(){},T._function.updateContext=function(){this.curContext()!==I.braceStatement&&this.state.context.push(I.functionExpression),this.state.exprAllowed=!1},T.backQuote.updateContext=function(){this.curContext()===I.template?this.state.context.pop():this.state.context.push(I.template),this.state.exprAllowed=!1};var L=function e(t,r){D(this,e),this.line=t,this.column=r},M=function e(t,r){D(this,e),this.start=t,this.end=r},R=function(){function e(){D(this,e)}return e.prototype.init=function(e,t){return this.strict=!1!==e.strictMode&&"module"===e.sourceType,this.input=t,this.potentialArrowAt=-1,this.inMethod=this.inFunction=this.inGenerator=this.inAsync=this.inPropertyName=this.inType=this.inClassProperty=this.noAnonFunctionType=!1,this.labels=[],this.decorators=[],this.tokens=[],this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.pos=this.lineStart=0,this.curLine=e.startLine,this.type=T.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=[I.braceStatement],this.exprAllowed=!0,this.containsEsc=this.containsOctal=!1,this.octalPosition=null,this.invalidTemplateEscapePosition=null,this.exportedIdentifiers=[],this},e.prototype.curPosition=function(){return new L(this.curLine,this.pos-this.lineStart)},e.prototype.clone=function(t){var r=new e;for(var n in this){var i=this[n];t&&"context"!==n||!Array.isArray(i)||(i=i.slice()),r[n]=i}return r},e}(),V={},U=["jsx","doExpressions","objectRestSpread","decorators","classProperties","exportExtensions","asyncGenerators","functionBind","functionSent","dynamicImport","flow"],q=function(e){function t(r,n){D(this,t),r=function(e){var t={};for(var r in E)t[r]=e&&r in e?e[r]:E[r];return t}(r);var i=S(this,e.call(this,r,n));return i.options=r,i.inModule="module"===i.options.sourceType,i.input=n,i.plugins=i.loadPlugins(i.options.plugins),i.filename=r.sourceFilename,0===i.state.pos&&"#"===i.input[0]&&"!"===i.input[1]&&i.skipLineComment(2),i}return C(t,e),t.prototype.isReservedWord=function(e){return"await"===e?this.inModule:f[6](e)},t.prototype.hasPlugin=function(e){return!!(this.plugins["*"]&&U.indexOf(e)>-1)||!!this.plugins[e]},t.prototype.extend=function(e,t){this[e]=t(this[e])},t.prototype.loadAllPlugins=function(){var e=this,t=Object.keys(V).filter(function(e){return"flow"!==e&&"estree"!==e});t.push("flow"),t.forEach(function(t){var r=V[t];r&&r(e)})},t.prototype.loadPlugins=function(e){if(e.indexOf("*")>=0)return this.loadAllPlugins(),{"*":!0};var t={};e.indexOf("flow")>=0&&(e=e.filter(function(e){return"flow"!==e})).push("flow"),e.indexOf("estree")>=0&&(e=e.filter(function(e){return"estree"!==e})).unshift("estree");for(var r=e,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}var a=s;if(!t[a]){t[a]=!0;var o=V[a];o&&o(this)}}return t},t.prototype.parse=function(){var e=this.startNode(),t=this.startNode();return this.nextToken(),this.parseTopLevel(e,t)},t}(function(){function e(t,r){D(this,e),this.state=new R,this.state.init(t,r)}return e.prototype.next=function(){this.isLookahead||this.state.tokens.push(new function e(t){D(this,e),this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new M(t.startLoc,t.endLoc)}(this.state)),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},e.prototype.eat=function(e){return!!this.match(e)&&(this.next(),!0)},e.prototype.match=function(e){return this.state.type===e},e.prototype.isKeyword=function(e){return d(e)},e.prototype.lookahead=function(){var e=this.state;this.state=e.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;var t=this.state.clone(!0);return this.state=e,t},e.prototype.setStrict=function(e){if(this.state.strict=e,this.match(T.num)||this.match(T.string)){for(this.state.pos=this.state.start;this.state.pos=this.input.length?this.finishToken(T.eof):e.override?e.override(this):this.readToken(this.fullCharCodeAtPos())},e.prototype.readToken=function(e){return s(e)||92===e?this.readWord():this.getTokenFromCode(e)},e.prototype.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.state.pos);if(e<=55295||e>=57344)return e;return(e<<10)+this.input.charCodeAt(this.state.pos+1)-56613888},e.prototype.pushComment=function(e,t,r,n,i,s){var a={type:e?"CommentBlock":"CommentLine",value:t,start:r,end:n,loc:new M(i,s)};this.isLookahead||(this.state.tokens.push(a),this.state.comments.push(a),this.addComment(a))},e.prototype.skipBlockComment=function(){var e=this.state.curPosition(),t=this.state.pos,r=this.input.indexOf("*/",this.state.pos+=2);-1===r&&this.raise(this.state.pos-2,"Unterminated comment"),this.state.pos=r+2,O.lastIndex=t;for(var n=void 0;(n=O.exec(this.input))&&n.index8&&e<14||e>=5760&&j.test(String.fromCharCode(e))))break e;++this.state.pos}}},e.prototype.finishToken=function(e,t){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var r=this.state.type;this.state.type=e,this.state.value=t,this.updateContext(r)},e.prototype.readToken_dot=function(){var e=this.input.charCodeAt(this.state.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.state.pos+2);return 46===e&&46===t?(this.state.pos+=3,this.finishToken(T.ellipsis)):(++this.state.pos,this.finishToken(T.dot))},e.prototype.readToken_slash=function(){if(this.state.exprAllowed)return++this.state.pos,this.readRegexp();return 61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.assign,2):this.finishOp(T.slash,1)},e.prototype.readToken_mult_modulo=function(e){var t=42===e?T.star:T.modulo,r=1,n=this.input.charCodeAt(this.state.pos+1);return 42===n&&(r++,n=this.input.charCodeAt(this.state.pos+2),t=T.exponent),61===n&&(r++,t=T.assign),this.finishOp(t,r)},e.prototype.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.state.pos+1);return t===e?this.finishOp(124===e?T.logicalOR:T.logicalAND,2):61===t?this.finishOp(T.assign,2):124===e&&125===t&&this.hasPlugin("flow")?this.finishOp(T.braceBarR,2):this.finishOp(124===e?T.bitwiseOR:T.bitwiseAND,1)},e.prototype.readToken_caret=function(){return 61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.assign,2):this.finishOp(T.bitwiseXOR,1)},e.prototype.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.state.pos+1);return t===e?45===t&&62===this.input.charCodeAt(this.state.pos+2)&&B.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(T.incDec,2):61===t?this.finishOp(T.assign,2):this.finishOp(T.plusMin,1)},e.prototype.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.state.pos+1),r=1;return t===e?(r=62===e&&62===this.input.charCodeAt(this.state.pos+2)?3:2,61===this.input.charCodeAt(this.state.pos+r)?this.finishOp(T.assign,r+1):this.finishOp(T.bitShift,r)):33===t&&60===e&&45===this.input.charCodeAt(this.state.pos+2)&&45===this.input.charCodeAt(this.state.pos+3)?(this.inModule&&this.unexpected(),this.skipLineComment(4),this.skipSpace(),this.nextToken()):(61===t&&(r=2),this.finishOp(T.relational,r))},e.prototype.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(T.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2):61===e&&62===t?(this.state.pos+=2,this.finishToken(T.arrow)):this.finishOp(61===e?T.eq:T.prefix,1)},e.prototype.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.state.pos,this.finishToken(T.parenL);case 41:return++this.state.pos,this.finishToken(T.parenR);case 59:return++this.state.pos,this.finishToken(T.semi);case 44:return++this.state.pos,this.finishToken(T.comma);case 91:return++this.state.pos,this.finishToken(T.bracketL);case 93:return++this.state.pos,this.finishToken(T.bracketR);case 123:return this.hasPlugin("flow")&&124===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.braceBarL,2):(++this.state.pos,this.finishToken(T.braceL));case 125:return++this.state.pos,this.finishToken(T.braceR);case 58:return this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.doubleColon,2):(++this.state.pos,this.finishToken(T.colon));case 63:return++this.state.pos,this.finishToken(T.question);case 64:return++this.state.pos,this.finishToken(T.at);case 96:return++this.state.pos,this.finishToken(T.backQuote);case 48:var t=this.input.charCodeAt(this.state.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 126:return this.finishOp(T.prefix,1)}this.raise(this.state.pos,"Unexpected character '"+u(e)+"'")},e.prototype.finishOp=function(e,t){var r=this.input.slice(this.state.pos,this.state.pos+t);return this.state.pos+=t,this.finishToken(e,r)},e.prototype.readRegexp=function(){for(var e=this.state.pos,t=void 0,r=void 0;;){this.state.pos>=this.input.length&&this.raise(e,"Unterminated regular expression");var n=this.input.charAt(this.state.pos);if(B.test(n)&&this.raise(e,"Unterminated regular expression"),t)t=!1;else{if("["===n)r=!0;else if("]"===n&&r)r=!1;else if("/"===n&&!r)break;t="\\"===n}++this.state.pos}var i=this.input.slice(e,this.state.pos);++this.state.pos;var s=this.readWord1();if(s){/^[gmsiyu]*$/.test(s)||this.raise(e,"Invalid regular expression flag")}return this.finishToken(T.regexp,{pattern:i,flags:s})},e.prototype.readInt=function(e,t){for(var r=this.state.pos,n=0,i=0,s=null==t?1/0:t;i=97?a-97+10:a>=65?a-65+10:a>=48&&a<=57?a-48:1/0)>=e)break;++this.state.pos,n=n*e+o}return this.state.pos===r||null!=t&&this.state.pos-r!==t?null:n},e.prototype.readRadixNumber=function(e){this.state.pos+=2;var t=this.readInt(e);return null==t&&this.raise(this.state.start+2,"Expected number in radix "+e),s(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number"),this.finishToken(T.num,t)},e.prototype.readNumber=function(e){var t=this.state.pos,r=48===this.input.charCodeAt(t),n=!1;e||null!==this.readInt(10)||this.raise(t,"Invalid number"),r&&this.state.pos==t+1&&(r=!1);var i=this.input.charCodeAt(this.state.pos);46!==i||r||(++this.state.pos,this.readInt(10),n=!0,i=this.input.charCodeAt(this.state.pos)),69!==i&&101!==i||r||(43!==(i=this.input.charCodeAt(++this.state.pos))&&45!==i||++this.state.pos,null===this.readInt(10)&&this.raise(t,"Invalid number"),n=!0),s(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number");var a=this.input.slice(t,this.state.pos),o=void 0;return n?o=parseFloat(a):r&&1!==a.length?this.state.strict?this.raise(t,"Invalid number"):o=/[89]/.test(a)?parseInt(a,10):parseInt(a,8):o=parseInt(a,10),this.finishToken(T.num,o)},e.prototype.readCodePoint=function(e){var t=void 0;if(123===this.input.charCodeAt(this.state.pos)){var r=++this.state.pos;if(t=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos,e),++this.state.pos,null===t)--this.state.invalidTemplateEscapePosition;else if(t>1114111){if(!e)return this.state.invalidTemplateEscapePosition=r-2,null;this.raise(r,"Code point out of bounds")}}else t=this.readHexChar(4,e);return t},e.prototype.readString=function(e){for(var t="",r=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var n=this.input.charCodeAt(this.state.pos);if(n===e)break;92===n?(t+=this.input.slice(r,this.state.pos),t+=this.readEscapedChar(!1),r=this.state.pos):(o(n)&&this.raise(this.state.start,"Unterminated string constant"),++this.state.pos)}return t+=this.input.slice(r,this.state.pos++),this.finishToken(T.string,t)},e.prototype.readTmplToken=function(){for(var e="",t=this.state.pos,r=!1;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated template");var n=this.input.charCodeAt(this.state.pos);if(96===n||36===n&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(T.template)?36===n?(this.state.pos+=2,this.finishToken(T.dollarBraceL)):(++this.state.pos,this.finishToken(T.backQuote)):(e+=this.input.slice(t,this.state.pos),this.finishToken(T.template,r?null:e));if(92===n){e+=this.input.slice(t,this.state.pos);var i=this.readEscapedChar(!0);null===i?r=!0:e+=i,t=this.state.pos}else if(o(n)){switch(e+=this.input.slice(t,this.state.pos),++this.state.pos,n){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(n)}++this.state.curLine,this.state.lineStart=this.state.pos,t=this.state.pos}else++this.state.pos}},e.prototype.readEscapedChar=function(e){var t=!e,r=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,r){case 110:return"\n";case 114:return"\r";case 120:var n=this.readHexChar(2,t);return null===n?null:String.fromCharCode(n);case 117:var i=this.readCodePoint(t);return null===i?null:u(i);case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:return this.state.lineStart=this.state.pos,++this.state.curLine,"";default:if(r>=48&&r<=55){var s=this.state.pos-1,a=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],o=parseInt(a,8);if(o>255&&(a=a.slice(0,-1),o=parseInt(a,8)),o>0){if(e)return this.state.invalidTemplateEscapePosition=s,null;this.state.strict?this.raise(s,"Octal literal in strict mode"):this.state.containsOctal||(this.state.containsOctal=!0,this.state.octalPosition=s)}return this.state.pos+=a.length-1,String.fromCharCode(o)}return String.fromCharCode(r)}},e.prototype.readHexChar=function(e,t){var r=this.state.pos,n=this.readInt(16,e);return null===n&&(t?this.raise(r,"Bad character escape sequence"):(this.state.pos=r-1,this.state.invalidTemplateEscapePosition=r-1)),n},e.prototype.readWord1=function(){this.state.containsEsc=!1;for(var e="",t=!0,r=this.state.pos;this.state.pos1&&void 0!==arguments[1]?arguments[1]:"Unexpected token";t&&"object"===(void 0===t?"undefined":A(t))&&t.label&&(t="Unexpected token, expected "+t.label),this.raise(null!=e?e:this.state.start,t)};var X=q.prototype;X.parseTopLevel=function(e,t){return t.sourceType=this.options.sourceType,this.parseBlockBody(t,!0,!0,T.eof),e.program=this.finishNode(t,"Program"),e.comments=this.state.comments,e.tokens=this.state.tokens,this.finishNode(e,"File")};var W={kind:"loop"},J={kind:"switch"};X.stmtToDirective=function(e){var t=e.expression,r=this.startNodeAt(t.start,t.loc.start),n=this.startNodeAt(e.start,e.loc.start),i=this.input.slice(t.start,t.end),s=r.value=i.slice(1,-1);return this.addExtra(r,"raw",i),this.addExtra(r,"rawValue",s),n.value=this.finishNodeAt(r,"DirectiveLiteral",t.end,t.loc.end),this.finishNodeAt(n,"Directive",e.end,e.loc.end)},X.parseStatement=function(e,t){this.match(T.at)&&this.parseDecorators(!0);var r=this.state.type,n=this.startNode();switch(r){case T._break:case T._continue:return this.parseBreakContinueStatement(n,r.keyword);case T._debugger:return this.parseDebuggerStatement(n);case T._do:return this.parseDoStatement(n);case T._for:return this.parseForStatement(n);case T._function:return e||this.unexpected(),this.parseFunctionStatement(n);case T._class:return e||this.unexpected(),this.parseClass(n,!0);case T._if:return this.parseIfStatement(n);case T._return:return this.parseReturnStatement(n);case T._switch:return this.parseSwitchStatement(n);case T._throw:return this.parseThrowStatement(n);case T._try:return this.parseTryStatement(n);case T._let:case T._const:e||this.unexpected();case T._var:return this.parseVarStatement(n,r);case T._while:return this.parseWhileStatement(n);case T._with:return this.parseWithStatement(n);case T.braceL:return this.parseBlock();case T.semi:return this.parseEmptyStatement(n);case T._export:case T._import:if(this.hasPlugin("dynamicImport")&&this.lookahead().type===T.parenL)break;return this.options.allowImportExportEverywhere||(t||this.raise(this.state.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.state.start,"'import' and 'export' may appear only with 'sourceType: \"module\"'")),r===T._import?this.parseImport(n):this.parseExport(n);case T.name:if("async"===this.state.value){var i=this.state.clone();if(this.next(),this.match(T._function)&&!this.canInsertSemicolon())return this.expect(T._function),this.parseFunction(n,!0,!1,!0);this.state=i}}var s=this.state.value,a=this.parseExpression();return r===T.name&&"Identifier"===a.type&&this.eat(T.colon)?this.parseLabeledStatement(n,s,a):this.parseExpressionStatement(n,a)},X.takeDecorators=function(e){this.state.decorators.length&&(e.decorators=this.state.decorators,this.state.decorators=[])},X.parseDecorators=function(e){for(;this.match(T.at);){var t=this.parseDecorator();this.state.decorators.push(t)}e&&this.match(T._export)||this.match(T._class)||this.raise(this.state.start,"Leading decorators must be attached to a class declaration")},X.parseDecorator=function(){this.hasPlugin("decorators")||this.unexpected();var e=this.startNode();return this.next(),e.expression=this.parseMaybeAssign(),this.finishNode(e,"Decorator")},X.parseBreakContinueStatement=function(e,t){var r="break"===t;this.next(),this.isLineTerminator()?e.label=null:this.match(T.name)?(e.label=this.parseIdentifier(),this.semicolon()):this.unexpected();var n=void 0;for(n=0;n=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}a.name===t&&this.raise(r.start,"Label '"+t+"' is already declared")}for(var o=this.state.type.isLoop?"loop":this.match(T._switch)?"switch":null,u=this.state.labels.length-1;u>=0;u--){var l=this.state.labels[u];if(l.statementStart!==e.start)break;l.statementStart=this.state.start,l.kind=o}return this.state.labels.push({name:t,kind:o,statementStart:this.state.start}),e.body=this.parseStatement(!0),this.state.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e){var t=this.startNode();return this.expect(T.braceL),this.parseBlockBody(t,e,!1,T.braceR),this.finishNode(t,"BlockStatement")},X.isValidDirective=function(e){return"ExpressionStatement"===e.type&&"StringLiteral"===e.expression.type&&!e.expression.extra.parenthesized},X.parseBlockBody=function(e,t,r,n){e.body=[],e.directives=[];for(var i=!1,s=void 0,a=void 0;!this.eat(n);){i||!this.state.containsOctal||a||(a=this.state.octalPosition);var o=this.parseStatement(!0,r);if(t&&!i&&this.isValidDirective(o)){var u=this.stmtToDirective(o);e.directives.push(u),void 0===s&&"use strict"===u.value.value&&(s=this.state.strict,this.setStrict(!0),a&&this.raise(a,"Octal literal in strict mode"))}else i=!0,e.body.push(o)}!1===s&&this.setStrict(!1)},X.parseFor=function(e,t){return e.init=t,this.expect(T.semi),e.test=this.match(T.semi)?null:this.parseExpression(),this.expect(T.semi),e.update=this.match(T.parenR)?null:this.parseExpression(),this.expect(T.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t,r){var n=void 0;return r?(this.eatContextual("of"),n="ForAwaitStatement"):(n=this.match(T._in)?"ForInStatement":"ForOfStatement",this.next()),e.left=t,e.right=this.parseExpression(),this.expect(T.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,n)},X.parseVar=function(e,t,r){for(e.declarations=[],e.kind=r.keyword;;){var n=this.startNode();if(this.parseVarHead(n),this.eat(T.eq)?n.init=this.parseMaybeAssign(t):r!==T._const||this.match(T._in)||this.isContextual("of")?"Identifier"===n.id.type||t&&(this.match(T._in)||this.isContextual("of"))?n.init=null:this.raise(this.state.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(T.comma))break}return e},X.parseVarHead=function(e){e.id=this.parseBindingAtom(),this.checkLVal(e.id,!0,void 0,"variable declaration")},X.parseFunction=function(e,t,r,n,i){var s=this.state.inMethod;return this.state.inMethod=!1,this.initFunction(e,n),this.match(T.star)&&(e.async&&!this.hasPlugin("asyncGenerators")?this.unexpected():(e.generator=!0,this.next())),!t||i||this.match(T.name)||this.match(T._yield)||this.unexpected(),(this.match(T.name)||this.match(T._yield))&&(e.id=this.parseBindingIdentifier()),this.parseFunctionParams(e),this.parseFunctionBody(e,r),this.state.inMethod=s,this.finishNode(e,t?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(T.parenL),e.params=this.parseBindingList(T.parenR)},X.parseClass=function(e,t,r){return this.next(),this.takeDecorators(e),this.parseClassId(e,t,r),this.parseClassSuper(e),this.parseClassBody(e),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.isClassProperty=function(){return this.match(T.eq)||this.match(T.semi)||this.match(T.braceR)},X.isClassMethod=function(){return this.match(T.parenL)},X.isNonstaticConstructor=function(e){return!(e.computed||e.static||"constructor"!==e.key.name&&"constructor"!==e.key.value)},X.parseClassBody=function(e){var t=this.state.strict;this.state.strict=!0;var r=!1,n=!1,i=[],s=this.startNode();for(s.body=[],this.expect(T.braceL);!this.eat(T.braceR);)if(this.eat(T.semi))i.length>0&&this.raise(this.state.lastTokEnd,"Decorators must not be followed by a semicolon");else if(this.match(T.at))i.push(this.parseDecorator());else{var a=this.startNode();if(i.length&&(a.decorators=i,i=[]),a.static=!1,this.match(T.name)&&"static"===this.state.value){var o=this.parseIdentifier(!0);if(this.isClassMethod()){a.kind="method",a.computed=!1,a.key=o,this.parseClassMethod(s,a,!1,!1);continue}if(this.isClassProperty()){a.computed=!1,a.key=o,s.body.push(this.parseClassProperty(a));continue}a.static=!0}if(this.eat(T.star))a.kind="method",this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't be a generator"),a.computed||!a.static||"prototype"!==a.key.name&&"prototype"!==a.key.value||this.raise(a.key.start,"Classes may not have static property named prototype"),this.parseClassMethod(s,a,!0,!1);else{var u=this.match(T.name),l=this.parsePropertyName(a);if(a.computed||!a.static||"prototype"!==a.key.name&&"prototype"!==a.key.value||this.raise(a.key.start,"Classes may not have static property named prototype"),this.isClassMethod())this.isNonstaticConstructor(a)?(n?this.raise(l.start,"Duplicate constructor in the same class"):a.decorators&&this.raise(a.start,"You can't attach decorators to a class constructor"),n=!0,a.kind="constructor"):a.kind="method",this.parseClassMethod(s,a,!1,!1);else if(this.isClassProperty())this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Classes may not have a non-static field named 'constructor'"),s.body.push(this.parseClassProperty(a));else if(u&&"async"===l.name&&!this.isLineTerminator()){var c=this.hasPlugin("asyncGenerators")&&this.eat(T.star);a.kind="method",this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't be an async function"),this.parseClassMethod(s,a,c,!0)}else!u||"get"!==l.name&&"set"!==l.name||this.isLineTerminator()&&this.match(T.star)?this.hasPlugin("classConstructorCall")&&u&&"call"===l.name&&this.match(T.name)&&"constructor"===this.state.value?(r?this.raise(a.start,"Duplicate constructor call in the same class"):a.decorators&&this.raise(a.start,"You can't attach decorators to a class constructor"),r=!0,a.kind="constructorCall",this.parsePropertyName(a),this.parseClassMethod(s,a,!1,!1)):this.isLineTerminator()?(this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Classes may not have a non-static field named 'constructor'"),s.body.push(this.parseClassProperty(a))):this.unexpected():(a.kind=l.name,this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't have get/set modifier"),this.parseClassMethod(s,a,!1,!1),this.checkGetterSetterParamCount(a))}}i.length&&this.raise(this.state.start,"You have trailing decorators with no method"),e.body=this.finishNode(s,"ClassBody"),this.state.strict=t},X.parseClassProperty=function(e){return this.state.inClassProperty=!0,this.match(T.eq)?(this.hasPlugin("classProperties")||this.unexpected(),this.next(),e.value=this.parseMaybeAssign()):e.value=null,this.semicolon(),this.state.inClassProperty=!1,this.finishNode(e,"ClassProperty")},X.parseClassMethod=function(e,t,r,n){this.parseMethod(t,r,n),e.body.push(this.finishNode(t,"ClassMethod"))},X.parseClassId=function(e,t,r){this.match(T.name)?e.id=this.parseIdentifier():r||!t?e.id=null:this.unexpected()},X.parseClassSuper=function(e){e.superClass=this.eat(T._extends)?this.parseExprSubscripts():null},X.parseExport=function(e){if(this.next(),this.match(T.star)){var t=this.startNode();if(this.next(),!this.hasPlugin("exportExtensions")||!this.eatContextual("as"))return this.parseExportFrom(e,!0),this.finishNode(e,"ExportAllDeclaration");t.exported=this.parseIdentifier(),e.specifiers=[this.finishNode(t,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(e),this.parseExportFrom(e,!0)}else if(this.hasPlugin("exportExtensions")&&this.isExportDefaultSpecifier()){var r=this.startNode();if(r.exported=this.parseIdentifier(!0),e.specifiers=[this.finishNode(r,"ExportDefaultSpecifier")],this.match(T.comma)&&this.lookahead().type===T.star){this.expect(T.comma);var n=this.startNode();this.expect(T.star),this.expectContextual("as"),n.exported=this.parseIdentifier(),e.specifiers.push(this.finishNode(n,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(e);this.parseExportFrom(e,!0)}else{if(this.eat(T._default)){var i=this.startNode(),s=!1;return this.eat(T._function)?i=this.parseFunction(i,!0,!1,!1,!0):this.match(T._class)?i=this.parseClass(i,!0,!0):(s=!0,i=this.parseMaybeAssign()),e.declaration=i,s&&this.semicolon(),this.checkExport(e,!0,!0),this.finishNode(e,"ExportDefaultDeclaration")}this.shouldParseExportDeclaration()?(e.specifiers=[],e.source=null,e.declaration=this.parseExportDeclaration(e)):(e.declaration=null,e.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(e))}return this.checkExport(e,!0),this.finishNode(e,"ExportNamedDeclaration")},X.parseExportDeclaration=function(){return this.parseStatement(!0)},X.isExportDefaultSpecifier=function(){if(this.match(T.name))return"async"!==this.state.value;if(!this.match(T._default))return!1;var e=this.lookahead();return e.type===T.comma||e.type===T.name&&"from"===e.value},X.parseExportSpecifiersMaybe=function(e){this.eat(T.comma)&&(e.specifiers=e.specifiers.concat(this.parseExportSpecifiers()))},X.parseExportFrom=function(e,t){this.eatContextual("from")?(e.source=this.match(T.string)?this.parseExprAtom():this.unexpected(),this.checkExport(e)):t?this.unexpected():e.source=null,this.semicolon()},X.shouldParseExportDeclaration=function(){return"var"===this.state.type.keyword||"const"===this.state.type.keyword||"let"===this.state.type.keyword||"function"===this.state.type.keyword||"class"===this.state.type.keyword||this.isContextual("async")},X.checkExport=function(e,t,r){if(t)if(r)this.checkDuplicateExports(e,"default");else if(e.specifiers&&e.specifiers.length)for(var n=e.specifiers,i=Array.isArray(n),s=0,n=i?n:n[Symbol.iterator]();;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a;this.checkDuplicateExports(o,o.exported.name)}else if(e.declaration)if("FunctionDeclaration"===e.declaration.type||"ClassDeclaration"===e.declaration.type)this.checkDuplicateExports(e,e.declaration.id.name);else if("VariableDeclaration"===e.declaration.type)for(var u=e.declaration.declarations,l=Array.isArray(u),c=0,u=l?u:u[Symbol.iterator]();;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if((c=u.next()).done)break;p=c.value}var h=p;this.checkDeclaration(h.id)}if(this.state.decorators.length){var f=e.declaration&&("ClassDeclaration"===e.declaration.type||"ClassExpression"===e.declaration.type);e.declaration&&f||this.raise(e.start,"You can only use decorators on an export when exporting a class"),this.takeDecorators(e.declaration)}},X.checkDeclaration=function(e){if("ObjectPattern"===e.type)for(var t=e.properties,r=Array.isArray(t),n=0,t=r?t:t[Symbol.iterator]();;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;this.checkDeclaration(s)}else if("ArrayPattern"===e.type)for(var a=e.elements,o=Array.isArray(a),u=0,a=o?a:a[Symbol.iterator]();;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var c=l;c&&this.checkDeclaration(c)}else"ObjectProperty"===e.type?this.checkDeclaration(e.value):"RestElement"===e.type||"RestProperty"===e.type?this.checkDeclaration(e.argument):"Identifier"===e.type&&this.checkDuplicateExports(e,e.name)},X.checkDuplicateExports=function(e,t){this.state.exportedIdentifiers.indexOf(t)>-1&&this.raiseDuplicateExportError(e,t),this.state.exportedIdentifiers.push(t)},X.raiseDuplicateExportError=function(e,t){this.raise(e.start,"default"===t?"Only one default export allowed per module.":"`"+t+"` has already been exported. Exported identifiers must be unique.")},X.parseExportSpecifiers=function(){var e=[],t=!0,r=void 0;for(this.expect(T.braceL);!this.eat(T.braceR);){if(t)t=!1;else if(this.expect(T.comma),this.eat(T.braceR))break;var n=this.match(T._default);n&&!r&&(r=!0);var i=this.startNode();i.local=this.parseIdentifier(n),i.exported=this.eatContextual("as")?this.parseIdentifier(!0):i.local.__clone(),e.push(this.finishNode(i,"ExportSpecifier"))}return r&&!this.isContextual("from")&&this.unexpected(),e},X.parseImport=function(e){return this.eat(T._import),this.match(T.string)?(e.specifiers=[],e.source=this.parseExprAtom()):(e.specifiers=[],this.parseImportSpecifiers(e),this.expectContextual("from"),e.source=this.match(T.string)?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifiers=function(e){var t=!0;if(this.match(T.name)){var r=this.state.start,n=this.state.startLoc;if(e.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(),r,n)),!this.eat(T.comma))return}if(this.match(T.star)){var i=this.startNode();return this.next(),this.expectContextual("as"),i.local=this.parseIdentifier(),this.checkLVal(i.local,!0,void 0,"import namespace specifier"),void e.specifiers.push(this.finishNode(i,"ImportNamespaceSpecifier"))}for(this.expect(T.braceL);!this.eat(T.braceR);){if(t)t=!1;else if(this.eat(T.colon)&&this.unexpected(null,"ES2015 named imports do not destructure. Use another statement for destructuring after the import."),this.expect(T.comma),this.eat(T.braceR))break;this.parseImportSpecifier(e)}},X.parseImportSpecifier=function(e){var t=this.startNode();t.imported=this.parseIdentifier(!0),this.eatContextual("as")?t.local=this.parseIdentifier():(this.checkReservedWord(t.imported.name,t.start,!0,!0),t.local=t.imported.__clone()),this.checkLVal(t.local,!0,void 0,"import specifier"),e.specifiers.push(this.finishNode(t,"ImportSpecifier"))},X.parseImportSpecifierDefault=function(e,t,r){var n=this.startNodeAt(t,r);return n.local=e,this.checkLVal(n.local,!0,void 0,"default import specifier"),this.finishNode(n,"ImportDefaultSpecifier")};var z=q.prototype;z.toAssignable=function(e,t,r){if(e)switch(e.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":e.type="ObjectPattern";for(var n=e.properties,i=Array.isArray(n),s=0,n=i?n:n[Symbol.iterator]();;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a;"ObjectMethod"===o.type?"get"===o.kind||"set"===o.kind?this.raise(o.key.start,"Object pattern can't contain getter or setter"):this.raise(o.key.start,"Object pattern can't contain methods"):this.toAssignable(o,t,"object destructuring pattern")}break;case"ObjectProperty":this.toAssignable(e.value,t,r);break;case"SpreadProperty":e.type="RestProperty";var u=e.argument;this.toAssignable(u,t,r);break;case"ArrayExpression":e.type="ArrayPattern",this.toAssignableList(e.elements,t,r);break;case"AssignmentExpression":"="===e.operator?(e.type="AssignmentPattern",delete e.operator):this.raise(e.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!t)break;default:var l="Invalid left-hand side"+(r?" in "+r:"expression");this.raise(e.start,l)}return e},z.toAssignableList=function(e,t,r){var n=e.length;if(n){var i=e[n-1];if(i&&"RestElement"===i.type)--n;else if(i&&"SpreadElement"===i.type){i.type="RestElement";var s=i.argument;this.toAssignable(s,t,r),"Identifier"!==s.type&&"MemberExpression"!==s.type&&"ArrayPattern"!==s.type&&this.unexpected(s.start),--n}}for(var a=0;a=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var l=u;"ObjectProperty"===l.type&&(l=l.value),this.checkLVal(l,t,r,"object destructuring pattern")}break;case"ArrayPattern":for(var c=e.elements,p=Array.isArray(c),h=0,c=p?c:c[Symbol.iterator]();;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if((h=c.next()).done)break;f=h.value}var d=f;d&&this.checkLVal(d,t,r,"array destructuring pattern")}break;case"AssignmentPattern":this.checkLVal(e.left,t,r,"assignment pattern");break;case"RestProperty":this.checkLVal(e.argument,t,r,"rest property");break;case"RestElement":this.checkLVal(e.argument,t,r,"rest element");break;default:var m=(t?"Binding invalid":"Invalid")+" left-hand side"+(n?" in "+n:"expression");this.raise(e.start,m)}};var Y=q.prototype;Y.checkPropClash=function(e,t){if(!e.computed&&!e.kind){var r=e.key;"__proto__"===("Identifier"===r.type?r.name:String(r.value))&&(t.proto&&this.raise(r.start,"Redefinition of __proto__ property"),t.proto=!0)}},Y.getExpression=function(){this.nextToken();var e=this.parseExpression();return this.match(T.eof)||this.unexpected(),e},Y.parseExpression=function(e,t){var r=this.state.start,n=this.state.startLoc,i=this.parseMaybeAssign(e,t);if(this.match(T.comma)){var s=this.startNodeAt(r,n);for(s.expressions=[i];this.eat(T.comma);)s.expressions.push(this.parseMaybeAssign(e,t));return this.toReferencedList(s.expressions),this.finishNode(s,"SequenceExpression")}return i},Y.parseMaybeAssign=function(e,t,r,n){var i=this.state.start,s=this.state.startLoc;if(this.match(T._yield)&&this.state.inGenerator){var a=this.parseYield();return r&&(a=r.call(this,a,i,s)),a}var o=void 0;t?o=!1:(t={start:0},o=!0),(this.match(T.parenL)||this.match(T.name))&&(this.state.potentialArrowAt=this.state.start);var u=this.parseMaybeConditional(e,t,n);if(r&&(u=r.call(this,u,i,s)),this.state.type.isAssign){var l=this.startNodeAt(i,s);if(l.operator=this.state.value,l.left=this.match(T.eq)?this.toAssignable(u,void 0,"assignment expression"):u,t.start=0,this.checkLVal(u,void 0,void 0,"assignment expression"),u.extra&&u.extra.parenthesized){var c=void 0;"ObjectPattern"===u.type?c="`({a}) = 0` use `({a} = 0)`":"ArrayPattern"===u.type&&(c="`([a]) = 0` use `([a] = 0)`"),c&&this.raise(u.start,"You're trying to assign to a parenthesized expression, eg. instead of "+c)}return this.next(),l.right=this.parseMaybeAssign(e),this.finishNode(l,"AssignmentExpression")}return o&&t.start&&this.unexpected(t.start),u},Y.parseMaybeConditional=function(e,t,r){var n=this.state.start,i=this.state.startLoc,s=this.parseExprOps(e,t);return t&&t.start?s:this.parseConditional(s,e,n,i,r)},Y.parseConditional=function(e,t,r,n){if(this.eat(T.question)){var i=this.startNodeAt(r,n);return i.test=e,i.consequent=this.parseMaybeAssign(),this.expect(T.colon),i.alternate=this.parseMaybeAssign(t),this.finishNode(i,"ConditionalExpression")}return e},Y.parseExprOps=function(e,t){var r=this.state.start,n=this.state.startLoc,i=this.parseMaybeUnary(t);return t&&t.start?i:this.parseExprOp(i,r,n,-1,e)},Y.parseExprOp=function(e,t,r,n,i){var s=this.state.type.binop;if(!(null==s||i&&this.match(T._in))&&s>n){var a=this.startNodeAt(t,r);a.left=e,a.operator=this.state.value,"**"!==a.operator||"UnaryExpression"!==e.type||!e.extra||e.extra.parenthesizedArgument||e.extra.parenthesized||this.raise(e.argument.start,"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");var o=this.state.type;this.next();var u=this.state.start,l=this.state.startLoc;return a.right=this.parseExprOp(this.parseMaybeUnary(),u,l,o.rightAssociative?s-1:s,i),this.finishNode(a,o===T.logicalOR||o===T.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(a,t,r,n,i)}return e},Y.parseMaybeUnary=function(e){if(this.state.type.prefix){var t=this.startNode(),r=this.match(T.incDec);t.operator=this.state.value,t.prefix=!0,this.next();var n=this.state.type;return t.argument=this.parseMaybeUnary(),this.addExtra(t,"parenthesizedArgument",!(n!==T.parenL||t.argument.extra&&t.argument.extra.parenthesized)),e&&e.start&&this.unexpected(e.start),r?this.checkLVal(t.argument,void 0,void 0,"prefix operation"):this.state.strict&&"delete"===t.operator&&"Identifier"===t.argument.type&&this.raise(t.start,"Deleting local variable in strict mode"),this.finishNode(t,r?"UpdateExpression":"UnaryExpression")}var i=this.state.start,s=this.state.startLoc,a=this.parseExprSubscripts(e);if(e&&e.start)return a;for(;this.state.type.postfix&&!this.canInsertSemicolon();){var o=this.startNodeAt(i,s);o.operator=this.state.value,o.prefix=!1,o.argument=a,this.checkLVal(a,void 0,void 0,"postfix operation"),this.next(),a=this.finishNode(o,"UpdateExpression")}return a},Y.parseExprSubscripts=function(e){var t=this.state.start,r=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseExprAtom(e);return"ArrowFunctionExpression"===i.type&&i.start===n?i:e&&e.start?i:this.parseSubscripts(i,t,r)},Y.parseSubscripts=function(e,t,r,n){for(;;){if(!n&&this.eat(T.doubleColon)){var i=this.startNodeAt(t,r);return i.object=e,i.callee=this.parseNoCallExpr(),this.parseSubscripts(this.finishNode(i,"BindExpression"),t,r,n)}if(this.eat(T.dot)){var s=this.startNodeAt(t,r);s.object=e,s.property=this.parseIdentifier(!0),s.computed=!1,e=this.finishNode(s,"MemberExpression")}else if(this.eat(T.bracketL)){var a=this.startNodeAt(t,r);a.object=e,a.property=this.parseExpression(),a.computed=!0,this.expect(T.bracketR),e=this.finishNode(a,"MemberExpression")}else if(!n&&this.match(T.parenL)){var o=this.state.potentialArrowAt===e.start&&"Identifier"===e.type&&"async"===e.name&&!this.canInsertSemicolon();this.next();var u=this.startNodeAt(t,r);if(u.callee=e,u.arguments=this.parseCallExpressionArguments(T.parenR,o),"Import"===u.callee.type&&1!==u.arguments.length&&this.raise(u.start,"import() requires exactly one argument"),e=this.finishNode(u,"CallExpression"),o&&this.shouldParseAsyncArrow())return this.parseAsyncArrowFromCallExpression(this.startNodeAt(t,r),u);this.toReferencedList(u.arguments)}else{if(!this.match(T.backQuote))return e;var l=this.startNodeAt(t,r);l.tag=e,l.quasi=this.parseTemplate(!0),e=this.finishNode(l,"TaggedTemplateExpression")}}},Y.parseCallExpressionArguments=function(e,t){for(var r=[],n=void 0,i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(T.comma),this.eat(e))break;this.match(T.parenL)&&!n&&(n=this.state.start),r.push(this.parseExprListItem(!1,t?{start:0}:void 0,t?{start:0}:void 0))}return t&&n&&this.shouldParseAsyncArrow()&&this.unexpected(),r},Y.shouldParseAsyncArrow=function(){return this.match(T.arrow)},Y.parseAsyncArrowFromCallExpression=function(e,t){return this.expect(T.arrow),this.parseArrowExpression(e,t.arguments,!0)},Y.parseNoCallExpr=function(){var e=this.state.start,t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),e,t,!0)},Y.parseExprAtom=function(e){var t=this.state.potentialArrowAt===this.state.start,r=void 0;switch(this.state.type){case T._super:return this.state.inMethod||this.state.inClassProperty||this.options.allowSuperOutsideMethod||this.raise(this.state.start,"'super' outside of function or class"),r=this.startNode(),this.next(),this.match(T.parenL)||this.match(T.bracketL)||this.match(T.dot)||this.unexpected(),this.match(T.parenL)&&"constructor"!==this.state.inMethod&&!this.options.allowSuperOutsideMethod&&this.raise(r.start,"super() outside of class constructor"),this.finishNode(r,"Super");case T._import:return this.hasPlugin("dynamicImport")||this.unexpected(),r=this.startNode(),this.next(),this.match(T.parenL)||this.unexpected(null,T.parenL),this.finishNode(r,"Import");case T._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case T._yield:this.state.inGenerator&&this.unexpected();case T.name:r=this.startNode();var n="await"===this.state.value&&this.state.inAsync,i=this.shouldAllowYieldIdentifier(),s=this.parseIdentifier(n||i);if("await"===s.name){if(this.state.inAsync||this.inModule)return this.parseAwait(r)}else{if("async"===s.name&&this.match(T._function)&&!this.canInsertSemicolon())return this.next(),this.parseFunction(r,!1,!1,!0);if(t&&"async"===s.name&&this.match(T.name)){var a=[this.parseIdentifier()];return this.expect(T.arrow),this.parseArrowExpression(r,a,!0)}}return t&&!this.canInsertSemicolon()&&this.eat(T.arrow)?this.parseArrowExpression(r,[s]):s;case T._do:if(this.hasPlugin("doExpressions")){var o=this.startNode();this.next();var u=this.state.inFunction,l=this.state.labels;return this.state.labels=[],this.state.inFunction=!1,o.body=this.parseBlock(!1,!0),this.state.inFunction=u,this.state.labels=l,this.finishNode(o,"DoExpression")}case T.regexp:var c=this.state.value;return r=this.parseLiteral(c.value,"RegExpLiteral"),r.pattern=c.pattern,r.flags=c.flags,r;case T.num:return this.parseLiteral(this.state.value,"NumericLiteral");case T.string:return this.parseLiteral(this.state.value,"StringLiteral");case T._null:return r=this.startNode(),this.next(),this.finishNode(r,"NullLiteral");case T._true:case T._false:return r=this.startNode(),r.value=this.match(T._true),this.next(),this.finishNode(r,"BooleanLiteral");case T.parenL:return this.parseParenAndDistinguishExpression(null,null,t);case T.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(T.bracketR,!0,e),this.toReferencedList(r.elements),this.finishNode(r,"ArrayExpression");case T.braceL:return this.parseObj(!1,e);case T._function:return this.parseFunctionExpression();case T.at:this.parseDecorators();case T._class:return r=this.startNode(),this.takeDecorators(r),this.parseClass(r,!1);case T._new:return this.parseNew();case T.backQuote:return this.parseTemplate(!1);case T.doubleColon:r=this.startNode(),this.next(),r.object=null;var p=r.callee=this.parseNoCallExpr();if("MemberExpression"===p.type)return this.finishNode(r,"BindExpression");this.raise(p.start,"Binding should be performed on object property.");default:this.unexpected()}},Y.parseFunctionExpression=function(){var e=this.startNode(),t=this.parseIdentifier(!0);return this.state.inGenerator&&this.eat(T.dot)&&this.hasPlugin("functionSent")?this.parseMetaProperty(e,t,"sent"):this.parseFunction(e,!1)},Y.parseMetaProperty=function(e,t,r){return e.meta=t,e.property=this.parseIdentifier(!0),e.property.name!==r&&this.raise(e.property.start,"The only valid meta property for new is "+t.name+"."+r),this.finishNode(e,"MetaProperty")},Y.parseLiteral=function(e,t,r,n){r=r||this.state.start,n=n||this.state.startLoc;var i=this.startNodeAt(r,n);return this.addExtra(i,"rawValue",e),this.addExtra(i,"raw",this.input.slice(r,this.state.end)),i.value=e,this.next(),this.finishNode(i,t)},Y.parseParenExpression=function(){this.expect(T.parenL);var e=this.parseExpression();return this.expect(T.parenR),e},Y.parseParenAndDistinguishExpression=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;var n=void 0;this.expect(T.parenL);for(var i=this.state.start,s=this.state.startLoc,a=[],o={start:0},u={start:0},l=!0,c=void 0,p=void 0;!this.match(T.parenR);){if(l)l=!1;else if(this.expect(T.comma,u.start||null),this.match(T.parenR)){p=this.state.start;break}if(this.match(T.ellipsis)){var h=this.state.start,f=this.state.startLoc;c=this.state.start,a.push(this.parseParenItem(this.parseRest(),h,f));break}a.push(this.parseMaybeAssign(!1,o,this.parseParenItem,u))}var d=this.state.start,m=this.state.startLoc;this.expect(T.parenR);var y=this.startNodeAt(e,t);if(r&&this.shouldParseArrow()&&(y=this.parseArrow(y))){for(var g=a,b=Array.isArray(g),v=0,g=b?g:g[Symbol.iterator]();;){var x;if(b){if(v>=g.length)break;x=g[v++]}else{if((v=g.next()).done)break;x=v.value}var E=x;E.extra&&E.extra.parenthesized&&this.unexpected(E.extra.parenStart)}return this.parseArrowExpression(y,a)}return a.length||this.unexpected(this.state.lastTokStart),p&&this.unexpected(p),c&&this.unexpected(c),o.start&&this.unexpected(o.start),u.start&&this.unexpected(u.start),a.length>1?((n=this.startNodeAt(i,s)).expressions=a,this.toReferencedList(n.expressions),this.finishNodeAt(n,"SequenceExpression",d,m)):n=a[0],this.addExtra(n,"parenthesized",!0),this.addExtra(n,"parenStart",e),n},Y.shouldParseArrow=function(){return!this.canInsertSemicolon()},Y.parseArrow=function(e){if(this.eat(T.arrow))return e},Y.parseParenItem=function(e){return e},Y.parseNew=function(){var e=this.startNode(),t=this.parseIdentifier(!0);if(this.eat(T.dot)){var r=this.parseMetaProperty(e,t,"target");return this.state.inFunction||this.raise(r.property.start,"new.target can only be used in functions"),r}return e.callee=this.parseNoCallExpr(),this.eat(T.parenL)?(e.arguments=this.parseExprList(T.parenR),this.toReferencedList(e.arguments)):e.arguments=[],this.finishNode(e,"NewExpression")},Y.parseTemplateElement=function(e){var t=this.startNode();return null===this.state.value&&(e&&this.hasPlugin("templateInvalidEscapes")?this.state.invalidTemplateEscapePosition=null:this.raise(this.state.invalidTemplateEscapePosition,"Invalid escape sequence in template")),t.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),t.tail=this.match(T.backQuote),this.finishNode(t,"TemplateElement")},Y.parseTemplate=function(e){var t=this.startNode();this.next(),t.expressions=[];var r=this.parseTemplateElement(e);for(t.quasis=[r];!r.tail;)this.expect(T.dollarBraceL),t.expressions.push(this.parseExpression()),this.expect(T.braceR),t.quasis.push(r=this.parseTemplateElement(e));return this.next(),this.finishNode(t,"TemplateLiteral")},Y.parseObj=function(e,t){var r=[],n=Object.create(null),i=!0,s=this.startNode();s.properties=[],this.next();for(var a=null;!this.eat(T.braceR);){if(i)i=!1;else if(this.expect(T.comma),this.eat(T.braceR))break;for(;this.match(T.at);)r.push(this.parseDecorator());var o=this.startNode(),u=!1,l=!1,c=void 0,p=void 0;if(r.length&&(o.decorators=r,r=[]),this.hasPlugin("objectRestSpread")&&this.match(T.ellipsis)){if(o=this.parseSpread(e?{start:0}:void 0),o.type=e?"RestProperty":"SpreadProperty",e&&this.toAssignable(o.argument,!0,"object pattern"),s.properties.push(o),!e)continue;var h=this.state.start;if(null===a){if(this.eat(T.braceR))break;if(this.match(T.comma)&&this.lookahead().type===T.braceR)continue;a=h;continue}this.unexpected(a,"Cannot have multiple rest elements when destructuring")}if(o.method=!1,o.shorthand=!1,(e||t)&&(c=this.state.start,p=this.state.startLoc),e||(u=this.eat(T.star)),!e&&this.isContextual("async")){u&&this.unexpected();var f=this.parseIdentifier();this.match(T.colon)||this.match(T.parenL)||this.match(T.braceR)||this.match(T.eq)||this.match(T.comma)?(o.key=f,o.computed=!1):(l=!0,this.hasPlugin("asyncGenerators")&&(u=this.eat(T.star)),this.parsePropertyName(o))}else this.parsePropertyName(o);this.parseObjPropValue(o,c,p,u,l,e,t),this.checkPropClash(o,n),o.shorthand&&this.addExtra(o,"shorthand",!0),s.properties.push(o)}return null!==a&&this.unexpected(a,"The rest element has to be the last element when destructuring"),r.length&&this.raise(this.state.start,"You have trailing decorators with no property"),this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},Y.isGetterOrSetterMethod=function(e,t){return!t&&!e.computed&&"Identifier"===e.key.type&&("get"===e.key.name||"set"===e.key.name)&&(this.match(T.string)||this.match(T.num)||this.match(T.bracketL)||this.match(T.name)||this.state.type.keyword)},Y.checkGetterSetterParamCount=function(e){var t="get"===e.kind?0:1;if(e.params.length!==t){var r=e.start;"get"===e.kind?this.raise(r,"getter should have no params"):this.raise(r,"setter should have exactly one param")}},Y.parseObjectMethod=function(e,t,r,n){return r||t||this.match(T.parenL)?(n&&this.unexpected(),e.kind="method",e.method=!0,this.parseMethod(e,t,r),this.finishNode(e,"ObjectMethod")):this.isGetterOrSetterMethod(e,n)?((t||r)&&this.unexpected(),e.kind=e.key.name,this.parsePropertyName(e),this.parseMethod(e),this.checkGetterSetterParamCount(e),this.finishNode(e,"ObjectMethod")):void 0},Y.parseObjectProperty=function(e,t,r,n,i){return this.eat(T.colon)?(e.value=n?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,i),this.finishNode(e,"ObjectProperty")):e.computed||"Identifier"!==e.key.type?void 0:(this.checkReservedWord(e.key.name,e.key.start,!0,!0),n?e.value=this.parseMaybeDefault(t,r,e.key.__clone()):this.match(T.eq)&&i?(i.start||(i.start=this.state.start),e.value=this.parseMaybeDefault(t,r,e.key.__clone())):e.value=e.key.__clone(),e.shorthand=!0,this.finishNode(e,"ObjectProperty"))},Y.parseObjPropValue=function(e,t,r,n,i,s,a){var o=this.parseObjectMethod(e,n,i,s)||this.parseObjectProperty(e,t,r,s,a);return o||this.unexpected(),o},Y.parsePropertyName=function(e){if(this.eat(T.bracketL))e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(T.bracketR);else{e.computed=!1;var t=this.state.inPropertyName;this.state.inPropertyName=!0,e.key=this.match(T.num)||this.match(T.string)?this.parseExprAtom():this.parseIdentifier(!0),this.state.inPropertyName=t}return e.key},Y.initFunction=function(e,t){e.id=null,e.generator=!1,e.expression=!1,e.async=!!t},Y.parseMethod=function(e,t,r){var n=this.state.inMethod;return this.state.inMethod=e.kind||!0,this.initFunction(e,r),this.expect(T.parenL),e.params=this.parseBindingList(T.parenR),e.generator=!!t,this.parseFunctionBody(e),this.state.inMethod=n,e},Y.parseArrowExpression=function(e,t,r){return this.initFunction(e,r),e.params=this.toAssignableList(t,!0,"arrow function parameters"),this.parseFunctionBody(e,!0),this.finishNode(e,"ArrowFunctionExpression")},Y.isStrictBody=function(e,t){if(!t&&e.body.directives.length)for(var r=e.body.directives,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}if("use strict"===s.value.value)return!0}return!1},Y.parseFunctionBody=function(e,t){var r=t&&!this.match(T.braceL),n=this.state.inAsync;if(this.state.inAsync=e.async,r)e.body=this.parseMaybeAssign(),e.expression=!0;else{var i=this.state.inFunction,s=this.state.inGenerator,a=this.state.labels;this.state.inFunction=!0,this.state.inGenerator=e.generator,this.state.labels=[],e.body=this.parseBlock(!0),e.expression=!1,this.state.inFunction=i,this.state.inGenerator=s,this.state.labels=a}this.state.inAsync=n;var o=this.isStrictBody(e,r),u=this.state.strict||t||o;if(o&&e.id&&"Identifier"===e.id.type&&"yield"===e.id.name&&this.raise(e.id.start,"Binding yield in strict mode"),u){var l=Object.create(null),c=this.state.strict;o&&(this.state.strict=!0),e.id&&this.checkLVal(e.id,!0,void 0,"function name");for(var p=e.params,h=Array.isArray(p),f=0,p=h?p:p[Symbol.iterator]();;){var d;if(h){if(f>=p.length)break;d=p[f++]}else{if((f=p.next()).done)break;d=f.value}var m=d;o&&"Identifier"!==m.type&&this.raise(m.start,"Non-simple parameter in strict mode"),this.checkLVal(m,!0,l,"function parameter list")}this.state.strict=c}},Y.parseExprList=function(e,t,r){for(var n=[],i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(T.comma),this.eat(e))break;n.push(this.parseExprListItem(t,r))}return n},Y.parseExprListItem=function(e,t,r){return e&&this.match(T.comma)?null:this.match(T.ellipsis)?this.parseSpread(t):this.parseMaybeAssign(!1,t,this.parseParenItem,r)},Y.parseIdentifier=function(e){var t=this.startNode();return e||this.checkReservedWord(this.state.value,this.state.start,!!this.state.type.keyword,!1),this.match(T.name)?t.name=this.state.value:this.state.type.keyword?t.name=this.state.type.keyword:this.unexpected(),!e&&"await"===t.name&&this.state.inAsync&&this.raise(t.start,"invalid use of await inside of an async function"),t.loc.identifierName=t.name,this.next(),this.finishNode(t,"Identifier")},Y.checkReservedWord=function(e,t,r,n){(this.isReservedWord(e)||r&&this.isKeyword(e))&&this.raise(t,e+" is a reserved word"),this.state.strict&&(f.strict(e)||n&&f.strictBind(e))&&this.raise(t,e+" is a reserved word in strict mode")},Y.parseAwait=function(e){return this.state.inAsync||this.unexpected(),this.match(T.star)&&this.raise(e.start,"await* has been removed from the async functions proposal. Use Promise.all() instead."),e.argument=this.parseMaybeUnary(),this.finishNode(e,"AwaitExpression")},Y.parseYield=function(){var e=this.startNode();return this.next(),this.match(T.semi)||this.canInsertSemicolon()||!this.match(T.star)&&!this.state.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(T.star),e.argument=this.parseMaybeAssign()),this.finishNode(e,"YieldExpression")};var H=q.prototype,$=["leadingComments","trailingComments","innerComments"],Q=function(){function e(t,r,n){D(this,e),this.type="",this.start=t,this.end=0,this.loc=new M(r),n&&(this.loc.filename=n)}return e.prototype.__clone=function(){var t=new e;for(var r in this)$.indexOf(r)<0&&(t[r]=this[r]);return t},e}();H.startNode=function(){return new Q(this.state.start,this.state.startLoc,this.filename)},H.startNodeAt=function(e,t){return new Q(e,t,this.filename)},H.finishNode=function(e,t){return l.call(this,e,t,this.state.lastTokEnd,this.state.lastTokEndLoc)},H.finishNodeAt=function(e,t,r,n){return l.call(this,e,t,r,n)};q.prototype.raise=function(e,t){var r=function(e,t){for(var r=1,n=0;;){O.lastIndex=n;var i=O.exec(e);if(!(i&&i.index0)){var t=this.state.commentStack,r=void 0,n=void 0,i=void 0,s=void 0,a=void 0;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=e.end?(i=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else{var o=c(t);t.length>0&&o.trailingComments&&o.trailingComments[0].start>=e.end&&(i=o.trailingComments,o.trailingComments=null)}for(t.length>0&&c(t).start>=e.start&&(r=t.pop());t.length>0&&c(t).start>=e.start;)n=t.pop();if(!n&&r&&(n=r),r&&this.state.leadingComments.length>0){var u=c(this.state.leadingComments);if("ObjectProperty"===r.type){if(u.start>=e.start&&this.state.commentPreviousNode){for(a=0;a0&&(r.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}else if("CallExpression"===e.type&&e.arguments&&e.arguments.length){var l=c(e.arguments);l&&u.start>=l.start&&u.end<=e.end&&this.state.commentPreviousNode&&this.state.leadingComments.length>0&&(l.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}if(n){if(n.leadingComments)if(n!==e&&c(n.leadingComments).end<=e.start)e.leadingComments=n.leadingComments,n.leadingComments=null;else for(s=n.leadingComments.length-2;s>=0;--s)if(n.leadingComments[s].end<=e.start){e.leadingComments=n.leadingComments.splice(0,s+1);break}}else if(this.state.leadingComments.length>0)if(c(this.state.leadingComments).end<=e.start){if(this.state.commentPreviousNode)for(a=0;a0&&(e.leadingComments=this.state.leadingComments,this.state.leadingComments=[])}else{for(s=0;se.start);s++);e.leadingComments=this.state.leadingComments.slice(0,s),0===e.leadingComments.length&&(e.leadingComments=null),0===(i=this.state.leadingComments.slice(s)).length&&(i=null)}this.state.commentPreviousNode=e,i&&(i.length&&i[0].start>=e.start&&c(i).end<=e.end?e.innerComments=i:e.trailingComments=i),t.push(e)}};var ee=q.prototype;ee.estreeParseRegExpLiteral=function(e){var t=e.pattern,r=e.flags,n=null;try{n=new RegExp(t,r)}catch(e){}var i=this.estreeParseLiteral(n);return i.regex={pattern:t,flags:r},i},ee.estreeParseLiteral=function(e){return this.parseLiteral(e,"Literal")},ee.directiveToStmt=function(e){var t=e.value,r=this.startNodeAt(e.start,e.loc.start),n=this.startNodeAt(t.start,t.loc.start);return n.value=t.value,n.raw=t.extra.raw,r.expression=this.finishNodeAt(n,"Literal",t.end,t.loc.end),r.directive=t.extra.raw.slice(1,-1),this.finishNodeAt(r,"ExpressionStatement",e.end,e.loc.end)};var te=["any","mixed","empty","bool","boolean","number","string","void","null"],re=q.prototype;re.flowParseTypeInitialiser=function(e){var t=this.state.inType;this.state.inType=!0,this.expect(e||T.colon);var r=this.flowParseType();return this.state.inType=t,r},re.flowParsePredicate=function(){var e=this.startNode(),t=this.state.startLoc,r=this.state.start;this.expect(T.modulo);var n=this.state.startLoc;return this.expectContextual("checks"),t.line===n.line&&t.column===n.column-1||this.raise(r,"Spaces between ´%´ and ´checks´ are not allowed here."),this.eat(T.parenL)?(e.expression=this.parseExpression(),this.expect(T.parenR),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")},re.flowParseTypeAndPredicateInitialiser=function(){var e=this.state.inType;this.state.inType=!0,this.expect(T.colon);var t=null,r=null;return this.match(T.modulo)?(this.state.inType=e,r=this.flowParsePredicate()):(t=this.flowParseType(),this.state.inType=e,this.match(T.modulo)&&(r=this.flowParsePredicate())),[t,r]},re.flowParseDeclareClass=function(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},re.flowParseDeclareFunction=function(e){this.next();var t=e.id=this.parseIdentifier(),r=this.startNode(),n=this.startNode();this.isRelational("<")?r.typeParameters=this.flowParseTypeParameterDeclaration():r.typeParameters=null,this.expect(T.parenL);var i=this.flowParseFunctionTypeParams();r.params=i.params,r.rest=i.rest,this.expect(T.parenR);var s=null,a=this.flowParseTypeAndPredicateInitialiser();return r.returnType=a[0],s=a[1],n.typeAnnotation=this.finishNode(r,"FunctionTypeAnnotation"),n.predicate=s,t.typeAnnotation=this.finishNode(n,"TypeAnnotation"),this.finishNode(t,t.type),this.semicolon(),this.finishNode(e,"DeclareFunction")},re.flowParseDeclare=function(e){return this.match(T._class)?this.flowParseDeclareClass(e):this.match(T._function)?this.flowParseDeclareFunction(e):this.match(T._var)?this.flowParseDeclareVariable(e):this.isContextual("module")?this.lookahead().type===T.dot?this.flowParseDeclareModuleExports(e):this.flowParseDeclareModule(e):this.isContextual("type")?this.flowParseDeclareTypeAlias(e):this.isContextual("opaque")?this.flowParseDeclareOpaqueType(e):this.isContextual("interface")?this.flowParseDeclareInterface(e):this.match(T._export)?this.flowParseDeclareExportDeclaration(e):void this.unexpected()},re.flowParseDeclareExportDeclaration=function(e){if(this.expect(T._export),this.isContextual("opaque"))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");throw this.unexpected()},re.flowParseDeclareVariable=function(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(e,"DeclareVariable")},re.flowParseDeclareModule=function(e){this.next(),this.match(T.string)?e.id=this.parseExprAtom():e.id=this.parseIdentifier();var t=e.body=this.startNode(),r=t.body=[];for(this.expect(T.braceL);!this.match(T.braceR);){var n=this.startNode();if(this.match(T._import)){var i=this.lookahead();"type"!==i.value&&"typeof"!==i.value&&this.unexpected(null,"Imports within a `declare module` body must always be `import type` or `import typeof`"),this.parseImport(n)}else this.expectContextual("declare","Only declares and type imports are allowed inside declare module"),n=this.flowParseDeclare(n,!0);r.push(n)}return this.expect(T.braceR),this.finishNode(t,"BlockStatement"),this.finishNode(e,"DeclareModule")},re.flowParseDeclareModuleExports=function(e){return this.expectContextual("module"),this.expect(T.dot),this.expectContextual("exports"),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")},re.flowParseDeclareTypeAlias=function(e){return this.next(),this.flowParseTypeAlias(e),this.finishNode(e,"DeclareTypeAlias")},re.flowParseDeclareOpaqueType=function(e){return this.next(),this.flowParseOpaqueType(e,!0),this.finishNode(e,"DeclareOpaqueType")},re.flowParseDeclareInterface=function(e){return this.next(),this.flowParseInterfaceish(e),this.finishNode(e,"DeclareInterface")},re.flowParseInterfaceish=function(e){if(e.id=this.parseIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],e.mixins=[],this.eat(T._extends))do{e.extends.push(this.flowParseInterfaceExtends())}while(this.eat(T.comma));if(this.isContextual("mixins")){this.next();do{e.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(T.comma))}e.body=this.flowParseObjectType(!0,!1,!1)},re.flowParseInterfaceExtends=function(){var e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")},re.flowParseInterface=function(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},re.flowParseRestrictedIdentifier=function(e){return te.indexOf(this.state.value)>-1&&this.raise(this.state.start,"Cannot overwrite primitive type "+this.state.value),this.parseIdentifier(e)},re.flowParseTypeAlias=function(e){return e.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(T.eq),this.semicolon(),this.finishNode(e,"TypeAlias")},re.flowParseOpaqueType=function(e,t){return this.expectContextual("type"),e.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(T.colon)&&(e.supertype=this.flowParseTypeInitialiser(T.colon)),e.impltype=null,t||(e.impltype=this.flowParseTypeInitialiser(T.eq)),this.semicolon(),this.finishNode(e,"OpaqueType")},re.flowParseTypeParameter=function(){var e=this.startNode(),t=this.flowParseVariance(),r=this.flowParseTypeAnnotatableIdentifier();return e.name=r.name,e.variance=t,e.bound=r.typeAnnotation,this.match(T.eq)&&(this.eat(T.eq),e.default=this.flowParseType()),this.finishNode(e,"TypeParameter")},re.flowParseTypeParameterDeclaration=function(){var e=this.state.inType,t=this.startNode();t.params=[],this.state.inType=!0,this.isRelational("<")||this.match(T.jsxTagStart)?this.next():this.unexpected();do{t.params.push(this.flowParseTypeParameter()),this.isRelational(">")||this.expect(T.comma)}while(!this.isRelational(">"));return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterDeclaration")},re.flowParseTypeParameterInstantiation=function(){var e=this.startNode(),t=this.state.inType;for(e.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)e.params.push(this.flowParseType()),this.isRelational(">")||this.expect(T.comma);return this.expectRelational(">"),this.state.inType=t,this.finishNode(e,"TypeParameterInstantiation")},re.flowParseObjectPropertyKey=function(){return this.match(T.num)||this.match(T.string)?this.parseExprAtom():this.parseIdentifier(!0)},re.flowParseObjectTypeIndexer=function(e,t,r){return e.static=t,this.expect(T.bracketL),this.lookahead().type===T.colon?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(T.bracketR),e.value=this.flowParseTypeInitialiser(),e.variance=r,this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeIndexer")},re.flowParseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(T.parenL);!this.match(T.parenR)&&!this.match(T.ellipsis);)e.params.push(this.flowParseFunctionTypeParam()),this.match(T.parenR)||this.expect(T.comma);return this.eat(T.ellipsis)&&(e.rest=this.flowParseFunctionTypeParam()),this.expect(T.parenR),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")},re.flowParseObjectTypeMethod=function(e,t,r,n){var i=this.startNodeAt(e,t);return i.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e,t)),i.static=r,i.key=n,i.optional=!1,this.flowObjectTypeSemicolon(),this.finishNode(i,"ObjectTypeProperty")},re.flowParseObjectTypeCallProperty=function(e,t){var r=this.startNode();return e.static=t,e.value=this.flowParseObjectTypeMethodish(r),this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeCallProperty")},re.flowParseObjectType=function(e,t,r){var n=this.state.inType;this.state.inType=!0;var i=this.startNode(),s=void 0,a=void 0,o=!1;i.callProperties=[],i.properties=[],i.indexers=[];var u=void 0,l=void 0;for(t&&this.match(T.braceBarL)?(this.expect(T.braceBarL),u=T.braceBarR,l=!0):(this.expect(T.braceL),u=T.braceR,l=!1),i.exact=l;!this.match(u);){var c=!1,p=this.state.start,h=this.state.startLoc;s=this.startNode(),e&&this.isContextual("static")&&this.lookahead().type!==T.colon&&(this.next(),o=!0);var f=this.state.start,d=this.flowParseVariance();this.match(T.bracketL)?i.indexers.push(this.flowParseObjectTypeIndexer(s,o,d)):this.match(T.parenL)||this.isRelational("<")?(d&&this.unexpected(f),i.callProperties.push(this.flowParseObjectTypeCallProperty(s,o))):this.match(T.ellipsis)?(r||this.unexpected(null,"Spread operator cannot appear in class or interface definitions"),d&&this.unexpected(d.start,"Spread properties cannot have variance"),this.expect(T.ellipsis),s.argument=this.flowParseType(),this.flowObjectTypeSemicolon(),i.properties.push(this.finishNode(s,"ObjectTypeSpreadProperty"))):(a=this.flowParseObjectPropertyKey(),this.isRelational("<")||this.match(T.parenL)?(d&&this.unexpected(d.start),i.properties.push(this.flowParseObjectTypeMethod(p,h,o,a))):(this.eat(T.question)&&(c=!0),s.key=a,s.value=this.flowParseTypeInitialiser(),s.optional=c,s.static=o,s.variance=d,this.flowObjectTypeSemicolon(),i.properties.push(this.finishNode(s,"ObjectTypeProperty")))),o=!1}this.expect(u);var m=this.finishNode(i,"ObjectTypeAnnotation");return this.state.inType=n,m},re.flowObjectTypeSemicolon=function(){this.eat(T.semi)||this.eat(T.comma)||this.match(T.braceR)||this.match(T.braceBarR)||this.unexpected()},re.flowParseQualifiedTypeIdentifier=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;for(var n=r||this.parseIdentifier();this.eat(T.dot);){var i=this.startNodeAt(e,t);i.qualification=n,i.id=this.parseIdentifier(),n=this.finishNode(i,"QualifiedTypeIdentifier")}return n},re.flowParseGenericType=function(e,t,r){var n=this.startNodeAt(e,t);return n.typeParameters=null,n.id=this.flowParseQualifiedTypeIdentifier(e,t,r),this.isRelational("<")&&(n.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(n,"GenericTypeAnnotation")},re.flowParseTypeofType=function(){var e=this.startNode();return this.expect(T._typeof),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},re.flowParseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(T.bracketL);this.state.pos0&&void 0!==arguments[0]?arguments[0]:[],rest:null};!this.match(T.parenR)&&!this.match(T.ellipsis);)e.params.push(this.flowParseFunctionTypeParam()),this.match(T.parenR)||this.expect(T.comma);return this.eat(T.ellipsis)&&(e.rest=this.flowParseFunctionTypeParam()),e},re.flowIdentToTypeAnnotation=function(e,t,r,n){switch(n.name){case"any":return this.finishNode(r,"AnyTypeAnnotation");case"void":return this.finishNode(r,"VoidTypeAnnotation");case"bool":case"boolean":return this.finishNode(r,"BooleanTypeAnnotation");case"mixed":return this.finishNode(r,"MixedTypeAnnotation");case"empty":return this.finishNode(r,"EmptyTypeAnnotation");case"number":return this.finishNode(r,"NumberTypeAnnotation");case"string":return this.finishNode(r,"StringTypeAnnotation");default:return this.flowParseGenericType(e,t,n)}},re.flowParsePrimaryType=function(){var e=this.state.start,t=this.state.startLoc,r=this.startNode(),n=void 0,i=void 0,s=!1,a=this.state.noAnonFunctionType;switch(this.state.type){case T.name:return this.flowIdentToTypeAnnotation(e,t,r,this.parseIdentifier());case T.braceL:return this.flowParseObjectType(!1,!1,!0);case T.braceBarL:return this.flowParseObjectType(!1,!0,!0);case T.bracketL:return this.flowParseTupleType();case T.relational:if("<"===this.state.value)return r.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(T.parenL),n=this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(T.parenR),this.expect(T.arrow),r.returnType=this.flowParseType(),this.finishNode(r,"FunctionTypeAnnotation");break;case T.parenL:if(this.next(),!this.match(T.parenR)&&!this.match(T.ellipsis))if(this.match(T.name)){var o=this.lookahead().type;s=o!==T.question&&o!==T.colon}else s=!0;if(s){if(this.state.noAnonFunctionType=!1,i=this.flowParseType(),this.state.noAnonFunctionType=a,this.state.noAnonFunctionType||!(this.match(T.comma)||this.match(T.parenR)&&this.lookahead().type===T.arrow))return this.expect(T.parenR),i;this.eat(T.comma)}return n=i?this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(i)]):this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(T.parenR),this.expect(T.arrow),r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation");case T.string:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case T._true:case T._false:return r.value=this.match(T._true),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case T.plusMin:if("-"===this.state.value)return this.next(),this.match(T.num)||this.unexpected(null,"Unexpected token, expected number"),this.parseLiteral(-this.state.value,"NumericLiteralTypeAnnotation",r.start,r.loc.start);this.unexpected();case T.num:return this.parseLiteral(this.state.value,"NumericLiteralTypeAnnotation");case T._null:return r.value=this.match(T._null),this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case T._this:return r.value=this.match(T._this),this.next(),this.finishNode(r,"ThisTypeAnnotation");case T.star:return this.next(),this.finishNode(r,"ExistentialTypeParam");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType()}this.unexpected()},re.flowParsePostfixType=function(){for(var e=this.state.start,t=this.state.startLoc,r=this.flowParsePrimaryType();!this.canInsertSemicolon()&&this.match(T.bracketL);){var n=this.startNodeAt(e,t);n.elementType=r,this.expect(T.bracketL),this.expect(T.bracketR),r=this.finishNode(n,"ArrayTypeAnnotation")}return r},re.flowParsePrefixType=function(){var e=this.startNode();return this.eat(T.question)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()},re.flowParseAnonFunctionWithoutParens=function(){var e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(T.arrow)){var t=this.startNodeAt(e.start,e.loc.start);return t.params=[this.reinterpretTypeAsFunctionTypeParam(e)],t.rest=null,t.returnType=this.flowParseType(),t.typeParameters=null,this.finishNode(t,"FunctionTypeAnnotation")}return e},re.flowParseIntersectionType=function(){var e=this.startNode();this.eat(T.bitwiseAND);var t=this.flowParseAnonFunctionWithoutParens();for(e.types=[t];this.eat(T.bitwiseAND);)e.types.push(this.flowParseAnonFunctionWithoutParens());return 1===e.types.length?t:this.finishNode(e,"IntersectionTypeAnnotation")},re.flowParseUnionType=function(){var e=this.startNode();this.eat(T.bitwiseOR);var t=this.flowParseIntersectionType();for(e.types=[t];this.eat(T.bitwiseOR);)e.types.push(this.flowParseIntersectionType());return 1===e.types.length?t:this.finishNode(e,"UnionTypeAnnotation")},re.flowParseType=function(){var e=this.state.inType;this.state.inType=!0;var t=this.flowParseUnionType();return this.state.inType=e,t},re.flowParseTypeAnnotation=function(){var e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")},re.flowParseTypeAndPredicateAnnotation=function(){var e=this.startNode(),t=this.flowParseTypeAndPredicateInitialiser();return e.typeAnnotation=t[0],e.predicate=t[1],this.finishNode(e,"TypeAnnotation")},re.flowParseTypeAnnotatableIdentifier=function(){var e=this.flowParseRestrictedIdentifier();return this.match(T.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e,e.type)),e},re.typeCastToParameter=function(e){return e.expression.typeAnnotation=e.typeAnnotation,this.finishNodeAt(e.expression,e.expression.type,e.typeAnnotation.end,e.typeAnnotation.loc.end)},re.flowParseVariance=function(){var e=null;return this.match(T.plusMin)&&("+"===this.state.value?e="plus":"-"===this.state.value&&(e="minus"),this.next()),e};var ne=String.fromCodePoint;if(!ne){var ie=String.fromCharCode,se=Math.floor;ne=function(){var e=[],t=void 0,r=void 0,n=-1,i=arguments.length;if(!i)return"";for(var s="";++n1114111||se(a)!=a)throw RangeError("Invalid code point: "+a);a<=65535?e.push(a):(t=55296+((a-=65536)>>10),r=a%1024+56320,e.push(t,r)),(n+1==i||e.length>16384)&&(s+=ie.apply(null,e),e.length=0)}return s}}var ae=ne,oe={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},ue=/^[\da-fA-F]+$/,le=/^\d+$/;I.j_oTag=new N("...",!0,!0),T.jsxName=new w("jsxName"),T.jsxText=new w("jsxText",{beforeExpr:!0}),T.jsxTagStart=new w("jsxTagStart",{startsExpr:!0}),T.jsxTagEnd=new w("jsxTagEnd"),T.jsxTagStart.updateContext=function(){this.state.context.push(I.j_expr),this.state.context.push(I.j_oTag),this.state.exprAllowed=!1},T.jsxTagEnd.updateContext=function(e){var t=this.state.context.pop();t===I.j_oTag&&e===T.slash||t===I.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===I.j_expr):this.state.exprAllowed=!0};var ce=q.prototype;ce.jsxReadToken=function(){for(var e="",t=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated JSX contents");var r=this.input.charCodeAt(this.state.pos);switch(r){case 60:case 123:return this.state.pos===this.state.start?60===r&&this.state.exprAllowed?(++this.state.pos,this.finishToken(T.jsxTagStart)):this.getTokenFromCode(r):(e+=this.input.slice(t,this.state.pos),this.finishToken(T.jsxText,e));case 38:e+=this.input.slice(t,this.state.pos),e+=this.jsxReadEntity(),t=this.state.pos;break;default:o(r)?(e+=this.input.slice(t,this.state.pos),e+=this.jsxReadNewLine(!0),t=this.state.pos):++this.state.pos}}},ce.jsxReadNewLine=function(e){var t=this.input.charCodeAt(this.state.pos),r=void 0;return++this.state.pos,13===t&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,r=e?"\n":"\r\n"):r=String.fromCharCode(t),++this.state.curLine,this.state.lineStart=this.state.pos,r},ce.jsxReadString=function(e){for(var t="",r=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var n=this.input.charCodeAt(this.state.pos);if(n===e)break;38===n?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadEntity(),r=this.state.pos):o(n)?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadNewLine(!1),r=this.state.pos):++this.state.pos}return t+=this.input.slice(r,this.state.pos++),this.finishToken(T.string,t)},ce.jsxReadEntity=function(){for(var e="",t=0,r=void 0,n=this.input[this.state.pos],i=++this.state.pos;this.state.pos")}return r.openingElement=i,r.closingElement=s,r.children=n,this.match(T.relational)&&"<"===this.state.value&&this.raise(this.state.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(r,"JSXElement")},ce.jsxParseElement=function(){var e=this.state.start,t=this.state.startLoc;return this.next(),this.jsxParseElementAt(e,t)};V.estree=function(e){e.extend("checkDeclaration",function(e){return function(t){p(t)?this.checkDeclaration(t.value):e.call(this,t)}}),e.extend("checkGetterSetterParamCount",function(){return function(e){var t="get"===e.kind?0:1;if(e.value.params.length!==t){var r=e.start;"get"===e.kind?this.raise(r,"getter should have no params"):this.raise(r,"setter should have exactly one param")}}}),e.extend("checkLVal",function(e){return function(t,r,n){var i=this;switch(t.type){case"ObjectPattern":t.properties.forEach(function(e){i.checkLVal("Property"===e.type?e.value:e,r,n,"object destructuring pattern")});break;default:for(var s=arguments.length,a=Array(s>3?s-3:0),o=3;o0)for(var r=e.body.body,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}var a=s;if("ExpressionStatement"!==a.type||"Literal"!==a.expression.type)break;if("use strict"===a.expression.value)return!0}return!1}}),e.extend("isValidDirective",function(){return function(e){return!("ExpressionStatement"!==e.type||"Literal"!==e.expression.type||"string"!=typeof e.expression.value||e.expression.extra&&e.expression.extra.parenthesized)}}),e.extend("stmtToDirective",function(e){return function(t){var r=e.call(this,t),n=t.expression.value;return r.value.value=n,r}}),e.extend("parseBlockBody",function(e){return function(t){for(var r=this,n=arguments.length,i=Array(n>1?n-1:0),s=1;s1?n-1:0),s=1;s2?n-2:0),s=2;s=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var c=l;"get"===c.kind||"set"===c.kind?this.raise(c.key.start,"Object pattern can't contain getter or setter"):c.method?this.raise(c.key.start,"Object pattern can't contain methods"):this.toAssignable(c,r,"object destructuring pattern")}return t}return e.call.apply(e,[this,t,r].concat(i))}})},V.flow=function(e){e.extend("parseFunctionBody",function(e){return function(t,r){return this.match(T.colon)&&!r&&(t.returnType=this.flowParseTypeAndPredicateAnnotation()),e.call(this,t,r)}}),e.extend("parseStatement",function(e){return function(t,r){if(this.state.strict&&this.match(T.name)&&"interface"===this.state.value){var n=this.startNode();return this.next(),this.flowParseInterface(n)}return e.call(this,t,r)}}),e.extend("parseExpressionStatement",function(e){return function(t,r){if("Identifier"===r.type)if("declare"===r.name){if(this.match(T._class)||this.match(T.name)||this.match(T._function)||this.match(T._var)||this.match(T._export))return this.flowParseDeclare(t)}else if(this.match(T.name)){if("interface"===r.name)return this.flowParseInterface(t);if("type"===r.name)return this.flowParseTypeAlias(t);if("opaque"===r.name)return this.flowParseOpaqueType(t,!1)}return e.call(this,t,r)}}),e.extend("shouldParseExportDeclaration",function(e){return function(){return this.isContextual("type")||this.isContextual("interface")||this.isContextual("opaque")||e.call(this)}}),e.extend("isExportDefaultSpecifier",function(e){return function(){return(!this.match(T.name)||"type"!==this.state.value&&"interface"!==this.state.value&&"opaque"!==this.state.value)&&e.call(this)}}),e.extend("parseConditional",function(e){return function(t,r,n,i,s){if(s&&this.match(T.question)){var a=this.state.clone();try{return e.call(this,t,r,n,i)}catch(e){if(e instanceof SyntaxError)return this.state=a,s.start=e.pos||this.state.start,t;throw e}}return e.call(this,t,r,n,i)}}),e.extend("parseParenItem",function(e){return function(t,r,n){if(t=e.call(this,t,r,n),this.eat(T.question)&&(t.optional=!0),this.match(T.colon)){var i=this.startNodeAt(r,n);return i.expression=t,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return t}}),e.extend("parseExport",function(e){return function(t){return"ExportNamedDeclaration"===(t=e.call(this,t)).type&&(t.exportKind=t.exportKind||"value"),t}}),e.extend("parseExportDeclaration",function(e){return function(t){if(this.isContextual("type")){t.exportKind="type";var r=this.startNode();return this.next(),this.match(T.braceL)?(t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t),null):this.flowParseTypeAlias(r)}if(this.isContextual("opaque")){t.exportKind="type";var n=this.startNode();return this.next(),this.flowParseOpaqueType(n,!1)}if(this.isContextual("interface")){t.exportKind="type";var i=this.startNode();return this.next(),this.flowParseInterface(i)}return e.call(this,t)}}),e.extend("parseClassId",function(e){return function(t){e.apply(this,arguments),this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration())}}),e.extend("isKeyword",function(e){return function(t){return(!this.state.inType||"void"!==t)&&e.call(this,t)}}),e.extend("readToken",function(e){return function(t){return!this.state.inType||62!==t&&60!==t?e.call(this,t):this.finishOp(T.relational,1)}}),e.extend("jsx_readToken",function(e){return function(){if(!this.state.inType)return e.call(this)}}),e.extend("toAssignable",function(e){return function(t,r,n){return"TypeCastExpression"===t.type?e.call(this,this.typeCastToParameter(t),r,n):e.call(this,t,r,n)}}),e.extend("toAssignableList",function(e){return function(t,r,n){for(var i=0;i2?n-2:0),s=2;s=0&&l>0){for(n=[],s=r.length;c>=0&&!o;)c==u?(n.push(c),u=r.indexOf(e,c+1)):1==n.length?o=[n.pop(),l]:((i=n.pop())=0?u:l;n.length&&(o=[s,a])}return o}t.exports=n,n.range=s},{}],188:[function(e,t,r){"use strict";function n(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return a[e>>18&63]+a[e>>12&63]+a[e>>6&63]+a[63&e]}function s(e,t,r){for(var n,s=[],a=t;a0?l-4:l;var c=0;for(t=0;t>16&255,a[c++]=i>>8&255,a[c++]=255&i;return 2===s?(i=o[e.charCodeAt(t)]<<2|o[e.charCodeAt(t+1)]>>4,a[c++]=255&i):1===s&&(i=o[e.charCodeAt(t)]<<10|o[e.charCodeAt(t+1)]<<4|o[e.charCodeAt(t+2)]>>2,a[c++]=i>>8&255,a[c++]=255&i),a},r.fromByteArray=function(e){for(var t,r=e.length,n=r%3,i="",o=[],u=0,l=r-n;ul?l:u+16383));return 1===n?(t=e[r-1],i+=a[t>>2],i+=a[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=a[t>>10],i+=a[t>>4&63],i+=a[t<<2&63],i+="="),o.push(i),o.join("")};for(var a=[],o=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,p=l.length;c=t}function c(e,t){var r=[],i=h("{","}",e);if(!i||/\$$/.test(i.pre))return[e];var f=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),d=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),y=f||d,g=i.body.indexOf(",")>=0;if(!y&&!g)return i.post.match(/,.*\}/)?(e=i.pre+"{"+i.body+m+i.post,c(e)):[e];var b;if(y)b=i.body.split(/\.\./);else if(1===(b=s(i.body)).length&&1===(b=c(b[0],!1).map(a)).length){return(E=i.post.length?c(i.post,!1):[""]).map(function(e){return i.pre+b[0]+e})}var v,x=i.pre,E=i.post.length?c(i.post,!1):[""];if(y){var A=n(b[0]),D=n(b[1]),C=Math.max(b[0].length,b[1].length),S=3==b.length?Math.abs(n(b[2])):1,_=u;D0){var P=new Array(T+1).join("0");F=k<0?"-"+P+F.slice(1):P+F}}v.push(F)}}else v=p(b,function(e){return c(e,!1)});for(var B=0;BN)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return o(e)}return s(e,t,r)}function s(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return T(e)?function(e,t,r){if(t<0||e.byteLength=N)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+N.toString(16)+" bytes");return 0|e}function c(e,t){if(i.isBuffer(e))return e.length;if(P(e)||T(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return w(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return k(e).length;default:if(n)return w(e).length;t=(""+t).toLowerCase(),n=!0}}function p(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var n=e.length;(!t||t<0)&&(t=0);(!r||r<0||r>n)&&(r=n);for(var i="",s=t;s2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,B(r)&&(r=s?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(s)return-1;r=e.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof t&&(t=i.from(t,n)),i.isBuffer(t))return 0===t.length?-1:d(e,t,r,n,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):d(e,[t],r,n,s);throw new TypeError("val must be string, number or Buffer")}function d(e,t,r,n,i){function s(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,o=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,o/=2,u/=2,r/=2}var l;if(i){var c=-1;for(l=r;lo&&(r=o-u),l=r;l>=0;l--){for(var p=!0,h=0;hi&&(n=i):n=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var a=0;a>8,i=r%256,s.push(i),s.push(n);return s}(t,e.length-r),e,r,n)}function E(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:s>223?3:s>191?2:1;if(i+o<=r){var u,l,c,p;switch(o){case 1:s<128&&(a=s);break;case 2:128==(192&(u=e[i+1]))&&(p=(31&s)<<6|63&u)>127&&(a=p);break;case 3:u=e[i+1],l=e[i+2],128==(192&u)&&128==(192&l)&&(p=(15&s)<<12|(63&u)<<6|63&l)>2047&&(p<55296||p>57343)&&(a=p);break;case 4:u=e[i+1],l=e[i+2],c=e[i+3],128==(192&u)&&128==(192&l)&&128==(192&c)&&(p=(15&s)<<18|(63&u)<<12|(63&l)<<6|63&c)>65535&&p<1114112&&(a=p)}}null===a?(a=65533,o=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=o}return function(e){var t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nr)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,r,n,s,a){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||te.length)throw new RangeError("Index out of range")}function C(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function S(e,t,r,n,i){return t=+t,r>>>=0,i||C(e,0,r,4),j.write(e,t,r,n,23,4),r+4}function _(e,t,r,n,i){return t=+t,r>>>=0,i||C(e,0,r,8),j.write(e,t,r,n,52,8),r+8}function w(e,t){t=t||1/0;for(var r,n=e.length,i=null,s=[],a=0;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function k(e){return O.toByteArray(function(e){if((e=e.trim().replace(L,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function F(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function T(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function P(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function B(e){return e!=e}var O=e("base64-js"),j=e("ieee754");r.Buffer=i,r.SlowBuffer=function(e){return+e!=e&&(e=0),i.alloc(+e)},r.INSPECT_MAX_BYTES=50;var N=2147483647;r.kMaxLength=N,(i.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}())||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,r){return s(e,t,r)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?n(e):void 0!==t?"string"==typeof r?n(e).fill(t,r):n(e).fill(t):n(e)}(e,t,r)},i.allocUnsafe=function(e){return o(e)},i.allocUnsafeSlow=function(e){return o(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer},i.compare=function(e,t){if(!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,s=0,a=Math.min(r,n);s0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},i.prototype.compare=function(e,t,r,n,s){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===s&&(s=this.length),t<0||r>e.length||n<0||s>this.length)throw new RangeError("out of range index");if(n>=s&&t>=r)return 0;if(n>=s)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,s>>>=0,this===e)return 0;for(var a=s-n,o=r-t,u=Math.min(a,o),l=this.slice(n,s),c=e.slice(t,r),p=0;p>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var s=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return y(this,e,t,r);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return b(this,e,t,r);case"base64":return v(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var I=4096;i.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||A(e,t,this.length);for(var n=this[e],i=1,s=0;++s>>=0,t>>>=0,r||A(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},i.prototype.readUInt8=function(e,t){return e>>>=0,t||A(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||A(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||A(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||A(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||A(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||A(e,t,this.length);for(var n=this[e],i=1,s=0;++s=i&&(n-=Math.pow(2,8*t)),n},i.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||A(e,t,this.length);for(var n=t,i=1,s=this[e+--n];n>0&&(i*=256);)s+=this[e+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||A(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||A(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt16BE=function(e,t){e>>>=0,t||A(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||A(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||A(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||A(e,4,this.length),j.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||A(e,4,this.length),j.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||A(e,8,this.length),j.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||A(e,8,this.length),j.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){D(this,e,t,r,Math.pow(2,8*r)-1,0)}var i=1,s=0;for(this[t]=255&e;++s>>=0,r>>>=0,!n){D(this,e,t,r,Math.pow(2,8*r)-1,0)}var i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},i.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);D(this,e,t,r,i-1,-i)}var s=0,a=1,o=0;for(this[t]=255&e;++s>0)-o&255;return t+r},i.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);D(this,e,t,r,i-1,-i)}var s=r-1,a=1,o=0;for(this[t+s]=255&e;--s>=0&&(a*=256);)e<0&&0===o&&0!==this[t+s+1]&&(o=1),this[t+s]=(e/a>>0)-o&255;return t+r},i.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,r){return S(this,e,t,!0,r)},i.prototype.writeFloatBE=function(e,t,r){return S(this,e,t,!1,r)},i.prototype.writeDoubleLE=function(e,t,r){return _(this,e,t,!0,r)},i.prototype.writeDoubleBE=function(e,t,r){return _(this,e,t,!1,r)},i.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(s<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var a;if("number"==typeof e)for(a=t;ac;)if((o=u[c++])!=o)return!0}else for(;l>c;c++)if((e||c in u)&&u[c]===r)return e||c||0;return!e&&-1}}},{"./_to-absolute-index":273,"./_to-iobject":275,"./_to-length":276}],214:[function(e,t,r){var n=e("./_ctx"),i=e("./_iobject"),s=e("./_to-object"),a=e("./_to-length"),o=e("./_array-species-create");t.exports=function(e,t){var r=1==e,u=2==e,l=3==e,c=4==e,p=6==e,h=5==e||p,f=t||o;return function(t,o,d){for(var m,y,g=s(t),b=i(g),v=n(o,d,3),x=a(b.length),E=0,A=r?f(t,x):u?f(t,0):void 0;x>E;E++)if((h||E in b)&&(m=b[E],y=v(m,E,g),e))if(r)A[E]=y;else if(y)switch(e){case 3:return!0;case 5:return m;case 6:return E;case 2:A.push(m)}else if(c)return!1;return p?-1:l||c?c:A}}},{"./_array-species-create":216,"./_ctx":224,"./_iobject":238,"./_to-length":276,"./_to-object":277}],215:[function(e,t,r){var n=e("./_is-object"),i=e("./_is-array"),s=e("./_wks")("species");t.exports=function(e){var t;return i(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!i(t.prototype)||(t=void 0),n(t)&&null===(t=t[s])&&(t=void 0)),void 0===t?Array:t}},{"./_is-array":240,"./_is-object":241,"./_wks":283}],216:[function(e,t,r){var n=e("./_array-species-constructor");t.exports=function(e,t){return new(n(e))(t)}},{"./_array-species-constructor":215}],217:[function(e,t,r){var n=e("./_cof"),i=e("./_wks")("toStringTag"),s="Arguments"==n(function(){return arguments}());t.exports=function(e){var t,r,a;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),i))?r:s?n(t):"Object"==(a=n(t))&&"function"==typeof t.callee?"Arguments":a}},{"./_cof":218,"./_wks":283}],218:[function(e,t,r){var n={}.toString;t.exports=function(e){return n.call(e).slice(8,-1)}},{}],219:[function(e,t,r){"use strict";var n=e("./_object-dp").f,i=e("./_object-create"),s=e("./_redefine-all"),a=e("./_ctx"),o=e("./_an-instance"),u=e("./_for-of"),l=e("./_iter-define"),c=e("./_iter-step"),p=e("./_set-species"),h=e("./_descriptors"),f=e("./_meta").fastKey,d=e("./_validate-collection"),m=h?"_s":"size",y=function(e,t){var r,n=f(t);if("F"!==n)return e._i[n];for(r=e._f;r;r=r.n)if(r.k==t)return r};t.exports={getConstructor:function(e,t,r,l){var c=e(function(e,n){o(e,c,t,"_i"),e._t=t,e._i=i(null),e._f=void 0,e._l=void 0,e[m]=0,void 0!=n&&u(n,r,e[l],e)});return s(c.prototype,{clear:function(){for(var e=d(this,t),r=e._i,n=e._f;n;n=n.n)n.r=!0,n.p&&(n.p=n.p.n=void 0),delete r[n.i];e._f=e._l=void 0,e[m]=0},delete:function(e){var r=d(this,t),n=y(r,e);if(n){var i=n.n,s=n.p;delete r._i[n.i],n.r=!0,s&&(s.n=i),i&&(i.p=s),r._f==n&&(r._f=i),r._l==n&&(r._l=s),r[m]--}return!!n},forEach:function(e){d(this,t);for(var r,n=a(e,arguments.length>1?arguments[1]:void 0,3);r=r?r.n:this._f;)for(n(r.v,r.k,this);r&&r.r;)r=r.p},has:function(e){return!!y(d(this,t),e)}}),h&&n(c.prototype,"size",{get:function(){return d(this,t)[m]}}),c},def:function(e,t,r){var n,i,s=y(e,t);return s?s.v=r:(e._l=s={i:i=f(t,!0),k:t,v:r,p:n=e._l,n:void 0,r:!1},e._f||(e._f=s),n&&(n.n=s),e[m]++,"F"!==i&&(e._i[i]=s)),e},getEntry:y,setStrong:function(e,t,r){l(e,t,function(e,r){this._t=d(e,t),this._k=r,this._l=void 0},function(){for(var e=this._k,t=this._l;t&&t.r;)t=t.p;return this._t&&(this._l=t=t?t.n:this._t._f)?"keys"==e?c(0,t.k):"values"==e?c(0,t.v):c(0,[t.k,t.v]):(this._t=void 0,c(1))},r?"entries":"values",!r,!0),p(t)}}},{"./_an-instance":210,"./_ctx":224,"./_descriptors":226,"./_for-of":232,"./_iter-define":244,"./_iter-step":245,"./_meta":248,"./_object-create":250,"./_object-dp":251,"./_redefine-all":263,"./_set-species":268,"./_validate-collection":280}],220:[function(e,t,r){var n=e("./_classof"),i=e("./_array-from-iterable");t.exports=function(e){return function(){if(n(this)!=e)throw TypeError(e+"#toJSON isn't generic");return i(this)}}},{"./_array-from-iterable":212,"./_classof":217}],221:[function(e,t,r){"use strict";var n=e("./_redefine-all"),i=e("./_meta").getWeak,s=e("./_an-object"),a=e("./_is-object"),o=e("./_an-instance"),u=e("./_for-of"),l=e("./_array-methods"),c=e("./_has"),p=e("./_validate-collection"),h=l(5),f=l(6),d=0,m=function(e){return e._l||(e._l=new y)},y=function(){this.a=[]},g=function(e,t){return h(e.a,function(e){return e[0]===t})};y.prototype={get:function(e){var t=g(this,e);if(t)return t[1]},has:function(e){return!!g(this,e)},set:function(e,t){var r=g(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=f(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}},t.exports={getConstructor:function(e,t,r,s){var l=e(function(e,n){o(e,l,t,"_i"),e._t=t,e._i=d++,e._l=void 0,void 0!=n&&u(n,r,e[s],e)});return n(l.prototype,{delete:function(e){if(!a(e))return!1;var r=i(e);return!0===r?m(p(this,t)).delete(e):r&&c(r,this._i)&&delete r[this._i]},has:function(e){if(!a(e))return!1;var r=i(e);return!0===r?m(p(this,t)).has(e):r&&c(r,this._i)}}),l},def:function(e,t,r){var n=i(s(t),!0);return!0===n?m(e).set(t,r):n[e._i]=r,e},ufstore:m}},{"./_an-instance":210,"./_an-object":211,"./_array-methods":214,"./_for-of":232,"./_has":234,"./_is-object":241,"./_meta":248,"./_redefine-all":263,"./_validate-collection":280}],222:[function(e,t,r){"use strict";var n=e("./_global"),i=e("./_export"),s=e("./_meta"),a=e("./_fails"),o=e("./_hide"),u=e("./_redefine-all"),l=e("./_for-of"),c=e("./_an-instance"),p=e("./_is-object"),h=e("./_set-to-string-tag"),f=e("./_object-dp").f,d=e("./_array-methods")(0),m=e("./_descriptors");t.exports=function(e,t,r,y,g,b){var v=n[e],x=v,E=g?"set":"add",A=x&&x.prototype,D={};return m&&"function"==typeof x&&(b||A.forEach&&!a(function(){(new x).entries().next()}))?(x=t(function(t,r){c(t,x,e,"_c"),t._c=new v,void 0!=r&&l(r,g,t[E],t)}),d("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in A&&(!b||"clear"!=e)&&o(x.prototype,e,function(r,n){if(c(this,x,e),!t&&b&&!p(r))return"get"==e&&void 0;var i=this._c[e](0===r?0:r,n);return t?this:i})}),b||f(x.prototype,"size",{get:function(){return this._c.size}})):(x=y.getConstructor(t,e,g,E),u(x.prototype,r),s.NEED=!0),h(x,e),D[e]=x,i(i.G+i.W+i.F,D),b||y.setStrong(x,e,g),x}},{"./_an-instance":210,"./_array-methods":214,"./_descriptors":226,"./_export":230,"./_fails":231,"./_for-of":232,"./_global":233,"./_hide":235,"./_is-object":241,"./_meta":248,"./_object-dp":251,"./_redefine-all":263,"./_set-to-string-tag":269}],223:[function(e,t,r){var n=t.exports={version:"2.5.1"};"number"==typeof __e&&(__e=n)},{}],224:[function(e,t,r){var n=e("./_a-function");t.exports=function(e,t,r){if(n(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,i){return e.call(t,r,n,i)}}return function(){return e.apply(t,arguments)}}},{"./_a-function":208}],225:[function(e,t,r){t.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},{}],226:[function(e,t,r){t.exports=!e("./_fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./_fails":231}],227:[function(e,t,r){var n=e("./_is-object"),i=e("./_global").document,s=n(i)&&n(i.createElement);t.exports=function(e){return s?i.createElement(e):{}}},{"./_global":233,"./_is-object":241}],228:[function(e,t,r){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},{}],229:[function(e,t,r){var n=e("./_object-keys"),i=e("./_object-gops"),s=e("./_object-pie");t.exports=function(e){var t=n(e),r=i.f;if(r)for(var a,o=r(e),u=s.f,l=0;o.length>l;)u.call(e,a=o[l++])&&t.push(a);return t}},{"./_object-gops":256,"./_object-keys":259,"./_object-pie":260}],230:[function(e,t,r){var n=e("./_global"),i=e("./_core"),s=e("./_ctx"),a=e("./_hide"),o=function(e,t,r){var u,l,c,p=e&o.F,h=e&o.G,f=e&o.S,d=e&o.P,m=e&o.B,y=e&o.W,g=h?i:i[t]||(i[t]={}),b=g.prototype,v=h?n:f?n[t]:(n[t]||{}).prototype;h&&(r=t);for(u in r)(l=!p&&v&&void 0!==v[u])&&u in g||(c=l?v[u]:r[u],g[u]=h&&"function"!=typeof v[u]?r[u]:m&&l?s(c,n):y&&v[u]==c?function(e){var t=function(t,r,n){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,n)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(c):d&&"function"==typeof c?s(Function.call,c):c,d&&((g.virtual||(g.virtual={}))[u]=c,e&o.R&&b&&!b[u]&&a(b,u,c)))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,o.U=64,o.R=128,t.exports=o},{"./_core":223,"./_ctx":224,"./_global":233,"./_hide":235}],231:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],232:[function(e,t,r){var n=e("./_ctx"),i=e("./_iter-call"),s=e("./_is-array-iter"),a=e("./_an-object"),o=e("./_to-length"),u=e("./core.get-iterator-method"),l={},c={};(r=t.exports=function(e,t,r,p,h){var f,d,m,y,g=h?function(){return e}:u(e),b=n(r,p,t?2:1),v=0;if("function"!=typeof g)throw TypeError(e+" is not iterable!");if(s(g)){for(f=o(e.length);f>v;v++)if((y=t?b(a(d=e[v])[0],d[1]):b(e[v]))===l||y===c)return y}else for(m=g.call(e);!(d=m.next()).done;)if((y=i(m,b,d.value,t))===l||y===c)return y}).BREAK=l,r.RETURN=c},{"./_an-object":211,"./_ctx":224,"./_is-array-iter":239,"./_iter-call":242,"./_to-length":276,"./core.get-iterator-method":284}],233:[function(e,t,r){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},{}],234:[function(e,t,r){var n={}.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],235:[function(e,t,r){var n=e("./_object-dp"),i=e("./_property-desc");t.exports=e("./_descriptors")?function(e,t,r){return n.f(e,t,i(1,r))}:function(e,t,r){return e[t]=r,e}},{"./_descriptors":226,"./_object-dp":251,"./_property-desc":262}],236:[function(e,t,r){var n=e("./_global").document;t.exports=n&&n.documentElement},{"./_global":233}],237:[function(e,t,r){t.exports=!e("./_descriptors")&&!e("./_fails")(function(){return 7!=Object.defineProperty(e("./_dom-create")("div"),"a",{get:function(){return 7}}).a})},{"./_descriptors":226,"./_dom-create":227,"./_fails":231}],238:[function(e,t,r){var n=e("./_cof");t.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==n(e)?e.split(""):Object(e)}},{"./_cof":218}],239:[function(e,t,r){var n=e("./_iterators"),i=e("./_wks")("iterator"),s=Array.prototype;t.exports=function(e){return void 0!==e&&(n.Array===e||s[i]===e)}},{"./_iterators":246,"./_wks":283}],240:[function(e,t,r){var n=e("./_cof");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"./_cof":218}],241:[function(e,t,r){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],242:[function(e,t,r){var n=e("./_an-object");t.exports=function(e,t,r,i){try{return i?t(n(r)[0],r[1]):t(r)}catch(t){var s=e.return;throw void 0!==s&&n(s.call(e)),t}}},{"./_an-object":211}],243:[function(e,t,r){"use strict";var n=e("./_object-create"),i=e("./_property-desc"),s=e("./_set-to-string-tag"),a={};e("./_hide")(a,e("./_wks")("iterator"),function(){return this}),t.exports=function(e,t,r){e.prototype=n(a,{next:i(1,r)}),s(e,t+" Iterator")}},{"./_hide":235,"./_object-create":250,"./_property-desc":262,"./_set-to-string-tag":269,"./_wks":283}],244:[function(e,t,r){"use strict";var n=e("./_library"),i=e("./_export"),s=e("./_redefine"),a=e("./_hide"),o=e("./_has"),u=e("./_iterators"),l=e("./_iter-create"),c=e("./_set-to-string-tag"),p=e("./_object-gpo"),h=e("./_wks")("iterator"),f=!([].keys&&"next"in[].keys()),d=function(){return this};t.exports=function(e,t,r,m,y,g,b){l(r,t,m);var v,x,E,A=function(e){if(!f&&e in _)return _[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},D=t+" Iterator",C="values"==y,S=!1,_=e.prototype,w=_[h]||_["@@iterator"]||y&&_[y],k=w||A(y),F=y?C?A("entries"):k:void 0,T="Array"==t?_.entries||w:w;if(T&&(E=p(T.call(new e)))!==Object.prototype&&E.next&&(c(E,D,!0),n||o(E,h)||a(E,h,d)),C&&w&&"values"!==w.name&&(S=!0,k=function(){return w.call(this)}),n&&!b||!f&&!S&&_[h]||a(_,h,k),u[t]=k,u[D]=d,y)if(v={values:C?k:A("values"),keys:g?k:A("keys"),entries:F},b)for(x in v)x in _||s(_,x,v[x]);else i(i.P+i.F*(f||S),t,v);return v}},{"./_export":230,"./_has":234,"./_hide":235,"./_iter-create":243,"./_iterators":246,"./_library":247,"./_object-gpo":257,"./_redefine":264,"./_set-to-string-tag":269,"./_wks":283}],245:[function(e,t,r){t.exports=function(e,t){return{value:t,done:!!e}}},{}],246:[function(e,t,r){t.exports={}},{}],247:[function(e,t,r){t.exports=!0},{}],248:[function(e,t,r){var n=e("./_uid")("meta"),i=e("./_is-object"),s=e("./_has"),a=e("./_object-dp").f,o=0,u=Object.isExtensible||function(){return!0},l=!e("./_fails")(function(){return u(Object.preventExtensions({}))}),c=function(e){a(e,n,{value:{i:"O"+ ++o,w:{}}})},p=t.exports={KEY:n,NEED:!1,fastKey:function(e,t){if(!i(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!s(e,n)){if(!u(e))return"F";if(!t)return"E";c(e)}return e[n].i},getWeak:function(e,t){if(!s(e,n)){if(!u(e))return!0;if(!t)return!1;c(e)}return e[n].w},onFreeze:function(e){return l&&p.NEED&&u(e)&&!s(e,n)&&c(e),e}}},{"./_fails":231,"./_has":234,"./_is-object":241,"./_object-dp":251,"./_uid":279}],249:[function(e,t,r){"use strict";var n=e("./_object-keys"),i=e("./_object-gops"),s=e("./_object-pie"),a=e("./_to-object"),o=e("./_iobject"),u=Object.assign;t.exports=!u||e("./_fails")(function(){var e={},t={},r=Symbol(),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach(function(e){t[e]=e}),7!=u({},e)[r]||Object.keys(u({},t)).join("")!=n})?function(e,t){for(var r=a(e),u=arguments.length,l=1,c=i.f,p=s.f;u>l;)for(var h,f=o(arguments[l++]),d=c?n(f).concat(c(f)):n(f),m=d.length,y=0;m>y;)p.call(f,h=d[y++])&&(r[h]=f[h]);return r}:u},{"./_fails":231,"./_iobject":238,"./_object-gops":256,"./_object-keys":259,"./_object-pie":260,"./_to-object":277}],250:[function(e,t,r){var n=e("./_an-object"),i=e("./_object-dps"),s=e("./_enum-bug-keys"),a=e("./_shared-key")("IE_PROTO"),o=function(){},u=function(){var t,r=e("./_dom-create")("iframe"),n=s.length;for(r.style.display="none",e("./_html").appendChild(r),r.src="javascript:",(t=r.contentWindow.document).open(),t.write("