diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..545cef1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +node_modules/* linguist-generated=true diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..d2d3a74 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,18 @@ +name: Tests +on: + push: + branches: [main] + pull_request: +jobs: + tests: + name: Tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Use Node.js 15.x + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + - run: npm ci + - run: npm run build --if-present + - run: npm test diff --git a/__tests__/lint.test.js b/__tests__/lint.test.js new file mode 100644 index 0000000..003abf9 --- /dev/null +++ b/__tests__/lint.test.js @@ -0,0 +1,81 @@ +// noinspection JSUnresolvedFunction,JSUnresolvedVariable + +const lint = require('../src/lint.js'); + +test('failure', () => { + const title = 'chore: use internal PR linting action'; + const body = `Use the internal GitHub Action for linting PR title/body. + +We're using an internal one so that we can ensure a few things specific +to Finder's use case, including the correct placement of the Jira +reference.`; + + const errorCallback = jest.fn(() => {}); + lint(body, title, errorCallback, () => {}); + expect(errorCallback.mock.calls.length).toBe(1); +}); + +test('failure with empty line', () => { + const title = 'chore: something'; + const body = `Some description + +Closes ABC-123 +`; + + const errorCallback = jest.fn(() => {}); + lint(body, title, errorCallback, () => {}); + expect(errorCallback.mock.calls.length).toBe(1); +}); + +test('failure with XYZ-123', () => { + const title = 'chore: something'; + const body = `Some description + +Closes XYZ-123`; + + const errorCallback = jest.fn(() => {}); + lint(body, title, errorCallback, () => {}); + expect(errorCallback.mock.calls.length).toBe(1); +}); + +test('success', () => { + const title = 'chore: reinstate PR linter'; + const body = `Upgrading to v1.0.6 which should fix the issue where PR descriptions +like this one were failing the check: +https://github.com/finderau/site/pull/5057 + +Relates to SRE-225`; + + const errorCallback = jest.fn(() => {}); + lint(body, title, errorCallback, () => {}); + expect(errorCallback.mock.calls.length).toBe(0); +}); + +test('success with checkboxes', () => { + const title = 'feat: improve redirect page performance'; + const body = `#### Ticket Number +https://finder.atlassian.net/browse/CST-2332 + +#### Description +This PR improves redirect page performance by fixing the mechanism, which allows getting the correct niche from the URL if available. This saves time-intensive searches for the correct niche in Product API. + + +--- + +### Pre-deployment checklist + +- [ ] Confirmed that code can be deployed (no code freeze, support confirmed at least for 2 hours, sign-off from a leader if deployment outside of support hours) +- [ ] Code tested on the local or staging environment both on FIN and FUS (cross-browser and cross-device testing where appropriate) +- [ ] Code optimized ([Speed standards](https://github.com/finderau/engineering-standards/blob/master/general/2019-05-29-speed-standards.md) and not negatively affecting performance ([Web Vitals testing guide](https://finder.atlassian.net/wiki/spaces/GPD/pages/2075558987/Testing+Speed+Web+Vitals)) +- [ ] Deployment communicated properly according to [Release Risk calculation](https://github.com/finderau/engineering-standards/blob/master/general/2020-06-03-major-deployment-guidelines.md#release-risk-calculation) +- [ ] No active secrets (keys, tokens, passwords, etc) have been included in any of the commits at any point (remove and rotate them otherwise) +- [ ] Environmental variables set (both FIN and FUS) + +Remember to follow the [Major Deployment Guidelines](https://github.com/finderau/engineering-standards/blob/master/general/2020-06-03-major-deployment-guidelines.md) when deploying. + +Relates to CST-2332`; + + const errorCallback = jest.fn(() => {}); + lint(body, title, errorCallback, () => {}); + expect(errorCallback.mock.calls.length).toBe(0); +}); diff --git a/node_modules/.bin/browserslist b/node_modules/.bin/browserslist new file mode 120000 index 0000000..3cd991b --- /dev/null +++ b/node_modules/.bin/browserslist @@ -0,0 +1 @@ +../browserslist/cli.js \ No newline at end of file diff --git a/node_modules/.bin/browserslist-lint b/node_modules/.bin/browserslist-lint new file mode 120000 index 0000000..b11e16f --- /dev/null +++ b/node_modules/.bin/browserslist-lint @@ -0,0 +1 @@ +../update-browserslist-db/cli.js \ No newline at end of file diff --git a/node_modules/.bin/esparse b/node_modules/.bin/esparse new file mode 120000 index 0000000..7423b18 --- /dev/null +++ b/node_modules/.bin/esparse @@ -0,0 +1 @@ +../esprima/bin/esparse.js \ No newline at end of file diff --git a/node_modules/.bin/esvalidate b/node_modules/.bin/esvalidate new file mode 120000 index 0000000..16069ef --- /dev/null +++ b/node_modules/.bin/esvalidate @@ -0,0 +1 @@ +../esprima/bin/esvalidate.js \ No newline at end of file diff --git a/node_modules/.bin/import-local-fixture b/node_modules/.bin/import-local-fixture new file mode 120000 index 0000000..ff4b104 --- /dev/null +++ b/node_modules/.bin/import-local-fixture @@ -0,0 +1 @@ +../import-local/fixtures/cli.js \ No newline at end of file diff --git a/node_modules/.bin/jest b/node_modules/.bin/jest new file mode 120000 index 0000000..61c1861 --- /dev/null +++ b/node_modules/.bin/jest @@ -0,0 +1 @@ +../jest/bin/jest.js \ No newline at end of file diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml new file mode 120000 index 0000000..9dbd010 --- /dev/null +++ b/node_modules/.bin/js-yaml @@ -0,0 +1 @@ +../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/node_modules/.bin/jsesc b/node_modules/.bin/jsesc new file mode 120000 index 0000000..7237604 --- /dev/null +++ b/node_modules/.bin/jsesc @@ -0,0 +1 @@ +../jsesc/bin/jsesc \ No newline at end of file diff --git a/node_modules/.bin/json5 b/node_modules/.bin/json5 new file mode 120000 index 0000000..217f379 --- /dev/null +++ b/node_modules/.bin/json5 @@ -0,0 +1 @@ +../json5/lib/cli.js \ No newline at end of file diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 120000 index 0000000..6f8415e --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1 @@ +../which/bin/node-which \ No newline at end of file diff --git a/node_modules/.bin/parser b/node_modules/.bin/parser new file mode 120000 index 0000000..ce7bf97 --- /dev/null +++ b/node_modules/.bin/parser @@ -0,0 +1 @@ +../@babel/parser/bin/babel-parser.js \ No newline at end of file diff --git a/node_modules/.bin/resolve b/node_modules/.bin/resolve new file mode 120000 index 0000000..b6afda6 --- /dev/null +++ b/node_modules/.bin/resolve @@ -0,0 +1 @@ +../resolve/bin/resolve \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/@actions/core/package.json b/node_modules/@actions/core/package.json index 45341c3..f5f9413 100644 --- a/node_modules/@actions/core/package.json +++ b/node_modules/@actions/core/package.json @@ -1,16 +1,45 @@ { - "name": "@actions/core", - "version": "1.9.1", - "description": "Actions core lib", - "keywords": [ - "github", - "actions", - "core" + "_args": [ + [ + "@actions/core@1.9.1", + "/Users/jasonoconal/dev/src/github-pr-linter" + ] ], - "homepage": "https://github.com/actions/toolkit/tree/main/packages/core", - "license": "MIT", - "main": "lib/core.js", - "types": "lib/core.d.ts", + "_from": "@actions/core@1.9.1", + "_id": "@actions/core@1.9.1", + "_inBundle": false, + "_integrity": "sha512-5ad+U2YGrmmiw6du20AQW5XuWo7UKN2052FjSV7MX+Wfjf8sCqcsZe62NfgHys4QI4/Y+vQvLKYL8jWtA1ZBTA==", + "_location": "/@actions/core", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@actions/core@1.9.1", + "name": "@actions/core", + "escapedName": "@actions%2fcore", + "scope": "@actions", + "rawSpec": "1.9.1", + "saveSpec": null, + "fetchSpec": "1.9.1" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.9.1.tgz", + "_spec": "1.9.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter", + "bugs": { + "url": "https://github.com/actions/toolkit/issues" + }, + "dependencies": { + "@actions/http-client": "^2.0.1", + "uuid": "^8.3.2" + }, + "description": "Actions core lib", + "devDependencies": { + "@types/node": "^12.0.2", + "@types/uuid": "^8.3.4" + }, "directories": { "lib": "lib", "test": "__tests__" @@ -19,6 +48,15 @@ "lib", "!.DS_Store" ], + "homepage": "https://github.com/actions/toolkit/tree/main/packages/core", + "keywords": [ + "github", + "actions", + "core" + ], + "license": "MIT", + "main": "lib/core.js", + "name": "@actions/core", "publishConfig": { "access": "public" }, @@ -32,15 +70,6 @@ "test": "echo \"Error: run tests from root\" && exit 1", "tsc": "tsc" }, - "bugs": { - "url": "https://github.com/actions/toolkit/issues" - }, - "dependencies": { - "@actions/http-client": "^2.0.1", - "uuid": "^8.3.2" - }, - "devDependencies": { - "@types/node": "^12.0.2", - "@types/uuid": "^8.3.4" - } + "types": "lib/core.d.ts", + "version": "1.9.1" } diff --git a/node_modules/@actions/github/package.json b/node_modules/@actions/github/package.json index 30da327..e95b369 100644 --- a/node_modules/@actions/github/package.json +++ b/node_modules/@actions/github/package.json @@ -1,15 +1,46 @@ { - "name": "@actions/github", - "version": "5.0.3", - "description": "Actions github lib", - "keywords": [ - "github", - "actions" + "_args": [ + [ + "@actions/github@5.0.3", + "/Users/jasonoconal/dev/src/github-pr-linter" + ] ], - "homepage": "https://github.com/actions/toolkit/tree/main/packages/github", - "license": "MIT", - "main": "lib/github.js", - "types": "lib/github.d.ts", + "_from": "@actions/github@5.0.3", + "_id": "@actions/github@5.0.3", + "_inBundle": false, + "_integrity": "sha512-myjA/pdLQfhUGLtRZC/J4L1RXOG4o6aYdiEq+zr5wVVKljzbFld+xv10k1FX6IkIJtNxbAq44BdwSNpQ015P0A==", + "_location": "/@actions/github", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@actions/github@5.0.3", + "name": "@actions/github", + "escapedName": "@actions%2fgithub", + "scope": "@actions", + "rawSpec": "5.0.3", + "saveSpec": null, + "fetchSpec": "5.0.3" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/@actions/github/-/github-5.0.3.tgz", + "_spec": "5.0.3", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter", + "bugs": { + "url": "https://github.com/actions/toolkit/issues" + }, + "dependencies": { + "@actions/http-client": "^2.0.1", + "@octokit/core": "^3.6.0", + "@octokit/plugin-paginate-rest": "^2.17.0", + "@octokit/plugin-rest-endpoint-methods": "^5.13.0" + }, + "description": "Actions github lib", + "devDependencies": { + "proxy": "^1.0.2" + }, "directories": { "lib": "lib", "test": "__tests__" @@ -18,6 +49,14 @@ "lib", "!.DS_Store" ], + "homepage": "https://github.com/actions/toolkit/tree/main/packages/github", + "keywords": [ + "github", + "actions" + ], + "license": "MIT", + "main": "lib/github.js", + "name": "@actions/github", "publishConfig": { "access": "public" }, @@ -28,22 +67,12 @@ }, "scripts": { "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", - "test": "jest", "build": "tsc", "format": "prettier --write **/*.ts", "format-check": "prettier --check **/*.ts", + "test": "jest", "tsc": "tsc" }, - "bugs": { - "url": "https://github.com/actions/toolkit/issues" - }, - "dependencies": { - "@actions/http-client": "^2.0.1", - "@octokit/core": "^3.6.0", - "@octokit/plugin-paginate-rest": "^2.17.0", - "@octokit/plugin-rest-endpoint-methods": "^5.13.0" - }, - "devDependencies": { - "proxy": "^1.0.2" - } + "types": "lib/github.d.ts", + "version": "5.0.3" } diff --git a/node_modules/@actions/http-client/package.json b/node_modules/@actions/http-client/package.json index c1de221..2d958f1 100644 --- a/node_modules/@actions/http-client/package.json +++ b/node_modules/@actions/http-client/package.json @@ -1,16 +1,45 @@ { - "name": "@actions/http-client", - "version": "2.0.1", - "description": "Actions Http Client", - "keywords": [ - "github", - "actions", - "http" + "_args": [ + [ + "@actions/http-client@2.0.1", + "/Users/jasonoconal/dev/src/github-pr-linter" + ] ], - "homepage": "https://github.com/actions/toolkit/tree/main/packages/http-client", - "license": "MIT", - "main": "lib/index.js", - "types": "lib/index.d.ts", + "_from": "@actions/http-client@2.0.1", + "_id": "@actions/http-client@2.0.1", + "_inBundle": false, + "_integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==", + "_location": "/@actions/http-client", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@actions/http-client@2.0.1", + "name": "@actions/http-client", + "escapedName": "@actions%2fhttp-client", + "scope": "@actions", + "rawSpec": "2.0.1", + "saveSpec": null, + "fetchSpec": "2.0.1" + }, + "_requiredBy": [ + "/@actions/core", + "/@actions/github" + ], + "_resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz", + "_spec": "2.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter", + "bugs": { + "url": "https://github.com/actions/toolkit/issues" + }, + "dependencies": { + "tunnel": "^0.0.6" + }, + "description": "Actions Http Client", + "devDependencies": { + "@types/tunnel": "0.0.3", + "proxy": "^1.0.1" + }, "directories": { "lib": "lib", "test": "__tests__" @@ -19,6 +48,15 @@ "lib", "!.DS_Store" ], + "homepage": "https://github.com/actions/toolkit/tree/main/packages/http-client", + "keywords": [ + "github", + "actions", + "http" + ], + "license": "MIT", + "main": "lib/index.js", + "name": "@actions/http-client", "publishConfig": { "access": "public" }, @@ -29,20 +67,12 @@ }, "scripts": { "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", - "test": "echo \"Error: run tests from root\" && exit 1", "build": "tsc", "format": "prettier --write **/*.ts", "format-check": "prettier --check **/*.ts", + "test": "echo \"Error: run tests from root\" && exit 1", "tsc": "tsc" }, - "bugs": { - "url": "https://github.com/actions/toolkit/issues" - }, - "devDependencies": { - "@types/tunnel": "0.0.3", - "proxy": "^1.0.1" - }, - "dependencies": { - "tunnel": "^0.0.6" - } + "types": "lib/index.d.ts", + "version": "2.0.1" } diff --git a/node_modules/@ampproject/remapping/LICENSE b/node_modules/@ampproject/remapping/LICENSE new file mode 100644 index 0000000..f367dfb --- /dev/null +++ b/node_modules/@ampproject/remapping/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2019 Google LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@ampproject/remapping/README.md b/node_modules/@ampproject/remapping/README.md new file mode 100644 index 0000000..1463c9f --- /dev/null +++ b/node_modules/@ampproject/remapping/README.md @@ -0,0 +1,218 @@ +# @ampproject/remapping + +> Remap sequential sourcemaps through transformations to point at the original source code + +Remapping allows you to take the sourcemaps generated through transforming your code and "remap" +them to the original source locations. Think "my minified code, transformed with babel and bundled +with webpack", all pointing to the correct location in your original source code. + +With remapping, none of your source code transformations need to be aware of the input's sourcemap, +they only need to generate an output sourcemap. This greatly simplifies building custom +transformations (think a find-and-replace). + +## Installation + +```sh +npm install @ampproject/remapping +``` + +## Usage + +```typescript +function remapping( + map: SourceMap | SourceMap[], + loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined), + options?: { excludeContent: boolean, decodedMappings: boolean } +): SourceMap; + +// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the +// "source" location (where child sources are resolved relative to, or the location of original +// source), and the ability to override the "content" of an original source for inclusion in the +// output sourcemap. +type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +} +``` + +`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer +in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents +a transformed file (it has a sourcmap associated with it), then the `loader` should return that +sourcemap. If not, the path will be treated as an original, untransformed source code. + +```js +// Babel transformed "helloworld.js" into "transformed.js" +const transformedMap = JSON.stringify({ + file: 'transformed.js', + // 1st column of 2nd line of output file translates into the 1st source + // file, line 3, column 2 + mappings: ';CAEE', + sources: ['helloworld.js'], + version: 3, +}); + +// Uglify minified "transformed.js" into "transformed.min.js" +const minifiedTransformedMap = JSON.stringify({ + file: 'transformed.min.js', + // 0th column of 1st line of output file translates into the 1st source + // file, line 2, column 1. + mappings: 'AACC', + names: [], + sources: ['transformed.js'], + version: 3, +}); + +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + // The "transformed.js" file is an transformed file. + if (file === 'transformed.js') { + // The root importer is empty. + console.assert(ctx.importer === ''); + // The depth in the sourcemap tree we're currently loading. + // The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc. + console.assert(ctx.depth === 1); + + return transformedMap; + } + + // Loader will be called to load transformedMap's source file pointers as well. + console.assert(file === 'helloworld.js'); + // `transformed.js`'s sourcemap points into `helloworld.js`. + console.assert(ctx.importer === 'transformed.js'); + // This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`. + console.assert(ctx.depth === 2); + return null; + } +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +In this example, `loader` will be called twice: + +1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the + associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can + be traced through it into the source files it represents. +2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so + we return `null`. + +The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If +you were to read the `mappings`, it says "0th column of the first line output line points to the 1st +column of the 2nd line of the file `helloworld.js`". + +### Multiple transformations of a file + +As a convenience, if you have multiple single-source transformations of a file, you may pass an +array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this +changes the `importer` and `depth` of each call to our loader. So our above example could have been +written as: + +```js +const remapped = remapping( + [minifiedTransformedMap, transformedMap], + () => null +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +### Advanced control of the loading graph + +#### `source` + +The `source` property can overridden to any value to change the location of the current load. Eg, +for an original source file, it allows us to change the location to the original source regardless +of what the sourcemap source entry says. And for transformed files, it allows us to change the +relative resolving location for child sources of the loaded sourcemap. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // We pretend the transformed.js file actually exists in the 'src/' directory. When the nested + // source files are loaded, they will now be relative to `src/`. + ctx.source = 'src/transformed.js'; + return transformedMap; + } + + console.assert(file === 'src/helloworld.js'); + // We could futher change the source of this original file, eg, to be inside a nested directory + // itself. This will be reflected in the remapped sourcemap. + ctx.source = 'src/nested/transformed.js'; + return null; + } +); + +console.log(remapped); +// { +// …, +// sources: ['src/nested/helloworld.js'], +// }; +``` + + +#### `content` + +The `content` property can be overridden when we encounter an original source file. Eg, this allows +you to manually provide the source content of the original file regardless of whether the +`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove +the source content. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap + // would not include any `sourcesContent` values. + return transformedMap; + } + + console.assert(file === 'helloworld.js'); + // We can read the file to provide the source content. + ctx.content = fs.readFileSync(file, 'utf8'); + return null; + } +); + +console.log(remapped); +// { +// …, +// sourcesContent: [ +// 'console.log("Hello world!")', +// ], +// }; +``` + +### Options + +#### excludeContent + +By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the +`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce +the size out the sourcemap. + +#### decodedMappings + +By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the +`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of +encoding into a VLQ string. diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs b/node_modules/@ampproject/remapping/dist/remapping.mjs new file mode 100644 index 0000000..c6e66b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs @@ -0,0 +1,204 @@ +import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping'; +import { GenMapping, addSegment, setSourceContent, decodedMap, encodedMap } from '@jridgewell/gen-mapping'; + +const SOURCELESS_MAPPING = { + source: null, + column: null, + line: null, + name: null, + content: null, +}; +const EMPTY_SOURCES = []; +function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + let lastSource = null; + let lastSourceLine = null; + let lastSourceColumn = null; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + // So we traced a segment down into its original source file. Now push a + // new segment pointing to this location. + const { column, line, name, content, source } = traced; + if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) { + continue; + } + lastSourceLine = line; + lastSourceColumn = column; + lastSource = source; + // Sigh, TypeScript can't figure out source/line/column are either all null, or all non-null... + addSegment(gen, i, genCol, source, line, column, name); + if (content != null) + setSourceContent(gen, source, content); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return { column, line, name, source: source.source, content: source.content }; + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? decodedMap(map) : encodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +export { remapping as default }; +//# sourceMappingURL=remapping.mjs.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs.map b/node_modules/@ampproject/remapping/dist/remapping.mjs.map new file mode 100644 index 0000000..54066bb --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.mjs","sources":["../../src/source-map-tree.ts","../../src/build-source-map-tree.ts","../../src/source-map.ts","../../src/remapping.ts"],"sourcesContent":[null,null,null,null],"names":[],"mappings":";;;AAqBA,MAAM,kBAAkB,GAAG;AACzB,IAAA,MAAM,EAAE,IAAI;AACZ,IAAA,MAAM,EAAE,IAAI;AACZ,IAAA,IAAI,EAAE,IAAI;AACV,IAAA,IAAI,EAAE,IAAI;AACV,IAAA,OAAO,EAAE,IAAI;CACd,CAAC;AACF,MAAM,aAAa,GAAc,EAAE,CAAC;AAkBpC,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAc,EACd,OAAsB,EAAA;IAEtB,OAAO;QACL,GAAG;QACH,OAAO;QACP,MAAM;QACN,OAAO;KACD,CAAC;AACX,CAAC;AAED;;;AAGG;AACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;IACzD,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC;AAED;;;AAGG;AACa,SAAA,cAAc,CAAC,MAAc,EAAE,OAAsB,EAAA;IACnE,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACtD,CAAC;AAED;;;AAGG;AACG,SAAU,aAAa,CAAC,IAAe,EAAA;AAC3C,IAAA,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC3C,IAAA,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC;AAC5B,IAAA,MAAM,YAAY,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;AAE1C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC5C,QAAA,MAAM,QAAQ,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;QAEjC,IAAI,UAAU,GAAG,IAAI,CAAC;QACtB,IAAI,cAAc,GAAG,IAAI,CAAC;QAC1B,IAAI,gBAAgB,GAAG,IAAI,CAAC;AAE5B,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACxC,YAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC5B,YAAA,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;YAC1B,IAAI,MAAM,GAAkC,kBAAkB,CAAC;;;AAI/D,YAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;gBACxB,MAAM,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AACvC,gBAAA,MAAM,GAAG,mBAAmB,CAC1B,MAAM,EACN,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAClD,CAAC;;;gBAIF,IAAI,MAAM,IAAI,IAAI;oBAAE,SAAS;AAC9B,aAAA;;;AAID,YAAA,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;YACvD,IAAI,IAAI,KAAK,cAAc,IAAI,MAAM,KAAK,gBAAgB,IAAI,MAAM,KAAK,UAAU,EAAE;gBACnF,SAAS;AACV,aAAA;YACD,cAAc,GAAG,IAAI,CAAC;YACtB,gBAAgB,GAAG,MAAM,CAAC;YAC1B,UAAU,GAAG,MAAM,CAAC;;AAGnB,YAAA,UAAkB,CAAC,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;YAChE,IAAI,OAAO,IAAI,IAAI;AAAE,gBAAA,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAC7D,SAAA;AACF,KAAA;AAED,IAAA,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;AAGG;AACG,SAAU,mBAAmB,CACjC,MAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAY,EAAA;AAEZ,IAAA,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;AACf,QAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AAC/E,KAAA;AAED,IAAA,MAAM,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;;IAGvD,IAAI,OAAO,IAAI,IAAI;AAAE,QAAA,OAAO,IAAI,CAAC;;;AAGjC,IAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,kBAAkB,CAAC;IAEpD,OAAO,mBAAmB,CACxB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAC1B,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAC3D,CAAC;AACJ;;AC1JA,SAAS,OAAO,CAAI,KAAc,EAAA;AAChC,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK,CAAC;IACvC,OAAO,CAAC,KAAK,CAAC,CAAC;AACjB,CAAC;AAED;;;;;;;;;;AAUG;AACW,SAAU,kBAAkB,CACxC,KAAwC,EACxC,MAAuB,EAAA;IAEvB,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5D,IAAA,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAG,CAAC;AAExB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACpC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;AAC9B,YAAA,MAAM,IAAI,KAAK,CACb,CAAA,mBAAA,EAAsB,CAAC,CAAuC,qCAAA,CAAA;AAC5D,gBAAA,uEAAuE,CAC1E,CAAC;AACH,SAAA;AACF,KAAA;AAED,IAAA,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;AACrC,IAAA,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;AACzC,QAAA,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACnC,KAAA;AACD,IAAA,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,KAAK,CACZ,GAAa,EACb,MAAuB,EACvB,QAAgB,EAChB,aAAqB,EAAA;AAErB,IAAA,MAAM,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;AAEhD,IAAA,MAAM,KAAK,GAAG,aAAa,GAAG,CAAC,CAAC;IAChC,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,UAAyB,EAAE,CAAS,KAAa;;;;;AAKrF,QAAA,MAAM,GAAG,GAAkB;YACzB,QAAQ;YACR,KAAK;YACL,MAAM,EAAE,UAAU,IAAI,EAAE;AACxB,YAAA,OAAO,EAAE,SAAS;SACnB,CAAC;;;QAIF,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAE1C,QAAA,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;;AAGhC,QAAA,IAAI,SAAS;AAAE,YAAA,OAAO,KAAK,CAAC,IAAI,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;;;;;QAMpF,MAAM,aAAa,GACjB,OAAO,KAAK,SAAS,GAAG,OAAO,GAAG,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;AAC9E,QAAA,OAAO,cAAc,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AAC/C,KAAC,CAAC,CAAC;AAEH,IAAA,OAAO,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;AAClC;;ACjFA;;;AAGG;AACW,MAAO,SAAS,CAAA;IAS5B,WAAY,CAAA,GAAe,EAAE,OAAgB,EAAA;AAC3C,QAAA,MAAM,GAAG,GAAG,OAAO,CAAC,eAAe,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;AAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;AACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;AACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;AAE7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;AAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;AACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;AAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;AACzE,SAAA;KACF;IAED,QAAQ,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;KAC7B;AACF;;ACpBD;;;;;;;;;;;;;;AAcG;AACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;IAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;IAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClD;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js b/node_modules/@ampproject/remapping/dist/remapping.umd.js new file mode 100644 index 0000000..593c61d --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js @@ -0,0 +1,209 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) : + typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping)); +})(this, (function (traceMapping, genMapping) { 'use strict'; + + const SOURCELESS_MAPPING = { + source: null, + column: null, + line: null, + name: null, + content: null, + }; + const EMPTY_SOURCES = []; + function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; + } + /** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ + function MapSource(map, sources) { + return Source(map, sources, '', null); + } + /** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ + function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ + function traceMappings(tree) { + const gen = new genMapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = traceMapping.decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + let lastSource = null; + let lastSourceLine = null; + let lastSourceColumn = null; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + // So we traced a segment down into its original source file. Now push a + // new segment pointing to this location. + const { column, line, name, content, source } = traced; + if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) { + continue; + } + lastSourceLine = line; + lastSourceColumn = column; + lastSource = source; + // Sigh, TypeScript can't figure out source/line/column are either all null, or all non-null... + genMapping.addSegment(gen, i, genCol, source, line, column, name); + if (content != null) + genMapping.setSourceContent(gen, source, content); + } + } + return gen; + } + /** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ + function originalPositionFor(source, line, column, name) { + if (!source.map) { + return { column, line, name, source: source.source, content: source.content }; + } + const segment = traceMapping.traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); + } + + function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; + } + /** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ + function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; + } + function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); + } + + /** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ + class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? genMapping.decodedMap(map) : genMapping.encodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } + } + + /** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ + function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); + } + + return remapping; + +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js.map b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map new file mode 100644 index 0000000..726f2bc --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.umd.js","sources":["../../src/source-map-tree.ts","../../src/build-source-map-tree.ts","../../src/source-map.ts","../../src/remapping.ts"],"sourcesContent":[null,null,null,null],"names":["GenMapping","decodedMappings","addSegment","setSourceContent","traceSegment","TraceMap","decodedMap","encodedMap"],"mappings":";;;;;;IAqBA,MAAM,kBAAkB,GAAG;IACzB,IAAA,MAAM,EAAE,IAAI;IACZ,IAAA,MAAM,EAAE,IAAI;IACZ,IAAA,IAAI,EAAE,IAAI;IACV,IAAA,IAAI,EAAE,IAAI;IACV,IAAA,OAAO,EAAE,IAAI;KACd,CAAC;IACF,MAAM,aAAa,GAAc,EAAE,CAAC;IAkBpC,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAc,EACd,OAAsB,EAAA;QAEtB,OAAO;YACL,GAAG;YACH,OAAO;YACP,MAAM;YACN,OAAO;SACD,CAAC;IACX,CAAC;IAED;;;IAGG;IACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;QACzD,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IACxC,CAAC;IAED;;;IAGG;IACa,SAAA,cAAc,CAAC,MAAc,EAAE,OAAsB,EAAA;QACnE,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED;;;IAGG;IACG,SAAU,aAAa,CAAC,IAAe,EAAA;IAC3C,IAAA,MAAM,GAAG,GAAG,IAAIA,qBAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QACpD,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAC3C,IAAA,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC;IAC5B,IAAA,MAAM,YAAY,GAAGC,4BAAe,CAAC,GAAG,CAAC,CAAC;IAE1C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IAC5C,QAAA,MAAM,QAAQ,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;YAEjC,IAAI,UAAU,GAAG,IAAI,CAAC;YACtB,IAAI,cAAc,GAAG,IAAI,CAAC;YAC1B,IAAI,gBAAgB,GAAG,IAAI,CAAC;IAE5B,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACxC,YAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC5B,YAAA,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;gBAC1B,IAAI,MAAM,GAAkC,kBAAkB,CAAC;;;IAI/D,YAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;oBACxB,MAAM,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACvC,gBAAA,MAAM,GAAG,mBAAmB,CAC1B,MAAM,EACN,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAClD,CAAC;;;oBAIF,IAAI,MAAM,IAAI,IAAI;wBAAE,SAAS;IAC9B,aAAA;;;IAID,YAAA,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;gBACvD,IAAI,IAAI,KAAK,cAAc,IAAI,MAAM,KAAK,gBAAgB,IAAI,MAAM,KAAK,UAAU,EAAE;oBACnF,SAAS;IACV,aAAA;gBACD,cAAc,GAAG,IAAI,CAAC;gBACtB,gBAAgB,GAAG,MAAM,CAAC;gBAC1B,UAAU,GAAG,MAAM,CAAC;;IAGnB,YAAAC,qBAAkB,CAAC,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;gBAChE,IAAI,OAAO,IAAI,IAAI;IAAE,gBAAAC,2BAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC7D,SAAA;IACF,KAAA;IAED,IAAA,OAAO,GAAG,CAAC;IACb,CAAC;IAED;;;IAGG;IACG,SAAU,mBAAmB,CACjC,MAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAY,EAAA;IAEZ,IAAA,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;IACf,QAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;IAC/E,KAAA;IAED,IAAA,MAAM,OAAO,GAAGC,yBAAY,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;;QAGvD,IAAI,OAAO,IAAI,IAAI;IAAE,QAAA,OAAO,IAAI,CAAC;;;IAGjC,IAAA,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;IAAE,QAAA,OAAO,kBAAkB,CAAC;QAEpD,OAAO,mBAAmB,CACxB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAC1B,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,CAAC,CAAC,EACV,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAC3D,CAAC;IACJ;;IC1JA,SAAS,OAAO,CAAI,KAAc,EAAA;IAChC,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;IAAE,QAAA,OAAO,KAAK,CAAC;QACvC,OAAO,CAAC,KAAK,CAAC,CAAC;IACjB,CAAC;IAED;;;;;;;;;;IAUG;IACW,SAAU,kBAAkB,CACxC,KAAwC,EACxC,MAAuB,EAAA;QAEvB,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,IAAIC,qBAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5D,IAAA,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAG,CAAC;IAExB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;IAC9B,YAAA,MAAM,IAAI,KAAK,CACb,CAAA,mBAAA,EAAsB,CAAC,CAAuC,qCAAA,CAAA;IAC5D,gBAAA,uEAAuE,CAC1E,CAAC;IACH,SAAA;IACF,KAAA;IAED,IAAA,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;IACrC,IAAA,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;IACzC,QAAA,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IACnC,KAAA;IACD,IAAA,OAAO,IAAI,CAAC;IACd,CAAC;IAED,SAAS,KAAK,CACZ,GAAa,EACb,MAAuB,EACvB,QAAgB,EAChB,aAAqB,EAAA;IAErB,IAAA,MAAM,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;IAEhD,IAAA,MAAM,KAAK,GAAG,aAAa,GAAG,CAAC,CAAC;QAChC,MAAM,QAAQ,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,UAAyB,EAAE,CAAS,KAAa;;;;;IAKrF,QAAA,MAAM,GAAG,GAAkB;gBACzB,QAAQ;gBACR,KAAK;gBACL,MAAM,EAAE,UAAU,IAAI,EAAE;IACxB,YAAA,OAAO,EAAE,SAAS;aACnB,CAAC;;;YAIF,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAE1C,QAAA,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,CAAC;;IAGhC,QAAA,IAAI,SAAS;IAAE,YAAA,OAAO,KAAK,CAAC,IAAIA,qBAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;;;;;YAMpF,MAAM,aAAa,GACjB,OAAO,KAAK,SAAS,GAAG,OAAO,GAAG,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAC9E,QAAA,OAAO,cAAc,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC/C,KAAC,CAAC,CAAC;IAEH,IAAA,OAAO,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAClC;;ICjFA;;;IAGG;IACW,MAAO,SAAS,CAAA;QAS5B,WAAY,CAAA,GAAe,EAAE,OAAgB,EAAA;IAC3C,QAAA,MAAM,GAAG,GAAG,OAAO,CAAC,eAAe,GAAGC,qBAAU,CAAC,GAAG,CAAC,GAAGC,qBAAU,CAAC,GAAG,CAAC,CAAC;YACxE,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;IAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;IACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;IAE7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;IACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;IAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;IACzE,SAAA;SACF;QAED,QAAQ,GAAA;IACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SAC7B;IACF;;ICpBD;;;;;;;;;;;;;;IAcG;IACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;QAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;QAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAClD;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts new file mode 100644 index 0000000..f87fcea --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts @@ -0,0 +1,14 @@ +import type { MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader } from './types'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; diff --git a/node_modules/@ampproject/remapping/dist/types/remapping.d.ts b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts new file mode 100644 index 0000000..0b58ea9 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts @@ -0,0 +1,19 @@ +import SourceMap from './source-map'; +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types'; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts new file mode 100644 index 0000000..3b6b1bf --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts @@ -0,0 +1,48 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export declare type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; +} | { + column: null; + line: null; + name: null; + source: null; + content: null; +}; +export declare type OriginalSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: string | null; +}; +export declare type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: string | null; +}; +export declare type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts new file mode 100644 index 0000000..ef999b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts @@ -0,0 +1,17 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + constructor(map: GenMapping, options: Options); + toString(): string; +} diff --git a/node_modules/@ampproject/remapping/dist/types/types.d.ts b/node_modules/@ampproject/remapping/dist/types/types.d.ts new file mode 100644 index 0000000..730a963 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/types.d.ts @@ -0,0 +1,14 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export declare type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +}; +export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export declare type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/node_modules/@ampproject/remapping/package.json b/node_modules/@ampproject/remapping/package.json new file mode 100644 index 0000000..2109f81 --- /dev/null +++ b/node_modules/@ampproject/remapping/package.json @@ -0,0 +1,96 @@ +{ + "_from": "@ampproject/remapping@^2.1.0", + "_id": "@ampproject/remapping@2.2.0", + "_inBundle": false, + "_integrity": "sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w==", + "_location": "/@ampproject/remapping", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@ampproject/remapping@^2.1.0", + "name": "@ampproject/remapping", + "escapedName": "@ampproject%2fremapping", + "scope": "@ampproject", + "rawSpec": "^2.1.0", + "saveSpec": null, + "fetchSpec": "^2.1.0" + }, + "_requiredBy": [ + "/@babel/core" + ], + "_resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", + "_shasum": "56c133824780de3174aed5ab6834f3026790154d", + "_spec": "@ampproject/remapping@^2.1.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/core", + "author": { + "name": "Justin Ridgewell", + "email": "jridgewell@google.com" + }, + "bugs": { + "url": "https://github.com/ampproject/remapping/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "deprecated": false, + "description": "Remap sequential sourcemaps through transformations to point at the original source code", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/jest": "27.4.1", + "@typescript-eslint/eslint-plugin": "5.20.0", + "@typescript-eslint/parser": "5.20.0", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "jest": "27.5.1", + "jest-config": "27.5.1", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "ts-jest": "27.1.4", + "tslib": "2.4.0", + "typescript": "4.6.3" + }, + "engines": { + "node": ">=6.0.0" + }, + "files": [ + "dist" + ], + "homepage": "https://github.com/ampproject/remapping#readme", + "keywords": [ + "source", + "map", + "remap" + ], + "license": "Apache-2.0", + "main": "dist/remapping.umd.js", + "module": "dist/remapping.mjs", + "name": "@ampproject/remapping", + "repository": { + "type": "git", + "url": "git+https://github.com/ampproject/remapping.git" + }, + "scripts": { + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "jest --coverage", + "test:watch": "jest --coverage --watch" + }, + "typings": "dist/types/remapping.d.ts", + "version": "2.2.0" +} diff --git a/node_modules/@babel/code-frame/LICENSE b/node_modules/@babel/code-frame/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/code-frame/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/code-frame/README.md b/node_modules/@babel/code-frame/README.md new file mode 100644 index 0000000..08cacb0 --- /dev/null +++ b/node_modules/@babel/code-frame/README.md @@ -0,0 +1,19 @@ +# @babel/code-frame + +> Generate errors that contain a code frame that point to source locations. + +See our website [@babel/code-frame](https://babeljs.io/docs/en/babel-code-frame) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/code-frame +``` + +or using yarn: + +```sh +yarn add @babel/code-frame --dev +``` diff --git a/node_modules/@babel/code-frame/lib/index.js b/node_modules/@babel/code-frame/lib/index.js new file mode 100644 index 0000000..cba3f83 --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js @@ -0,0 +1,163 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.codeFrameColumns = codeFrameColumns; +exports.default = _default; + +var _highlight = require("@babel/highlight"); + +let deprecationWarningShown = false; + +function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; +} + +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + +function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + + if (startLine === -1) { + start = 0; + } + + if (endLine === -1) { + end = source.length; + } + + const lineDiff = endLine - startLine; + const markerLines = {}; + + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + + return { + start, + end, + markerLines + }; +} + +function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = (0, _highlight.getChalk)(opts); + const defs = getDefs(chalk); + + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; + + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + + if (hasMarker) { + let markerLine = ""; + + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } +} + +function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); +} \ No newline at end of file diff --git a/node_modules/@babel/code-frame/package.json b/node_modules/@babel/code-frame/package.json new file mode 100644 index 0000000..5872eab --- /dev/null +++ b/node_modules/@babel/code-frame/package.json @@ -0,0 +1,65 @@ +{ + "_from": "@babel/code-frame@^7.12.13", + "_id": "@babel/code-frame@7.18.6", + "_inBundle": false, + "_integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "_location": "/@babel/code-frame", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/code-frame@^7.12.13", + "name": "@babel/code-frame", + "escapedName": "@babel%2fcode-frame", + "scope": "@babel", + "rawSpec": "^7.12.13", + "saveSpec": null, + "fetchSpec": "^7.12.13" + }, + "_requiredBy": [ + "/@babel/core", + "/@babel/template", + "/@babel/traverse", + "/jest-message-util", + "/parse-json" + ], + "_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "_shasum": "3b25d38c89600baa2dcc219edfa88a74eb2c427a", + "_spec": "@babel/code-frame@^7.12.13", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-message-util", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "deprecated": false, + "description": "Generate errors that contain a code frame that point to source locations.", + "devDependencies": { + "@types/chalk": "^2.0.0", + "chalk": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-code-frame", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/code-frame", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-code-frame" + }, + "type": "commonjs", + "version": "7.18.6" +} diff --git a/node_modules/@babel/compat-data/LICENSE b/node_modules/@babel/compat-data/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/compat-data/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/compat-data/README.md b/node_modules/@babel/compat-data/README.md new file mode 100644 index 0000000..9f3abde --- /dev/null +++ b/node_modules/@babel/compat-data/README.md @@ -0,0 +1,19 @@ +# @babel/compat-data + +> + +See our website [@babel/compat-data](https://babeljs.io/docs/en/babel-compat-data) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/compat-data +``` + +or using yarn: + +```sh +yarn add @babel/compat-data +``` diff --git a/node_modules/@babel/compat-data/corejs2-built-ins.js b/node_modules/@babel/compat-data/corejs2-built-ins.js new file mode 100644 index 0000000..68ce97f --- /dev/null +++ b/node_modules/@babel/compat-data/corejs2-built-ins.js @@ -0,0 +1 @@ +module.exports = require("./data/corejs2-built-ins.json"); diff --git a/node_modules/@babel/compat-data/corejs3-shipped-proposals.js b/node_modules/@babel/compat-data/corejs3-shipped-proposals.js new file mode 100644 index 0000000..6a85b4d --- /dev/null +++ b/node_modules/@babel/compat-data/corejs3-shipped-proposals.js @@ -0,0 +1 @@ +module.exports = require("./data/corejs3-shipped-proposals.json"); diff --git a/node_modules/@babel/compat-data/data/corejs2-built-ins.json b/node_modules/@babel/compat-data/data/corejs2-built-ins.json new file mode 100644 index 0000000..b9e4cfe --- /dev/null +++ b/node_modules/@babel/compat-data/data/corejs2-built-ins.json @@ -0,0 +1,1789 @@ +{ + "es6.array.copy-within": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "32", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.every": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.fill": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "31", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.filter": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.array.find": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.find-index": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es7.array.flat-map": { + "chrome": "69", + "opera": "56", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "11", + "ios": "12", + "samsung": "10", + "electron": "4.0" + }, + "es6.array.for-each": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.from": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "36", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es7.array.includes": { + "chrome": "47", + "opera": "34", + "edge": "14", + "firefox": "102", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "es6.array.index-of": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.is-array": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.iterator": { + "chrome": "66", + "opera": "53", + "edge": "12", + "firefox": "60", + "safari": "9", + "node": "10", + "ios": "9", + "samsung": "9", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es6.array.last-index-of": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.map": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.array.of": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.reduce": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.reduce-right": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.slice": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.array.some": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.sort": { + "chrome": "63", + "opera": "50", + "edge": "12", + "firefox": "5", + "safari": "12", + "node": "10", + "ie": "9", + "ios": "12", + "samsung": "8", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es6.array.species": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.date.now": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.date.to-iso-string": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3.5", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.date.to-json": { + "chrome": "5", + "opera": "12.10", + "edge": "12", + "firefox": "4", + "safari": "10", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "10", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.date.to-primitive": { + "chrome": "47", + "opera": "34", + "edge": "15", + "firefox": "44", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "es6.date.to-string": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "10", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.function.bind": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.function.has-instance": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "50", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.function.name": { + "chrome": "5", + "opera": "10.50", + "edge": "14", + "firefox": "2", + "safari": "4", + "node": "0.4", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.map": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.math.acosh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.asinh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.atanh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.cbrt": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.clz32": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.cosh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.expm1": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.fround": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "26", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.hypot": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "27", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.imul": { + "chrome": "30", + "opera": "17", + "edge": "12", + "firefox": "23", + "safari": "7", + "node": "0.12", + "android": "4.4", + "ios": "7", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.log1p": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.log10": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.log2": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.sign": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.sinh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.tanh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.trunc": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.constructor": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.number.epsilon": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.number.is-finite": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "16", + "safari": "9", + "node": "0.8", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.is-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "16", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.is-nan": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "15", + "safari": "9", + "node": "0.8", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.is-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "32", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.max-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.min-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.parse-float": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.number.parse-int": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.object.assign": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "36", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.object.create": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.object.define-getter": { + "chrome": "62", + "opera": "49", + "edge": "16", + "firefox": "48", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es7.object.define-setter": { + "chrome": "62", + "opera": "49", + "edge": "16", + "firefox": "48", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es6.object.define-property": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.object.define-properties": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.object.entries": { + "chrome": "54", + "opera": "41", + "edge": "14", + "firefox": "47", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "electron": "1.4" + }, + "es6.object.freeze": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.get-own-property-descriptor": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es7.object.get-own-property-descriptors": { + "chrome": "54", + "opera": "41", + "edge": "15", + "firefox": "50", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "electron": "1.4" + }, + "es6.object.get-own-property-names": { + "chrome": "40", + "opera": "27", + "edge": "12", + "firefox": "33", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.object.get-prototype-of": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es7.object.lookup-getter": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "36", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es7.object.lookup-setter": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "36", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es6.object.prevent-extensions": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.to-string": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "51", + "safari": "10", + "node": "8", + "ios": "10", + "samsung": "7", + "electron": "1.7" + }, + "es6.object.is": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "22", + "safari": "9", + "node": "0.8", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.object.is-frozen": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.is-sealed": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.is-extensible": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.keys": { + "chrome": "40", + "opera": "27", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.object.seal": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.set-prototype-of": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ie": "11", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.object.values": { + "chrome": "54", + "opera": "41", + "edge": "14", + "firefox": "47", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "electron": "1.4" + }, + "es6.promise": { + "chrome": "51", + "opera": "38", + "edge": "14", + "firefox": "45", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es7.promise.finally": { + "chrome": "63", + "opera": "50", + "edge": "18", + "firefox": "58", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "8", + "electron": "3.0" + }, + "es6.reflect.apply": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.construct": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.define-property": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.delete-property": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.get": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.get-own-property-descriptor": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.get-prototype-of": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.has": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.is-extensible": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.own-keys": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.prevent-extensions": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.set": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.set-prototype-of": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.regexp.constructor": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "40", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.regexp.flags": { + "chrome": "49", + "opera": "36", + "edge": "79", + "firefox": "37", + "safari": "9", + "node": "6", + "ios": "9", + "samsung": "5", + "electron": "0.37" + }, + "es6.regexp.match": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "electron": "1.1" + }, + "es6.regexp.replace": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.regexp.split": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.regexp.search": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "electron": "1.1" + }, + "es6.regexp.to-string": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "39", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.set": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.symbol": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "51", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es7.symbol.async-iterator": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "8", + "electron": "3.0" + }, + "es6.string.anchor": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.big": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.blink": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.bold": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.code-point-at": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.ends-with": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.fixed": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.fontcolor": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.fontsize": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.from-code-point": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.includes": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "40", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.italics": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.iterator": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.string.link": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es7.string.pad-start": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "48", + "safari": "10", + "node": "8", + "ios": "10", + "samsung": "7", + "rhino": "1.7.13", + "electron": "1.7" + }, + "es7.string.pad-end": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "48", + "safari": "10", + "node": "8", + "ios": "10", + "samsung": "7", + "rhino": "1.7.13", + "electron": "1.7" + }, + "es6.string.raw": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "34", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.14", + "electron": "0.21" + }, + "es6.string.repeat": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "24", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.small": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.starts-with": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.strike": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.sub": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.sup": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.trim": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3.5", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.string.trim-left": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "61", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "9", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es7.string.trim-right": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "61", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "9", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es6.typed.array-buffer": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.data-view": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "15", + "safari": "5.1", + "node": "0.4", + "ie": "10", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.typed.int8-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint8-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint8-clamped-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.int16-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint16-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.int32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.float32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.float64-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.weak-map": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "9", + "node": "6.5", + "ios": "9", + "samsung": "5", + "electron": "1.2" + }, + "es6.weak-set": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "9", + "node": "6.5", + "ios": "9", + "samsung": "5", + "electron": "1.2" + } +} diff --git a/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json b/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json new file mode 100644 index 0000000..7ce01ed --- /dev/null +++ b/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json @@ -0,0 +1,5 @@ +[ + "esnext.global-this", + "esnext.promise.all-settled", + "esnext.string.match-all" +] diff --git a/node_modules/@babel/compat-data/data/native-modules.json b/node_modules/@babel/compat-data/data/native-modules.json new file mode 100644 index 0000000..bf63499 --- /dev/null +++ b/node_modules/@babel/compat-data/data/native-modules.json @@ -0,0 +1,18 @@ +{ + "es6.module": { + "chrome": "61", + "and_chr": "61", + "edge": "16", + "firefox": "60", + "and_ff": "60", + "node": "13.2.0", + "opera": "48", + "op_mob": "48", + "safari": "10.1", + "ios": "10.3", + "samsung": "8.2", + "android": "61", + "electron": "2.0", + "ios_saf": "10.3" + } +} diff --git a/node_modules/@babel/compat-data/data/overlapping-plugins.json b/node_modules/@babel/compat-data/data/overlapping-plugins.json new file mode 100644 index 0000000..6ad09e4 --- /dev/null +++ b/node_modules/@babel/compat-data/data/overlapping-plugins.json @@ -0,0 +1,22 @@ +{ + "transform-async-to-generator": [ + "bugfix/transform-async-arrows-in-class" + ], + "transform-parameters": [ + "bugfix/transform-edge-default-parameters", + "bugfix/transform-safari-id-destructuring-collision-in-function-expression" + ], + "transform-function-name": [ + "bugfix/transform-edge-function-name" + ], + "transform-block-scoping": [ + "bugfix/transform-safari-block-shadowing", + "bugfix/transform-safari-for-shadowing" + ], + "transform-template-literals": [ + "bugfix/transform-tagged-template-caching" + ], + "proposal-optional-chaining": [ + "bugfix/transform-v8-spread-parameters-in-optional-chaining" + ] +} diff --git a/node_modules/@babel/compat-data/data/plugin-bugfixes.json b/node_modules/@babel/compat-data/data/plugin-bugfixes.json new file mode 100644 index 0000000..a16d707 --- /dev/null +++ b/node_modules/@babel/compat-data/data/plugin-bugfixes.json @@ -0,0 +1,157 @@ +{ + "bugfix/transform-async-arrows-in-class": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "11", + "node": "7.6", + "ios": "11", + "samsung": "6", + "electron": "1.6" + }, + "bugfix/transform-edge-default-parameters": { + "chrome": "49", + "opera": "36", + "edge": "18", + "firefox": "52", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "bugfix/transform-edge-function-name": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "bugfix/transform-safari-block-shadowing": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "44", + "safari": "11", + "node": "6", + "ie": "11", + "ios": "11", + "samsung": "5", + "electron": "0.37" + }, + "bugfix/transform-safari-for-shadowing": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "4", + "safari": "11", + "node": "6", + "ie": "11", + "ios": "11", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.37" + }, + "bugfix/transform-safari-id-destructuring-collision-in-function-expression": { + "chrome": "49", + "opera": "36", + "edge": "14", + "firefox": "2", + "node": "6", + "samsung": "5", + "electron": "0.37" + }, + "bugfix/transform-tagged-template-caching": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "34", + "safari": "13", + "node": "4", + "ios": "13", + "samsung": "3.4", + "rhino": "1.7.14", + "electron": "0.21" + }, + "bugfix/transform-v8-spread-parameters-in-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "ios": "13.4", + "electron": "13.0" + }, + "proposal-optional-chaining": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "74", + "safari": "13.1", + "node": "14", + "ios": "13.4", + "samsung": "13", + "electron": "8.0" + }, + "transform-parameters": { + "chrome": "49", + "opera": "36", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "transform-async-to-generator": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "10.1", + "node": "7.6", + "ios": "10.3", + "samsung": "6", + "electron": "1.6" + }, + "transform-template-literals": { + "chrome": "41", + "opera": "28", + "edge": "13", + "firefox": "34", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "electron": "0.21" + }, + "transform-function-name": { + "chrome": "51", + "opera": "38", + "edge": "14", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-block-scoping": { + "chrome": "49", + "opera": "36", + "edge": "14", + "firefox": "51", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + } +} diff --git a/node_modules/@babel/compat-data/data/plugins.json b/node_modules/@babel/compat-data/data/plugins.json new file mode 100644 index 0000000..96c64ca --- /dev/null +++ b/node_modules/@babel/compat-data/data/plugins.json @@ -0,0 +1,478 @@ +{ + "proposal-class-static-block": { + "chrome": "94", + "opera": "80", + "edge": "94", + "firefox": "93", + "node": "16.11", + "electron": "15.0" + }, + "proposal-private-property-in-object": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "90", + "safari": "15", + "node": "16.9", + "ios": "15", + "electron": "13.0" + }, + "proposal-class-properties": { + "chrome": "74", + "opera": "62", + "edge": "79", + "firefox": "90", + "safari": "14.1", + "node": "12", + "ios": "15", + "samsung": "11", + "electron": "6.0" + }, + "proposal-private-methods": { + "chrome": "84", + "opera": "70", + "edge": "84", + "firefox": "90", + "safari": "15", + "node": "14.6", + "ios": "15", + "samsung": "14", + "electron": "10.0" + }, + "proposal-numeric-separator": { + "chrome": "75", + "opera": "62", + "edge": "79", + "firefox": "70", + "safari": "13", + "node": "12.5", + "ios": "13", + "samsung": "11", + "rhino": "1.7.14", + "electron": "6.0" + }, + "proposal-logical-assignment-operators": { + "chrome": "85", + "opera": "71", + "edge": "85", + "firefox": "79", + "safari": "14", + "node": "15", + "ios": "14", + "samsung": "14", + "electron": "10.0" + }, + "proposal-nullish-coalescing-operator": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "72", + "safari": "13.1", + "node": "14", + "ios": "13.4", + "samsung": "13", + "electron": "8.0" + }, + "proposal-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "ios": "13.4", + "electron": "13.0" + }, + "proposal-json-strings": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "9", + "rhino": "1.7.14", + "electron": "3.0" + }, + "proposal-optional-catch-binding": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "58", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "transform-parameters": { + "chrome": "49", + "opera": "36", + "edge": "18", + "firefox": "53", + "node": "6", + "samsung": "5", + "electron": "0.37" + }, + "proposal-async-generator-functions": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "8", + "electron": "3.0" + }, + "proposal-object-rest-spread": { + "chrome": "60", + "opera": "47", + "edge": "79", + "firefox": "55", + "safari": "11.1", + "node": "8.3", + "ios": "11.3", + "samsung": "8", + "electron": "2.0" + }, + "transform-dotall-regex": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "8.10", + "ios": "11.3", + "samsung": "8", + "electron": "3.0" + }, + "proposal-unicode-property-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "transform-named-capturing-groups-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "transform-async-to-generator": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "11", + "node": "7.6", + "ios": "11", + "samsung": "6", + "electron": "1.6" + }, + "transform-exponentiation-operator": { + "chrome": "52", + "opera": "39", + "edge": "14", + "firefox": "52", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "electron": "1.3" + }, + "transform-template-literals": { + "chrome": "41", + "opera": "28", + "edge": "13", + "firefox": "34", + "safari": "13", + "node": "4", + "ios": "13", + "samsung": "3.4", + "electron": "0.21" + }, + "transform-literals": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "53", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "electron": "0.30" + }, + "transform-function-name": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-arrow-functions": { + "chrome": "47", + "opera": "34", + "edge": "13", + "firefox": "43", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.36" + }, + "transform-block-scoped-functions": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "46", + "safari": "10", + "node": "4", + "ie": "11", + "ios": "10", + "samsung": "3.4", + "electron": "0.21" + }, + "transform-classes": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-object-super": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-shorthand-properties": { + "chrome": "43", + "opera": "30", + "edge": "12", + "firefox": "33", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.14", + "electron": "0.27" + }, + "transform-duplicate-keys": { + "chrome": "42", + "opera": "29", + "edge": "12", + "firefox": "34", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "electron": "0.25" + }, + "transform-computed-properties": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "34", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "4", + "electron": "0.30" + }, + "transform-for-of": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-sticky-regex": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "3", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "transform-unicode-escapes": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "53", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "electron": "0.30" + }, + "transform-unicode-regex": { + "chrome": "50", + "opera": "37", + "edge": "13", + "firefox": "46", + "safari": "12", + "node": "6", + "ios": "12", + "samsung": "5", + "electron": "1.1" + }, + "transform-spread": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-destructuring": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-block-scoping": { + "chrome": "49", + "opera": "36", + "edge": "14", + "firefox": "51", + "safari": "11", + "node": "6", + "ios": "11", + "samsung": "5", + "electron": "0.37" + }, + "transform-typeof-symbol": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "transform-new-target": { + "chrome": "46", + "opera": "33", + "edge": "14", + "firefox": "41", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-regenerator": { + "chrome": "50", + "opera": "37", + "edge": "13", + "firefox": "53", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "transform-member-expression-literals": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "2", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "transform-property-literals": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "2", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "transform-reserved-words": { + "chrome": "13", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.6", + "ie": "9", + "android": "4.4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "proposal-export-namespace-from": { + "chrome": "72", + "and_chr": "72", + "edge": "79", + "firefox": "80", + "and_ff": "80", + "node": "13.2", + "opera": "60", + "op_mob": "51", + "samsung": "11.0", + "android": "72", + "electron": "5.0" + } +} diff --git a/node_modules/@babel/compat-data/native-modules.js b/node_modules/@babel/compat-data/native-modules.js new file mode 100644 index 0000000..8e97da4 --- /dev/null +++ b/node_modules/@babel/compat-data/native-modules.js @@ -0,0 +1 @@ +module.exports = require("./data/native-modules.json"); diff --git a/node_modules/@babel/compat-data/overlapping-plugins.js b/node_modules/@babel/compat-data/overlapping-plugins.js new file mode 100644 index 0000000..88242e4 --- /dev/null +++ b/node_modules/@babel/compat-data/overlapping-plugins.js @@ -0,0 +1 @@ +module.exports = require("./data/overlapping-plugins.json"); diff --git a/node_modules/@babel/compat-data/package.json b/node_modules/@babel/compat-data/package.json new file mode 100644 index 0000000..0328942 --- /dev/null +++ b/node_modules/@babel/compat-data/package.json @@ -0,0 +1,73 @@ +{ + "_from": "@babel/compat-data@^7.18.8", + "_id": "@babel/compat-data@7.18.13", + "_inBundle": false, + "_integrity": "sha512-5yUzC5LqyTFp2HLmDoxGQelcdYgSpP9xsnMWBphAscOdFrHSAVbLNzWiy32sVNDqJRDiJK6klfDnAgu6PAGSHw==", + "_location": "/@babel/compat-data", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/compat-data@^7.18.8", + "name": "@babel/compat-data", + "escapedName": "@babel%2fcompat-data", + "scope": "@babel", + "rawSpec": "^7.18.8", + "saveSpec": null, + "fetchSpec": "^7.18.8" + }, + "_requiredBy": [ + "/@babel/helper-compilation-targets" + ], + "_resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.18.13.tgz", + "_shasum": "6aff7b350a1e8c3e40b029e46cbe78e24a913483", + "_spec": "@babel/compat-data@^7.18.8", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/helper-compilation-targets", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": ">", + "devDependencies": { + "@mdn/browser-compat-data": "^4.0.10", + "core-js-compat": "^3.22.1", + "electron-to-chromium": "^1.4.113" + }, + "engines": { + "node": ">=6.9.0" + }, + "exports": { + "./plugins": "./plugins.js", + "./native-modules": "./native-modules.js", + "./corejs2-built-ins": "./corejs2-built-ins.js", + "./corejs3-shipped-proposals": "./corejs3-shipped-proposals.js", + "./overlapping-plugins": "./overlapping-plugins.js", + "./plugin-bugfixes": "./plugin-bugfixes.js" + }, + "homepage": "https://github.com/babel/babel#readme", + "keywords": [ + "babel", + "compat-table", + "compat-data" + ], + "license": "MIT", + "name": "@babel/compat-data", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-compat-data" + }, + "scripts": { + "build-data": "./scripts/download-compat-table.sh && node ./scripts/build-data.js && node ./scripts/build-modules-support.js && node ./scripts/build-bugfixes-targets.js" + }, + "type": "commonjs", + "version": "7.18.13" +} diff --git a/node_modules/@babel/compat-data/plugin-bugfixes.js b/node_modules/@babel/compat-data/plugin-bugfixes.js new file mode 100644 index 0000000..f390181 --- /dev/null +++ b/node_modules/@babel/compat-data/plugin-bugfixes.js @@ -0,0 +1 @@ +module.exports = require("./data/plugin-bugfixes.json"); diff --git a/node_modules/@babel/compat-data/plugins.js b/node_modules/@babel/compat-data/plugins.js new file mode 100644 index 0000000..42646ed --- /dev/null +++ b/node_modules/@babel/compat-data/plugins.js @@ -0,0 +1 @@ +module.exports = require("./data/plugins.json"); diff --git a/node_modules/@babel/core/LICENSE b/node_modules/@babel/core/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/core/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/core/README.md b/node_modules/@babel/core/README.md new file mode 100644 index 0000000..9b3a950 --- /dev/null +++ b/node_modules/@babel/core/README.md @@ -0,0 +1,19 @@ +# @babel/core + +> Babel compiler core. + +See our website [@babel/core](https://babeljs.io/docs/en/babel-core) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/core +``` + +or using yarn: + +```sh +yarn add @babel/core --dev +``` diff --git a/node_modules/@babel/core/cjs-proxy.cjs b/node_modules/@babel/core/cjs-proxy.cjs new file mode 100644 index 0000000..4bf8b5c --- /dev/null +++ b/node_modules/@babel/core/cjs-proxy.cjs @@ -0,0 +1,29 @@ +"use strict"; + +const babelP = import("./lib/index.js"); + +const functionNames = [ + "createConfigItem", + "loadPartialConfig", + "loadOptions", + "transform", + "transformFile", + "transformFromAst", + "parse", +]; + +for (const name of functionNames) { + exports[`${name}Sync`] = function () { + throw new Error( + `"${name}Sync" is not supported when loading @babel/core using require()` + ); + }; + exports[name] = function (...args) { + babelP.then(babel => { + babel[name](...args); + }); + }; + exports[`${name}Async`] = function (...args) { + return babelP.then(babel => babel[`${name}Async`](...args)); + }; +} diff --git a/node_modules/@babel/core/lib/config/cache-contexts.js b/node_modules/@babel/core/lib/config/cache-contexts.js new file mode 100644 index 0000000..d28d24c --- /dev/null +++ b/node_modules/@babel/core/lib/config/cache-contexts.js @@ -0,0 +1 @@ +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/caching.js b/node_modules/@babel/core/lib/config/caching.js new file mode 100644 index 0000000..515fad0 --- /dev/null +++ b/node_modules/@babel/core/lib/config/caching.js @@ -0,0 +1,326 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assertSimpleType = assertSimpleType; +exports.makeStrongCache = makeStrongCache; +exports.makeStrongCacheSync = makeStrongCacheSync; +exports.makeWeakCache = makeWeakCache; +exports.makeWeakCacheSync = makeWeakCacheSync; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _async = require("../gensync-utils/async"); + +var _util = require("./util"); + +const synchronize = gen => { + return _gensync()(gen).sync; +}; + +function* genTrue() { + return true; +} + +function makeWeakCache(handler) { + return makeCachedFunction(WeakMap, handler); +} + +function makeWeakCacheSync(handler) { + return synchronize(makeWeakCache(handler)); +} + +function makeStrongCache(handler) { + return makeCachedFunction(Map, handler); +} + +function makeStrongCacheSync(handler) { + return synchronize(makeStrongCache(handler)); +} + +function makeCachedFunction(CallCache, handler) { + const callCacheSync = new CallCache(); + const callCacheAsync = new CallCache(); + const futureCache = new CallCache(); + return function* cachedFunction(arg, data) { + const asyncContext = yield* (0, _async.isAsync)(); + const callCache = asyncContext ? callCacheAsync : callCacheSync; + const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data); + if (cached.valid) return cached.value; + const cache = new CacheConfigurator(data); + const handlerResult = handler(arg, cache); + let finishLock; + let value; + + if ((0, _util.isIterableIterator)(handlerResult)) { + value = yield* (0, _async.onFirstPause)(handlerResult, () => { + finishLock = setupAsyncLocks(cache, futureCache, arg); + }); + } else { + value = handlerResult; + } + + updateFunctionCache(callCache, cache, arg, value); + + if (finishLock) { + futureCache.delete(arg); + finishLock.release(value); + } + + return value; + }; +} + +function* getCachedValue(cache, arg, data) { + const cachedValue = cache.get(arg); + + if (cachedValue) { + for (const { + value, + valid + } of cachedValue) { + if (yield* valid(data)) return { + valid: true, + value + }; + } + } + + return { + valid: false, + value: null + }; +} + +function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) { + const cached = yield* getCachedValue(callCache, arg, data); + + if (cached.valid) { + return cached; + } + + if (asyncContext) { + const cached = yield* getCachedValue(futureCache, arg, data); + + if (cached.valid) { + const value = yield* (0, _async.waitFor)(cached.value.promise); + return { + valid: true, + value + }; + } + } + + return { + valid: false, + value: null + }; +} + +function setupAsyncLocks(config, futureCache, arg) { + const finishLock = new Lock(); + updateFunctionCache(futureCache, config, arg, finishLock); + return finishLock; +} + +function updateFunctionCache(cache, config, arg, value) { + if (!config.configured()) config.forever(); + let cachedValue = cache.get(arg); + config.deactivate(); + + switch (config.mode()) { + case "forever": + cachedValue = [{ + value, + valid: genTrue + }]; + cache.set(arg, cachedValue); + break; + + case "invalidate": + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + break; + + case "valid": + if (cachedValue) { + cachedValue.push({ + value, + valid: config.validator() + }); + } else { + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + } + + } +} + +class CacheConfigurator { + constructor(data) { + this._active = true; + this._never = false; + this._forever = false; + this._invalidate = false; + this._configured = false; + this._pairs = []; + this._data = void 0; + this._data = data; + } + + simple() { + return makeSimpleConfigurator(this); + } + + mode() { + if (this._never) return "never"; + if (this._forever) return "forever"; + if (this._invalidate) return "invalidate"; + return "valid"; + } + + forever() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._never) { + throw new Error("Caching has already been configured with .never()"); + } + + this._forever = true; + this._configured = true; + } + + never() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._forever) { + throw new Error("Caching has already been configured with .forever()"); + } + + this._never = true; + this._configured = true; + } + + using(handler) { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._never || this._forever) { + throw new Error("Caching has already been configured with .never or .forever()"); + } + + this._configured = true; + const key = handler(this._data); + const fn = (0, _async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`); + + if ((0, _async.isThenable)(key)) { + return key.then(key => { + this._pairs.push([key, fn]); + + return key; + }); + } + + this._pairs.push([key, fn]); + + return key; + } + + invalidate(handler) { + this._invalidate = true; + return this.using(handler); + } + + validator() { + const pairs = this._pairs; + return function* (data) { + for (const [key, fn] of pairs) { + if (key !== (yield* fn(data))) return false; + } + + return true; + }; + } + + deactivate() { + this._active = false; + } + + configured() { + return this._configured; + } + +} + +function makeSimpleConfigurator(cache) { + function cacheFn(val) { + if (typeof val === "boolean") { + if (val) cache.forever();else cache.never(); + return; + } + + return cache.using(() => assertSimpleType(val())); + } + + cacheFn.forever = () => cache.forever(); + + cacheFn.never = () => cache.never(); + + cacheFn.using = cb => cache.using(() => assertSimpleType(cb())); + + cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb())); + + return cacheFn; +} + +function assertSimpleType(value) { + if ((0, _async.isThenable)(value)) { + throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`); + } + + if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { + throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); + } + + return value; +} + +class Lock { + constructor() { + this.released = false; + this.promise = void 0; + this._resolve = void 0; + this.promise = new Promise(resolve => { + this._resolve = resolve; + }); + } + + release(value) { + this.released = true; + + this._resolve(value); + } + +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/config-chain.js b/node_modules/@babel/core/lib/config/config-chain.js new file mode 100644 index 0000000..dce70e1 --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-chain.js @@ -0,0 +1,566 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildPresetChain = buildPresetChain; +exports.buildPresetChainWalker = void 0; +exports.buildRootChain = buildRootChain; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +var _options = require("./validation/options"); + +var _patternToRegex = require("./pattern-to-regex"); + +var _printer = require("./printer"); + +var _files = require("./files"); + +var _caching = require("./caching"); + +var _configDescriptors = require("./config-descriptors"); + +const debug = _debug()("babel:config:config-chain"); + +function* buildPresetChain(arg, context) { + const chain = yield* buildPresetChainWalker(arg, context); + if (!chain) return null; + return { + plugins: dedupDescriptors(chain.plugins), + presets: dedupDescriptors(chain.presets), + options: chain.options.map(o => normalizeOptions(o)), + files: new Set() + }; +} + +const buildPresetChainWalker = makeChainWalker({ + root: preset => loadPresetDescriptors(preset), + env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName), + overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index), + overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName), + createLogger: () => () => {} +}); +exports.buildPresetChainWalker = buildPresetChainWalker; +const loadPresetDescriptors = (0, _caching.makeWeakCacheSync)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors)); +const loadPresetEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName))); +const loadPresetOverridesDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index))); +const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName)))); + +function* buildRootChain(opts, context) { + let configReport, babelRcReport; + const programmaticLogger = new _printer.ConfigPrinter(); + const programmaticChain = yield* loadProgrammaticChain({ + options: opts, + dirname: context.cwd + }, context, undefined, programmaticLogger); + if (!programmaticChain) return null; + const programmaticReport = yield* programmaticLogger.output(); + let configFile; + + if (typeof opts.configFile === "string") { + configFile = yield* (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller); + } else if (opts.configFile !== false) { + configFile = yield* (0, _files.findRootConfig)(context.root, context.envName, context.caller); + } + + let { + babelrc, + babelrcRoots + } = opts; + let babelrcRootsDirectory = context.cwd; + const configFileChain = emptyChain(); + const configFileLogger = new _printer.ConfigPrinter(); + + if (configFile) { + const validatedFile = validateConfigFile(configFile); + const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger); + if (!result) return null; + configReport = yield* configFileLogger.output(); + + if (babelrc === undefined) { + babelrc = validatedFile.options.babelrc; + } + + if (babelrcRoots === undefined) { + babelrcRootsDirectory = validatedFile.dirname; + babelrcRoots = validatedFile.options.babelrcRoots; + } + + mergeChain(configFileChain, result); + } + + let ignoreFile, babelrcFile; + let isIgnored = false; + const fileChain = emptyChain(); + + if ((babelrc === true || babelrc === undefined) && typeof context.filename === "string") { + const pkgData = yield* (0, _files.findPackageData)(context.filename); + + if (pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { + ({ + ignore: ignoreFile, + config: babelrcFile + } = yield* (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller)); + + if (ignoreFile) { + fileChain.files.add(ignoreFile.filepath); + } + + if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { + isIgnored = true; + } + + if (babelrcFile && !isIgnored) { + const validatedFile = validateBabelrcFile(babelrcFile); + const babelrcLogger = new _printer.ConfigPrinter(); + const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger); + + if (!result) { + isIgnored = true; + } else { + babelRcReport = yield* babelrcLogger.output(); + mergeChain(fileChain, result); + } + } + + if (babelrcFile && isIgnored) { + fileChain.files.add(babelrcFile.filepath); + } + } + } + + if (context.showConfig) { + console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n") + "\n-----End Babel configs-----"); + } + + const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); + return { + plugins: isIgnored ? [] : dedupDescriptors(chain.plugins), + presets: isIgnored ? [] : dedupDescriptors(chain.presets), + options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)), + fileHandling: isIgnored ? "ignored" : "transpile", + ignore: ignoreFile || undefined, + babelrc: babelrcFile || undefined, + config: configFile || undefined, + files: chain.files + }; +} + +function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) { + if (typeof babelrcRoots === "boolean") return babelrcRoots; + const absoluteRoot = context.root; + + if (babelrcRoots === undefined) { + return pkgData.directories.indexOf(absoluteRoot) !== -1; + } + + let babelrcPatterns = babelrcRoots; + + if (!Array.isArray(babelrcPatterns)) { + babelrcPatterns = [babelrcPatterns]; + } + + babelrcPatterns = babelrcPatterns.map(pat => { + return typeof pat === "string" ? _path().resolve(babelrcRootsDirectory, pat) : pat; + }); + + if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { + return pkgData.directories.indexOf(absoluteRoot) !== -1; + } + + return babelrcPatterns.some(pat => { + if (typeof pat === "string") { + pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory); + } + + return pkgData.directories.some(directory => { + return matchPattern(pat, babelrcRootsDirectory, directory, context); + }); + }); +} + +const validateConfigFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("configfile", file.options) +})); +const validateBabelrcFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("babelrcfile", file.options) +})); +const validateExtendFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("extendsfile", file.options) +})); +const loadProgrammaticChain = makeChainWalker({ + root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors), + env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName), + overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index), + overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName), + createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger) +}); +const loadFileChainWalker = makeChainWalker({ + root: file => loadFileDescriptors(file), + env: (file, envName) => loadFileEnvDescriptors(file)(envName), + overrides: (file, index) => loadFileOverridesDescriptors(file)(index), + overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName), + createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger) +}); + +function* loadFileChain(input, context, files, baseLogger) { + const chain = yield* loadFileChainWalker(input, context, files, baseLogger); + + if (chain) { + chain.files.add(input.filepath); + } + + return chain; +} + +const loadFileDescriptors = (0, _caching.makeWeakCacheSync)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors)); +const loadFileEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName))); +const loadFileOverridesDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index))); +const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName)))); + +function buildFileLogger(filepath, context, baseLogger) { + if (!baseLogger) { + return () => {}; + } + + return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Config, { + filepath + }); +} + +function buildRootDescriptors({ + dirname, + options +}, alias, descriptors) { + return descriptors(dirname, options, alias); +} + +function buildProgrammaticLogger(_, context, baseLogger) { + var _context$caller; + + if (!baseLogger) { + return () => {}; + } + + return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Programmatic, { + callerName: (_context$caller = context.caller) == null ? void 0 : _context$caller.name + }); +} + +function buildEnvDescriptors({ + dirname, + options +}, alias, descriptors, envName) { + const opts = options.env && options.env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null; +} + +function buildOverrideDescriptors({ + dirname, + options +}, alias, descriptors, index) { + const opts = options.overrides && options.overrides[index]; + if (!opts) throw new Error("Assertion failure - missing override"); + return descriptors(dirname, opts, `${alias}.overrides[${index}]`); +} + +function buildOverrideEnvDescriptors({ + dirname, + options +}, alias, descriptors, index, envName) { + const override = options.overrides && options.overrides[index]; + if (!override) throw new Error("Assertion failure - missing override"); + const opts = override.env && override.env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null; +} + +function makeChainWalker({ + root, + env, + overrides, + overridesEnv, + createLogger +}) { + return function* (input, context, files = new Set(), baseLogger) { + const { + dirname + } = input; + const flattenedConfigs = []; + const rootOpts = root(input); + + if (configIsApplicable(rootOpts, dirname, context)) { + flattenedConfigs.push({ + config: rootOpts, + envName: undefined, + index: undefined + }); + const envOpts = env(input, context.envName); + + if (envOpts && configIsApplicable(envOpts, dirname, context)) { + flattenedConfigs.push({ + config: envOpts, + envName: context.envName, + index: undefined + }); + } + + (rootOpts.options.overrides || []).forEach((_, index) => { + const overrideOps = overrides(input, index); + + if (configIsApplicable(overrideOps, dirname, context)) { + flattenedConfigs.push({ + config: overrideOps, + index, + envName: undefined + }); + const overrideEnvOpts = overridesEnv(input, index, context.envName); + + if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) { + flattenedConfigs.push({ + config: overrideEnvOpts, + index, + envName: context.envName + }); + } + } + }); + } + + if (flattenedConfigs.some(({ + config: { + options: { + ignore, + only + } + } + }) => shouldIgnore(context, ignore, only, dirname))) { + return null; + } + + const chain = emptyChain(); + const logger = createLogger(input, context, baseLogger); + + for (const { + config, + index, + envName + } of flattenedConfigs) { + if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) { + return null; + } + + logger(config, index, envName); + yield* mergeChainOpts(chain, config); + } + + return chain; + }; +} + +function* mergeExtendsChain(chain, opts, dirname, context, files, baseLogger) { + if (opts.extends === undefined) return true; + const file = yield* (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller); + + if (files.has(file)) { + throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n")); + } + + files.add(file); + const fileChain = yield* loadFileChain(validateExtendFile(file), context, files, baseLogger); + files.delete(file); + if (!fileChain) return false; + mergeChain(chain, fileChain); + return true; +} + +function mergeChain(target, source) { + target.options.push(...source.options); + target.plugins.push(...source.plugins); + target.presets.push(...source.presets); + + for (const file of source.files) { + target.files.add(file); + } + + return target; +} + +function* mergeChainOpts(target, { + options, + plugins, + presets +}) { + target.options.push(options); + target.plugins.push(...(yield* plugins())); + target.presets.push(...(yield* presets())); + return target; +} + +function emptyChain() { + return { + options: [], + presets: [], + plugins: [], + files: new Set() + }; +} + +function normalizeOptions(opts) { + const options = Object.assign({}, opts); + delete options.extends; + delete options.env; + delete options.overrides; + delete options.plugins; + delete options.presets; + delete options.passPerPreset; + delete options.ignore; + delete options.only; + delete options.test; + delete options.include; + delete options.exclude; + + if (Object.prototype.hasOwnProperty.call(options, "sourceMap")) { + options.sourceMaps = options.sourceMap; + delete options.sourceMap; + } + + return options; +} + +function dedupDescriptors(items) { + const map = new Map(); + const descriptors = []; + + for (const item of items) { + if (typeof item.value === "function") { + const fnKey = item.value; + let nameMap = map.get(fnKey); + + if (!nameMap) { + nameMap = new Map(); + map.set(fnKey, nameMap); + } + + let desc = nameMap.get(item.name); + + if (!desc) { + desc = { + value: item + }; + descriptors.push(desc); + if (!item.ownPass) nameMap.set(item.name, desc); + } else { + desc.value = item; + } + } else { + descriptors.push({ + value: item + }); + } + } + + return descriptors.reduce((acc, desc) => { + acc.push(desc.value); + return acc; + }, []); +} + +function configIsApplicable({ + options +}, dirname, context) { + return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname)); +} + +function configFieldIsApplicable(context, test, dirname) { + const patterns = Array.isArray(test) ? test : [test]; + return matchesPatterns(context, patterns, dirname); +} + +function ignoreListReplacer(_key, value) { + if (value instanceof RegExp) { + return String(value); + } + + return value; +} + +function shouldIgnore(context, ignore, only, dirname) { + if (ignore && matchesPatterns(context, ignore, dirname)) { + var _context$filename; + + const message = `No config is applied to "${(_context$filename = context.filename) != null ? _context$filename : "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore, ignoreListReplacer)}\` from "${dirname}"`; + debug(message); + + if (context.showConfig) { + console.log(message); + } + + return true; + } + + if (only && !matchesPatterns(context, only, dirname)) { + var _context$filename2; + + const message = `No config is applied to "${(_context$filename2 = context.filename) != null ? _context$filename2 : "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only, ignoreListReplacer)}\` from "${dirname}"`; + debug(message); + + if (context.showConfig) { + console.log(message); + } + + return true; + } + + return false; +} + +function matchesPatterns(context, patterns, dirname) { + return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context)); +} + +function matchPattern(pattern, dirname, pathToTest, context) { + if (typeof pattern === "function") { + return !!pattern(pathToTest, { + dirname, + envName: context.envName, + caller: context.caller + }); + } + + if (typeof pathToTest !== "string") { + throw new Error(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`); + } + + if (typeof pattern === "string") { + pattern = (0, _patternToRegex.default)(pattern, dirname); + } + + return pattern.test(pathToTest); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/config-descriptors.js b/node_modules/@babel/core/lib/config/config-descriptors.js new file mode 100644 index 0000000..990c68c --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-descriptors.js @@ -0,0 +1,231 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createCachedDescriptors = createCachedDescriptors; +exports.createDescriptor = createDescriptor; +exports.createUncachedDescriptors = createUncachedDescriptors; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _functional = require("../gensync-utils/functional"); + +var _files = require("./files"); + +var _item = require("./item"); + +var _caching = require("./caching"); + +var _resolveTargets = require("./resolve-targets"); + +function isEqualDescriptor(a, b) { + return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved); +} + +function* handlerOf(value) { + return value; +} + +function optionsWithResolvedBrowserslistConfigFile(options, dirname) { + if (typeof options.browserslistConfigFile === "string") { + options.browserslistConfigFile = (0, _resolveTargets.resolveBrowserslistConfigFile)(options.browserslistConfigFile, dirname); + } + + return options; +} + +function createCachedDescriptors(dirname, options, alias) { + const { + plugins, + presets, + passPerPreset + } = options; + return { + options: optionsWithResolvedBrowserslistConfigFile(options, dirname), + plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => handlerOf([]), + presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => handlerOf([]) + }; +} + +function createUncachedDescriptors(dirname, options, alias) { + return { + options: optionsWithResolvedBrowserslistConfigFile(options, dirname), + plugins: (0, _functional.once)(() => createPluginDescriptors(options.plugins || [], dirname, alias)), + presets: (0, _functional.once)(() => createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset)) + }; +} + +const PRESET_DESCRIPTOR_CACHE = new WeakMap(); +const createCachedPresetDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, _caching.makeStrongCacheSync)(alias => (0, _caching.makeStrongCache)(function* (passPerPreset) { + const descriptors = yield* createPresetDescriptors(items, dirname, alias, passPerPreset); + return descriptors.map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc)); + })); +}); +const PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); +const createCachedPluginDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, _caching.makeStrongCache)(function* (alias) { + const descriptors = yield* createPluginDescriptors(items, dirname, alias); + return descriptors.map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)); + }); +}); +const DEFAULT_OPTIONS = {}; + +function loadCachedDescriptor(cache, desc) { + const { + value, + options = DEFAULT_OPTIONS + } = desc; + if (options === false) return desc; + let cacheByOptions = cache.get(value); + + if (!cacheByOptions) { + cacheByOptions = new WeakMap(); + cache.set(value, cacheByOptions); + } + + let possibilities = cacheByOptions.get(options); + + if (!possibilities) { + possibilities = []; + cacheByOptions.set(options, possibilities); + } + + if (possibilities.indexOf(desc) === -1) { + const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc)); + + if (matches.length > 0) { + return matches[0]; + } + + possibilities.push(desc); + } + + return desc; +} + +function* createPresetDescriptors(items, dirname, alias, passPerPreset) { + return yield* createDescriptors("preset", items, dirname, alias, passPerPreset); +} + +function* createPluginDescriptors(items, dirname, alias) { + return yield* createDescriptors("plugin", items, dirname, alias); +} + +function* createDescriptors(type, items, dirname, alias, ownPass) { + const descriptors = yield* _gensync().all(items.map((item, index) => createDescriptor(item, dirname, { + type, + alias: `${alias}$${index}`, + ownPass: !!ownPass + }))); + assertNoDuplicates(descriptors); + return descriptors; +} + +function* createDescriptor(pair, dirname, { + type, + alias, + ownPass +}) { + const desc = (0, _item.getItemDescriptor)(pair); + + if (desc) { + return desc; + } + + let name; + let options; + let value = pair; + + if (Array.isArray(value)) { + if (value.length === 3) { + [value, options, name] = value; + } else { + [value, options] = value; + } + } + + let file = undefined; + let filepath = null; + + if (typeof value === "string") { + if (typeof type !== "string") { + throw new Error("To resolve a string-based item, the type of item must be given"); + } + + const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset; + const request = value; + ({ + filepath, + value + } = yield* resolver(value, dirname)); + file = { + request, + resolved: filepath + }; + } + + if (!value) { + throw new Error(`Unexpected falsy value: ${String(value)}`); + } + + if (typeof value === "object" && value.__esModule) { + if (value.default) { + value = value.default; + } else { + throw new Error("Must export a default export when using ES6 modules."); + } + } + + if (typeof value !== "object" && typeof value !== "function") { + throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`); + } + + if (filepath !== null && typeof value === "object" && value) { + throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`); + } + + return { + name, + alias: filepath || alias, + value, + options, + dirname, + ownPass, + file + }; +} + +function assertNoDuplicates(items) { + const map = new Map(); + + for (const item of items) { + if (typeof item.value !== "function") continue; + let nameMap = map.get(item.value); + + if (!nameMap) { + nameMap = new Set(); + map.set(item.value, nameMap); + } + + if (nameMap.has(item.name)) { + const conflicts = items.filter(i => i.value === item.value); + throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n")); + } + + nameMap.add(item.name); + } +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/configuration.js b/node_modules/@babel/core/lib/config/files/configuration.js new file mode 100644 index 0000000..6a4ad78 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/configuration.js @@ -0,0 +1,360 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ROOT_CONFIG_FILENAMES = void 0; +exports.findConfigUpwards = findConfigUpwards; +exports.findRelativeConfig = findRelativeConfig; +exports.findRootConfig = findRootConfig; +exports.loadConfig = loadConfig; +exports.resolveShowConfigPath = resolveShowConfigPath; + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +function _fs() { + const data = require("fs"); + + _fs = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _json() { + const data = require("json5"); + + _json = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _caching = require("../caching"); + +var _configApi = require("../helpers/config-api"); + +var _utils = require("./utils"); + +var _moduleTypes = require("./module-types"); + +var _patternToRegex = require("../pattern-to-regex"); + +var fs = require("../../gensync-utils/fs"); + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +const debug = _debug()("babel:config:loading:files:configuration"); + +const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json"]; +exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES; +const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json"]; +const BABELIGNORE_FILENAME = ".babelignore"; + +function findConfigUpwards(rootDir) { + let dirname = rootDir; + + for (;;) { + for (const filename of ROOT_CONFIG_FILENAMES) { + if (_fs().existsSync(_path().join(dirname, filename))) { + return dirname; + } + } + + const nextDir = _path().dirname(dirname); + + if (dirname === nextDir) break; + dirname = nextDir; + } + + return null; +} + +function* findRelativeConfig(packageData, envName, caller) { + let config = null; + let ignore = null; + + const dirname = _path().dirname(packageData.filepath); + + for (const loc of packageData.directories) { + if (!config) { + var _packageData$pkg; + + config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null); + } + + if (!ignore) { + const ignoreLoc = _path().join(loc, BABELIGNORE_FILENAME); + + ignore = yield* readIgnoreConfig(ignoreLoc); + + if (ignore) { + debug("Found ignore %o from %o.", ignore.filepath, dirname); + } + } + } + + return { + config, + ignore + }; +} + +function findRootConfig(dirname, envName, caller) { + return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller); +} + +function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) { + const configs = yield* _gensync().all(names.map(filename => readConfig(_path().join(dirname, filename), envName, caller))); + const config = configs.reduce((previousConfig, config) => { + if (config && previousConfig) { + throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`); + } + + return config || previousConfig; + }, previousConfig); + + if (config) { + debug("Found configuration %o from %o.", config.filepath, dirname); + } + + return config; +} + +function* loadConfig(name, dirname, envName, caller) { + const filepath = (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, { + paths: [b] + }, M = require("module")) => { + let f = M._findPath(r, M._nodeModulePaths(b).concat(b)); + + if (f) return f; + f = new Error(`Cannot resolve module '${r}'`); + f.code = "MODULE_NOT_FOUND"; + throw f; + })(name, { + paths: [dirname] + }); + const conf = yield* readConfig(filepath, envName, caller); + + if (!conf) { + throw new Error(`Config file ${filepath} contains no configuration data`); + } + + debug("Loaded config %o from %o.", name, dirname); + return conf; +} + +function readConfig(filepath, envName, caller) { + const ext = _path().extname(filepath); + + return ext === ".js" || ext === ".cjs" || ext === ".mjs" ? readConfigJS(filepath, { + envName, + caller + }) : readConfigJSON5(filepath); +} + +const LOADING_CONFIGS = new Set(); +const readConfigJS = (0, _caching.makeStrongCache)(function* readConfigJS(filepath, cache) { + if (!_fs().existsSync(filepath)) { + cache.never(); + return null; + } + + if (LOADING_CONFIGS.has(filepath)) { + cache.never(); + debug("Auto-ignoring usage of config %o.", filepath); + return { + filepath, + dirname: _path().dirname(filepath), + options: {} + }; + } + + let options; + + try { + LOADING_CONFIGS.add(filepath); + options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously."); + } catch (err) { + err.message = `${filepath}: Error while loading config - ${err.message}`; + throw err; + } finally { + LOADING_CONFIGS.delete(filepath); + } + + let assertCache = false; + + if (typeof options === "function") { + yield* []; + options = options((0, _configApi.makeConfigAPI)(cache)); + assertCache = true; + } + + if (!options || typeof options !== "object" || Array.isArray(options)) { + throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`); + } + + if (typeof options.then === "function") { + throw new Error(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`); + } + + if (assertCache && !cache.configured()) throwConfigError(); + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => { + const babel = file.options["babel"]; + if (typeof babel === "undefined") return null; + + if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { + throw new Error(`${file.filepath}: .babel property must be an object`); + } + + return { + filepath: file.filepath, + dirname: file.dirname, + options: babel + }; +}); +const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => { + let options; + + try { + options = _json().parse(content); + } catch (err) { + err.message = `${filepath}: Error while parsing config - ${err.message}`; + throw err; + } + + if (!options) throw new Error(`${filepath}: No config detected`); + + if (typeof options !== "object") { + throw new Error(`${filepath}: Config returned typeof ${typeof options}`); + } + + if (Array.isArray(options)) { + throw new Error(`${filepath}: Expected config object but found array`); + } + + delete options["$schema"]; + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => { + const ignoreDir = _path().dirname(filepath); + + const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line); + + for (const pattern of ignorePatterns) { + if (pattern[0] === "!") { + throw new Error(`Negation of file paths is not supported.`); + } + } + + return { + filepath, + dirname: _path().dirname(filepath), + ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir)) + }; +}); + +function* resolveShowConfigPath(dirname) { + const targetPath = process.env.BABEL_SHOW_CONFIG_FOR; + + if (targetPath != null) { + const absolutePath = _path().resolve(dirname, targetPath); + + const stats = yield* fs.stat(absolutePath); + + if (!stats.isFile()) { + throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`); + } + + return absolutePath; + } + + return null; +} + +function throwConfigError() { + throw new Error(`\ +Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured +for various types of caching, using the first param of their handler functions: + +module.exports = function(api) { + // The API exposes the following: + + // Cache the returned value forever and don't call this function again. + api.cache(true); + + // Don't cache at all. Not recommended because it will be very slow. + api.cache(false); + + // Cached based on the value of some function. If this function returns a value different from + // a previously-encountered value, the plugins will re-evaluate. + var env = api.cache(() => process.env.NODE_ENV); + + // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for + // any possible NODE_ENV value that might come up during plugin execution. + var isProd = api.cache(() => process.env.NODE_ENV === "production"); + + // .cache(fn) will perform a linear search though instances to find the matching plugin based + // based on previous instantiated plugins. If you want to recreate the plugin and discard the + // previous instance whenever something changes, you may use: + var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production"); + + // Note, we also expose the following more-verbose versions of the above examples: + api.cache.forever(); // api.cache(true) + api.cache.never(); // api.cache(false) + api.cache.using(fn); // api.cache(fn) + + // Return the value that will be cached. + return { }; +};`); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/import-meta-resolve.js b/node_modules/@babel/core/lib/config/files/import-meta-resolve.js new file mode 100644 index 0000000..abb231e --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import-meta-resolve.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = resolve; + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +var _importMetaResolve = require("../../vendor/import-meta-resolve"); + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +let import_; + +try { + import_ = require("./import.cjs"); +} catch (_unused) {} + +const importMetaResolveP = import_ && process.execArgv.includes("--experimental-import-meta-resolve") ? import_("data:text/javascript,export default import.meta.resolve").then(m => m.default || _importMetaResolve.resolve, () => _importMetaResolve.resolve) : Promise.resolve(_importMetaResolve.resolve); + +function resolve(_x, _x2) { + return _resolve.apply(this, arguments); +} + +function _resolve() { + _resolve = _asyncToGenerator(function* (specifier, parent) { + return (yield importMetaResolveP)(specifier, parent); + }); + return _resolve.apply(this, arguments); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/import.cjs b/node_modules/@babel/core/lib/config/files/import.cjs new file mode 100644 index 0000000..cabb767 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import.cjs @@ -0,0 +1,5 @@ +module.exports = function import_(filepath) { + return import(filepath); +}; + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/index-browser.js b/node_modules/@babel/core/lib/config/files/index-browser.js new file mode 100644 index 0000000..023adbe --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index-browser.js @@ -0,0 +1,69 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ROOT_CONFIG_FILENAMES = void 0; +exports.findConfigUpwards = findConfigUpwards; +exports.findPackageData = findPackageData; +exports.findRelativeConfig = findRelativeConfig; +exports.findRootConfig = findRootConfig; +exports.loadConfig = loadConfig; +exports.loadPlugin = loadPlugin; +exports.loadPreset = loadPreset; +exports.resolvePlugin = resolvePlugin; +exports.resolvePreset = resolvePreset; +exports.resolveShowConfigPath = resolveShowConfigPath; + +function findConfigUpwards(rootDir) { + return null; +} + +function* findPackageData(filepath) { + return { + filepath, + directories: [], + pkg: null, + isPackage: false + }; +} + +function* findRelativeConfig(pkgData, envName, caller) { + return { + config: null, + ignore: null + }; +} + +function* findRootConfig(dirname, envName, caller) { + return null; +} + +function* loadConfig(name, dirname, envName, caller) { + throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); +} + +function* resolveShowConfigPath(dirname) { + return null; +} + +const ROOT_CONFIG_FILENAMES = []; +exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES; + +function resolvePlugin(name, dirname) { + return null; +} + +function resolvePreset(name, dirname) { + return null; +} + +function loadPlugin(name, dirname) { + throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`); +} + +function loadPreset(name, dirname) { + throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/index.js b/node_modules/@babel/core/lib/config/files/index.js new file mode 100644 index 0000000..cc93307 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index.js @@ -0,0 +1,87 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ROOT_CONFIG_FILENAMES", { + enumerable: true, + get: function () { + return _configuration.ROOT_CONFIG_FILENAMES; + } +}); +Object.defineProperty(exports, "findConfigUpwards", { + enumerable: true, + get: function () { + return _configuration.findConfigUpwards; + } +}); +Object.defineProperty(exports, "findPackageData", { + enumerable: true, + get: function () { + return _package.findPackageData; + } +}); +Object.defineProperty(exports, "findRelativeConfig", { + enumerable: true, + get: function () { + return _configuration.findRelativeConfig; + } +}); +Object.defineProperty(exports, "findRootConfig", { + enumerable: true, + get: function () { + return _configuration.findRootConfig; + } +}); +Object.defineProperty(exports, "loadConfig", { + enumerable: true, + get: function () { + return _configuration.loadConfig; + } +}); +Object.defineProperty(exports, "loadPlugin", { + enumerable: true, + get: function () { + return plugins.loadPlugin; + } +}); +Object.defineProperty(exports, "loadPreset", { + enumerable: true, + get: function () { + return plugins.loadPreset; + } +}); +exports.resolvePreset = exports.resolvePlugin = void 0; +Object.defineProperty(exports, "resolveShowConfigPath", { + enumerable: true, + get: function () { + return _configuration.resolveShowConfigPath; + } +}); + +var _package = require("./package"); + +var _configuration = require("./configuration"); + +var plugins = require("./plugins"); + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +({}); + +const resolvePlugin = _gensync()(plugins.resolvePlugin).sync; + +exports.resolvePlugin = resolvePlugin; + +const resolvePreset = _gensync()(plugins.resolvePreset).sync; + +exports.resolvePreset = resolvePreset; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/module-types.js b/node_modules/@babel/core/lib/config/files/module-types.js new file mode 100644 index 0000000..fd2a3f6 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/module-types.js @@ -0,0 +1,121 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadCjsOrMjsDefault; +exports.supportsESM = void 0; + +var _async = require("../../gensync-utils/async"); + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _url() { + const data = require("url"); + + _url = function () { + return data; + }; + + return data; +} + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +function _semver() { + const data = require("semver"); + + _semver = function () { + return data; + }; + + return data; +} + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +let import_; + +try { + import_ = require("./import.cjs"); +} catch (_unused) {} + +const supportsESM = _semver().satisfies(process.versions.node, "^12.17 || >=13.2"); + +exports.supportsESM = supportsESM; + +function* loadCjsOrMjsDefault(filepath, asyncError, fallbackToTranspiledModule = false) { + switch (guessJSModuleType(filepath)) { + case "cjs": + return loadCjsDefault(filepath, fallbackToTranspiledModule); + + case "unknown": + try { + return loadCjsDefault(filepath, fallbackToTranspiledModule); + } catch (e) { + if (e.code !== "ERR_REQUIRE_ESM") throw e; + } + + case "mjs": + if (yield* (0, _async.isAsync)()) { + return yield* (0, _async.waitFor)(loadMjsDefault(filepath)); + } + + throw new Error(asyncError); + } +} + +function guessJSModuleType(filename) { + switch (_path().extname(filename)) { + case ".cjs": + return "cjs"; + + case ".mjs": + return "mjs"; + + default: + return "unknown"; + } +} + +function loadCjsDefault(filepath, fallbackToTranspiledModule) { + const module = require(filepath); + + return module != null && module.__esModule ? module.default || (fallbackToTranspiledModule ? module : undefined) : module; +} + +function loadMjsDefault(_x) { + return _loadMjsDefault.apply(this, arguments); +} + +function _loadMjsDefault() { + _loadMjsDefault = _asyncToGenerator(function* (filepath) { + if (!import_) { + throw new Error("Internal error: Native ECMAScript modules aren't supported" + " by this platform.\n"); + } + + const module = yield import_((0, _url().pathToFileURL)(filepath)); + return module.default; + }); + return _loadMjsDefault.apply(this, arguments); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/package.js b/node_modules/@babel/core/lib/config/files/package.js new file mode 100644 index 0000000..c6b7f47 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/package.js @@ -0,0 +1,77 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findPackageData = findPackageData; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +var _utils = require("./utils"); + +const PACKAGE_FILENAME = "package.json"; + +function* findPackageData(filepath) { + let pkg = null; + const directories = []; + let isPackage = true; + + let dirname = _path().dirname(filepath); + + while (!pkg && _path().basename(dirname) !== "node_modules") { + directories.push(dirname); + pkg = yield* readConfigPackage(_path().join(dirname, PACKAGE_FILENAME)); + + const nextLoc = _path().dirname(dirname); + + if (dirname === nextLoc) { + isPackage = false; + break; + } + + dirname = nextLoc; + } + + return { + filepath, + directories, + pkg, + isPackage + }; +} + +const readConfigPackage = (0, _utils.makeStaticFileCache)((filepath, content) => { + let options; + + try { + options = JSON.parse(content); + } catch (err) { + err.message = `${filepath}: Error while parsing JSON - ${err.message}`; + throw err; + } + + if (!options) throw new Error(`${filepath}: No config detected`); + + if (typeof options !== "object") { + throw new Error(`${filepath}: Config returned typeof ${typeof options}`); + } + + if (Array.isArray(options)) { + throw new Error(`${filepath}: Expected config object but found array`); + } + + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/plugins.js b/node_modules/@babel/core/lib/config/files/plugins.js new file mode 100644 index 0000000..8cfa436 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/plugins.js @@ -0,0 +1,275 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.loadPlugin = loadPlugin; +exports.loadPreset = loadPreset; +exports.resolvePlugin = resolvePlugin; +exports.resolvePreset = resolvePreset; + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _async = require("../../gensync-utils/async"); + +var _moduleTypes = require("./module-types"); + +function _url() { + const data = require("url"); + + _url = function () { + return data; + }; + + return data; +} + +var _importMetaResolve = require("./import-meta-resolve"); + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +const debug = _debug()("babel:config:loading:files:plugins"); + +const EXACT_RE = /^module:/; +const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; +const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; +const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; +const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; +const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/; +const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/; +const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/; + +function* resolvePlugin(name, dirname) { + return yield* resolveStandardizedName("plugin", name, dirname); +} + +function* resolvePreset(name, dirname) { + return yield* resolveStandardizedName("preset", name, dirname); +} + +function* loadPlugin(name, dirname) { + const filepath = yield* resolvePlugin(name, dirname); + const value = yield* requireModule("plugin", filepath); + debug("Loaded plugin %o from %o.", name, dirname); + return { + filepath, + value + }; +} + +function* loadPreset(name, dirname) { + const filepath = yield* resolvePreset(name, dirname); + const value = yield* requireModule("preset", filepath); + debug("Loaded preset %o from %o.", name, dirname); + return { + filepath, + value + }; +} + +function standardizeName(type, name) { + if (_path().isAbsolute(name)) return name; + const isPreset = type === "preset"; + return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, ""); +} + +function* resolveAlternativesHelper(type, name) { + const standardizedName = standardizeName(type, name); + const { + error, + value + } = yield standardizedName; + if (!error) return value; + if (error.code !== "MODULE_NOT_FOUND") throw error; + + if (standardizedName !== name && !(yield name).error) { + error.message += `\n- If you want to resolve "${name}", use "module:${name}"`; + } + + if (!(yield standardizeName(type, "@babel/" + name)).error) { + error.message += `\n- Did you mean "@babel/${name}"?`; + } + + const oppositeType = type === "preset" ? "plugin" : "preset"; + + if (!(yield standardizeName(oppositeType, name)).error) { + error.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`; + } + + throw error; +} + +function tryRequireResolve(id, { + paths: [dirname] +}) { + try { + return { + error: null, + value: (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, { + paths: [b] + }, M = require("module")) => { + let f = M._findPath(r, M._nodeModulePaths(b).concat(b)); + + if (f) return f; + f = new Error(`Cannot resolve module '${r}'`); + f.code = "MODULE_NOT_FOUND"; + throw f; + })(id, { + paths: [dirname] + }) + }; + } catch (error) { + return { + error, + value: null + }; + } +} + +function tryImportMetaResolve(_x, _x2) { + return _tryImportMetaResolve.apply(this, arguments); +} + +function _tryImportMetaResolve() { + _tryImportMetaResolve = _asyncToGenerator(function* (id, options) { + try { + return { + error: null, + value: yield (0, _importMetaResolve.default)(id, options) + }; + } catch (error) { + return { + error, + value: null + }; + } + }); + return _tryImportMetaResolve.apply(this, arguments); +} + +function resolveStandardizedNameForRequire(type, name, dirname) { + const it = resolveAlternativesHelper(type, name); + let res = it.next(); + + while (!res.done) { + res = it.next(tryRequireResolve(res.value, { + paths: [dirname] + })); + } + + return res.value; +} + +function resolveStandardizedNameForImport(_x3, _x4, _x5) { + return _resolveStandardizedNameForImport.apply(this, arguments); +} + +function _resolveStandardizedNameForImport() { + _resolveStandardizedNameForImport = _asyncToGenerator(function* (type, name, dirname) { + const parentUrl = (0, _url().pathToFileURL)(_path().join(dirname, "./babel-virtual-resolve-base.js")).href; + const it = resolveAlternativesHelper(type, name); + let res = it.next(); + + while (!res.done) { + res = it.next(yield tryImportMetaResolve(res.value, parentUrl)); + } + + return (0, _url().fileURLToPath)(res.value); + }); + return _resolveStandardizedNameForImport.apply(this, arguments); +} + +const resolveStandardizedName = _gensync()({ + sync(type, name, dirname = process.cwd()) { + return resolveStandardizedNameForRequire(type, name, dirname); + }, + + async(type, name, dirname = process.cwd()) { + return _asyncToGenerator(function* () { + if (!_moduleTypes.supportsESM) { + return resolveStandardizedNameForRequire(type, name, dirname); + } + + try { + return yield resolveStandardizedNameForImport(type, name, dirname); + } catch (e) { + try { + return resolveStandardizedNameForRequire(type, name, dirname); + } catch (e2) { + if (e.type === "MODULE_NOT_FOUND") throw e; + if (e2.type === "MODULE_NOT_FOUND") throw e2; + throw e; + } + } + })(); + } + +}); + +{ + var LOADING_MODULES = new Set(); +} + +function* requireModule(type, name) { + { + if (!(yield* (0, _async.isAsync)()) && LOADING_MODULES.has(name)) { + throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.'); + } + } + + try { + { + LOADING_MODULES.add(name); + } + return yield* (0, _moduleTypes.default)(name, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously.", true); + } catch (err) { + err.message = `[BABEL]: ${err.message} (While processing: ${name})`; + throw err; + } finally { + { + LOADING_MODULES.delete(name); + } + } +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/types.js b/node_modules/@babel/core/lib/config/files/types.js new file mode 100644 index 0000000..d28d24c --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/types.js @@ -0,0 +1 @@ +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/utils.js b/node_modules/@babel/core/lib/config/files/utils.js new file mode 100644 index 0000000..84dbe02 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/utils.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.makeStaticFileCache = makeStaticFileCache; + +var _caching = require("../caching"); + +var fs = require("../../gensync-utils/fs"); + +function _fs2() { + const data = require("fs"); + + _fs2 = function () { + return data; + }; + + return data; +} + +function makeStaticFileCache(fn) { + return (0, _caching.makeStrongCache)(function* (filepath, cache) { + const cached = cache.invalidate(() => fileMtime(filepath)); + + if (cached === null) { + return null; + } + + return fn(filepath, yield* fs.readFile(filepath, "utf8")); + }); +} + +function fileMtime(filepath) { + if (!_fs2().existsSync(filepath)) return null; + + try { + return +_fs2().statSync(filepath).mtime; + } catch (e) { + if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; + } + + return null; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/full.js b/node_modules/@babel/core/lib/config/full.js new file mode 100644 index 0000000..cab5fd6 --- /dev/null +++ b/node_modules/@babel/core/lib/config/full.js @@ -0,0 +1,380 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _async = require("../gensync-utils/async"); + +var _util = require("./util"); + +var context = require("../index"); + +var _plugin = require("./plugin"); + +var _item = require("./item"); + +var _configChain = require("./config-chain"); + +var _deepArray = require("./helpers/deep-array"); + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +var _caching = require("./caching"); + +var _options = require("./validation/options"); + +var _plugins = require("./validation/plugins"); + +var _configApi = require("./helpers/config-api"); + +var _partial = require("./partial"); + +var Context = require("./cache-contexts"); + +var _default = _gensync()(function* loadFullConfig(inputOpts) { + var _opts$assumptions; + + const result = yield* (0, _partial.default)(inputOpts); + + if (!result) { + return null; + } + + const { + options, + context, + fileHandling + } = result; + + if (fileHandling === "ignored") { + return null; + } + + const optionDefaults = {}; + const { + plugins, + presets + } = options; + + if (!plugins || !presets) { + throw new Error("Assertion failure - plugins and presets exist"); + } + + const presetContext = Object.assign({}, context, { + targets: options.targets + }); + + const toDescriptor = item => { + const desc = (0, _item.getItemDescriptor)(item); + + if (!desc) { + throw new Error("Assertion failure - must be config item"); + } + + return desc; + }; + + const presetsDescriptors = presets.map(toDescriptor); + const initialPluginsDescriptors = plugins.map(toDescriptor); + const pluginDescriptorsByPass = [[]]; + const passes = []; + const externalDependencies = []; + const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) { + const presets = []; + + for (let i = 0; i < rawPresets.length; i++) { + const descriptor = rawPresets[i]; + + if (descriptor.options !== false) { + try { + var preset = yield* loadPresetDescriptor(descriptor, presetContext); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_OPTION") { + (0, _options.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e); + } + + throw e; + } + + externalDependencies.push(preset.externalDependencies); + + if (descriptor.ownPass) { + presets.push({ + preset: preset.chain, + pass: [] + }); + } else { + presets.unshift({ + preset: preset.chain, + pass: pluginDescriptorsPass + }); + } + } + } + + if (presets.length > 0) { + pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass)); + + for (const { + preset, + pass + } of presets) { + if (!preset) return true; + pass.push(...preset.plugins); + const ignored = yield* recursePresetDescriptors(preset.presets, pass); + if (ignored) return true; + preset.options.forEach(opts => { + (0, _util.mergeOptions)(optionDefaults, opts); + }); + } + } + })(presetsDescriptors, pluginDescriptorsByPass[0]); + if (ignored) return null; + const opts = optionDefaults; + (0, _util.mergeOptions)(opts, options); + const pluginContext = Object.assign({}, presetContext, { + assumptions: (_opts$assumptions = opts.assumptions) != null ? _opts$assumptions : {} + }); + yield* enhanceError(context, function* loadPluginDescriptors() { + pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); + + for (const descs of pluginDescriptorsByPass) { + const pass = []; + passes.push(pass); + + for (let i = 0; i < descs.length; i++) { + const descriptor = descs[i]; + + if (descriptor.options !== false) { + try { + var plugin = yield* loadPluginDescriptor(descriptor, pluginContext); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { + (0, _options.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e); + } + + throw e; + } + + pass.push(plugin); + externalDependencies.push(plugin.externalDependencies); + } + } + } + })(); + opts.plugins = passes[0]; + opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({ + plugins + })); + opts.passPerPreset = opts.presets.length > 0; + return { + options: opts, + passes: passes, + externalDependencies: (0, _deepArray.finalize)(externalDependencies) + }; +}); + +exports.default = _default; + +function enhanceError(context, fn) { + return function* (arg1, arg2) { + try { + return yield* fn(arg1, arg2); + } catch (e) { + if (!/^\[BABEL\]/.test(e.message)) { + e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`; + } + + throw e; + } + }; +} + +const makeDescriptorLoader = apiFactory => (0, _caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias +}, cache) { + if (options === false) throw new Error("Assertion failure"); + options = options || {}; + const externalDependencies = []; + let item = value; + + if (typeof value === "function") { + const factory = (0, _async.maybeAsync)(value, `You appear to be using an async plugin/preset, but Babel has been called synchronously`); + const api = Object.assign({}, context, apiFactory(cache, externalDependencies)); + + try { + item = yield* factory(api, options, dirname); + } catch (e) { + if (alias) { + e.message += ` (While processing: ${JSON.stringify(alias)})`; + } + + throw e; + } + } + + if (!item || typeof item !== "object") { + throw new Error("Plugin/Preset did not return an object."); + } + + if ((0, _async.isThenable)(item)) { + yield* []; + throw new Error(`You appear to be using a promise as a plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version. ` + `As an alternative, you can prefix the promise with "await". ` + `(While processing: ${JSON.stringify(alias)})`); + } + + if (externalDependencies.length > 0 && (!cache.configured() || cache.mode() === "forever")) { + let error = `A plugin/preset has external untracked dependencies ` + `(${externalDependencies[0]}), but the cache `; + + if (!cache.configured()) { + error += `has not been configured to be invalidated when the external dependencies change. `; + } else { + error += ` has been configured to never be invalidated. `; + } + + error += `Plugins/presets should configure their cache to be invalidated when the external ` + `dependencies change, for example using \`api.cache.invalidate(() => ` + `statSync(filepath).mtimeMs)\` or \`api.cache.never()\`\n` + `(While processing: ${JSON.stringify(alias)})`; + throw new Error(error); + } + + return { + value: item, + options, + dirname, + alias, + externalDependencies: (0, _deepArray.finalize)(externalDependencies) + }; +}); + +const pluginDescriptorLoader = makeDescriptorLoader(_configApi.makePluginAPI); +const presetDescriptorLoader = makeDescriptorLoader(_configApi.makePresetAPI); + +function* loadPluginDescriptor(descriptor, context) { + if (descriptor.value instanceof _plugin.default) { + if (descriptor.options) { + throw new Error("Passed options to an existing Plugin instance will not work."); + } + + return descriptor.value; + } + + return yield* instantiatePlugin(yield* pluginDescriptorLoader(descriptor, context), context); +} + +const instantiatePlugin = (0, _caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias, + externalDependencies +}, cache) { + const pluginObj = (0, _plugins.validatePluginObject)(value); + const plugin = Object.assign({}, pluginObj); + + if (plugin.visitor) { + plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor)); + } + + if (plugin.inherits) { + const inheritsDescriptor = { + name: undefined, + alias: `${alias}$inherits`, + value: plugin.inherits, + options, + dirname + }; + const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => { + return cache.invalidate(data => run(inheritsDescriptor, data)); + }); + plugin.pre = chain(inherits.pre, plugin.pre); + plugin.post = chain(inherits.post, plugin.post); + plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); + plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); + + if (inherits.externalDependencies.length > 0) { + if (externalDependencies.length === 0) { + externalDependencies = inherits.externalDependencies; + } else { + externalDependencies = (0, _deepArray.finalize)([externalDependencies, inherits.externalDependencies]); + } + } + } + + return new _plugin.default(plugin, options, alias, externalDependencies); +}); + +const validateIfOptionNeedsFilename = (options, descriptor) => { + if (options.test || options.include || options.exclude) { + const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */"; + throw new Error([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n")); + } +}; + +const validatePreset = (preset, context, descriptor) => { + if (!context.filename) { + const { + options + } = preset; + validateIfOptionNeedsFilename(options, descriptor); + + if (options.overrides) { + options.overrides.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor)); + } + } +}; + +function* loadPresetDescriptor(descriptor, context) { + const preset = instantiatePreset(yield* presetDescriptorLoader(descriptor, context)); + validatePreset(preset, context, descriptor); + return { + chain: yield* (0, _configChain.buildPresetChain)(preset, context), + externalDependencies: preset.externalDependencies + }; +} + +const instantiatePreset = (0, _caching.makeWeakCacheSync)(({ + value, + dirname, + alias, + externalDependencies +}) => { + return { + options: (0, _options.validate)("preset", value), + alias, + dirname, + externalDependencies + }; +}); + +function chain(a, b) { + const fns = [a, b].filter(Boolean); + if (fns.length <= 1) return fns[0]; + return function (...args) { + for (const fn of fns) { + fn.apply(this, args); + } + }; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/config-api.js b/node_modules/@babel/core/lib/config/helpers/config-api.js new file mode 100644 index 0000000..5fafead --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/config-api.js @@ -0,0 +1,109 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.makeConfigAPI = makeConfigAPI; +exports.makePluginAPI = makePluginAPI; +exports.makePresetAPI = makePresetAPI; + +function _semver() { + const data = require("semver"); + + _semver = function () { + return data; + }; + + return data; +} + +var _ = require("../../"); + +var _caching = require("../caching"); + +var Context = require("../cache-contexts"); + +function makeConfigAPI(cache) { + const env = value => cache.using(data => { + if (typeof value === "undefined") return data.envName; + + if (typeof value === "function") { + return (0, _caching.assertSimpleType)(value(data.envName)); + } + + return (Array.isArray(value) ? value : [value]).some(entry => { + if (typeof entry !== "string") { + throw new Error("Unexpected non-string value"); + } + + return entry === data.envName; + }); + }); + + const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller))); + + return { + version: _.version, + cache: cache.simple(), + env, + async: () => false, + caller, + assertVersion + }; +} + +function makePresetAPI(cache, externalDependencies) { + const targets = () => JSON.parse(cache.using(data => JSON.stringify(data.targets))); + + const addExternalDependency = ref => { + externalDependencies.push(ref); + }; + + return Object.assign({}, makeConfigAPI(cache), { + targets, + addExternalDependency + }); +} + +function makePluginAPI(cache, externalDependencies) { + const assumption = name => cache.using(data => data.assumptions[name]); + + return Object.assign({}, makePresetAPI(cache, externalDependencies), { + assumption + }); +} + +function assertVersion(range) { + if (typeof range === "number") { + if (!Number.isInteger(range)) { + throw new Error("Expected string or integer value."); + } + + range = `^${range}.0.0-0`; + } + + if (typeof range !== "string") { + throw new Error("Expected string or integer value."); + } + + if (_semver().satisfies(_.version, range)) return; + const limit = Error.stackTraceLimit; + + if (typeof limit === "number" && limit < 25) { + Error.stackTraceLimit = 25; + } + + const err = new Error(`Requires Babel "${range}", but was loaded with "${_.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`); + + if (typeof limit === "number") { + Error.stackTraceLimit = limit; + } + + throw Object.assign(err, { + code: "BABEL_VERSION_UNSUPPORTED", + version: _.version, + range + }); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/deep-array.js b/node_modules/@babel/core/lib/config/helpers/deep-array.js new file mode 100644 index 0000000..4aa198c --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/deep-array.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.finalize = finalize; +exports.flattenToSet = flattenToSet; + +function finalize(deepArr) { + return Object.freeze(deepArr); +} + +function flattenToSet(arr) { + const result = new Set(); + const stack = [arr]; + + while (stack.length > 0) { + for (const el of stack.pop()) { + if (Array.isArray(el)) stack.push(el);else result.add(el); + } + } + + return result; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/environment.js b/node_modules/@babel/core/lib/config/helpers/environment.js new file mode 100644 index 0000000..75910a7 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/environment.js @@ -0,0 +1,12 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getEnv = getEnv; + +function getEnv(defaultValue = "development") { + return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/index.js b/node_modules/@babel/core/lib/config/index.js new file mode 100644 index 0000000..116d3f0 --- /dev/null +++ b/node_modules/@babel/core/lib/config/index.js @@ -0,0 +1,83 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createConfigItem = createConfigItem; +exports.createConfigItemSync = exports.createConfigItemAsync = void 0; +Object.defineProperty(exports, "default", { + enumerable: true, + get: function () { + return _full.default; + } +}); +exports.loadPartialConfigSync = exports.loadPartialConfigAsync = exports.loadPartialConfig = exports.loadOptionsSync = exports.loadOptionsAsync = exports.loadOptions = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _full = require("./full"); + +var _partial = require("./partial"); + +var _item = require("./item"); + +const loadOptionsRunner = _gensync()(function* (opts) { + var _config$options; + + const config = yield* (0, _full.default)(opts); + return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null; +}); + +const createConfigItemRunner = _gensync()(_item.createConfigItem); + +const maybeErrback = runner => (argOrCallback, maybeCallback) => { + let arg; + let callback; + + if (maybeCallback === undefined && typeof argOrCallback === "function") { + callback = argOrCallback; + arg = undefined; + } else { + callback = maybeCallback; + arg = argOrCallback; + } + + return callback ? runner.errback(arg, callback) : runner.sync(arg); +}; + +const loadPartialConfig = maybeErrback(_partial.loadPartialConfig); +exports.loadPartialConfig = loadPartialConfig; +const loadPartialConfigSync = _partial.loadPartialConfig.sync; +exports.loadPartialConfigSync = loadPartialConfigSync; +const loadPartialConfigAsync = _partial.loadPartialConfig.async; +exports.loadPartialConfigAsync = loadPartialConfigAsync; +const loadOptions = maybeErrback(loadOptionsRunner); +exports.loadOptions = loadOptions; +const loadOptionsSync = loadOptionsRunner.sync; +exports.loadOptionsSync = loadOptionsSync; +const loadOptionsAsync = loadOptionsRunner.async; +exports.loadOptionsAsync = loadOptionsAsync; +const createConfigItemSync = createConfigItemRunner.sync; +exports.createConfigItemSync = createConfigItemSync; +const createConfigItemAsync = createConfigItemRunner.async; +exports.createConfigItemAsync = createConfigItemAsync; + +function createConfigItem(target, options, callback) { + if (callback !== undefined) { + return createConfigItemRunner.errback(target, options, callback); + } else if (typeof options === "function") { + return createConfigItemRunner.errback(target, undefined, callback); + } else { + return createConfigItemRunner.sync(target, options); + } +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/item.js b/node_modules/@babel/core/lib/config/item.js new file mode 100644 index 0000000..f0a185e --- /dev/null +++ b/node_modules/@babel/core/lib/config/item.js @@ -0,0 +1,77 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createConfigItem = createConfigItem; +exports.createItemFromDescriptor = createItemFromDescriptor; +exports.getItemDescriptor = getItemDescriptor; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +var _configDescriptors = require("./config-descriptors"); + +function createItemFromDescriptor(desc) { + return new ConfigItem(desc); +} + +function* createConfigItem(value, { + dirname = ".", + type +} = {}) { + const descriptor = yield* (0, _configDescriptors.createDescriptor)(value, _path().resolve(dirname), { + type, + alias: "programmatic item" + }); + return createItemFromDescriptor(descriptor); +} + +function getItemDescriptor(item) { + if (item != null && item[CONFIG_ITEM_BRAND]) { + return item._descriptor; + } + + return undefined; +} + +const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem"); + +class ConfigItem { + constructor(descriptor) { + this._descriptor = void 0; + this[CONFIG_ITEM_BRAND] = true; + this.value = void 0; + this.options = void 0; + this.dirname = void 0; + this.name = void 0; + this.file = void 0; + this._descriptor = descriptor; + Object.defineProperty(this, "_descriptor", { + enumerable: false + }); + Object.defineProperty(this, CONFIG_ITEM_BRAND, { + enumerable: false + }); + this.value = this._descriptor.value; + this.options = this._descriptor.options; + this.dirname = this._descriptor.dirname; + this.name = this._descriptor.name; + this.file = this._descriptor.file ? { + request: this._descriptor.file.request, + resolved: this._descriptor.file.resolved + } : undefined; + Object.freeze(this); + } + +} + +Object.freeze(ConfigItem.prototype); +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/partial.js b/node_modules/@babel/core/lib/config/partial.js new file mode 100644 index 0000000..2269da2 --- /dev/null +++ b/node_modules/@babel/core/lib/config/partial.js @@ -0,0 +1,198 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadPrivatePartialConfig; +exports.loadPartialConfig = void 0; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _plugin = require("./plugin"); + +var _util = require("./util"); + +var _item = require("./item"); + +var _configChain = require("./config-chain"); + +var _environment = require("./helpers/environment"); + +var _options = require("./validation/options"); + +var _files = require("./files"); + +var _resolveTargets = require("./resolve-targets"); + +const _excluded = ["showIgnoredFiles"]; + +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + +function resolveRootMode(rootDir, rootMode) { + switch (rootMode) { + case "root": + return rootDir; + + case "upward-optional": + { + const upwardRootDir = (0, _files.findConfigUpwards)(rootDir); + return upwardRootDir === null ? rootDir : upwardRootDir; + } + + case "upward": + { + const upwardRootDir = (0, _files.findConfigUpwards)(rootDir); + if (upwardRootDir !== null) return upwardRootDir; + throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${_files.ROOT_CONFIG_FILENAMES.join(", ")}".`), { + code: "BABEL_ROOT_NOT_FOUND", + dirname: rootDir + }); + } + + default: + throw new Error(`Assertion failure - unknown rootMode value.`); + } +} + +function* loadPrivatePartialConfig(inputOpts) { + if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) { + throw new Error("Babel options must be an object, null, or undefined"); + } + + const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {}; + const { + envName = (0, _environment.getEnv)(), + cwd = ".", + root: rootDir = ".", + rootMode = "root", + caller, + cloneInputAst = true + } = args; + + const absoluteCwd = _path().resolve(cwd); + + const absoluteRootDir = resolveRootMode(_path().resolve(absoluteCwd, rootDir), rootMode); + const filename = typeof args.filename === "string" ? _path().resolve(cwd, args.filename) : undefined; + const showConfigPath = yield* (0, _files.resolveShowConfigPath)(absoluteCwd); + const context = { + filename, + cwd: absoluteCwd, + root: absoluteRootDir, + envName, + caller, + showConfig: showConfigPath === filename + }; + const configChain = yield* (0, _configChain.buildRootChain)(args, context); + if (!configChain) return null; + const merged = { + assumptions: {} + }; + configChain.options.forEach(opts => { + (0, _util.mergeOptions)(merged, opts); + }); + const options = Object.assign({}, merged, { + targets: (0, _resolveTargets.resolveTargets)(merged, absoluteRootDir), + cloneInputAst, + babelrc: false, + configFile: false, + browserslistConfigFile: false, + passPerPreset: false, + envName: context.envName, + cwd: context.cwd, + root: context.root, + rootMode: "root", + filename: typeof context.filename === "string" ? context.filename : undefined, + plugins: configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)), + presets: configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)) + }); + return { + options, + context, + fileHandling: configChain.fileHandling, + ignore: configChain.ignore, + babelrc: configChain.babelrc, + config: configChain.config, + files: configChain.files + }; +} + +const loadPartialConfig = _gensync()(function* (opts) { + let showIgnoredFiles = false; + + if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) { + var _opts = opts; + ({ + showIgnoredFiles + } = _opts); + opts = _objectWithoutPropertiesLoose(_opts, _excluded); + _opts; + } + + const result = yield* loadPrivatePartialConfig(opts); + if (!result) return null; + const { + options, + babelrc, + ignore, + config, + fileHandling, + files + } = result; + + if (fileHandling === "ignored" && !showIgnoredFiles) { + return null; + } + + (options.plugins || []).forEach(item => { + if (item.value instanceof _plugin.default) { + throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); + } + }); + return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files); +}); + +exports.loadPartialConfig = loadPartialConfig; + +class PartialConfig { + constructor(options, babelrc, ignore, config, fileHandling, files) { + this.options = void 0; + this.babelrc = void 0; + this.babelignore = void 0; + this.config = void 0; + this.fileHandling = void 0; + this.files = void 0; + this.options = options; + this.babelignore = ignore; + this.babelrc = babelrc; + this.config = config; + this.fileHandling = fileHandling; + this.files = files; + Object.freeze(this); + } + + hasFilesystemConfig() { + return this.babelrc !== undefined || this.config !== undefined; + } + +} + +Object.freeze(PartialConfig.prototype); +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/pattern-to-regex.js b/node_modules/@babel/core/lib/config/pattern-to-regex.js new file mode 100644 index 0000000..f24d955 --- /dev/null +++ b/node_modules/@babel/core/lib/config/pattern-to-regex.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = pathToPattern; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +const sep = `\\${_path().sep}`; +const endSep = `(?:${sep}|$)`; +const substitution = `[^${sep}]+`; +const starPat = `(?:${substitution}${sep})`; +const starPatLast = `(?:${substitution}${endSep})`; +const starStarPat = `${starPat}*?`; +const starStarPatLast = `${starPat}*?${starPatLast}?`; + +function escapeRegExp(string) { + return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); +} + +function pathToPattern(pattern, dirname) { + const parts = _path().resolve(dirname, pattern).split(_path().sep); + + return new RegExp(["^", ...parts.map((part, i) => { + const last = i === parts.length - 1; + if (part === "**") return last ? starStarPatLast : starStarPat; + if (part === "*") return last ? starPatLast : starPat; + + if (part.indexOf("*.") === 0) { + return substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep); + } + + return escapeRegExp(part) + (last ? endSep : sep); + })].join("")); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/plugin.js b/node_modules/@babel/core/lib/config/plugin.js new file mode 100644 index 0000000..e0f2d34 --- /dev/null +++ b/node_modules/@babel/core/lib/config/plugin.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _deepArray = require("./helpers/deep-array"); + +class Plugin { + constructor(plugin, options, key, externalDependencies = (0, _deepArray.finalize)([])) { + this.key = void 0; + this.manipulateOptions = void 0; + this.post = void 0; + this.pre = void 0; + this.visitor = void 0; + this.parserOverride = void 0; + this.generatorOverride = void 0; + this.options = void 0; + this.externalDependencies = void 0; + this.key = plugin.name || key; + this.manipulateOptions = plugin.manipulateOptions; + this.post = plugin.post; + this.pre = plugin.pre; + this.visitor = plugin.visitor || {}; + this.parserOverride = plugin.parserOverride; + this.generatorOverride = plugin.generatorOverride; + this.options = options; + this.externalDependencies = externalDependencies; + } + +} + +exports.default = Plugin; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/printer.js b/node_modules/@babel/core/lib/config/printer.js new file mode 100644 index 0000000..51d7c1b --- /dev/null +++ b/node_modules/@babel/core/lib/config/printer.js @@ -0,0 +1,140 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ConfigPrinter = exports.ChainFormatter = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +const ChainFormatter = { + Programmatic: 0, + Config: 1 +}; +exports.ChainFormatter = ChainFormatter; +const Formatter = { + title(type, callerName, filepath) { + let title = ""; + + if (type === ChainFormatter.Programmatic) { + title = "programmatic options"; + + if (callerName) { + title += " from " + callerName; + } + } else { + title = "config " + filepath; + } + + return title; + }, + + loc(index, envName) { + let loc = ""; + + if (index != null) { + loc += `.overrides[${index}]`; + } + + if (envName != null) { + loc += `.env["${envName}"]`; + } + + return loc; + }, + + *optionsAndDescriptors(opt) { + const content = Object.assign({}, opt.options); + delete content.overrides; + delete content.env; + const pluginDescriptors = [...(yield* opt.plugins())]; + + if (pluginDescriptors.length) { + content.plugins = pluginDescriptors.map(d => descriptorToConfig(d)); + } + + const presetDescriptors = [...(yield* opt.presets())]; + + if (presetDescriptors.length) { + content.presets = [...presetDescriptors].map(d => descriptorToConfig(d)); + } + + return JSON.stringify(content, undefined, 2); + } + +}; + +function descriptorToConfig(d) { + var _d$file; + + let name = (_d$file = d.file) == null ? void 0 : _d$file.request; + + if (name == null) { + if (typeof d.value === "object") { + name = d.value; + } else if (typeof d.value === "function") { + name = `[Function: ${d.value.toString().slice(0, 50)} ... ]`; + } + } + + if (name == null) { + name = "[Unknown]"; + } + + if (d.options === undefined) { + return name; + } else if (d.name == null) { + return [name, d.options]; + } else { + return [name, d.options, d.name]; + } +} + +class ConfigPrinter { + constructor() { + this._stack = []; + } + + configure(enabled, type, { + callerName, + filepath + }) { + if (!enabled) return () => {}; + return (content, index, envName) => { + this._stack.push({ + type, + callerName, + filepath, + content, + index, + envName + }); + }; + } + + static *format(config) { + let title = Formatter.title(config.type, config.callerName, config.filepath); + const loc = Formatter.loc(config.index, config.envName); + if (loc) title += ` ${loc}`; + const content = yield* Formatter.optionsAndDescriptors(config.content); + return `${title}\n${content}`; + } + + *output() { + if (this._stack.length === 0) return ""; + const configs = yield* _gensync().all(this._stack.map(s => ConfigPrinter.format(s))); + return configs.join("\n\n"); + } + +} + +exports.ConfigPrinter = ConfigPrinter; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/resolve-targets-browser.js b/node_modules/@babel/core/lib/config/resolve-targets-browser.js new file mode 100644 index 0000000..1fd3f9e --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets-browser.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile; +exports.resolveTargets = resolveTargets; + +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + + _helperCompilationTargets = function () { + return data; + }; + + return data; +} + +function resolveBrowserslistConfigFile(browserslistConfigFile, configFilePath) { + return undefined; +} + +function resolveTargets(options, root) { + const optTargets = options.targets; + let targets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { + browsers: optTargets + }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = Object.assign({}, optTargets, { + esmodules: "intersect" + }); + } else { + targets = optTargets; + } + } + + return (0, _helperCompilationTargets().default)(targets, { + ignoreBrowserslistConfig: true, + browserslistEnv: options.browserslistEnv + }); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/resolve-targets.js b/node_modules/@babel/core/lib/config/resolve-targets.js new file mode 100644 index 0000000..585d86b --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile; +exports.resolveTargets = resolveTargets; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + + _helperCompilationTargets = function () { + return data; + }; + + return data; +} + +({}); + +function resolveBrowserslistConfigFile(browserslistConfigFile, configFileDir) { + return _path().resolve(configFileDir, browserslistConfigFile); +} + +function resolveTargets(options, root) { + const optTargets = options.targets; + let targets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { + browsers: optTargets + }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = Object.assign({}, optTargets, { + esmodules: "intersect" + }); + } else { + targets = optTargets; + } + } + + const { + browserslistConfigFile + } = options; + let configFile; + let ignoreBrowserslistConfig = false; + + if (typeof browserslistConfigFile === "string") { + configFile = browserslistConfigFile; + } else { + ignoreBrowserslistConfig = browserslistConfigFile === false; + } + + return (0, _helperCompilationTargets().default)(targets, { + ignoreBrowserslistConfig, + configFile, + configPath: root, + browserslistEnv: options.browserslistEnv + }); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/util.js b/node_modules/@babel/core/lib/config/util.js new file mode 100644 index 0000000..98b5870 --- /dev/null +++ b/node_modules/@babel/core/lib/config/util.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIterableIterator = isIterableIterator; +exports.mergeOptions = mergeOptions; + +function mergeOptions(target, source) { + for (const k of Object.keys(source)) { + if ((k === "parserOpts" || k === "generatorOpts" || k === "assumptions") && source[k]) { + const parserOpts = source[k]; + const targetObj = target[k] || (target[k] = {}); + mergeDefaultFields(targetObj, parserOpts); + } else { + const val = source[k]; + if (val !== undefined) target[k] = val; + } + } +} + +function mergeDefaultFields(target, source) { + for (const k of Object.keys(source)) { + const val = source[k]; + if (val !== undefined) target[k] = val; + } +} + +function isIterableIterator(value) { + return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function"; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/option-assertions.js b/node_modules/@babel/core/lib/config/validation/option-assertions.js new file mode 100644 index 0000000..8761d29 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/option-assertions.js @@ -0,0 +1,354 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.access = access; +exports.assertArray = assertArray; +exports.assertAssumptions = assertAssumptions; +exports.assertBabelrcSearch = assertBabelrcSearch; +exports.assertBoolean = assertBoolean; +exports.assertCallerMetadata = assertCallerMetadata; +exports.assertCompact = assertCompact; +exports.assertConfigApplicableTest = assertConfigApplicableTest; +exports.assertConfigFileSearch = assertConfigFileSearch; +exports.assertFunction = assertFunction; +exports.assertIgnoreList = assertIgnoreList; +exports.assertInputSourceMap = assertInputSourceMap; +exports.assertObject = assertObject; +exports.assertPluginList = assertPluginList; +exports.assertRootMode = assertRootMode; +exports.assertSourceMaps = assertSourceMaps; +exports.assertSourceType = assertSourceType; +exports.assertString = assertString; +exports.assertTargets = assertTargets; +exports.msg = msg; + +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + + _helperCompilationTargets = function () { + return data; + }; + + return data; +} + +var _options = require("./options"); + +function msg(loc) { + switch (loc.type) { + case "root": + return ``; + + case "env": + return `${msg(loc.parent)}.env["${loc.name}"]`; + + case "overrides": + return `${msg(loc.parent)}.overrides[${loc.index}]`; + + case "option": + return `${msg(loc.parent)}.${loc.name}`; + + case "access": + return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`; + + default: + throw new Error(`Assertion failure: Unknown type ${loc.type}`); + } +} + +function access(loc, name) { + return { + type: "access", + name, + parent: loc + }; +} + +function assertRootMode(loc, value) { + if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") { + throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`); + } + + return value; +} + +function assertSourceMaps(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") { + throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`); + } + + return value; +} + +function assertCompact(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "auto") { + throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`); + } + + return value; +} + +function assertSourceType(loc, value) { + if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") { + throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`); + } + + return value; +} + +function assertCallerMetadata(loc, value) { + const obj = assertObject(loc, value); + + if (obj) { + if (typeof obj.name !== "string") { + throw new Error(`${msg(loc)} set but does not contain "name" property string`); + } + + for (const prop of Object.keys(obj)) { + const propLoc = access(loc, prop); + const value = obj[prop]; + + if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") { + throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`); + } + } + } + + return value; +} + +function assertInputSourceMap(loc, value) { + if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) { + throw new Error(`${msg(loc)} must be a boolean, object, or undefined`); + } + + return value; +} + +function assertString(loc, value) { + if (value !== undefined && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a string, or undefined`); + } + + return value; +} + +function assertFunction(loc, value) { + if (value !== undefined && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a function, or undefined`); + } + + return value; +} + +function assertBoolean(loc, value) { + if (value !== undefined && typeof value !== "boolean") { + throw new Error(`${msg(loc)} must be a boolean, or undefined`); + } + + return value; +} + +function assertObject(loc, value) { + if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) { + throw new Error(`${msg(loc)} must be an object, or undefined`); + } + + return value; +} + +function assertArray(loc, value) { + if (value != null && !Array.isArray(value)) { + throw new Error(`${msg(loc)} must be an array, or undefined`); + } + + return value; +} + +function assertIgnoreList(loc, value) { + const arr = assertArray(loc, value); + + if (arr) { + arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item)); + } + + return arr; +} + +function assertIgnoreItem(loc, value) { + if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { + throw new Error(`${msg(loc)} must be an array of string/Function/RegExp values, or undefined`); + } + + return value; +} + +function assertConfigApplicableTest(loc, value) { + if (value === undefined) return value; + + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`); + } + + return value; +} + +function checkValidTest(value) { + return typeof value === "string" || typeof value === "function" || value instanceof RegExp; +} + +function assertConfigFileSearch(loc, value) { + if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`); + } + + return value; +} + +function assertBabelrcSearch(loc, value) { + if (value === undefined || typeof value === "boolean") return value; + + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`); + } + + return value; +} + +function assertPluginList(loc, value) { + const arr = assertArray(loc, value); + + if (arr) { + arr.forEach((item, i) => assertPluginItem(access(loc, i), item)); + } + + return arr; +} + +function assertPluginItem(loc, value) { + if (Array.isArray(value)) { + if (value.length === 0) { + throw new Error(`${msg(loc)} must include an object`); + } + + if (value.length > 3) { + throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`); + } + + assertPluginTarget(access(loc, 0), value[0]); + + if (value.length > 1) { + const opts = value[1]; + + if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) { + throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`); + } + } + + if (value.length === 3) { + const name = value[2]; + + if (name !== undefined && typeof name !== "string") { + throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`); + } + } + } else { + assertPluginTarget(loc, value); + } + + return value; +} + +function assertPluginTarget(loc, value) { + if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a string, object, function`); + } + + return value; +} + +function assertTargets(loc, value) { + if ((0, _helperCompilationTargets().isBrowsersQueryValid)(value)) return value; + + if (typeof value !== "object" || !value || Array.isArray(value)) { + throw new Error(`${msg(loc)} must be a string, an array of strings or an object`); + } + + const browsersLoc = access(loc, "browsers"); + const esmodulesLoc = access(loc, "esmodules"); + assertBrowsersList(browsersLoc, value.browsers); + assertBoolean(esmodulesLoc, value.esmodules); + + for (const key of Object.keys(value)) { + const val = value[key]; + const subLoc = access(loc, key); + if (key === "esmodules") assertBoolean(subLoc, val);else if (key === "browsers") assertBrowsersList(subLoc, val);else if (!Object.hasOwnProperty.call(_helperCompilationTargets().TargetNames, key)) { + const validTargets = Object.keys(_helperCompilationTargets().TargetNames).join(", "); + throw new Error(`${msg(subLoc)} is not a valid target. Supported targets are ${validTargets}`); + } else assertBrowserVersion(subLoc, val); + } + + return value; +} + +function assertBrowsersList(loc, value) { + if (value !== undefined && !(0, _helperCompilationTargets().isBrowsersQueryValid)(value)) { + throw new Error(`${msg(loc)} must be undefined, a string or an array of strings`); + } +} + +function assertBrowserVersion(loc, value) { + if (typeof value === "number" && Math.round(value) === value) return; + if (typeof value === "string") return; + throw new Error(`${msg(loc)} must be a string or an integer number`); +} + +function assertAssumptions(loc, value) { + if (value === undefined) return; + + if (typeof value !== "object" || value === null) { + throw new Error(`${msg(loc)} must be an object or undefined.`); + } + + let root = loc; + + do { + root = root.parent; + } while (root.type !== "root"); + + const inPreset = root.source === "preset"; + + for (const name of Object.keys(value)) { + const subLoc = access(loc, name); + + if (!_options.assumptionsNames.has(name)) { + throw new Error(`${msg(subLoc)} is not a supported assumption.`); + } + + if (typeof value[name] !== "boolean") { + throw new Error(`${msg(subLoc)} must be a boolean.`); + } + + if (inPreset && value[name] === false) { + throw new Error(`${msg(subLoc)} cannot be set to 'false' inside presets.`); + } + } + + return value; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/options.js b/node_modules/@babel/core/lib/config/validation/options.js new file mode 100644 index 0000000..7aa1582 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/options.js @@ -0,0 +1,213 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assumptionsNames = void 0; +exports.checkNoUnwrappedItemOptionPairs = checkNoUnwrappedItemOptionPairs; +exports.validate = validate; + +var _plugin = require("../plugin"); + +var _removed = require("./removed"); + +var _optionAssertions = require("./option-assertions"); + +const ROOT_VALIDATORS = { + cwd: _optionAssertions.assertString, + root: _optionAssertions.assertString, + rootMode: _optionAssertions.assertRootMode, + configFile: _optionAssertions.assertConfigFileSearch, + caller: _optionAssertions.assertCallerMetadata, + filename: _optionAssertions.assertString, + filenameRelative: _optionAssertions.assertString, + code: _optionAssertions.assertBoolean, + ast: _optionAssertions.assertBoolean, + cloneInputAst: _optionAssertions.assertBoolean, + envName: _optionAssertions.assertString +}; +const BABELRC_VALIDATORS = { + babelrc: _optionAssertions.assertBoolean, + babelrcRoots: _optionAssertions.assertBabelrcSearch +}; +const NONPRESET_VALIDATORS = { + extends: _optionAssertions.assertString, + ignore: _optionAssertions.assertIgnoreList, + only: _optionAssertions.assertIgnoreList, + targets: _optionAssertions.assertTargets, + browserslistConfigFile: _optionAssertions.assertConfigFileSearch, + browserslistEnv: _optionAssertions.assertString +}; +const COMMON_VALIDATORS = { + inputSourceMap: _optionAssertions.assertInputSourceMap, + presets: _optionAssertions.assertPluginList, + plugins: _optionAssertions.assertPluginList, + passPerPreset: _optionAssertions.assertBoolean, + assumptions: _optionAssertions.assertAssumptions, + env: assertEnvSet, + overrides: assertOverridesList, + test: _optionAssertions.assertConfigApplicableTest, + include: _optionAssertions.assertConfigApplicableTest, + exclude: _optionAssertions.assertConfigApplicableTest, + retainLines: _optionAssertions.assertBoolean, + comments: _optionAssertions.assertBoolean, + shouldPrintComment: _optionAssertions.assertFunction, + compact: _optionAssertions.assertCompact, + minified: _optionAssertions.assertBoolean, + auxiliaryCommentBefore: _optionAssertions.assertString, + auxiliaryCommentAfter: _optionAssertions.assertString, + sourceType: _optionAssertions.assertSourceType, + wrapPluginVisitorMethod: _optionAssertions.assertFunction, + highlightCode: _optionAssertions.assertBoolean, + sourceMaps: _optionAssertions.assertSourceMaps, + sourceMap: _optionAssertions.assertSourceMaps, + sourceFileName: _optionAssertions.assertString, + sourceRoot: _optionAssertions.assertString, + parserOpts: _optionAssertions.assertObject, + generatorOpts: _optionAssertions.assertObject +}; +{ + Object.assign(COMMON_VALIDATORS, { + getModuleId: _optionAssertions.assertFunction, + moduleRoot: _optionAssertions.assertString, + moduleIds: _optionAssertions.assertBoolean, + moduleId: _optionAssertions.assertString + }); +} +const knownAssumptions = ["arrayLikeIsIterable", "constantReexports", "constantSuper", "enumerableModuleMeta", "ignoreFunctionLength", "ignoreToPrimitiveHint", "iterableIsArray", "mutableTemplateObject", "noClassCalls", "noDocumentAll", "noIncompleteNsImportDetection", "noNewArrows", "objectRestNoSymbols", "privateFieldsAsProperties", "pureGetters", "setClassMethods", "setComputedProperties", "setPublicClassFields", "setSpreadProperties", "skipForOfIteratorClosing", "superIsCallableConstructor"]; +const assumptionsNames = new Set(knownAssumptions); +exports.assumptionsNames = assumptionsNames; + +function getSource(loc) { + return loc.type === "root" ? loc.source : getSource(loc.parent); +} + +function validate(type, opts) { + return validateNested({ + type: "root", + source: type + }, opts); +} + +function validateNested(loc, opts) { + const type = getSource(loc); + assertNoDuplicateSourcemap(opts); + Object.keys(opts).forEach(key => { + const optLoc = { + type: "option", + name: key, + parent: loc + }; + + if (type === "preset" && NONPRESET_VALIDATORS[key]) { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in preset options`); + } + + if (type !== "arguments" && ROOT_VALIDATORS[key]) { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`); + } + + if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) { + if (type === "babelrcfile" || type === "extendsfile") { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`); + } + + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`); + } + + const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError; + validator(optLoc, opts[key]); + }); + return opts; +} + +function throwUnknownError(loc) { + const key = loc.name; + + if (_removed.default[key]) { + const { + message, + version = 5 + } = _removed.default[key]; + throw new Error(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`); + } else { + const unknownOptErr = new Error(`Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`); + unknownOptErr.code = "BABEL_UNKNOWN_OPTION"; + throw unknownOptErr; + } +} + +function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function assertNoDuplicateSourcemap(opts) { + if (has(opts, "sourceMap") && has(opts, "sourceMaps")) { + throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); + } +} + +function assertEnvSet(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside of another .env block`); + } + + const parent = loc.parent; + const obj = (0, _optionAssertions.assertObject)(loc, value); + + if (obj) { + for (const envName of Object.keys(obj)) { + const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]); + if (!env) continue; + const envLoc = { + type: "env", + name: envName, + parent + }; + validateNested(envLoc, env); + } + } + + return obj; +} + +function assertOverridesList(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`); + } + + if (loc.parent.type === "overrides") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`); + } + + const parent = loc.parent; + const arr = (0, _optionAssertions.assertArray)(loc, value); + + if (arr) { + for (const [index, item] of arr.entries()) { + const objLoc = (0, _optionAssertions.access)(loc, index); + const env = (0, _optionAssertions.assertObject)(objLoc, item); + if (!env) throw new Error(`${(0, _optionAssertions.msg)(objLoc)} must be an object`); + const overridesLoc = { + type: "overrides", + index, + parent + }; + validateNested(overridesLoc, env); + } + } + + return arr; +} + +function checkNoUnwrappedItemOptionPairs(items, index, type, e) { + if (index === 0) return; + const lastItem = items[index - 1]; + const thisItem = items[index]; + + if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") { + e.message += `\n- Maybe you meant to use\n` + `"${type}s": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`; + } +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/plugins.js b/node_modules/@babel/core/lib/config/validation/plugins.js new file mode 100644 index 0000000..32c05c2 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/plugins.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validatePluginObject = validatePluginObject; + +var _optionAssertions = require("./option-assertions"); + +const VALIDATORS = { + name: _optionAssertions.assertString, + manipulateOptions: _optionAssertions.assertFunction, + pre: _optionAssertions.assertFunction, + post: _optionAssertions.assertFunction, + inherits: _optionAssertions.assertFunction, + visitor: assertVisitorMap, + parserOverride: _optionAssertions.assertFunction, + generatorOverride: _optionAssertions.assertFunction +}; + +function assertVisitorMap(loc, value) { + const obj = (0, _optionAssertions.assertObject)(loc, value); + + if (obj) { + Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop])); + + if (obj.enter || obj.exit) { + throw new Error(`${(0, _optionAssertions.msg)(loc)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`); + } + } + + return obj; +} + +function assertVisitorHandler(key, value) { + if (value && typeof value === "object") { + Object.keys(value).forEach(handler => { + if (handler !== "enter" && handler !== "exit") { + throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`); + } + }); + } else if (typeof value !== "function") { + throw new Error(`.visitor["${key}"] must be a function`); + } + + return value; +} + +function validatePluginObject(obj) { + const rootPath = { + type: "root", + source: "plugin" + }; + Object.keys(obj).forEach(key => { + const validator = VALIDATORS[key]; + + if (validator) { + const optLoc = { + type: "option", + name: key, + parent: rootPath + }; + validator(optLoc, obj[key]); + } else { + const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`); + invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY"; + throw invalidPluginPropertyError; + } + }); + return obj; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/removed.js b/node_modules/@babel/core/lib/config/validation/removed.js new file mode 100644 index 0000000..2419f2b --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/removed.js @@ -0,0 +1,67 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = { + 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: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves." + }, + 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" + }, + resolveModuleSource: { + version: 6, + message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options" + }, + metadata: { + version: 6, + message: "Generated plugin metadata is always included in the output result" + }, + sourceMapTarget: { + version: 6, + message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves." + } +}; +exports.default = _default; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/async.js b/node_modules/@babel/core/lib/gensync-utils/async.js new file mode 100644 index 0000000..7ce88d8 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/async.js @@ -0,0 +1,114 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.forwardAsync = forwardAsync; +exports.isAsync = void 0; +exports.isThenable = isThenable; +exports.maybeAsync = maybeAsync; +exports.waitFor = exports.onFirstPause = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +const runGenerator = _gensync()(function* (item) { + return yield* item; +}); + +const isAsync = _gensync()({ + sync: () => false, + errback: cb => cb(null, true) +}); + +exports.isAsync = isAsync; + +function maybeAsync(fn, message) { + return _gensync()({ + sync(...args) { + const result = fn.apply(this, args); + if (isThenable(result)) throw new Error(message); + return result; + }, + + async(...args) { + return Promise.resolve(fn.apply(this, args)); + } + + }); +} + +const withKind = _gensync()({ + sync: cb => cb("sync"), + async: function () { + var _ref = _asyncToGenerator(function* (cb) { + return cb("async"); + }); + + return function async(_x) { + return _ref.apply(this, arguments); + }; + }() +}); + +function forwardAsync(action, cb) { + const g = _gensync()(action); + + return withKind(kind => { + const adapted = g[kind]; + return cb(adapted); + }); +} + +const onFirstPause = _gensync()({ + name: "onFirstPause", + arity: 2, + sync: function (item) { + return runGenerator.sync(item); + }, + errback: function (item, firstPause, cb) { + let completed = false; + runGenerator.errback(item, (err, value) => { + completed = true; + cb(err, value); + }); + + if (!completed) { + firstPause(); + } + } +}); + +exports.onFirstPause = onFirstPause; + +const waitFor = _gensync()({ + sync: x => x, + async: function () { + var _ref2 = _asyncToGenerator(function* (x) { + return x; + }); + + return function async(_x2) { + return _ref2.apply(this, arguments); + }; + }() +}); + +exports.waitFor = waitFor; + +function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/fs.js b/node_modules/@babel/core/lib/gensync-utils/fs.js new file mode 100644 index 0000000..1d393c8 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/fs.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.stat = exports.readFile = void 0; + +function _fs() { + const data = require("fs"); + + _fs = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +const readFile = _gensync()({ + sync: _fs().readFileSync, + errback: _fs().readFile +}); + +exports.readFile = readFile; + +const stat = _gensync()({ + sync: _fs().statSync, + errback: _fs().stat +}); + +exports.stat = stat; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/functional.js b/node_modules/@babel/core/lib/gensync-utils/functional.js new file mode 100644 index 0000000..73893e0 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/functional.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.once = once; + +var _async = require("./async"); + +function once(fn) { + let result; + let resultP; + return function* () { + if (result) return result; + if (!(yield* (0, _async.isAsync)())) return result = yield* fn(); + if (resultP) return yield* (0, _async.waitFor)(resultP); + let resolve, reject; + resultP = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + + try { + result = yield* fn(); + resultP = null; + resolve(result); + return result; + } catch (error) { + reject(error); + throw error; + } + }; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/index.js b/node_modules/@babel/core/lib/index.js new file mode 100644 index 0000000..a98b8c7 --- /dev/null +++ b/node_modules/@babel/core/lib/index.js @@ -0,0 +1,268 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DEFAULT_EXTENSIONS = void 0; +Object.defineProperty(exports, "File", { + enumerable: true, + get: function () { + return _file.default; + } +}); +exports.OptionManager = void 0; +exports.Plugin = Plugin; +Object.defineProperty(exports, "buildExternalHelpers", { + enumerable: true, + get: function () { + return _buildExternalHelpers.default; + } +}); +Object.defineProperty(exports, "createConfigItem", { + enumerable: true, + get: function () { + return _config.createConfigItem; + } +}); +Object.defineProperty(exports, "createConfigItemAsync", { + enumerable: true, + get: function () { + return _config.createConfigItemAsync; + } +}); +Object.defineProperty(exports, "createConfigItemSync", { + enumerable: true, + get: function () { + return _config.createConfigItemSync; + } +}); +Object.defineProperty(exports, "getEnv", { + enumerable: true, + get: function () { + return _environment.getEnv; + } +}); +Object.defineProperty(exports, "loadOptions", { + enumerable: true, + get: function () { + return _config.loadOptions; + } +}); +Object.defineProperty(exports, "loadOptionsAsync", { + enumerable: true, + get: function () { + return _config.loadOptionsAsync; + } +}); +Object.defineProperty(exports, "loadOptionsSync", { + enumerable: true, + get: function () { + return _config.loadOptionsSync; + } +}); +Object.defineProperty(exports, "loadPartialConfig", { + enumerable: true, + get: function () { + return _config.loadPartialConfig; + } +}); +Object.defineProperty(exports, "loadPartialConfigAsync", { + enumerable: true, + get: function () { + return _config.loadPartialConfigAsync; + } +}); +Object.defineProperty(exports, "loadPartialConfigSync", { + enumerable: true, + get: function () { + return _config.loadPartialConfigSync; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.parse; + } +}); +Object.defineProperty(exports, "parseAsync", { + enumerable: true, + get: function () { + return _parse.parseAsync; + } +}); +Object.defineProperty(exports, "parseSync", { + enumerable: true, + get: function () { + return _parse.parseSync; + } +}); +Object.defineProperty(exports, "resolvePlugin", { + enumerable: true, + get: function () { + return _files.resolvePlugin; + } +}); +Object.defineProperty(exports, "resolvePreset", { + enumerable: true, + get: function () { + return _files.resolvePreset; + } +}); +Object.defineProperty((0, exports), "template", { + enumerable: true, + get: function () { + return _template().default; + } +}); +Object.defineProperty((0, exports), "tokTypes", { + enumerable: true, + get: function () { + return _parser().tokTypes; + } +}); +Object.defineProperty(exports, "transform", { + enumerable: true, + get: function () { + return _transform.transform; + } +}); +Object.defineProperty(exports, "transformAsync", { + enumerable: true, + get: function () { + return _transform.transformAsync; + } +}); +Object.defineProperty(exports, "transformFile", { + enumerable: true, + get: function () { + return _transformFile.transformFile; + } +}); +Object.defineProperty(exports, "transformFileAsync", { + enumerable: true, + get: function () { + return _transformFile.transformFileAsync; + } +}); +Object.defineProperty(exports, "transformFileSync", { + enumerable: true, + get: function () { + return _transformFile.transformFileSync; + } +}); +Object.defineProperty(exports, "transformFromAst", { + enumerable: true, + get: function () { + return _transformAst.transformFromAst; + } +}); +Object.defineProperty(exports, "transformFromAstAsync", { + enumerable: true, + get: function () { + return _transformAst.transformFromAstAsync; + } +}); +Object.defineProperty(exports, "transformFromAstSync", { + enumerable: true, + get: function () { + return _transformAst.transformFromAstSync; + } +}); +Object.defineProperty(exports, "transformSync", { + enumerable: true, + get: function () { + return _transform.transformSync; + } +}); +Object.defineProperty((0, exports), "traverse", { + enumerable: true, + get: function () { + return _traverse().default; + } +}); +exports.version = exports.types = void 0; + +var _file = require("./transformation/file/file"); + +var _buildExternalHelpers = require("./tools/build-external-helpers"); + +var _files = require("./config/files"); + +var _environment = require("./config/helpers/environment"); + +function _types() { + const data = require("@babel/types"); + + _types = function () { + return data; + }; + + return data; +} + +Object.defineProperty((0, exports), "types", { + enumerable: true, + get: function () { + return _types(); + } +}); + +function _parser() { + const data = require("@babel/parser"); + + _parser = function () { + return data; + }; + + return data; +} + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +function _template() { + const data = require("@babel/template"); + + _template = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transform = require("./transform"); + +var _transformFile = require("./transform-file"); + +var _transformAst = require("./transform-ast"); + +var _parse = require("./parse"); + +const version = "7.18.13"; +exports.version = version; +const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]); +exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS; + +class OptionManager { + init(opts) { + return (0, _config.loadOptionsSync)(opts); + } + +} + +exports.OptionManager = OptionManager; + +function Plugin(alias) { + throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`); +} + +0 && (exports.types = exports.traverse = exports.tokTypes = exports.template = 0); \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parse.js b/node_modules/@babel/core/lib/parse.js new file mode 100644 index 0000000..feb8515 --- /dev/null +++ b/node_modules/@babel/core/lib/parse.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseSync = exports.parseAsync = exports.parse = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _parser = require("./parser"); + +var _normalizeOpts = require("./transformation/normalize-opts"); + +const parseRunner = _gensync()(function* parse(code, opts) { + const config = yield* (0, _config.default)(opts); + + if (config === null) { + return null; + } + + return yield* (0, _parser.default)(config.passes, (0, _normalizeOpts.default)(config), code); +}); + +const parse = function parse(code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } + + if (callback === undefined) { + { + return parseRunner.sync(code, opts); + } + } + + parseRunner.errback(code, opts, callback); +}; + +exports.parse = parse; +const parseSync = parseRunner.sync; +exports.parseSync = parseSync; +const parseAsync = parseRunner.async; +exports.parseAsync = parseAsync; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parser/index.js b/node_modules/@babel/core/lib/parser/index.js new file mode 100644 index 0000000..29fca4a --- /dev/null +++ b/node_modules/@babel/core/lib/parser/index.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parser; + +function _parser() { + const data = require("@babel/parser"); + + _parser = function () { + return data; + }; + + return data; +} + +function _codeFrame() { + const data = require("@babel/code-frame"); + + _codeFrame = function () { + return data; + }; + + return data; +} + +var _missingPluginHelper = require("./util/missing-plugin-helper"); + +function* parser(pluginPasses, { + parserOpts, + highlightCode = true, + filename = "unknown" +}, code) { + try { + const results = []; + + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + parserOverride + } = plugin; + + if (parserOverride) { + const ast = parserOverride(code, parserOpts, _parser().parse); + if (ast !== undefined) results.push(ast); + } + } + } + + if (results.length === 0) { + return (0, _parser().parse)(code, parserOpts); + } else if (results.length === 1) { + yield* []; + + if (typeof results[0].then === "function") { + throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + + return results[0]; + } + + throw new Error("More than one plugin attempted to override parsing."); + } catch (err) { + if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { + err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; + } + + const { + loc, + missingPlugin + } = err; + + if (loc) { + const codeFrame = (0, _codeFrame().codeFrameColumns)(code, { + start: { + line: loc.line, + column: loc.column + 1 + } + }, { + highlightCode + }); + + if (missingPlugin) { + err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame); + } else { + err.message = `${filename}: ${err.message}\n\n` + codeFrame; + } + + err.code = "BABEL_PARSE_ERROR"; + } + + throw err; + } +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js new file mode 100644 index 0000000..740ff22 --- /dev/null +++ b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js @@ -0,0 +1,325 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateMissingPluginMessage; +const pluginNameMap = { + asyncDoExpressions: { + syntax: { + name: "@babel/plugin-syntax-async-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions" + } + }, + classProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-proposal-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-class-properties" + } + }, + classPrivateProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-proposal-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-class-properties" + } + }, + classPrivateMethods: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-proposal-private-methods", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-private-methods" + } + }, + classStaticBlock: { + syntax: { + name: "@babel/plugin-syntax-class-static-block", + url: "https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-syntax-class-static-block" + }, + transform: { + name: "@babel/plugin-proposal-class-static-block", + url: "https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-proposal-class-static-block" + } + }, + decimal: { + syntax: { + name: "@babel/plugin-syntax-decimal", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal" + } + }, + decorators: { + syntax: { + name: "@babel/plugin-syntax-decorators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators" + }, + transform: { + name: "@babel/plugin-proposal-decorators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators" + } + }, + doExpressions: { + syntax: { + name: "@babel/plugin-syntax-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions" + }, + transform: { + name: "@babel/plugin-proposal-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions" + } + }, + dynamicImport: { + syntax: { + name: "@babel/plugin-syntax-dynamic-import", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-dynamic-import" + } + }, + exportDefaultFrom: { + syntax: { + name: "@babel/plugin-syntax-export-default-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from" + }, + transform: { + name: "@babel/plugin-proposal-export-default-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from" + } + }, + exportNamespaceFrom: { + syntax: { + name: "@babel/plugin-syntax-export-namespace-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-namespace-from" + }, + transform: { + name: "@babel/plugin-proposal-export-namespace-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-namespace-from" + } + }, + flow: { + syntax: { + name: "@babel/plugin-syntax-flow", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow" + }, + transform: { + name: "@babel/preset-flow", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-flow" + } + }, + functionBind: { + syntax: { + name: "@babel/plugin-syntax-function-bind", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind" + }, + transform: { + name: "@babel/plugin-proposal-function-bind", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind" + } + }, + functionSent: { + syntax: { + name: "@babel/plugin-syntax-function-sent", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent" + }, + transform: { + name: "@babel/plugin-proposal-function-sent", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent" + } + }, + importMeta: { + syntax: { + name: "@babel/plugin-syntax-import-meta", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-meta" + } + }, + jsx: { + syntax: { + name: "@babel/plugin-syntax-jsx", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx" + }, + transform: { + name: "@babel/preset-react", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-react" + } + }, + importAssertions: { + syntax: { + name: "@babel/plugin-syntax-import-assertions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions" + } + }, + moduleStringNames: { + syntax: { + name: "@babel/plugin-syntax-module-string-names", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-module-string-names" + } + }, + numericSeparator: { + syntax: { + name: "@babel/plugin-syntax-numeric-separator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-numeric-separator" + }, + transform: { + name: "@babel/plugin-proposal-numeric-separator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-numeric-separator" + } + }, + optionalChaining: { + syntax: { + name: "@babel/plugin-syntax-optional-chaining", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-chaining" + }, + transform: { + name: "@babel/plugin-proposal-optional-chaining", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-optional-chaining" + } + }, + pipelineOperator: { + syntax: { + name: "@babel/plugin-syntax-pipeline-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator" + }, + transform: { + name: "@babel/plugin-proposal-pipeline-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator" + } + }, + privateIn: { + syntax: { + name: "@babel/plugin-syntax-private-property-in-object", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-private-property-in-object" + }, + transform: { + name: "@babel/plugin-proposal-private-property-in-object", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-private-property-in-object" + } + }, + recordAndTuple: { + syntax: { + name: "@babel/plugin-syntax-record-and-tuple", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple" + } + }, + regexpUnicodeSets: { + syntax: { + name: "@babel/plugin-syntax-unicode-sets-regex", + url: "https://github.com/babel/babel/blob/main/packages/babel-plugin-syntax-unicode-sets-regex/README.md" + }, + transform: { + name: "@babel/plugin-proposal-unicode-sets-regex", + url: "https://github.com/babel/babel/blob/main/packages/babel-plugin-proposalunicode-sets-regex/README.md" + } + }, + throwExpressions: { + syntax: { + name: "@babel/plugin-syntax-throw-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions" + }, + transform: { + name: "@babel/plugin-proposal-throw-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions" + } + }, + typescript: { + syntax: { + name: "@babel/plugin-syntax-typescript", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript" + }, + transform: { + name: "@babel/preset-typescript", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-typescript" + } + }, + asyncGenerators: { + syntax: { + name: "@babel/plugin-syntax-async-generators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-generators" + }, + transform: { + name: "@babel/plugin-proposal-async-generator-functions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-async-generator-functions" + } + }, + logicalAssignment: { + syntax: { + name: "@babel/plugin-syntax-logical-assignment-operators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-logical-assignment-operators" + }, + transform: { + name: "@babel/plugin-proposal-logical-assignment-operators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-logical-assignment-operators" + } + }, + nullishCoalescingOperator: { + syntax: { + name: "@babel/plugin-syntax-nullish-coalescing-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-nullish-coalescing-operator" + }, + transform: { + name: "@babel/plugin-proposal-nullish-coalescing-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-nullish-coalescing-opearator" + } + }, + objectRestSpread: { + syntax: { + name: "@babel/plugin-syntax-object-rest-spread", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-object-rest-spread" + }, + transform: { + name: "@babel/plugin-proposal-object-rest-spread", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-object-rest-spread" + } + }, + optionalCatchBinding: { + syntax: { + name: "@babel/plugin-syntax-optional-catch-binding", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-catch-binding" + }, + transform: { + name: "@babel/plugin-proposal-optional-catch-binding", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-optional-catch-binding" + } + } +}; +pluginNameMap.privateIn.syntax = pluginNameMap.privateIn.transform; + +const getNameURLCombination = ({ + name, + url +}) => `${name} (${url})`; + +function generateMissingPluginMessage(missingPluginName, loc, codeFrame) { + let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame; + const pluginInfo = pluginNameMap[missingPluginName]; + + if (pluginInfo) { + const { + syntax: syntaxPlugin, + transform: transformPlugin + } = pluginInfo; + + if (syntaxPlugin) { + const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); + + if (transformPlugin) { + const transformPluginInfo = getNameURLCombination(transformPlugin); + const sectionType = transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets"; + helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation. +If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`; + } else { + helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`; + } + } + } + + return helpMessage; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/tools/build-external-helpers.js b/node_modules/@babel/core/lib/tools/build-external-helpers.js new file mode 100644 index 0000000..cdd7214 --- /dev/null +++ b/node_modules/@babel/core/lib/tools/build-external-helpers.js @@ -0,0 +1,166 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +function helpers() { + const data = require("@babel/helpers"); + + helpers = function () { + return data; + }; + + return data; +} + +function _generator() { + const data = require("@babel/generator"); + + _generator = function () { + return data; + }; + + return data; +} + +function _template() { + const data = require("@babel/template"); + + _template = function () { + return data; + }; + + return data; +} + +function _t() { + const data = require("@babel/types"); + + _t = function () { + return data; + }; + + return data; +} + +var _file = require("../transformation/file/file"); + +const { + arrayExpression, + assignmentExpression, + binaryExpression, + blockStatement, + callExpression, + cloneNode, + conditionalExpression, + exportNamedDeclaration, + exportSpecifier, + expressionStatement, + functionExpression, + identifier, + memberExpression, + objectExpression, + program, + stringLiteral, + unaryExpression, + variableDeclaration, + variableDeclarator +} = _t(); + +const buildUmdWrapper = replacements => _template().default.statement` + (function (root, factory) { + if (typeof define === "function" && define.amd) { + define(AMD_ARGUMENTS, factory); + } else if (typeof exports === "object") { + factory(COMMON_ARGUMENTS); + } else { + factory(BROWSER_ARGUMENTS); + } + })(UMD_ROOT, function (FACTORY_PARAMETERS) { + FACTORY_BODY + }); + `(replacements); + +function buildGlobal(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + const container = functionExpression(null, [identifier("global")], blockStatement(body)); + const tree = program([expressionStatement(callExpression(container, [conditionalExpression(binaryExpression("===", unaryExpression("typeof", identifier("global")), stringLiteral("undefined")), identifier("self"), identifier("global"))]))]); + body.push(variableDeclaration("var", [variableDeclarator(namespace, assignmentExpression("=", memberExpression(identifier("global"), namespace), objectExpression([])))])); + buildHelpers(body, namespace, allowlist); + return tree; +} + +function buildModule(allowlist) { + const body = []; + const refs = buildHelpers(body, null, allowlist); + body.unshift(exportNamedDeclaration(null, Object.keys(refs).map(name => { + return exportSpecifier(cloneNode(refs[name]), identifier(name)); + }))); + return program(body, [], "module"); +} + +function buildUmd(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + body.push(variableDeclaration("var", [variableDeclarator(namespace, identifier("global"))])); + buildHelpers(body, namespace, allowlist); + return program([buildUmdWrapper({ + FACTORY_PARAMETERS: identifier("global"), + BROWSER_ARGUMENTS: assignmentExpression("=", memberExpression(identifier("root"), namespace), objectExpression([])), + COMMON_ARGUMENTS: identifier("exports"), + AMD_ARGUMENTS: arrayExpression([stringLiteral("exports")]), + FACTORY_BODY: body, + UMD_ROOT: identifier("this") + })]); +} + +function buildVar(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + body.push(variableDeclaration("var", [variableDeclarator(namespace, objectExpression([]))])); + const tree = program(body); + buildHelpers(body, namespace, allowlist); + body.push(expressionStatement(namespace)); + return tree; +} + +function buildHelpers(body, namespace, allowlist) { + const getHelperReference = name => { + return namespace ? memberExpression(namespace, identifier(name)) : identifier(`_${name}`); + }; + + const refs = {}; + helpers().list.forEach(function (name) { + if (allowlist && allowlist.indexOf(name) < 0) return; + const ref = refs[name] = getHelperReference(name); + helpers().ensure(name, _file.default); + const { + nodes + } = helpers().get(name, getHelperReference, ref); + body.push(...nodes); + }); + return refs; +} + +function _default(allowlist, outputType = "global") { + let tree; + const build = { + global: buildGlobal, + module: buildModule, + umd: buildUmd, + var: buildVar + }[outputType]; + + if (build) { + tree = build(allowlist); + } else { + throw new Error(`Unsupported output type ${outputType}`); + } + + return (0, _generator().default)(tree).code; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-ast.js b/node_modules/@babel/core/lib/transform-ast.js new file mode 100644 index 0000000..bc88af4 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-ast.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFromAstSync = exports.transformFromAstAsync = exports.transformFromAst = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transformation = require("./transformation"); + +const transformFromAstRunner = _gensync()(function* (ast, code, opts) { + const config = yield* (0, _config.default)(opts); + if (config === null) return null; + if (!ast) throw new Error("No AST given"); + return yield* (0, _transformation.run)(config, code, ast); +}); + +const transformFromAst = function transformFromAst(ast, code, optsOrCallback, maybeCallback) { + let opts; + let callback; + + if (typeof optsOrCallback === "function") { + callback = optsOrCallback; + opts = undefined; + } else { + opts = optsOrCallback; + callback = maybeCallback; + } + + if (callback === undefined) { + { + return transformFromAstRunner.sync(ast, code, opts); + } + } + + transformFromAstRunner.errback(ast, code, opts, callback); +}; + +exports.transformFromAst = transformFromAst; +const transformFromAstSync = transformFromAstRunner.sync; +exports.transformFromAstSync = transformFromAstSync; +const transformFromAstAsync = transformFromAstRunner.async; +exports.transformFromAstAsync = transformFromAstAsync; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-file-browser.js b/node_modules/@babel/core/lib/transform-file-browser.js new file mode 100644 index 0000000..5912b5c --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file-browser.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFile = void 0; +exports.transformFileAsync = transformFileAsync; +exports.transformFileSync = transformFileSync; + +const transformFile = function transformFile(filename, opts, callback) { + if (typeof opts === "function") { + callback = opts; + } + + callback(new Error("Transforming files is not supported in browsers"), null); +}; + +exports.transformFile = transformFile; + +function transformFileSync() { + throw new Error("Transforming files is not supported in browsers"); +} + +function transformFileAsync() { + return Promise.reject(new Error("Transforming files is not supported in browsers")); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-file.js b/node_modules/@babel/core/lib/transform-file.js new file mode 100644 index 0000000..ab99202 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFileSync = exports.transformFileAsync = exports.transformFile = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transformation = require("./transformation"); + +var fs = require("./gensync-utils/fs"); + +({}); + +const transformFileRunner = _gensync()(function* (filename, opts) { + const options = Object.assign({}, opts, { + filename + }); + const config = yield* (0, _config.default)(options); + if (config === null) return null; + const code = yield* fs.readFile(filename, "utf8"); + return yield* (0, _transformation.run)(config, code); +}); + +const transformFile = transformFileRunner.errback; +exports.transformFile = transformFile; +const transformFileSync = transformFileRunner.sync; +exports.transformFileSync = transformFileSync; +const transformFileAsync = transformFileRunner.async; +exports.transformFileAsync = transformFileAsync; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform.js b/node_modules/@babel/core/lib/transform.js new file mode 100644 index 0000000..7cc33b3 --- /dev/null +++ b/node_modules/@babel/core/lib/transform.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformSync = exports.transformAsync = exports.transform = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transformation = require("./transformation"); + +const transformRunner = _gensync()(function* transform(code, opts) { + const config = yield* (0, _config.default)(opts); + if (config === null) return null; + return yield* (0, _transformation.run)(config, code); +}); + +const transform = function transform(code, optsOrCallback, maybeCallback) { + let opts; + let callback; + + if (typeof optsOrCallback === "function") { + callback = optsOrCallback; + opts = undefined; + } else { + opts = optsOrCallback; + callback = maybeCallback; + } + + if (callback === undefined) { + { + return transformRunner.sync(code, opts); + } + } + + transformRunner.errback(code, opts, callback); +}; + +exports.transform = transform; +const transformSync = transformRunner.sync; +exports.transformSync = transformSync; +const transformAsync = transformRunner.async; +exports.transformAsync = transformAsync; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js new file mode 100644 index 0000000..cc20fe4 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js @@ -0,0 +1,95 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadBlockHoistPlugin; + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +var _plugin = require("../config/plugin"); + +let LOADED_PLUGIN; + +function loadBlockHoistPlugin() { + if (!LOADED_PLUGIN) { + LOADED_PLUGIN = new _plugin.default(Object.assign({}, blockHoistPlugin, { + visitor: _traverse().default.explode(blockHoistPlugin.visitor) + }), {}); + } + + return LOADED_PLUGIN; +} + +function priority(bodyNode) { + const priority = bodyNode == null ? void 0 : bodyNode._blockHoist; + if (priority == null) return 1; + if (priority === true) return 2; + return priority; +} + +function stableSort(body) { + const buckets = Object.create(null); + + for (let i = 0; i < body.length; i++) { + const n = body[i]; + const p = priority(n); + const bucket = buckets[p] || (buckets[p] = []); + bucket.push(n); + } + + const keys = Object.keys(buckets).map(k => +k).sort((a, b) => b - a); + let index = 0; + + for (const key of keys) { + const bucket = buckets[key]; + + for (const n of bucket) { + body[index++] = n; + } + } + + return body; +} + +const blockHoistPlugin = { + name: "internal.blockHoist", + visitor: { + Block: { + exit({ + node + }) { + const { + body + } = node; + let max = Math.pow(2, 30) - 1; + let hasChange = false; + + for (let i = 0; i < body.length; i++) { + const n = body[i]; + const p = priority(n); + + if (p > max) { + hasChange = true; + break; + } + + max = p; + } + + if (!hasChange) return; + node.body = stableSort(body.slice()); + } + + } + } +}; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/file.js b/node_modules/@babel/core/lib/transformation/file/file.js new file mode 100644 index 0000000..22ee007 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/file.js @@ -0,0 +1,255 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function helpers() { + const data = require("@babel/helpers"); + + helpers = function () { + return data; + }; + + return data; +} + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +function _codeFrame() { + const data = require("@babel/code-frame"); + + _codeFrame = function () { + return data; + }; + + return data; +} + +function _t() { + const data = require("@babel/types"); + + _t = function () { + return data; + }; + + return data; +} + +function _helperModuleTransforms() { + const data = require("@babel/helper-module-transforms"); + + _helperModuleTransforms = function () { + return data; + }; + + return data; +} + +function _semver() { + const data = require("semver"); + + _semver = function () { + return data; + }; + + return data; +} + +const { + cloneNode, + interpreterDirective +} = _t(); + +const errorVisitor = { + enter(path, state) { + const loc = path.node.loc; + + if (loc) { + state.loc = loc; + path.stop(); + } + } + +}; + +class File { + constructor(options, { + code, + ast, + inputMap + }) { + this._map = new Map(); + this.opts = void 0; + this.declarations = {}; + this.path = void 0; + this.ast = void 0; + this.scope = void 0; + this.metadata = {}; + this.code = ""; + this.inputMap = void 0; + this.hub = { + file: this, + getCode: () => this.code, + getScope: () => this.scope, + addHelper: this.addHelper.bind(this), + buildError: this.buildCodeFrameError.bind(this) + }; + this.opts = options; + this.code = code; + this.ast = ast; + this.inputMap = inputMap; + this.path = _traverse().NodePath.get({ + hub: this.hub, + parentPath: null, + parent: this.ast, + container: this.ast, + key: "program" + }).setContext(); + this.scope = this.path.scope; + } + + get shebang() { + const { + interpreter + } = this.path.node; + return interpreter ? interpreter.value : ""; + } + + set shebang(value) { + if (value) { + this.path.get("interpreter").replaceWith(interpreterDirective(value)); + } else { + this.path.get("interpreter").remove(); + } + } + + set(key, val) { + if (key === "helpersNamespace") { + throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'."); + } + + this._map.set(key, val); + } + + get(key) { + return this._map.get(key); + } + + has(key) { + return this._map.has(key); + } + + getModuleName() { + return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts); + } + + addImport() { + throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'."); + } + + availableHelper(name, versionRange) { + let minVersion; + + try { + minVersion = helpers().minVersion(name); + } catch (err) { + if (err.code !== "BABEL_HELPER_UNKNOWN") throw err; + return false; + } + + if (typeof versionRange !== "string") return true; + if (_semver().valid(versionRange)) versionRange = `^${versionRange}`; + return !_semver().intersects(`<${minVersion}`, versionRange) && !_semver().intersects(`>=8.0.0`, versionRange); + } + + addHelper(name) { + const declar = this.declarations[name]; + if (declar) return cloneNode(declar); + const generator = this.get("helperGenerator"); + + if (generator) { + const res = generator(name); + if (res) return res; + } + + helpers().ensure(name, File); + const uid = this.declarations[name] = this.scope.generateUidIdentifier(name); + const dependencies = {}; + + for (const dep of helpers().getDependencies(name)) { + dependencies[dep] = this.addHelper(dep); + } + + const { + nodes, + globals + } = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings())); + globals.forEach(name => { + if (this.path.scope.hasBinding(name, true)) { + this.path.scope.rename(name); + } + }); + nodes.forEach(node => { + node._compact = true; + }); + this.path.unshiftContainer("body", nodes); + this.path.get("body").forEach(path => { + if (nodes.indexOf(path.node) === -1) return; + if (path.isVariableDeclaration()) this.scope.registerDeclaration(path); + }); + return uid; + } + + addTemplateObject() { + throw new Error("This function has been moved into the template literal transform itself."); + } + + buildCodeFrameError(node, msg, _Error = SyntaxError) { + let loc = node && (node.loc || node._loc); + + if (!loc && node) { + const state = { + loc: null + }; + (0, _traverse().default)(node, errorVisitor, this.scope, state); + loc = state.loc; + let txt = "This is an error on an internal node. Probably an internal error."; + if (loc) txt += " Location has been estimated."; + msg += ` (${txt})`; + } + + if (loc) { + const { + highlightCode = true + } = this.opts; + msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, { + start: { + line: loc.start.line, + column: loc.start.column + 1 + }, + end: loc.end && loc.start.line === loc.end.line ? { + line: loc.end.line, + column: loc.end.column + 1 + } : undefined + }, { + highlightCode + }); + } + + return new _Error(msg); + } + +} + +exports.default = File; +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/generate.js b/node_modules/@babel/core/lib/transformation/file/generate.js new file mode 100644 index 0000000..9e30d97 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/generate.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateCode; + +function _convertSourceMap() { + const data = require("convert-source-map"); + + _convertSourceMap = function () { + return data; + }; + + return data; +} + +function _generator() { + const data = require("@babel/generator"); + + _generator = function () { + return data; + }; + + return data; +} + +var _mergeMap = require("./merge-map"); + +function generateCode(pluginPasses, file) { + const { + opts, + ast, + code, + inputMap + } = file; + const { + generatorOpts + } = opts; + const results = []; + + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + generatorOverride + } = plugin; + + if (generatorOverride) { + const result = generatorOverride(ast, generatorOpts, code, _generator().default); + if (result !== undefined) results.push(result); + } + } + } + + let result; + + if (results.length === 0) { + result = (0, _generator().default)(ast, generatorOpts, code); + } else if (results.length === 1) { + result = results[0]; + + if (typeof result.then === "function") { + throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); + } + } else { + throw new Error("More than one plugin attempted to override codegen."); + } + + let { + code: outputCode, + decodedMap: outputMap = result.map + } = result; + + if (outputMap) { + if (inputMap) { + outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap, generatorOpts.sourceFileName); + } else { + outputMap = result.map; + } + } + + if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { + outputCode += "\n" + _convertSourceMap().fromObject(outputMap).toComment(); + } + + if (opts.sourceMaps === "inline") { + outputMap = null; + } + + return { + outputCode, + outputMap + }; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/merge-map.js b/node_modules/@babel/core/lib/transformation/file/merge-map.js new file mode 100644 index 0000000..9a03119 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/merge-map.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mergeSourceMap; + +function _remapping() { + const data = require("@ampproject/remapping"); + + _remapping = function () { + return data; + }; + + return data; +} + +function mergeSourceMap(inputMap, map, sourceFileName) { + const source = sourceFileName.replace(/\\/g, "/"); + let found = false; + + const result = _remapping()(rootless(map), (s, ctx) => { + if (s === source && !found) { + found = true; + ctx.source = ""; + return rootless(inputMap); + } + + return null; + }); + + if (typeof inputMap.sourceRoot === "string") { + result.sourceRoot = inputMap.sourceRoot; + } + + return Object.assign({}, result); +} + +function rootless(map) { + return Object.assign({}, map, { + sourceRoot: null + }); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/index.js b/node_modules/@babel/core/lib/transformation/index.js new file mode 100644 index 0000000..1b78101 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/index.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = run; + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +var _pluginPass = require("./plugin-pass"); + +var _blockHoistPlugin = require("./block-hoist-plugin"); + +var _normalizeOpts = require("./normalize-opts"); + +var _normalizeFile = require("./normalize-file"); + +var _generate = require("./file/generate"); + +var _deepArray = require("../config/helpers/deep-array"); + +function* run(config, code, ast) { + const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); + const opts = file.opts; + + try { + yield* transformFile(file, config.passes); + } catch (e) { + var _opts$filename; + + e.message = `${(_opts$filename = opts.filename) != null ? _opts$filename : "unknown"}: ${e.message}`; + + if (!e.code) { + e.code = "BABEL_TRANSFORM_ERROR"; + } + + throw e; + } + + let outputCode, outputMap; + + try { + if (opts.code !== false) { + ({ + outputCode, + outputMap + } = (0, _generate.default)(config.passes, file)); + } + } catch (e) { + var _opts$filename2; + + e.message = `${(_opts$filename2 = opts.filename) != null ? _opts$filename2 : "unknown"}: ${e.message}`; + + if (!e.code) { + e.code = "BABEL_GENERATE_ERROR"; + } + + throw e; + } + + return { + metadata: file.metadata, + options: opts, + ast: opts.ast === true ? file.ast : null, + code: outputCode === undefined ? null : outputCode, + map: outputMap === undefined ? null : outputMap, + sourceType: file.ast.program.sourceType, + externalDependencies: (0, _deepArray.flattenToSet)(config.externalDependencies) + }; +} + +function* transformFile(file, pluginPasses) { + for (const pluginPairs of pluginPasses) { + const passPairs = []; + const passes = []; + const visitors = []; + + for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) { + const pass = new _pluginPass.default(file, plugin.key, plugin.options); + passPairs.push([plugin, pass]); + passes.push(pass); + visitors.push(plugin.visitor); + } + + for (const [plugin, pass] of passPairs) { + const fn = plugin.pre; + + if (fn) { + const result = fn.call(pass, file); + yield* []; + + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + + const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); + + (0, _traverse().default)(file.ast, visitor, file.scope); + + for (const [plugin, pass] of passPairs) { + const fn = plugin.post; + + if (fn) { + const result = fn.call(pass, file); + yield* []; + + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + } +} + +function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/normalize-file.js b/node_modules/@babel/core/lib/transformation/normalize-file.js new file mode 100644 index 0000000..0dba12d --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-file.js @@ -0,0 +1,169 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeFile; + +function _fs() { + const data = require("fs"); + + _fs = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +function _t() { + const data = require("@babel/types"); + + _t = function () { + return data; + }; + + return data; +} + +function _convertSourceMap() { + const data = require("convert-source-map"); + + _convertSourceMap = function () { + return data; + }; + + return data; +} + +var _file = require("./file/file"); + +var _parser = require("../parser"); + +var _cloneDeep = require("./util/clone-deep"); + +const { + file, + traverseFast +} = _t(); + +const debug = _debug()("babel:transform:file"); + +const LARGE_INPUT_SOURCEMAP_THRESHOLD = 3000000; + +function* normalizeFile(pluginPasses, options, code, ast) { + code = `${code || ""}`; + + if (ast) { + if (ast.type === "Program") { + ast = file(ast, [], []); + } else if (ast.type !== "File") { + throw new Error("AST root must be a Program or File node"); + } + + if (options.cloneInputAst) { + ast = (0, _cloneDeep.default)(ast); + } + } else { + ast = yield* (0, _parser.default)(pluginPasses, options, code); + } + + let inputMap = null; + + if (options.inputSourceMap !== false) { + if (typeof options.inputSourceMap === "object") { + inputMap = _convertSourceMap().fromObject(options.inputSourceMap); + } + + if (!inputMap) { + const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast); + + if (lastComment) { + try { + inputMap = _convertSourceMap().fromComment(lastComment); + } catch (err) { + debug("discarding unknown inline input sourcemap", err); + } + } + } + + if (!inputMap) { + const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast); + + if (typeof options.filename === "string" && lastComment) { + try { + const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment); + + const inputMapContent = _fs().readFileSync(_path().resolve(_path().dirname(options.filename), match[1])); + + if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) { + debug("skip merging input map > 1 MB"); + } else { + inputMap = _convertSourceMap().fromJSON(inputMapContent); + } + } catch (err) { + debug("discarding unknown file input sourcemap", err); + } + } else if (lastComment) { + debug("discarding un-loadable file input sourcemap"); + } + } + } + + return new _file.default(options, { + code, + ast: ast, + inputMap + }); +} + +const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/; +const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/; + +function extractCommentsFromList(regex, comments, lastComment) { + if (comments) { + comments = comments.filter(({ + value + }) => { + if (regex.test(value)) { + lastComment = value; + return false; + } + + return true; + }); + } + + return [comments, lastComment]; +} + +function extractComments(regex, ast) { + let lastComment = null; + traverseFast(ast, node => { + [node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment); + [node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment); + [node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment); + }); + return lastComment; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/normalize-opts.js b/node_modules/@babel/core/lib/transformation/normalize-opts.js new file mode 100644 index 0000000..7773d63 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-opts.js @@ -0,0 +1,64 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeOptions; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function normalizeOptions(config) { + const { + filename, + cwd, + filenameRelative = typeof filename === "string" ? _path().relative(cwd, filename) : "unknown", + sourceType = "module", + inputSourceMap, + sourceMaps = !!inputSourceMap, + sourceRoot = config.options.moduleRoot, + sourceFileName = _path().basename(filenameRelative), + comments = true, + compact = "auto" + } = config.options; + const opts = config.options; + const options = Object.assign({}, opts, { + parserOpts: Object.assign({ + sourceType: _path().extname(filenameRelative) === ".mjs" ? "module" : sourceType, + sourceFileName: filename, + plugins: [] + }, opts.parserOpts), + generatorOpts: Object.assign({ + filename, + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + retainLines: opts.retainLines, + comments, + shouldPrintComment: opts.shouldPrintComment, + compact, + minified: opts.minified, + sourceMaps, + sourceRoot, + sourceFileName + }, opts.generatorOpts) + }); + + for (const plugins of config.passes) { + for (const plugin of plugins) { + if (plugin.manipulateOptions) { + plugin.manipulateOptions(options, options.parserOpts); + } + } + } + + return options; +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/plugin-pass.js b/node_modules/@babel/core/lib/transformation/plugin-pass.js new file mode 100644 index 0000000..87cfc7f --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/plugin-pass.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +class PluginPass { + constructor(file, key, options) { + this._map = new Map(); + this.key = void 0; + this.file = void 0; + this.opts = void 0; + this.cwd = void 0; + this.filename = void 0; + this.key = key; + this.file = file; + this.opts = options || {}; + this.cwd = file.opts.cwd; + this.filename = file.opts.filename; + } + + set(key, val) { + this._map.set(key, val); + } + + get(key) { + return this._map.get(key); + } + + availableHelper(name, versionRange) { + return this.file.availableHelper(name, versionRange); + } + + addHelper(name) { + return this.file.addHelper(name); + } + + addImport() { + return this.file.addImport(); + } + + buildCodeFrameError(node, msg, _Error) { + return this.file.buildCodeFrameError(node, msg, _Error); + } + +} + +exports.default = PluginPass; +{ + PluginPass.prototype.getModuleName = function getModuleName() { + return this.file.getModuleName(); + }; +} +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/util/clone-deep.js b/node_modules/@babel/core/lib/transformation/util/clone-deep.js new file mode 100644 index 0000000..d32505d --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/util/clone-deep.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +function deepClone(value, cache) { + if (value !== null) { + if (cache.has(value)) return cache.get(value); + let cloned; + + if (Array.isArray(value)) { + cloned = new Array(value.length); + + for (let i = 0; i < value.length; i++) { + cloned[i] = typeof value[i] !== "object" ? value[i] : deepClone(value[i], cache); + } + } else { + cloned = {}; + const keys = Object.keys(value); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + cloned[key] = typeof value[key] !== "object" ? value[key] : deepClone(value[key], cache); + } + } + + cache.set(value, cloned); + return cloned; + } + + return value; +} + +function _default(value) { + if (typeof value !== "object") return value; + return deepClone(value, new Map()); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/lib/vendor/import-meta-resolve.js b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js new file mode 100644 index 0000000..274596b --- /dev/null +++ b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js @@ -0,0 +1,3557 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.moduleResolve = moduleResolve; +exports.resolve = resolve; + +function _url() { + const data = require("url"); + + _url = function () { + return data; + }; + + return data; +} + +function _fs() { + const data = _interopRequireWildcard(require("fs"), true); + + _fs = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _assert() { + const data = require("assert"); + + _assert = function () { + return data; + }; + + return data; +} + +function _util() { + const data = require("util"); + + _util = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var re$3 = { + exports: {} +}; +const SEMVER_SPEC_VERSION = '2.0.0'; +const MAX_LENGTH$2 = 256; +const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || 9007199254740991; +const MAX_SAFE_COMPONENT_LENGTH = 16; +var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH +}; +const debug$1 = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; +var debug_1 = debug$1; + +(function (module, exports) { + const { + MAX_SAFE_COMPONENT_LENGTH + } = constants; + const debug = debug_1; + exports = module.exports = {}; + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(name, index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`); + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`); + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + createToken('GTLT', '((?:<|>)?=?)'); + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`); + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`); + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + createToken('LONETILDE', '(?:~>?)'); + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken('LONECARET', '(?:\\^)'); + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`); + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); + createToken('STAR', '(<|>)?=?\\s*\\*'); + createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$'); +})(re$3, re$3.exports); + +const opts = ['includePrerelease', 'loose', 'rtl']; + +const parseOptions$2 = options => !options ? {} : typeof options !== 'object' ? { + loose: true +} : opts.filter(k => options[k]).reduce((o, k) => { + o[k] = true; + return o; +}, {}); + +var parseOptions_1 = parseOptions$2; +const numeric = /^[0-9]+$/; + +const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; +}; + +const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + +var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers +}; +const debug = debug_1; +const { + MAX_LENGTH: MAX_LENGTH$1, + MAX_SAFE_INTEGER +} = constants; +const { + re: re$2, + t: t$2 +} = re$3.exports; +const parseOptions$1 = parseOptions_1; +const { + compareIdentifiers +} = identifiers; + +class SemVer$c { + constructor(version, options) { + options = parseOptions$1(options); + + if (version instanceof SemVer$c) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`); + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`); + } + + debug('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m = version.trim().match(options.loose ? re$2[t$2.LOOSE] : re$2[t$2.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`); + } + + this.raw = version; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version'); + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version'); + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version'); + } + + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map(id => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + + return id; + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; + } + + return this.version; + } + + toString() { + return this.version; + } + + compare(other) { + debug('SemVer.compare', this.version, this.options, other); + + if (!(other instanceof SemVer$c)) { + if (typeof other === 'string' && other === this.version) { + return 0; + } + + other = new SemVer$c(other, this.options); + } + + if (other.version === this.version) { + return 0; + } + + return this.compareMain(other) || this.comparePre(other); + } + + compareMain(other) { + if (!(other instanceof SemVer$c)) { + other = new SemVer$c(other, this.options); + } + + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + } + + comparePre(other) { + if (!(other instanceof SemVer$c)) { + other = new SemVer$c(other, this.options); + } + + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + + let i = 0; + + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + + compareBuild(other) { + if (!(other instanceof SemVer$c)) { + other = new SemVer$c(other, this.options); + } + + let i = 0; + + do { + const a = this.build[i]; + const b = other.build[i]; + debug('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + + inc(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + + this.inc('pre', identifier); + break; + + case 'major': + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + + case 'minor': + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + + this.patch = 0; + this.prerelease = []; + break; + + case 'patch': + if (this.prerelease.length === 0) { + this.patch++; + } + + this.prerelease = []; + break; + + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) { + this.prerelease.push(0); + } + } + + if (identifier) { + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + + break; + + default: + throw new Error(`invalid increment argument: ${release}`); + } + + this.format(); + this.raw = this.version; + return this; + } + +} + +var semver$2 = SemVer$c; +const { + MAX_LENGTH +} = constants; +const { + re: re$1, + t: t$1 +} = re$3.exports; +const SemVer$b = semver$2; +const parseOptions = parseOptions_1; + +const parse$5 = (version, options) => { + options = parseOptions(options); + + if (version instanceof SemVer$b) { + return version; + } + + if (typeof version !== 'string') { + return null; + } + + if (version.length > MAX_LENGTH) { + return null; + } + + const r = options.loose ? re$1[t$1.LOOSE] : re$1[t$1.FULL]; + + if (!r.test(version)) { + return null; + } + + try { + return new SemVer$b(version, options); + } catch (er) { + return null; + } +}; + +var parse_1 = parse$5; +const parse$4 = parse_1; + +const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null; +}; + +var valid_1 = valid$1; +const parse$3 = parse_1; + +const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null; +}; + +var clean_1 = clean; +const SemVer$a = semver$2; + +const inc = (version, release, options, identifier) => { + if (typeof options === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$a(version instanceof SemVer$a ? version.version : version, options).inc(release, identifier).version; + } catch (er) { + return null; + } +}; + +var inc_1 = inc; +const SemVer$9 = semver$2; + +const compare$a = (a, b, loose) => new SemVer$9(a, loose).compare(new SemVer$9(b, loose)); + +var compare_1 = compare$a; +const compare$9 = compare_1; + +const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + +var eq_1 = eq$2; +const parse$2 = parse_1; +const eq$1 = eq_1; + +const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null; + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key; + } + } + } + + return defaultResult; + } +}; + +var diff_1 = diff; +const SemVer$8 = semver$2; + +const major = (a, loose) => new SemVer$8(a, loose).major; + +var major_1 = major; +const SemVer$7 = semver$2; + +const minor = (a, loose) => new SemVer$7(a, loose).minor; + +var minor_1 = minor; +const SemVer$6 = semver$2; + +const patch = (a, loose) => new SemVer$6(a, loose).patch; + +var patch_1 = patch; +const parse$1 = parse_1; + +const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; +}; + +var prerelease_1 = prerelease; +const compare$8 = compare_1; + +const rcompare = (a, b, loose) => compare$8(b, a, loose); + +var rcompare_1 = rcompare; +const compare$7 = compare_1; + +const compareLoose = (a, b) => compare$7(a, b, true); + +var compareLoose_1 = compareLoose; +const SemVer$5 = semver$2; + +const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$5(a, loose); + const versionB = new SemVer$5(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); +}; + +var compareBuild_1 = compareBuild$2; +const compareBuild$1 = compareBuild_1; + +const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + +var sort_1 = sort; +const compareBuild = compareBuild_1; + +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + +var rsort_1 = rsort; +const compare$6 = compare_1; + +const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + +var gt_1 = gt$3; +const compare$5 = compare_1; + +const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + +var lt_1 = lt$2; +const compare$4 = compare_1; + +const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + +var neq_1 = neq$1; +const compare$3 = compare_1; + +const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + +var gte_1 = gte$2; +const compare$2 = compare_1; + +const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + +var lte_1 = lte$2; +const eq = eq_1; +const neq = neq_1; +const gt$2 = gt_1; +const gte$1 = gte_1; +const lt$1 = lt_1; +const lte$1 = lte_1; + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version; + } + + if (typeof b === 'object') { + b = b.version; + } + + return a === b; + + case '!==': + if (typeof a === 'object') { + a = a.version; + } + + if (typeof b === 'object') { + b = b.version; + } + + return a !== b; + + case '': + case '=': + case '==': + return eq(a, b, loose); + + case '!=': + return neq(a, b, loose); + + case '>': + return gt$2(a, b, loose); + + case '>=': + return gte$1(a, b, loose); + + case '<': + return lt$1(a, b, loose); + + case '<=': + return lte$1(a, b, loose); + + default: + throw new TypeError(`Invalid operator: ${op}`); + } +}; + +var cmp_1 = cmp; +const SemVer$4 = semver$2; +const parse = parse_1; +const { + re, + t +} = re$3.exports; + +const coerce = (version, options) => { + if (version instanceof SemVer$4) { + return version; + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null; + } + + options = options || {}; + let match = null; + + if (!options.rtl) { + match = version.match(re[t.COERCE]); + } else { + let next; + + while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + + re[t.COERCERTL].lastIndex = -1; + } + + if (match === null) { + return null; + } + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options); +}; + +var coerce_1 = coerce; +var iterator; +var hasRequiredIterator; + +function requireIterator() { + if (hasRequiredIterator) return iterator; + hasRequiredIterator = 1; + + iterator = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value; + } + }; + }; + + return iterator; +} + +var yallist; +var hasRequiredYallist; + +function requireYallist() { + if (hasRequiredYallist) return yallist; + hasRequiredYallist = 1; + yallist = Yallist; + Yallist.Node = Node; + Yallist.create = Yallist; + + function Yallist(list) { + var self = this; + + if (!(self instanceof Yallist)) { + self = new Yallist(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self; + } + + Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list'); + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + return next; + }; + + Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return; + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + + if (head) { + head.prev = node; + } + + this.head = node; + + if (!this.tail) { + this.tail = node; + } + + this.length++; + }; + + Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return; + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + + if (tail) { + tail.next = node; + } + + this.tail = node; + + if (!this.head) { + this.head = node; + } + + this.length++; + }; + + Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + + return this.length; + }; + + Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + + return this.length; + }; + + Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined; + } + + var res = this.tail.value; + this.tail = this.tail.prev; + + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + + this.length--; + return res; + }; + + Yallist.prototype.shift = function () { + if (!this.head) { + return undefined; + } + + var res = this.head.value; + this.head = this.head.next; + + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + + this.length--; + return res; + }; + + Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + walker = walker.next; + } + + if (i === n && walker !== null) { + return walker.value; + } + }; + + Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + walker = walker.prev; + } + + if (i === n && walker !== null) { + return walker.value; + } + }; + + Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + + return res; + }; + + Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + + return res; + }; + + Yallist.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value'); + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc; + }; + + Yallist.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value'); + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc; + }; + + Yallist.prototype.toArray = function () { + var arr = new Array(this.length); + + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + + return arr; + }; + + Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + + return arr; + }; + + Yallist.prototype.slice = function (from, to) { + to = to || this.length; + + if (to < 0) { + to += this.length; + } + + from = from || 0; + + if (from < 0) { + from += this.length; + } + + var ret = new Yallist(); + + if (to < from || to < 0) { + return ret; + } + + if (from < 0) { + from = 0; + } + + if (to > this.length) { + to = this.length; + } + + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + + return ret; + }; + + Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length; + + if (to < 0) { + to += this.length; + } + + from = from || 0; + + if (from < 0) { + from += this.length; + } + + var ret = new Yallist(); + + if (to < from || to < 0) { + return ret; + } + + if (from < 0) { + from = 0; + } + + if (to > this.length) { + to = this.length; + } + + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + + return ret; + }; + + Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + + return ret; + }; + + Yallist.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + + this.head = tail; + this.tail = head; + return this; + }; + + function insert(self, node, value) { + var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + return inserted; + } + + function push(self, item) { + self.tail = new Node(item, self.tail, null, self); + + if (!self.head) { + self.head = self.tail; + } + + self.length++; + } + + function unshift(self, item) { + self.head = new Node(item, null, self.head, self); + + if (!self.tail) { + self.tail = self.head; + } + + self.length++; + } + + function Node(value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list); + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + requireIterator()(Yallist); + } catch (er) {} + + return yallist; +} + +var lruCache; +var hasRequiredLruCache; + +function requireLruCache() { + if (hasRequiredLruCache) return lruCache; + hasRequiredLruCache = 1; + const Yallist = requireYallist(); + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + class LRUCache { + constructor(options) { + if (typeof options === 'number') options = { + max: options + }; + if (!options) options = {}; + if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number'); + this[MAX] = options.max || Infinity; + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = typeof lc !== 'function' ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number'); + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + set max(mL) { + if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number'); + this[MAX] = mL || Infinity; + trim(this); + } + + get max() { + return this[MAX]; + } + + set allowStale(allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + + get allowStale() { + return this[ALLOW_STALE]; + } + + set maxAge(mA) { + if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number'); + this[MAX_AGE] = mA; + trim(this); + } + + get maxAge() { + return this[MAX_AGE]; + } + + set lengthCalculator(lC) { + if (typeof lC !== 'function') lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + + trim(this); + } + + get lengthCalculator() { + return this[LENGTH_CALCULATOR]; + } + + get length() { + return this[LENGTH]; + } + + get itemCount() { + return this[LRU_LIST].length; + } + + rforEach(fn, thisp) { + thisp = thisp || this; + + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach(fn, thisp) { + thisp = thisp || this; + + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys() { + return this[LRU_LIST].toArray().map(k => k.key); + } + + values() { + return this[LRU_LIST].toArray().map(k => k.value); + } + + reset() { + if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); + this[LRU_LIST] = new Yallist(); + this[LENGTH] = 0; + } + + dump() { + return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h); + } + + dumpLru() { + return this[LRU_LIST]; + } + + set(key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number'); + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false; + } + + const node = this[CACHE].get(key); + const item = node.value; + + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true; + } + + const hit = new Entry(key, value, len, now, maxAge); + + if (hit.length > this[MAX]) { + if (this[DISPOSE]) this[DISPOSE](key, value); + return false; + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true; + } + + has(key) { + if (!this[CACHE].has(key)) return false; + const hit = this[CACHE].get(key).value; + return !isStale(this, hit); + } + + get(key) { + return get(this, key, true); + } + + peek(key) { + return get(this, key, false); + } + + pop() { + const node = this[LRU_LIST].tail; + if (!node) return null; + del(this, node); + return node.value; + } + + del(key) { + del(this, this[CACHE].get(key)); + } + + load(arr) { + this.reset(); + const now = Date.now(); + + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) this.set(hit.k, hit.v);else { + const maxAge = expiresAt - now; + + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune() { + this[CACHE].forEach((value, key) => get(this, key, false)); + } + + } + + const get = (self, key, doUse) => { + const node = self[CACHE].get(key); + + if (node) { + const hit = node.value; + + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) return undefined; + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + + return hit.value; + } + }; + + const isStale = (self, hit) => { + if (!hit || !hit.maxAge && !self[MAX_AGE]) return false; + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && diff > self[MAX_AGE]; + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value); + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor(key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) hit = undefined; + } + + if (hit) fn.call(thisp, hit.value, hit.key, self); + }; + + lruCache = LRUCache; + return lruCache; +} + +var range; +var hasRequiredRange; + +function requireRange() { + if (hasRequiredRange) return range; + hasRequiredRange = 1; + + class Range { + constructor(range, options) { + options = parseOptions(options); + + if (range instanceof Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new Range(range.raw, options); + } + } + + if (range instanceof Comparator) { + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this; + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range; + this.set = range.split('||').map(r => this.parseRange(r.trim())).filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`); + } + + if (this.set.length > 1) { + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + + if (this.set.length === 0) { + this.set = [first]; + } else if (this.set.length > 1) { + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break; + } + } + } + } + + this.format(); + } + + format() { + this.range = this.set.map(comps => { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; + } + + toString() { + return this.range; + } + + parseRange(range) { + range = range.trim(); + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + + if (cached) { + return cached; + } + + const loose = this.options.loose; + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug('hyphen replace', range); + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range); + range = range.replace(re[t.TILDETRIM], tildeTrimReplace); + range = range.replace(re[t.CARETTRIM], caretTrimReplace); + range = range.split(/\s+/).join(' '); + let rangeList = range.split(' ').map(comp => parseComparator(comp, this.options)).join(' ').split(/\s+/).map(comp => replaceGTE0(comp, this.options)); + + if (loose) { + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options); + return !!comp.match(re[t.COMPARATORLOOSE]); + }); + } + + debug('range list', rangeList); + const rangeMap = new Map(); + const comparators = rangeList.map(comp => new Comparator(comp, this.options)); + + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp]; + } + + rangeMap.set(comp.value, comp); + } + + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete(''); + } + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result; + } + + intersects(range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(thisComparators => { + return isSatisfiable(thisComparators, options) && range.set.some(rangeComparators => { + return isSatisfiable(rangeComparators, options) && thisComparators.every(thisComparator => { + return rangeComparators.every(rangeComparator => { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + } + + test(version) { + if (!version) { + return false; + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true; + } + } + + return false; + } + + } + + range = Range; + const LRU = requireLruCache(); + const cache = new LRU({ + max: 1000 + }); + const parseOptions = parseOptions_1; + const Comparator = requireComparator(); + const debug = debug_1; + const SemVer = semver$2; + const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$3.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + + const isAny = c => c.value === ''; + + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every(otherComparator => { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + + return result; + }; + + const parseComparator = (comp, options) => { + debug('comp', comp, options); + comp = replaceCarets(comp, options); + debug('caret', comp); + comp = replaceTildes(comp, options); + debug('tildes', comp); + comp = replaceXRanges(comp, options); + debug('xrange', comp); + comp = replaceStars(comp, options); + debug('stars', comp); + return comp; + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + const replaceTildes = (comp, options) => comp.trim().split(/\s+/).map(c => { + return replaceTilde(c, options); + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + + debug('tilde return', ret); + return ret; + }); + }; + + const replaceCarets = (comp, options) => comp.trim().split(/\s+/).map(c => { + return replaceCaret(c, options); + }).join(' '); + + const replaceCaret = (comp, options) => { + debug('caret', comp, options); + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug('replaceCaret pr', pr); + + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + debug('no pr'); + + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + + debug('caret return', ret); + return ret; + }); + }; + + const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options); + return comp.split(/\s+/).map(c => { + return replaceXRange(c, options); + }).join(' '); + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + ret = '<0.0.0-0'; + } else { + ret = '*'; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + + p = 0; + + if (gtlt === '>') { + gtlt = '>='; + + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + gtlt = '<'; + + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') { + pr = '-0'; + } + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + + debug('xRange return', ret); + return ret; + }); + }; + + const replaceStars = (comp, options) => { + debug('replaceStars', comp, options); + return comp.trim().replace(re[t.STAR], ''); + }; + + const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options); + return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ''); + }; + + const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return `${from} ${to}`.trim(); + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false; + } + } + + if (version.prerelease.length && !options.includePrerelease) { + for (let i = 0; i < set.length; i++) { + debug(set[i].semver); + + if (set[i].semver === Comparator.ANY) { + continue; + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; + } + } + } + + return false; + } + + return true; + }; + + return range; +} + +var comparator; +var hasRequiredComparator; + +function requireComparator() { + if (hasRequiredComparator) return comparator; + hasRequiredComparator = 1; + const ANY = Symbol('SemVer ANY'); + + class Comparator { + static get ANY() { + return ANY; + } + + constructor(comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug('comp', this); + } + + parse(comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`); + } + + this.operator = m[1] !== undefined ? m[1] : ''; + + if (this.operator === '=') { + this.operator = ''; + } + + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + } + + toString() { + return this.value; + } + + test(version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY || version === ANY) { + return true; + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + + return cmp(version, this.operator, this.semver, this.options); + } + + intersects(comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true; + } + + return new Range(comp.value, options).test(this.value); + } else if (comp.operator === '') { + if (comp.value === '') { + return true; + } + + return new Range(this.value, options).test(comp.semver); + } + + const sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; + } + + } + + comparator = Comparator; + const parseOptions = parseOptions_1; + const { + re, + t + } = re$3.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer = semver$2; + const Range = requireRange(); + return comparator; +} + +const Range$8 = requireRange(); + +const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false; + } + + return range.test(version); +}; + +var satisfies_1 = satisfies$3; +const Range$7 = requireRange(); + +const toComparators = (range, options) => new Range$7(range, options).set.map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + +var toComparators_1 = toComparators; +const SemVer$3 = semver$2; +const Range$6 = requireRange(); + +const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null; + } + + versions.forEach(v => { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max; +}; + +var maxSatisfying_1 = maxSatisfying; +const SemVer$2 = semver$2; +const Range$5 = requireRange(); + +const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null; + } + + versions.forEach(v => { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min; +}; + +var minSatisfying_1 = minSatisfying; +const SemVer$1 = semver$2; +const Range$4 = requireRange(); +const gt$1 = gt_1; + +const minVersion = (range, loose) => { + range = new Range$4(range, loose); + let minver = new SemVer$1('0.0.0'); + + if (range.test(minver)) { + return minver; + } + + minver = new SemVer$1('0.0.0-0'); + + if (range.test(minver)) { + return minver; + } + + minver = null; + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let setMin = null; + comparators.forEach(comparator => { + const compver = new SemVer$1(comparator.semver.version); + + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + + compver.raw = compver.format(); + + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + + break; + + case '<': + case '<=': + break; + + default: + throw new Error(`Unexpected operation: ${comparator.operator}`); + } + }); + + if (setMin && (!minver || gt$1(minver, setMin))) { + minver = setMin; + } + } + + if (minver && range.test(minver)) { + return minver; + } + + return null; +}; + +var minVersion_1 = minVersion; +const Range$3 = requireRange(); + +const validRange = (range, options) => { + try { + return new Range$3(range, options).range || '*'; + } catch (er) { + return null; + } +}; + +var valid = validRange; +const SemVer = semver$2; +const Comparator$1 = requireComparator(); +const { + ANY: ANY$1 +} = Comparator$1; +const Range$2 = requireRange(); +const satisfies$2 = satisfies_1; +const gt = gt_1; +const lt = lt_1; +const lte = lte_1; +const gte = gte_1; + +const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + let gtfn, ltefn, ltfn, comp, ecomp; + + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + if (satisfies$2(version, range, options)) { + return false; + } + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let high = null; + let low = null; + comparators.forEach(comparator => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + + high = high || comparator; + low = low || comparator; + + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + + return true; +}; + +var outside_1 = outside$2; +const outside$1 = outside_1; + +const gtr = (version, range, options) => outside$1(version, range, '>', options); + +var gtr_1 = gtr; +const outside = outside_1; + +const ltr = (version, range, options) => outside(version, range, '<', options); + +var ltr_1 = ltr; +const Range$1 = requireRange(); + +const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2); +}; + +var intersects_1 = intersects; +const satisfies$1 = satisfies_1; +const compare$1 = compare_1; + +var simplify = (versions, range, options) => { + const set = []; + let first = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + + for (const version of v) { + const included = satisfies$1(version, range, options); + + if (included) { + prev = version; + + if (!first) { + first = version; + } + } else { + if (prev) { + set.push([first, prev]); + } + + prev = null; + first = null; + } + } + + if (first) { + set.push([first, null]); + } + + const ranges = []; + + for (const [min, max] of set) { + if (min === max) { + ranges.push(min); + } else if (!max && min === v[0]) { + ranges.push('*'); + } else if (!max) { + ranges.push(`>=${min}`); + } else if (min === v[0]) { + ranges.push(`<=${max}`); + } else { + ranges.push(`${min} - ${max}`); + } + } + + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range; +}; + +const Range = requireRange(); +const Comparator = requireComparator(); +const { + ANY +} = Comparator; +const satisfies = satisfies_1; +const compare = compare_1; + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true; + } + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + + if (isSub) { + continue OUTER; + } + } + + if (sawNonNull) { + return false; + } + } + + return true; +}; + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true; + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true; + } else if (options.includePrerelease) { + sub = [new Comparator('>=0.0.0-0')]; + } else { + sub = [new Comparator('>=0.0.0')]; + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true; + } else { + dom = [new Comparator('>=0.0.0')]; + } + } + + const eqSet = new Set(); + let gt, lt; + + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options); + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options); + } else { + eqSet.add(c.semver); + } + } + + if (eqSet.size > 1) { + return null; + } + + let gtltComp; + + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + + if (gtltComp > 0) { + return null; + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null; + } + } + + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null; + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null; + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false; + } + } + + return true; + } + + let higher, lower; + let hasDomLT, hasDomGT; + let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; + + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + + if (higher === c && higher !== gt) { + return false; + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false; + } + } + + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + + if (lower === c && lower !== lt) { + return false; + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false; + } + } + + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false; + } + } + + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false; + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false; + } + + if (needDomGTPre || needDomLTPre) { + return false; + } + + return true; +}; + +const higherGT = (a, b, options) => { + if (!a) { + return b; + } + + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a; +}; + +const lowerLT = (a, b, options) => { + if (!a) { + return b; + } + + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a; +}; + +var subset_1 = subset; +const internalRe = re$3.exports; +var semver$1 = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$2, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: requireComparator(), + Range: requireRange(), + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1 +}; +var semver = semver$1; + +var builtins = function ({ + version = process.version, + experimental = false +} = {}) { + var coreModules = ['assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'module', 'net', 'os', 'path', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'sys', 'timers', 'tls', 'tty', 'url', 'util', 'vm', 'zlib']; + if (semver.lt(version, '6.0.0')) coreModules.push('freelist'); + if (semver.gte(version, '1.0.0')) coreModules.push('v8'); + if (semver.gte(version, '1.1.0')) coreModules.push('process'); + if (semver.gte(version, '8.0.0')) coreModules.push('inspector'); + if (semver.gte(version, '8.1.0')) coreModules.push('async_hooks'); + if (semver.gte(version, '8.4.0')) coreModules.push('http2'); + if (semver.gte(version, '8.5.0')) coreModules.push('perf_hooks'); + if (semver.gte(version, '10.0.0')) coreModules.push('trace_events'); + + if (semver.gte(version, '10.5.0') && (experimental || semver.gte(version, '12.0.0'))) { + coreModules.push('worker_threads'); + } + + if (semver.gte(version, '12.16.0') && experimental) { + coreModules.push('wasi'); + } + + return coreModules; +}; + +const reader = { + read +}; + +function read(jsonPath) { + return find(_path().dirname(jsonPath)); +} + +function find(dir) { + try { + const string = _fs().default.readFileSync(_path().toNamespacedPath(_path().join(dir, 'package.json')), 'utf8'); + + return { + string + }; + } catch (error) { + if (error.code === 'ENOENT') { + const parent = _path().dirname(dir); + + if (dir !== parent) return find(parent); + return { + string: undefined + }; + } + + throw error; + } +} + +const isWindows = process.platform === 'win32'; +const own$1 = {}.hasOwnProperty; +const codes = {}; +const messages = new Map(); +const nodeInternalPrefix = '__node_internal_'; +let userStackTraceLimit; +codes.ERR_INVALID_MODULE_SPECIFIER = createError('ERR_INVALID_MODULE_SPECIFIER', (request, reason, base = undefined) => { + return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ''}`; +}, TypeError); +codes.ERR_INVALID_PACKAGE_CONFIG = createError('ERR_INVALID_PACKAGE_CONFIG', (path, base, message) => { + return `Invalid package config ${path}${base ? ` while importing ${base}` : ''}${message ? `. ${message}` : ''}`; +}, Error); +codes.ERR_INVALID_PACKAGE_TARGET = createError('ERR_INVALID_PACKAGE_TARGET', (pkgPath, key, target, isImport = false, base = undefined) => { + const relError = typeof target === 'string' && !isImport && target.length > 0 && !target.startsWith('./'); + + if (key === '.') { + _assert()(isImport === false); + + return `Invalid "exports" main target ${JSON.stringify(target)} defined ` + `in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ? '; targets must start with "./"' : ''}`; + } + + return `Invalid "${isImport ? 'imports' : 'exports'}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ? '; targets must start with "./"' : ''}`; +}, Error); +codes.ERR_MODULE_NOT_FOUND = createError('ERR_MODULE_NOT_FOUND', (path, base, type = 'package') => { + return `Cannot find ${type} '${path}' imported from ${base}`; +}, Error); +codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError('ERR_PACKAGE_IMPORT_NOT_DEFINED', (specifier, packagePath, base) => { + return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ''} imported from ${base}`; +}, TypeError); +codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => { + if (subpath === '.') return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ''}`; + return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ''}`; +}, Error); +codes.ERR_UNSUPPORTED_DIR_IMPORT = createError('ERR_UNSUPPORTED_DIR_IMPORT', "Directory import '%s' is not supported " + 'resolving ES modules imported from %s', Error); +codes.ERR_UNKNOWN_FILE_EXTENSION = createError('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension "%s" for %s', TypeError); +codes.ERR_INVALID_ARG_VALUE = createError('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { + let inspected = (0, _util().inspect)(value); + + if (inspected.length > 128) { + inspected = `${inspected.slice(0, 128)}...`; + } + + const type = name.includes('.') ? 'property' : 'argument'; + return `The ${type} '${name}' ${reason}. Received ${inspected}`; +}, TypeError); +codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError('ERR_UNSUPPORTED_ESM_URL_SCHEME', url => { + let message = 'Only file and data URLs are supported by the default ESM loader'; + + if (isWindows && url.protocol.length === 2) { + message += '. On Windows, absolute paths must be valid file:// URLs'; + } + + message += `. Received protocol '${url.protocol}'`; + return message; +}, Error); + +function createError(sym, value, def) { + messages.set(sym, value); + return makeNodeErrorWithCode(def, sym); +} + +function makeNodeErrorWithCode(Base, key) { + return NodeError; + + function NodeError(...args) { + const limit = Error.stackTraceLimit; + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; + const error = new Base(); + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; + const message = getMessage(key, args, error); + Object.defineProperty(error, 'message', { + value: message, + enumerable: false, + writable: true, + configurable: true + }); + Object.defineProperty(error, 'toString', { + value() { + return `${this.name} [${key}]: ${this.message}`; + }, + + enumerable: false, + writable: true, + configurable: true + }); + addCodeToName(error, Base.name, key); + error.code = key; + return error; + } +} + +const addCodeToName = hideStackFrames(function (error, name, code) { + error = captureLargerStackTrace(error); + error.name = `${name} [${code}]`; + error.stack; + + if (name === 'SystemError') { + Object.defineProperty(error, 'name', { + value: name, + enumerable: false, + writable: true, + configurable: true + }); + } else { + delete error.name; + } +}); + +function isErrorStackTraceLimitWritable() { + const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit'); + + if (desc === undefined) { + return Object.isExtensible(Error); + } + + return own$1.call(desc, 'writable') ? desc.writable : desc.set !== undefined; +} + +function hideStackFrames(fn) { + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, 'name', { + value: hidden + }); + return fn; +} + +const captureLargerStackTrace = hideStackFrames(function (error) { + const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); + + if (stackTraceLimitIsWritable) { + userStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Number.POSITIVE_INFINITY; + } + + Error.captureStackTrace(error); + if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; + return error; +}); + +function getMessage(key, args, self) { + const message = messages.get(key); + + if (typeof message === 'function') { + _assert()(message.length <= args.length, `Code: ${key}; The provided arguments length (${args.length}) does not ` + `match the required ones (${message.length}).`); + + return Reflect.apply(message, self, args); + } + + const expectedLength = (message.match(/%[dfijoOs]/g) || []).length; + + _assert()(expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not ` + `match the required ones (${expectedLength}).`); + + if (args.length === 0) return message; + args.unshift(message); + return Reflect.apply(_util().format, null, args); +} + +const { + ERR_UNKNOWN_FILE_EXTENSION +} = codes; +const extensionFormatMap = { + __proto__: null, + '.cjs': 'commonjs', + '.js': 'module', + '.mjs': 'module' +}; + +function defaultGetFormat(url) { + if (url.startsWith('node:')) { + return { + format: 'builtin' + }; + } + + const parsed = new (_url().URL)(url); + + if (parsed.protocol === 'data:') { + const { + 1: mime + } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [null, null]; + const format = mime === 'text/javascript' ? 'module' : null; + return { + format + }; + } + + if (parsed.protocol === 'file:') { + const ext = _path().extname(parsed.pathname); + + let format; + + if (ext === '.js') { + format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs'; + } else { + format = extensionFormatMap[ext]; + } + + if (!format) { + throw new ERR_UNKNOWN_FILE_EXTENSION(ext, (0, _url().fileURLToPath)(url)); + } + + return { + format: format || null + }; + } + + return { + format: null + }; +} + +const listOfBuiltins = builtins(); +const { + ERR_INVALID_MODULE_SPECIFIER, + ERR_INVALID_PACKAGE_CONFIG, + ERR_INVALID_PACKAGE_TARGET, + ERR_MODULE_NOT_FOUND, + ERR_PACKAGE_IMPORT_NOT_DEFINED, + ERR_PACKAGE_PATH_NOT_EXPORTED, + ERR_UNSUPPORTED_DIR_IMPORT, + ERR_UNSUPPORTED_ESM_URL_SCHEME, + ERR_INVALID_ARG_VALUE +} = codes; +const own = {}.hasOwnProperty; +const DEFAULT_CONDITIONS = Object.freeze(['node', 'import']); +const DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS); +const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/; +const patternRegEx = /\*/g; +const encodedSepRegEx = /%2f|%2c/i; +const emittedPackageWarnings = new Set(); +const packageJsonCache = new Map(); + +function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) { + const pjsonPath = (0, _url().fileURLToPath)(pjsonUrl); + if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return; + emittedPackageWarnings.add(pjsonPath + '|' + match); + process.emitWarning(`Use of deprecated folder mapping "${match}" in the ${isExports ? '"exports"' : '"imports"'} field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, _url().fileURLToPath)(base)}` : ''}.\n` + `Update this package.json to use a subpath pattern like "${match}*".`, 'DeprecationWarning', 'DEP0148'); +} + +function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { + const { + format + } = defaultGetFormat(url.href); + if (format !== 'module') return; + const path = (0, _url().fileURLToPath)(url.href); + const pkgPath = (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)); + const basePath = (0, _url().fileURLToPath)(base); + if (main) process.emitWarning(`Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, ` + `excluding the full filename and extension to the resolved file at "${path.slice(pkgPath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is` + 'deprecated for ES modules.', 'DeprecationWarning', 'DEP0151');else process.emitWarning(`No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path.slice(pkgPath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, 'DeprecationWarning', 'DEP0151'); +} + +function getConditionsSet(conditions) { + if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) { + if (!Array.isArray(conditions)) { + throw new ERR_INVALID_ARG_VALUE('conditions', conditions, 'expected an array'); + } + + return new Set(conditions); + } + + return DEFAULT_CONDITIONS_SET; +} + +function tryStatSync(path) { + try { + return (0, _fs().statSync)(path); + } catch (_unused) { + return new (_fs().Stats)(); + } +} + +function getPackageConfig(path, specifier, base) { + const existing = packageJsonCache.get(path); + + if (existing !== undefined) { + return existing; + } + + const source = reader.read(path).string; + + if (source === undefined) { + const packageConfig = { + pjsonPath: path, + exists: false, + main: undefined, + name: undefined, + type: 'none', + exports: undefined, + imports: undefined + }; + packageJsonCache.set(path, packageConfig); + return packageConfig; + } + + let packageJson; + + try { + packageJson = JSON.parse(source); + } catch (error) { + throw new ERR_INVALID_PACKAGE_CONFIG(path, (base ? `"${specifier}" from ` : '') + (0, _url().fileURLToPath)(base || specifier), error.message); + } + + const { + exports, + imports, + main, + name, + type + } = packageJson; + const packageConfig = { + pjsonPath: path, + exists: true, + main: typeof main === 'string' ? main : undefined, + name: typeof name === 'string' ? name : undefined, + type: type === 'module' || type === 'commonjs' ? type : 'none', + exports, + imports: imports && typeof imports === 'object' ? imports : undefined + }; + packageJsonCache.set(path, packageConfig); + return packageConfig; +} + +function getPackageScopeConfig(resolved) { + let packageJsonUrl = new (_url().URL)('./package.json', resolved); + + while (true) { + const packageJsonPath = packageJsonUrl.pathname; + if (packageJsonPath.endsWith('node_modules/package.json')) break; + const packageConfig = getPackageConfig((0, _url().fileURLToPath)(packageJsonUrl), resolved); + if (packageConfig.exists) return packageConfig; + const lastPackageJsonUrl = packageJsonUrl; + packageJsonUrl = new (_url().URL)('../package.json', packageJsonUrl); + if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) break; + } + + const packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + const packageConfig = { + pjsonPath: packageJsonPath, + exists: false, + main: undefined, + name: undefined, + type: 'none', + exports: undefined, + imports: undefined + }; + packageJsonCache.set(packageJsonPath, packageConfig); + return packageConfig; +} + +function fileExists(url) { + return tryStatSync((0, _url().fileURLToPath)(url)).isFile(); +} + +function legacyMainResolve(packageJsonUrl, packageConfig, base) { + let guess; + + if (packageConfig.main !== undefined) { + guess = new (_url().URL)(`./${packageConfig.main}`, packageJsonUrl); + if (fileExists(guess)) return guess; + const tries = [`./${packageConfig.main}.js`, `./${packageConfig.main}.json`, `./${packageConfig.main}.node`, `./${packageConfig.main}/index.js`, `./${packageConfig.main}/index.json`, `./${packageConfig.main}/index.node`]; + let i = -1; + + while (++i < tries.length) { + guess = new (_url().URL)(tries[i], packageJsonUrl); + if (fileExists(guess)) break; + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess; + } + } + + const tries = ['./index.js', './index.json', './index.node']; + let i = -1; + + while (++i < tries.length) { + guess = new (_url().URL)(tries[i], packageJsonUrl); + if (fileExists(guess)) break; + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess; + } + + throw new ERR_MODULE_NOT_FOUND((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base)); +} + +function finalizeResolution(resolved, base) { + if (encodedSepRegEx.test(resolved.pathname)) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, 'must not include encoded "/" or "\\" characters', (0, _url().fileURLToPath)(base)); + const path = (0, _url().fileURLToPath)(resolved); + const stats = tryStatSync(path.endsWith('/') ? path.slice(-1) : path); + + if (stats.isDirectory()) { + const error = new ERR_UNSUPPORTED_DIR_IMPORT(path, (0, _url().fileURLToPath)(base)); + error.url = String(resolved); + throw error; + } + + if (!stats.isFile()) { + throw new ERR_MODULE_NOT_FOUND(path || resolved.pathname, base && (0, _url().fileURLToPath)(base), 'module'); + } + + return resolved; +} + +function throwImportNotDefined(specifier, packageJsonUrl, base) { + throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base)); +} + +function throwExportsNotFound(subpath, packageJsonUrl, base) { + throw new ERR_PACKAGE_PATH_NOT_EXPORTED((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, base && (0, _url().fileURLToPath)(base)); +} + +function throwInvalidSubpath(subpath, packageJsonUrl, internal, base) { + const reason = `request is not a valid subpath for the "${internal ? 'imports' : 'exports'}" resolution of ${(0, _url().fileURLToPath)(packageJsonUrl)}`; + throw new ERR_INVALID_MODULE_SPECIFIER(subpath, reason, base && (0, _url().fileURLToPath)(base)); +} + +function throwInvalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { + target = typeof target === 'object' && target !== null ? JSON.stringify(target, null, '') : `${target}`; + throw new ERR_INVALID_PACKAGE_TARGET((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, target, internal, base && (0, _url().fileURLToPath)(base)); +} + +function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, conditions) { + if (subpath !== '' && !pattern && target[target.length - 1] !== '/') throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + + if (!target.startsWith('./')) { + if (internal && !target.startsWith('../') && !target.startsWith('/')) { + let isURL = false; + + try { + new (_url().URL)(target); + isURL = true; + } catch (_unused2) {} + + if (!isURL) { + const exportTarget = pattern ? target.replace(patternRegEx, subpath) : target + subpath; + return packageResolve(exportTarget, packageJsonUrl, conditions); + } + } + + throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + } + + if (invalidSegmentRegEx.test(target.slice(2))) throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + const resolved = new (_url().URL)(target, packageJsonUrl); + const resolvedPath = resolved.pathname; + const packagePath = new (_url().URL)('.', packageJsonUrl).pathname; + if (!resolvedPath.startsWith(packagePath)) throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + if (subpath === '') return resolved; + if (invalidSegmentRegEx.test(subpath)) throwInvalidSubpath(match + subpath, packageJsonUrl, internal, base); + if (pattern) return new (_url().URL)(resolved.href.replace(patternRegEx, subpath)); + return new (_url().URL)(subpath, resolved); +} + +function isArrayIndex(key) { + const keyNumber = Number(key); + if (`${keyNumber}` !== key) return false; + return keyNumber >= 0 && keyNumber < 0xffffffff; +} + +function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, conditions) { + if (typeof target === 'string') { + return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, conditions); + } + + if (Array.isArray(target)) { + const targetList = target; + if (targetList.length === 0) return null; + let lastException; + let i = -1; + + while (++i < targetList.length) { + const targetItem = targetList[i]; + let resolved; + + try { + resolved = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, conditions); + } catch (error) { + lastException = error; + if (error.code === 'ERR_INVALID_PACKAGE_TARGET') continue; + throw error; + } + + if (resolved === undefined) continue; + + if (resolved === null) { + lastException = null; + continue; + } + + return resolved; + } + + if (lastException === undefined || lastException === null) { + return lastException; + } + + throw lastException; + } + + if (typeof target === 'object' && target !== null) { + const keys = Object.getOwnPropertyNames(target); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (isArrayIndex(key)) { + throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain numeric property keys.'); + } + } + + i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (key === 'default' || conditions && conditions.has(key)) { + const conditionalTarget = target[key]; + const resolved = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, conditions); + if (resolved === undefined) continue; + return resolved; + } + } + + return undefined; + } + + if (target === null) { + return null; + } + + throwInvalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base); +} + +function isConditionalExportsMainSugar(exports, packageJsonUrl, base) { + if (typeof exports === 'string' || Array.isArray(exports)) return true; + if (typeof exports !== 'object' || exports === null) return false; + const keys = Object.getOwnPropertyNames(exports); + let isConditionalSugar = false; + let i = 0; + let j = -1; + + while (++j < keys.length) { + const key = keys[j]; + const curIsConditionalSugar = key === '' || key[0] !== '.'; + + if (i++ === 0) { + isConditionalSugar = curIsConditionalSugar; + } else if (isConditionalSugar !== curIsConditionalSugar) { + throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain some keys starting with \'.\' and some not.' + ' The exports object must either be an object of package subpath keys' + ' or an object of main entry condition name keys only.'); + } + } + + return isConditionalSugar; +} + +function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) { + let exports = packageConfig.exports; + if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) exports = { + '.': exports + }; + + if (own.call(exports, packageSubpath)) { + const target = exports[packageSubpath]; + const resolved = resolvePackageTarget(packageJsonUrl, target, '', packageSubpath, base, false, false, conditions); + if (resolved === null || resolved === undefined) throwExportsNotFound(packageSubpath, packageJsonUrl, base); + return { + resolved, + exact: true + }; + } + + let bestMatch = ''; + const keys = Object.getOwnPropertyNames(exports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (key[key.length - 1] === '*' && packageSubpath.startsWith(key.slice(0, -1)) && packageSubpath.length >= key.length && key.length > bestMatch.length) { + bestMatch = key; + } else if (key[key.length - 1] === '/' && packageSubpath.startsWith(key) && key.length > bestMatch.length) { + bestMatch = key; + } + } + + if (bestMatch) { + const target = exports[bestMatch]; + const pattern = bestMatch[bestMatch.length - 1] === '*'; + const subpath = packageSubpath.slice(bestMatch.length - (pattern ? 1 : 0)); + const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, false, conditions); + if (resolved === null || resolved === undefined) throwExportsNotFound(packageSubpath, packageJsonUrl, base); + if (!pattern) emitFolderMapDeprecation(bestMatch, packageJsonUrl, true, base); + return { + resolved, + exact: pattern + }; + } + + throwExportsNotFound(packageSubpath, packageJsonUrl, base); +} + +function packageImportsResolve(name, base, conditions) { + if (name === '#' || name.startsWith('#/')) { + const reason = 'is not a valid internal imports specifier name'; + throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, _url().fileURLToPath)(base)); + } + + let packageJsonUrl; + const packageConfig = getPackageScopeConfig(base); + + if (packageConfig.exists) { + packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath); + const imports = packageConfig.imports; + + if (imports) { + if (own.call(imports, name)) { + const resolved = resolvePackageTarget(packageJsonUrl, imports[name], '', name, base, false, true, conditions); + if (resolved !== null) return { + resolved, + exact: true + }; + } else { + let bestMatch = ''; + const keys = Object.getOwnPropertyNames(imports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (key[key.length - 1] === '*' && name.startsWith(key.slice(0, -1)) && name.length >= key.length && key.length > bestMatch.length) { + bestMatch = key; + } else if (key[key.length - 1] === '/' && name.startsWith(key) && key.length > bestMatch.length) { + bestMatch = key; + } + } + + if (bestMatch) { + const target = imports[bestMatch]; + const pattern = bestMatch[bestMatch.length - 1] === '*'; + const subpath = name.slice(bestMatch.length - (pattern ? 1 : 0)); + const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, true, conditions); + + if (resolved !== null) { + if (!pattern) emitFolderMapDeprecation(bestMatch, packageJsonUrl, false, base); + return { + resolved, + exact: pattern + }; + } + } + } + } + } + + throwImportNotDefined(name, packageJsonUrl, base); +} + +function getPackageType(url) { + const packageConfig = getPackageScopeConfig(url); + return packageConfig.type; +} + +function parsePackageName(specifier, base) { + let separatorIndex = specifier.indexOf('/'); + let validPackageName = true; + let isScoped = false; + + if (specifier[0] === '@') { + isScoped = true; + + if (separatorIndex === -1 || specifier.length === 0) { + validPackageName = false; + } else { + separatorIndex = specifier.indexOf('/', separatorIndex + 1); + } + } + + const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex); + let i = -1; + + while (++i < packageName.length) { + if (packageName[i] === '%' || packageName[i] === '\\') { + validPackageName = false; + break; + } + } + + if (!validPackageName) { + throw new ERR_INVALID_MODULE_SPECIFIER(specifier, 'is not a valid package name', (0, _url().fileURLToPath)(base)); + } + + const packageSubpath = '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex)); + return { + packageName, + packageSubpath, + isScoped + }; +} + +function packageResolve(specifier, base, conditions) { + const { + packageName, + packageSubpath, + isScoped + } = parsePackageName(specifier, base); + const packageConfig = getPackageScopeConfig(base); + + if (packageConfig.exists) { + const packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath); + + if (packageConfig.name === packageName && packageConfig.exports !== undefined && packageConfig.exports !== null) { + return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions).resolved; + } + } + + let packageJsonUrl = new (_url().URL)('./node_modules/' + packageName + '/package.json', base); + let packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + let lastPath; + + do { + const stat = tryStatSync(packageJsonPath.slice(0, -13)); + + if (!stat.isDirectory()) { + lastPath = packageJsonPath; + packageJsonUrl = new (_url().URL)((isScoped ? '../../../../node_modules/' : '../../../node_modules/') + packageName + '/package.json', packageJsonUrl); + packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + continue; + } + + const packageConfig = getPackageConfig(packageJsonPath, specifier, base); + if (packageConfig.exports !== undefined && packageConfig.exports !== null) return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions).resolved; + if (packageSubpath === '.') return legacyMainResolve(packageJsonUrl, packageConfig, base); + return new (_url().URL)(packageSubpath, packageJsonUrl); + } while (packageJsonPath.length !== lastPath.length); + + throw new ERR_MODULE_NOT_FOUND(packageName, (0, _url().fileURLToPath)(base)); +} + +function isRelativeSpecifier(specifier) { + if (specifier[0] === '.') { + if (specifier.length === 1 || specifier[1] === '/') return true; + + if (specifier[1] === '.' && (specifier.length === 2 || specifier[2] === '/')) { + return true; + } + } + + return false; +} + +function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { + if (specifier === '') return false; + if (specifier[0] === '/') return true; + return isRelativeSpecifier(specifier); +} + +function moduleResolve(specifier, base, conditions) { + let resolved; + + if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { + resolved = new (_url().URL)(specifier, base); + } else if (specifier[0] === '#') { + ({ + resolved + } = packageImportsResolve(specifier, base, conditions)); + } else { + try { + resolved = new (_url().URL)(specifier); + } catch (_unused3) { + resolved = packageResolve(specifier, base, conditions); + } + } + + return finalizeResolution(resolved, base); +} + +function defaultResolve(specifier, context = {}) { + const { + parentURL + } = context; + let parsed; + + try { + parsed = new (_url().URL)(specifier); + + if (parsed.protocol === 'data:') { + return { + url: specifier + }; + } + } catch (_unused4) {} + + if (parsed && parsed.protocol === 'node:') return { + url: specifier + }; + if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:') throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed); + + if (listOfBuiltins.includes(specifier)) { + return { + url: 'node:' + specifier + }; + } + + if (parentURL.startsWith('data:')) { + new (_url().URL)(specifier, parentURL); + } + + const conditions = getConditionsSet(context.conditions); + let url = moduleResolve(specifier, new (_url().URL)(parentURL), conditions); + const urlPath = (0, _url().fileURLToPath)(url); + const real = (0, _fs().realpathSync)(urlPath); + const old = url; + url = (0, _url().pathToFileURL)(real + (urlPath.endsWith(_path().sep) ? '/' : '')); + url.search = old.search; + url.hash = old.hash; + return { + url: `${url}` + }; +} + +function resolve(_x, _x2) { + return _resolve.apply(this, arguments); +} + +function _resolve() { + _resolve = _asyncToGenerator(function* (specifier, parent) { + if (!parent) { + throw new Error('Please pass `parent`: `import-meta-resolve` cannot ponyfill that'); + } + + try { + return defaultResolve(specifier, { + parentURL: parent + }).url; + } catch (error) { + return error.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ? error.url : Promise.reject(error); + } + }); + return _resolve.apply(this, arguments); +} + +0 && 0; \ No newline at end of file diff --git a/node_modules/@babel/core/package.json b/node_modules/@babel/core/package.json new file mode 100644 index 0000000..86e919f --- /dev/null +++ b/node_modules/@babel/core/package.json @@ -0,0 +1,114 @@ +{ + "_from": "@babel/core@^7.11.6", + "_id": "@babel/core@7.18.13", + "_inBundle": false, + "_integrity": "sha512-ZisbOvRRusFktksHSG6pjj1CSvkPkcZq/KHD45LAkVP/oiHJkNBZWfpvlLmX8OtHDG8IuzsFlVRWo08w7Qxn0A==", + "_location": "/@babel/core", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/core@^7.11.6", + "name": "@babel/core", + "escapedName": "@babel%2fcore", + "scope": "@babel", + "rawSpec": "^7.11.6", + "saveSpec": null, + "fetchSpec": "^7.11.6" + }, + "_requiredBy": [ + "/@jest/transform", + "/istanbul-lib-instrument", + "/jest-config", + "/jest-snapshot" + ], + "_resolved": "https://registry.npmjs.org/@babel/core/-/core-7.18.13.tgz", + "_shasum": "9be8c44512751b05094a4d3ab05fc53a47ce00ac", + "_spec": "@babel/core@^7.11.6", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/transform", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "browser": { + "./lib/config/files/index.js": "./lib/config/files/index-browser.js", + "./lib/config/resolve-targets.js": "./lib/config/resolve-targets-browser.js", + "./lib/transform-file.js": "./lib/transform-file-browser.js", + "./src/config/files/index.ts": "./src/config/files/index-browser.ts", + "./src/config/resolve-targets.ts": "./src/config/resolve-targets-browser.ts", + "./src/transform-file.ts": "./src/transform-file-browser.ts" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen" + }, + "bundleDependencies": false, + "dependencies": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.18.13", + "@babel/helper-compilation-targets": "^7.18.9", + "@babel/helper-module-transforms": "^7.18.9", + "@babel/helpers": "^7.18.9", + "@babel/parser": "^7.18.13", + "@babel/template": "^7.18.10", + "@babel/traverse": "^7.18.13", + "@babel/types": "^7.18.13", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "deprecated": false, + "description": "Babel compiler core.", + "devDependencies": { + "@babel/helper-transform-fixture-test-runner": "^7.18.10", + "@babel/plugin-syntax-flow": "^7.18.6", + "@babel/plugin-transform-flow-strip-types": "^7.18.9", + "@babel/plugin-transform-modules-commonjs": "^7.18.6", + "@babel/preset-env": "^7.18.10", + "@jridgewell/trace-mapping": "^0.3.8", + "@types/convert-source-map": "^1.5.1", + "@types/debug": "^4.1.0", + "@types/gensync": "^1.0.0", + "@types/resolve": "^1.3.2", + "@types/semver": "^5.4.0", + "rimraf": "^3.0.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + }, + "homepage": "https://babel.dev/docs/en/next/babel-core", + "keywords": [ + "6to5", + "babel", + "classes", + "const", + "es6", + "harmony", + "let", + "modules", + "transpile", + "transpiler", + "var", + "babel-core", + "compiler" + ], + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/core", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-core" + }, + "type": "commonjs", + "version": "7.18.13" +} diff --git a/node_modules/@babel/core/src/config/files/index-browser.ts b/node_modules/@babel/core/src/config/files/index-browser.ts new file mode 100644 index 0000000..08f91f6 --- /dev/null +++ b/node_modules/@babel/core/src/config/files/index-browser.ts @@ -0,0 +1,109 @@ +import type { Handler } from "gensync"; + +import type { + ConfigFile, + IgnoreFile, + RelativeConfig, + FilePackageData, +} from "./types"; + +import type { CallerMetadata } from "../validation/options"; + +export type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData }; + +export function findConfigUpwards( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + rootDir: string, +): string | null { + return null; +} + +// eslint-disable-next-line require-yield +export function* findPackageData(filepath: string): Handler { + return { + filepath, + directories: [], + pkg: null, + isPackage: false, + }; +} + +// eslint-disable-next-line require-yield +export function* findRelativeConfig( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + pkgData: FilePackageData, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + return { config: null, ignore: null }; +} + +// eslint-disable-next-line require-yield +export function* findRootConfig( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + dirname: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + return null; +} + +// eslint-disable-next-line require-yield +export function* loadConfig( + name: string, + dirname: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); +} + +// eslint-disable-next-line require-yield +export function* resolveShowConfigPath( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + dirname: string, +): Handler { + return null; +} + +export const ROOT_CONFIG_FILENAMES: string[] = []; + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function resolvePlugin(name: string, dirname: string): string | null { + return null; +} + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function resolvePreset(name: string, dirname: string): string | null { + return null; +} + +export function loadPlugin( + name: string, + dirname: string, +): Handler<{ + filepath: string; + value: unknown; +}> { + throw new Error( + `Cannot load plugin ${name} relative to ${dirname} in a browser`, + ); +} + +export function loadPreset( + name: string, + dirname: string, +): Handler<{ + filepath: string; + value: unknown; +}> { + throw new Error( + `Cannot load preset ${name} relative to ${dirname} in a browser`, + ); +} diff --git a/node_modules/@babel/core/src/config/files/index.ts b/node_modules/@babel/core/src/config/files/index.ts new file mode 100644 index 0000000..31e8560 --- /dev/null +++ b/node_modules/@babel/core/src/config/files/index.ts @@ -0,0 +1,30 @@ +type indexBrowserType = typeof import("./index-browser"); +type indexType = typeof import("./index"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of index-browser, since this file may be replaced at bundle time with index-browser. +({} as any as indexBrowserType as indexType); + +export { findPackageData } from "./package"; + +export { + findConfigUpwards, + findRelativeConfig, + findRootConfig, + loadConfig, + resolveShowConfigPath, + ROOT_CONFIG_FILENAMES, +} from "./configuration"; +export type { + ConfigFile, + IgnoreFile, + RelativeConfig, + FilePackageData, +} from "./types"; +export { loadPlugin, loadPreset } from "./plugins"; + +import gensync from "gensync"; +import * as plugins from "./plugins"; + +export const resolvePlugin = gensync(plugins.resolvePlugin).sync; +export const resolvePreset = gensync(plugins.resolvePreset).sync; diff --git a/node_modules/@babel/core/src/config/resolve-targets-browser.ts b/node_modules/@babel/core/src/config/resolve-targets-browser.ts new file mode 100644 index 0000000..60745dd --- /dev/null +++ b/node_modules/@babel/core/src/config/resolve-targets-browser.ts @@ -0,0 +1,40 @@ +import type { ValidatedOptions } from "./validation/options"; +import getTargets, { + type InputTargets, +} from "@babel/helper-compilation-targets"; + +import type { Targets } from "@babel/helper-compilation-targets"; + +export function resolveBrowserslistConfigFile( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + browserslistConfigFile: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + configFilePath: string, +): string | void { + return undefined; +} + +export function resolveTargets( + options: ValidatedOptions, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + root: string, +): Targets { + const optTargets = options.targets; + let targets: InputTargets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { browsers: optTargets }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = { ...optTargets, esmodules: "intersect" }; + } else { + // https://github.com/microsoft/TypeScript/issues/17002 + targets = optTargets as InputTargets; + } + } + + return getTargets(targets, { + ignoreBrowserslistConfig: true, + browserslistEnv: options.browserslistEnv, + }); +} diff --git a/node_modules/@babel/core/src/config/resolve-targets.ts b/node_modules/@babel/core/src/config/resolve-targets.ts new file mode 100644 index 0000000..a7d9a79 --- /dev/null +++ b/node_modules/@babel/core/src/config/resolve-targets.ts @@ -0,0 +1,56 @@ +type browserType = typeof import("./resolve-targets-browser"); +type nodeType = typeof import("./resolve-targets"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of index-browser, since this file may be replaced at bundle time with index-browser. +({} as any as browserType as nodeType); + +import type { ValidatedOptions } from "./validation/options"; +import path from "path"; +import getTargets, { + type InputTargets, +} from "@babel/helper-compilation-targets"; + +import type { Targets } from "@babel/helper-compilation-targets"; + +export function resolveBrowserslistConfigFile( + browserslistConfigFile: string, + configFileDir: string, +): string | undefined { + return path.resolve(configFileDir, browserslistConfigFile); +} + +export function resolveTargets( + options: ValidatedOptions, + root: string, +): Targets { + const optTargets = options.targets; + let targets: InputTargets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { browsers: optTargets }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = { ...optTargets, esmodules: "intersect" }; + } else { + // https://github.com/microsoft/TypeScript/issues/17002 + targets = optTargets as InputTargets; + } + } + + const { browserslistConfigFile } = options; + let configFile; + let ignoreBrowserslistConfig = false; + if (typeof browserslistConfigFile === "string") { + configFile = browserslistConfigFile; + } else { + ignoreBrowserslistConfig = browserslistConfigFile === false; + } + + return getTargets(targets, { + ignoreBrowserslistConfig, + configFile, + configPath: root, + browserslistEnv: options.browserslistEnv, + }); +} diff --git a/node_modules/@babel/core/src/transform-file-browser.ts b/node_modules/@babel/core/src/transform-file-browser.ts new file mode 100644 index 0000000..f316cb4 --- /dev/null +++ b/node_modules/@babel/core/src/transform-file-browser.ts @@ -0,0 +1,31 @@ +// duplicated from transform-file so we do not have to import anything here +type TransformFile = { + (filename: string, callback: (error: Error, file: null) => void): void; + ( + filename: string, + opts: any, + callback: (error: Error, file: null) => void, + ): void; +}; + +export const transformFile: TransformFile = function transformFile( + filename, + opts, + callback?: (error: Error, file: null) => void, +) { + if (typeof opts === "function") { + callback = opts; + } + + callback(new Error("Transforming files is not supported in browsers"), null); +}; + +export function transformFileSync(): never { + throw new Error("Transforming files is not supported in browsers"); +} + +export function transformFileAsync() { + return Promise.reject( + new Error("Transforming files is not supported in browsers"), + ); +} diff --git a/node_modules/@babel/core/src/transform-file.ts b/node_modules/@babel/core/src/transform-file.ts new file mode 100644 index 0000000..5701cf2 --- /dev/null +++ b/node_modules/@babel/core/src/transform-file.ts @@ -0,0 +1,41 @@ +import gensync, { type Handler } from "gensync"; + +import loadConfig from "./config"; +import type { InputOptions, ResolvedConfig } from "./config"; +import { run } from "./transformation"; +import type { FileResult, FileResultCallback } from "./transformation"; +import * as fs from "./gensync-utils/fs"; + +type transformFileBrowserType = typeof import("./transform-file-browser"); +type transformFileType = typeof import("./transform-file"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of transform-file-browser, since this file may be replaced at bundle time with +// transform-file-browser. +({} as any as transformFileBrowserType as transformFileType); + +type TransformFile = { + (filename: string, callback: FileResultCallback): void; + ( + filename: string, + opts: InputOptions | undefined | null, + callback: FileResultCallback, + ): void; +}; + +const transformFileRunner = gensync(function* ( + filename: string, + opts?: InputOptions, +): Handler { + const options = { ...opts, filename }; + + const config: ResolvedConfig | null = yield* loadConfig(options); + if (config === null) return null; + + const code = yield* fs.readFile(filename, "utf8"); + return yield* run(config, code); +}); + +export const transformFile = transformFileRunner.errback as TransformFile; +export const transformFileSync = transformFileRunner.sync; +export const transformFileAsync = transformFileRunner.async; diff --git a/node_modules/@babel/generator/LICENSE b/node_modules/@babel/generator/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/generator/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/generator/README.md b/node_modules/@babel/generator/README.md new file mode 100644 index 0000000..b760238 --- /dev/null +++ b/node_modules/@babel/generator/README.md @@ -0,0 +1,19 @@ +# @babel/generator + +> Turns an AST into code. + +See our website [@babel/generator](https://babeljs.io/docs/en/babel-generator) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20generator%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/generator +``` + +or using yarn: + +```sh +yarn add @babel/generator --dev +``` diff --git a/node_modules/@babel/generator/lib/buffer.js b/node_modules/@babel/generator/lib/buffer.js new file mode 100644 index 0000000..d9a230b --- /dev/null +++ b/node_modules/@babel/generator/lib/buffer.js @@ -0,0 +1,364 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function SourcePos() { + return { + identifierName: undefined, + line: undefined, + column: undefined, + filename: undefined + }; +} + +class Buffer { + constructor(map) { + this._map = null; + this._buf = ""; + this._str = ""; + this._appendCount = 0; + this._last = 0; + this._queue = []; + this._queueCursor = 0; + this._position = { + line: 1, + column: 0 + }; + this._sourcePosition = SourcePos(); + this._disallowedPop = { + identifierName: undefined, + line: undefined, + column: undefined, + filename: undefined, + objectReusable: true + }; + this._map = map; + + this._allocQueue(); + } + + _allocQueue() { + const queue = this._queue; + + for (let i = 0; i < 16; i++) { + queue.push({ + char: 0, + repeat: 1, + line: undefined, + column: undefined, + identifierName: undefined, + filename: "" + }); + } + } + + _pushQueue(char, repeat, line, column, identifierName, filename) { + const cursor = this._queueCursor; + + if (cursor === this._queue.length) { + this._allocQueue(); + } + + const item = this._queue[cursor]; + item.char = char; + item.repeat = repeat; + item.line = line; + item.column = column; + item.identifierName = identifierName; + item.filename = filename; + this._queueCursor++; + } + + _popQueue() { + if (this._queueCursor === 0) { + throw new Error("Cannot pop from empty queue"); + } + + return this._queue[--this._queueCursor]; + } + + get() { + this._flush(); + + const map = this._map; + const result = { + code: (this._buf + this._str).trimRight(), + decodedMap: map == null ? void 0 : map.getDecoded(), + + get map() { + const resultMap = map ? map.get() : null; + result.map = resultMap; + return resultMap; + }, + + set map(value) { + Object.defineProperty(result, "map", { + value, + writable: true + }); + }, + + get rawMappings() { + const mappings = map == null ? void 0 : map.getRawMappings(); + result.rawMappings = mappings; + return mappings; + }, + + set rawMappings(value) { + Object.defineProperty(result, "rawMappings", { + value, + writable: true + }); + } + + }; + return result; + } + + append(str, maybeNewline) { + this._flush(); + + this._append(str, this._sourcePosition, maybeNewline); + } + + appendChar(char) { + this._flush(); + + this._appendChar(char, 1, this._sourcePosition); + } + + queue(char) { + if (char === 10) { + while (this._queueCursor !== 0) { + const char = this._queue[this._queueCursor - 1].char; + + if (char !== 32 && char !== 9) { + break; + } + + this._queueCursor--; + } + } + + const sourcePosition = this._sourcePosition; + + this._pushQueue(char, 1, sourcePosition.line, sourcePosition.column, sourcePosition.identifierName, sourcePosition.filename); + } + + queueIndentation(char, repeat) { + this._pushQueue(char, repeat, undefined, undefined, undefined, undefined); + } + + _flush() { + const queueCursor = this._queueCursor; + const queue = this._queue; + + for (let i = 0; i < queueCursor; i++) { + const item = queue[i]; + + this._appendChar(item.char, item.repeat, item); + } + + this._queueCursor = 0; + } + + _appendChar(char, repeat, sourcePos) { + this._last = char; + this._str += repeat > 1 ? String.fromCharCode(char).repeat(repeat) : String.fromCharCode(char); + + if (char !== 10) { + this._mark(sourcePos.line, sourcePos.column, sourcePos.identifierName, sourcePos.filename); + + this._position.column += repeat; + } else { + this._position.line++; + this._position.column = 0; + } + } + + _append(str, sourcePos, maybeNewline) { + const len = str.length; + this._last = str.charCodeAt(len - 1); + + if (++this._appendCount > 4096) { + +this._str; + this._buf += this._str; + this._str = str; + this._appendCount = 0; + } else { + this._str += str; + } + + if (!maybeNewline && !this._map) { + this._position.column += len; + return; + } + + const { + column, + identifierName, + filename + } = sourcePos; + let line = sourcePos.line; + let i = str.indexOf("\n"); + let last = 0; + + if (i !== 0) { + this._mark(line, column, identifierName, filename); + } + + while (i !== -1) { + this._position.line++; + this._position.column = 0; + last = i + 1; + + if (last < str.length) { + this._mark(++line, 0, identifierName, filename); + } + + i = str.indexOf("\n", last); + } + + this._position.column += str.length - last; + } + + _mark(line, column, identifierName, filename) { + var _this$_map; + + (_this$_map = this._map) == null ? void 0 : _this$_map.mark(this._position, line, column, identifierName, filename); + } + + removeTrailingNewline() { + const queueCursor = this._queueCursor; + + if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 10) { + this._queueCursor--; + } + } + + removeLastSemicolon() { + const queueCursor = this._queueCursor; + + if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 59) { + this._queueCursor--; + } + } + + getLastChar() { + const queueCursor = this._queueCursor; + return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last; + } + + endsWithCharAndNewline() { + const queue = this._queue; + const queueCursor = this._queueCursor; + + if (queueCursor !== 0) { + const lastCp = queue[queueCursor - 1].char; + if (lastCp !== 10) return; + + if (queueCursor > 1) { + return queue[queueCursor - 2].char; + } else { + return this._last; + } + } + } + + hasContent() { + return this._queueCursor !== 0 || !!this._last; + } + + exactSource(loc, cb) { + if (!this._map) return cb(); + this.source("start", loc); + cb(); + this.source("end", loc); + + this._disallowPop("start", loc); + } + + source(prop, loc) { + if (!loc) return; + + this._normalizePosition(prop, loc, this._sourcePosition); + } + + withSource(prop, loc, cb) { + if (!this._map) return cb(); + const originalLine = this._sourcePosition.line; + const originalColumn = this._sourcePosition.column; + const originalFilename = this._sourcePosition.filename; + const originalIdentifierName = this._sourcePosition.identifierName; + this.source(prop, loc); + cb(); + + if (this._disallowedPop.objectReusable || this._disallowedPop.line !== originalLine || this._disallowedPop.column !== originalColumn || this._disallowedPop.filename !== originalFilename) { + this._sourcePosition.line = originalLine; + this._sourcePosition.column = originalColumn; + this._sourcePosition.filename = originalFilename; + this._sourcePosition.identifierName = originalIdentifierName; + this._disallowedPop.objectReusable = true; + } + } + + _disallowPop(prop, loc) { + if (!loc) return; + const disallowedPop = this._disallowedPop; + + this._normalizePosition(prop, loc, disallowedPop); + + disallowedPop.objectReusable = false; + } + + _normalizePosition(prop, loc, targetObj) { + const pos = loc[prop]; + targetObj.identifierName = prop === "start" && loc.identifierName || undefined; + + if (pos) { + targetObj.line = pos.line; + targetObj.column = pos.column; + targetObj.filename = loc.filename; + } else { + targetObj.line = null; + targetObj.column = null; + targetObj.filename = null; + } + } + + getCurrentColumn() { + const queue = this._queue; + let lastIndex = -1; + let len = 0; + + for (let i = 0; i < this._queueCursor; i++) { + const item = queue[i]; + + if (item.char === 10) { + lastIndex = i; + len += item.repeat; + } + } + + return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex; + } + + getCurrentLine() { + let count = 0; + const queue = this._queue; + + for (let i = 0; i < this._queueCursor; i++) { + if (queue[i].char === 10) { + count++; + } + } + + return this._position.line + count; + } + +} + +exports.default = Buffer; \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/base.js b/node_modules/@babel/generator/lib/generators/base.js new file mode 100644 index 0000000..21fef78 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/base.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BlockStatement = BlockStatement; +exports.Directive = Directive; +exports.DirectiveLiteral = DirectiveLiteral; +exports.File = File; +exports.InterpreterDirective = InterpreterDirective; +exports.Placeholder = Placeholder; +exports.Program = Program; + +function File(node) { + if (node.program) { + this.print(node.program.interpreter, node); + } + + this.print(node.program, node); +} + +function Program(node) { + this.printInnerComments(node, false); + this.printSequence(node.directives, node); + if (node.directives && node.directives.length) this.newline(); + this.printSequence(node.body, node); +} + +function BlockStatement(node) { + var _node$directives; + + this.tokenChar(123); + this.printInnerComments(node); + const hasDirectives = (_node$directives = node.directives) == null ? void 0 : _node$directives.length; + + if (node.body.length || hasDirectives) { + this.newline(); + this.printSequence(node.directives, node, { + indent: true + }); + if (hasDirectives) this.newline(); + this.printSequence(node.body, node, { + indent: true + }); + this.removeTrailingNewline(); + this.source("end", node.loc); + if (!this.endsWith(10)) this.newline(); + this.rightBrace(); + } else { + this.source("end", node.loc); + this.tokenChar(125); + } +} + +function Directive(node) { + this.print(node.value, node); + this.semicolon(); +} + +const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/; +const unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/; + +function DirectiveLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.token(raw); + return; + } + + const { + value + } = node; + + if (!unescapedDoubleQuoteRE.test(value)) { + this.token(`"${value}"`); + } else if (!unescapedSingleQuoteRE.test(value)) { + this.token(`'${value}'`); + } else { + throw new Error("Malformed AST: it is not possible to print a directive containing" + " both unescaped single and double quotes."); + } +} + +function InterpreterDirective(node) { + this.token(`#!${node.value}\n`, true); +} + +function Placeholder(node) { + this.token("%%"); + this.print(node.name); + this.token("%%"); + + if (node.expectedNode === "Statement") { + this.semicolon(); + } +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/classes.js b/node_modules/@babel/generator/lib/generators/classes.js new file mode 100644 index 0000000..a95b137 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/classes.js @@ -0,0 +1,215 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClassAccessorProperty = ClassAccessorProperty; +exports.ClassBody = ClassBody; +exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration; +exports.ClassMethod = ClassMethod; +exports.ClassPrivateMethod = ClassPrivateMethod; +exports.ClassPrivateProperty = ClassPrivateProperty; +exports.ClassProperty = ClassProperty; +exports.StaticBlock = StaticBlock; +exports._classMethodHead = _classMethodHead; + +var _t = require("@babel/types"); + +const { + isExportDefaultDeclaration, + isExportNamedDeclaration +} = _t; + +function ClassDeclaration(node, parent) { + { + if (!this.format.decoratorsBeforeExport || !isExportDefaultDeclaration(parent) && !isExportNamedDeclaration(parent)) { + this.printJoin(node.decorators, node); + } + } + + if (node.declare) { + this.word("declare"); + this.space(); + } + + if (node.abstract) { + this.word("abstract"); + this.space(); + } + + this.word("class"); + this.printInnerComments(node); + + if (node.id) { + this.space(); + this.print(node.id, node); + } + + this.print(node.typeParameters, node); + + if (node.superClass) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.superClass, node); + this.print(node.superTypeParameters, node); + } + + if (node.implements) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); + } + + this.space(); + this.print(node.body, node); +} + +function ClassBody(node) { + this.tokenChar(123); + this.printInnerComments(node); + + if (node.body.length === 0) { + this.tokenChar(125); + } else { + this.newline(); + this.indent(); + this.printSequence(node.body, node); + this.dedent(); + if (!this.endsWith(10)) this.newline(); + this.rightBrace(); + } +} + +function ClassProperty(node) { + this.printJoin(node.decorators, node); + this.source("end", node.key.loc); + this.tsPrintClassMemberModifiers(node); + + if (node.computed) { + this.tokenChar(91); + this.print(node.key, node); + this.tokenChar(93); + } else { + this._variance(node); + + this.print(node.key, node); + } + + if (node.optional) { + this.tokenChar(63); + } + + if (node.definite) { + this.tokenChar(33); + } + + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); +} + +function ClassAccessorProperty(node) { + this.printJoin(node.decorators, node); + this.source("end", node.key.loc); + this.tsPrintClassMemberModifiers(node); + this.word("accessor"); + this.printInnerComments(node); + this.space(); + + if (node.computed) { + this.tokenChar(91); + this.print(node.key, node); + this.tokenChar(93); + } else { + this._variance(node); + + this.print(node.key, node); + } + + if (node.optional) { + this.tokenChar(63); + } + + if (node.definite) { + this.tokenChar(33); + } + + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); +} + +function ClassPrivateProperty(node) { + this.printJoin(node.decorators, node); + + if (node.static) { + this.word("static"); + this.space(); + } + + this.print(node.key, node); + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); +} + +function ClassMethod(node) { + this._classMethodHead(node); + + this.space(); + this.print(node.body, node); +} + +function ClassPrivateMethod(node) { + this._classMethodHead(node); + + this.space(); + this.print(node.body, node); +} + +function _classMethodHead(node) { + this.printJoin(node.decorators, node); + this.source("end", node.key.loc); + this.tsPrintClassMemberModifiers(node); + + this._methodHead(node); +} + +function StaticBlock(node) { + this.word("static"); + this.space(); + this.tokenChar(123); + + if (node.body.length === 0) { + this.tokenChar(125); + } else { + this.newline(); + this.printSequence(node.body, node, { + indent: true + }); + this.rightBrace(); + } +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/expressions.js b/node_modules/@babel/generator/lib/generators/expressions.js new file mode 100644 index 0000000..10125d1 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/expressions.js @@ -0,0 +1,352 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression; +exports.AssignmentPattern = AssignmentPattern; +exports.AwaitExpression = AwaitExpression; +exports.BindExpression = BindExpression; +exports.CallExpression = CallExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.Decorator = Decorator; +exports.DoExpression = DoExpression; +exports.EmptyStatement = EmptyStatement; +exports.ExpressionStatement = ExpressionStatement; +exports.Import = Import; +exports.MemberExpression = MemberExpression; +exports.MetaProperty = MetaProperty; +exports.ModuleExpression = ModuleExpression; +exports.NewExpression = NewExpression; +exports.OptionalCallExpression = OptionalCallExpression; +exports.OptionalMemberExpression = OptionalMemberExpression; +exports.ParenthesizedExpression = ParenthesizedExpression; +exports.PrivateName = PrivateName; +exports.SequenceExpression = SequenceExpression; +exports.Super = Super; +exports.ThisExpression = ThisExpression; +exports.UnaryExpression = UnaryExpression; +exports.UpdateExpression = UpdateExpression; +exports.V8IntrinsicIdentifier = V8IntrinsicIdentifier; +exports.YieldExpression = YieldExpression; + +var _t = require("@babel/types"); + +var n = require("../node"); + +const { + isCallExpression, + isLiteral, + isMemberExpression, + isNewExpression +} = _t; + +function UnaryExpression(node) { + if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof" || node.operator === "throw") { + this.word(node.operator); + this.space(); + } else { + this.token(node.operator); + } + + this.print(node.argument, node); +} + +function DoExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } + + this.word("do"); + this.space(); + this.print(node.body, node); +} + +function ParenthesizedExpression(node) { + this.tokenChar(40); + this.print(node.expression, node); + this.tokenChar(41); +} + +function UpdateExpression(node) { + if (node.prefix) { + this.token(node.operator); + this.print(node.argument, node); + } else { + this.printTerminatorless(node.argument, node, true); + this.token(node.operator); + } +} + +function ConditionalExpression(node) { + this.print(node.test, node); + this.space(); + this.tokenChar(63); + this.space(); + this.print(node.consequent, node); + this.space(); + this.tokenChar(58); + this.space(); + this.print(node.alternate, node); +} + +function NewExpression(node, parent) { + this.word("new"); + this.space(); + this.print(node.callee, node); + + if (this.format.minified && node.arguments.length === 0 && !node.optional && !isCallExpression(parent, { + callee: node + }) && !isMemberExpression(parent) && !isNewExpression(parent)) { + return; + } + + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + + if (node.optional) { + this.token("?."); + } + + this.tokenChar(40); + this.printList(node.arguments, node); + this.tokenChar(41); +} + +function SequenceExpression(node) { + this.printList(node.expressions, node); +} + +function ThisExpression() { + this.word("this"); +} + +function Super() { + this.word("super"); +} + +function isDecoratorMemberExpression(node) { + switch (node.type) { + case "Identifier": + return true; + + case "MemberExpression": + return !node.computed && node.property.type === "Identifier" && isDecoratorMemberExpression(node.object); + + default: + return false; + } +} + +function shouldParenthesizeDecoratorExpression(node) { + if (node.type === "CallExpression") { + node = node.callee; + } + + if (node.type === "ParenthesizedExpression") { + return false; + } + + return !isDecoratorMemberExpression(node); +} + +function Decorator(node) { + this.tokenChar(64); + const { + expression + } = node; + + if (shouldParenthesizeDecoratorExpression(expression)) { + this.tokenChar(40); + this.print(expression, node); + this.tokenChar(41); + } else { + this.print(expression, node); + } + + this.newline(); +} + +function OptionalMemberExpression(node) { + this.print(node.object, node); + + if (!node.computed && isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + + let computed = node.computed; + + if (isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } + + if (node.optional) { + this.token("?."); + } + + if (computed) { + this.tokenChar(91); + this.print(node.property, node); + this.tokenChar(93); + } else { + if (!node.optional) { + this.tokenChar(46); + } + + this.print(node.property, node); + } +} + +function OptionalCallExpression(node) { + this.print(node.callee, node); + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + + if (node.optional) { + this.token("?."); + } + + this.tokenChar(40); + this.printList(node.arguments, node); + this.tokenChar(41); +} + +function CallExpression(node) { + this.print(node.callee, node); + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + this.tokenChar(40); + this.printList(node.arguments, node); + this.tokenChar(41); +} + +function Import() { + this.word("import"); +} + +function AwaitExpression(node) { + this.word("await"); + + if (node.argument) { + this.space(); + this.printTerminatorless(node.argument, node, false); + } +} + +function YieldExpression(node) { + this.word("yield"); + + if (node.delegate) { + this.tokenChar(42); + } + + if (node.argument) { + this.space(); + this.printTerminatorless(node.argument, node, false); + } +} + +function EmptyStatement() { + this.semicolon(true); +} + +function ExpressionStatement(node) { + this.print(node.expression, node); + this.semicolon(); +} + +function AssignmentPattern(node) { + this.print(node.left, node); + if (node.left.optional) this.tokenChar(63); + this.print(node.left.typeAnnotation, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.right, node); +} + +function AssignmentExpression(node, parent) { + const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); + + if (parens) { + this.tokenChar(40); + } + + this.print(node.left, node); + this.space(); + + if (node.operator === "in" || node.operator === "instanceof") { + this.word(node.operator); + } else { + this.token(node.operator); + } + + this.space(); + this.print(node.right, node); + + if (parens) { + this.tokenChar(41); + } +} + +function BindExpression(node) { + this.print(node.object, node); + this.token("::"); + this.print(node.callee, node); +} + +function MemberExpression(node) { + this.print(node.object, node); + + if (!node.computed && isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + + let computed = node.computed; + + if (isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } + + if (computed) { + this.tokenChar(91); + this.print(node.property, node); + this.tokenChar(93); + } else { + this.tokenChar(46); + this.print(node.property, node); + } +} + +function MetaProperty(node) { + this.print(node.meta, node); + this.tokenChar(46); + this.print(node.property, node); +} + +function PrivateName(node) { + this.tokenChar(35); + this.print(node.id, node); +} + +function V8IntrinsicIdentifier(node) { + this.tokenChar(37); + this.word(node.name); +} + +function ModuleExpression(node) { + this.word("module"); + this.space(); + this.tokenChar(123); + + if (node.body.body.length === 0) { + this.tokenChar(125); + } else { + this.newline(); + this.printSequence(node.body.body, node, { + indent: true + }); + this.rightBrace(); + } +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/flow.js b/node_modules/@babel/generator/lib/generators/flow.js new file mode 100644 index 0000000..ffdb1d0 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/flow.js @@ -0,0 +1,795 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AnyTypeAnnotation = AnyTypeAnnotation; +exports.ArrayTypeAnnotation = ArrayTypeAnnotation; +exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; +exports.BooleanTypeAnnotation = BooleanTypeAnnotation; +exports.DeclareClass = DeclareClass; +exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; +exports.DeclareExportDeclaration = DeclareExportDeclaration; +exports.DeclareFunction = DeclareFunction; +exports.DeclareInterface = DeclareInterface; +exports.DeclareModule = DeclareModule; +exports.DeclareModuleExports = DeclareModuleExports; +exports.DeclareOpaqueType = DeclareOpaqueType; +exports.DeclareTypeAlias = DeclareTypeAlias; +exports.DeclareVariable = DeclareVariable; +exports.DeclaredPredicate = DeclaredPredicate; +exports.EmptyTypeAnnotation = EmptyTypeAnnotation; +exports.EnumBooleanBody = EnumBooleanBody; +exports.EnumBooleanMember = EnumBooleanMember; +exports.EnumDeclaration = EnumDeclaration; +exports.EnumDefaultedMember = EnumDefaultedMember; +exports.EnumNumberBody = EnumNumberBody; +exports.EnumNumberMember = EnumNumberMember; +exports.EnumStringBody = EnumStringBody; +exports.EnumStringMember = EnumStringMember; +exports.EnumSymbolBody = EnumSymbolBody; +exports.ExistsTypeAnnotation = ExistsTypeAnnotation; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.FunctionTypeParam = FunctionTypeParam; +exports.IndexedAccessType = IndexedAccessType; +exports.InferredPredicate = InferredPredicate; +exports.InterfaceDeclaration = InterfaceDeclaration; +exports.GenericTypeAnnotation = exports.ClassImplements = exports.InterfaceExtends = InterfaceExtends; +exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation; +exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; +exports.MixedTypeAnnotation = MixedTypeAnnotation; +exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _types2.NumericLiteral; + } +}); +exports.NumberTypeAnnotation = NumberTypeAnnotation; +exports.ObjectTypeAnnotation = ObjectTypeAnnotation; +exports.ObjectTypeCallProperty = ObjectTypeCallProperty; +exports.ObjectTypeIndexer = ObjectTypeIndexer; +exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot; +exports.ObjectTypeProperty = ObjectTypeProperty; +exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; +exports.OpaqueType = OpaqueType; +exports.OptionalIndexedAccessType = OptionalIndexedAccessType; +exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; +Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _types2.StringLiteral; + } +}); +exports.StringTypeAnnotation = StringTypeAnnotation; +exports.SymbolTypeAnnotation = SymbolTypeAnnotation; +exports.ThisTypeAnnotation = ThisTypeAnnotation; +exports.TupleTypeAnnotation = TupleTypeAnnotation; +exports.TypeAlias = TypeAlias; +exports.TypeAnnotation = TypeAnnotation; +exports.TypeCastExpression = TypeCastExpression; +exports.TypeParameter = TypeParameter; +exports.TypeParameterDeclaration = exports.TypeParameterInstantiation = TypeParameterInstantiation; +exports.TypeofTypeAnnotation = TypeofTypeAnnotation; +exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.Variance = Variance; +exports.VoidTypeAnnotation = VoidTypeAnnotation; +exports._interfaceish = _interfaceish; +exports._variance = _variance; + +var _t = require("@babel/types"); + +var _modules = require("./modules"); + +var _types2 = require("./types"); + +const { + isDeclareExportDeclaration, + isStatement +} = _t; + +function AnyTypeAnnotation() { + this.word("any"); +} + +function ArrayTypeAnnotation(node) { + this.print(node.elementType, node, true); + this.tokenChar(91); + this.tokenChar(93); +} + +function BooleanTypeAnnotation() { + this.word("boolean"); +} + +function BooleanLiteralTypeAnnotation(node) { + this.word(node.value ? "true" : "false"); +} + +function NullLiteralTypeAnnotation() { + this.word("null"); +} + +function DeclareClass(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.word("class"); + this.space(); + + this._interfaceish(node); +} + +function DeclareFunction(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.word("function"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation.typeAnnotation, node); + + if (node.predicate) { + this.space(); + this.print(node.predicate, node); + } + + this.semicolon(); +} + +function InferredPredicate() { + this.tokenChar(37); + this.word("checks"); +} + +function DeclaredPredicate(node) { + this.tokenChar(37); + this.word("checks"); + this.tokenChar(40); + this.print(node.value, node); + this.tokenChar(41); +} + +function DeclareInterface(node) { + this.word("declare"); + this.space(); + this.InterfaceDeclaration(node); +} + +function DeclareModule(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.space(); + this.print(node.id, node); + this.space(); + this.print(node.body, node); +} + +function DeclareModuleExports(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.tokenChar(46); + this.word("exports"); + this.print(node.typeAnnotation, node); +} + +function DeclareTypeAlias(node) { + this.word("declare"); + this.space(); + this.TypeAlias(node); +} + +function DeclareOpaqueType(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.OpaqueType(node); +} + +function DeclareVariable(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.word("var"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation, node); + this.semicolon(); +} + +function DeclareExportDeclaration(node) { + this.word("declare"); + this.space(); + this.word("export"); + this.space(); + + if (node.default) { + this.word("default"); + this.space(); + } + + FlowExportDeclaration.call(this, node); +} + +function DeclareExportAllDeclaration(node) { + this.word("declare"); + this.space(); + + _modules.ExportAllDeclaration.call(this, node); +} + +function EnumDeclaration(node) { + const { + id, + body + } = node; + this.word("enum"); + this.space(); + this.print(id, node); + this.print(body, node); +} + +function enumExplicitType(context, name, hasExplicitType) { + if (hasExplicitType) { + context.space(); + context.word("of"); + context.space(); + context.word(name); + } + + context.space(); +} + +function enumBody(context, node) { + const { + members + } = node; + context.token("{"); + context.indent(); + context.newline(); + + for (const member of members) { + context.print(member, node); + context.newline(); + } + + if (node.hasUnknownMembers) { + context.token("..."); + context.newline(); + } + + context.dedent(); + context.token("}"); +} + +function EnumBooleanBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "boolean", explicitType); + enumBody(this, node); +} + +function EnumNumberBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "number", explicitType); + enumBody(this, node); +} + +function EnumStringBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "string", explicitType); + enumBody(this, node); +} + +function EnumSymbolBody(node) { + enumExplicitType(this, "symbol", true); + enumBody(this, node); +} + +function EnumDefaultedMember(node) { + const { + id + } = node; + this.print(id, node); + this.tokenChar(44); +} + +function enumInitializedMember(context, node) { + const { + id, + init + } = node; + context.print(id, node); + context.space(); + context.token("="); + context.space(); + context.print(init, node); + context.token(","); +} + +function EnumBooleanMember(node) { + enumInitializedMember(this, node); +} + +function EnumNumberMember(node) { + enumInitializedMember(this, node); +} + +function EnumStringMember(node) { + enumInitializedMember(this, node); +} + +function FlowExportDeclaration(node) { + if (node.declaration) { + const declar = node.declaration; + this.print(declar, node); + if (!isStatement(declar)) this.semicolon(); + } else { + this.tokenChar(123); + + if (node.specifiers.length) { + this.space(); + this.printList(node.specifiers, node); + this.space(); + } + + this.tokenChar(125); + + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + } + + this.semicolon(); + } +} + +function ExistsTypeAnnotation() { + this.tokenChar(42); +} + +function FunctionTypeAnnotation(node, parent) { + this.print(node.typeParameters, node); + this.tokenChar(40); + + if (node.this) { + this.word("this"); + this.tokenChar(58); + this.space(); + this.print(node.this.typeAnnotation, node); + + if (node.params.length || node.rest) { + this.tokenChar(44); + this.space(); + } + } + + this.printList(node.params, node); + + if (node.rest) { + if (node.params.length) { + this.tokenChar(44); + this.space(); + } + + this.token("..."); + this.print(node.rest, node); + } + + this.tokenChar(41); + + if (parent && (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction" || parent.type === "ObjectTypeProperty" && parent.method)) { + this.tokenChar(58); + } else { + this.space(); + this.token("=>"); + } + + this.space(); + this.print(node.returnType, node); +} + +function FunctionTypeParam(node) { + this.print(node.name, node); + if (node.optional) this.tokenChar(63); + + if (node.name) { + this.tokenChar(58); + this.space(); + } + + this.print(node.typeAnnotation, node); +} + +function InterfaceExtends(node) { + this.print(node.id, node); + this.print(node.typeParameters, node, true); +} + +function _interfaceish(node) { + var _node$extends; + + this.print(node.id, node); + this.print(node.typeParameters, node); + + if ((_node$extends = node.extends) != null && _node$extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); + } + + if (node.mixins && node.mixins.length) { + this.space(); + this.word("mixins"); + this.space(); + this.printList(node.mixins, node); + } + + if (node.implements && node.implements.length) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); + } + + this.space(); + this.print(node.body, node); +} + +function _variance(node) { + if (node.variance) { + if (node.variance.kind === "plus") { + this.tokenChar(43); + } else if (node.variance.kind === "minus") { + this.tokenChar(45); + } + } +} + +function InterfaceDeclaration(node) { + this.word("interface"); + this.space(); + + this._interfaceish(node); +} + +function andSeparator() { + this.space(); + this.tokenChar(38); + this.space(); +} + +function InterfaceTypeAnnotation(node) { + this.word("interface"); + + if (node.extends && node.extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); + } + + this.space(); + this.print(node.body, node); +} + +function IntersectionTypeAnnotation(node) { + this.printJoin(node.types, node, { + separator: andSeparator + }); +} + +function MixedTypeAnnotation() { + this.word("mixed"); +} + +function EmptyTypeAnnotation() { + this.word("empty"); +} + +function NullableTypeAnnotation(node) { + this.tokenChar(63); + this.print(node.typeAnnotation, node); +} + +function NumberTypeAnnotation() { + this.word("number"); +} + +function StringTypeAnnotation() { + this.word("string"); +} + +function ThisTypeAnnotation() { + this.word("this"); +} + +function TupleTypeAnnotation(node) { + this.tokenChar(91); + this.printList(node.types, node); + this.tokenChar(93); +} + +function TypeofTypeAnnotation(node) { + this.word("typeof"); + this.space(); + this.print(node.argument, node); +} + +function TypeAlias(node) { + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.right, node); + this.semicolon(); +} + +function TypeAnnotation(node) { + this.tokenChar(58); + this.space(); + if (node.optional) this.tokenChar(63); + this.print(node.typeAnnotation, node); +} + +function TypeParameterInstantiation(node) { + this.tokenChar(60); + this.printList(node.params, node, {}); + this.tokenChar(62); +} + +function TypeParameter(node) { + this._variance(node); + + this.word(node.name); + + if (node.bound) { + this.print(node.bound, node); + } + + if (node.default) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.default, node); + } +} + +function OpaqueType(node) { + this.word("opaque"); + this.space(); + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); + + if (node.supertype) { + this.tokenChar(58); + this.space(); + this.print(node.supertype, node); + } + + if (node.impltype) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.impltype, node); + } + + this.semicolon(); +} + +function ObjectTypeAnnotation(node) { + if (node.exact) { + this.token("{|"); + } else { + this.tokenChar(123); + } + + const props = [...node.properties, ...(node.callProperties || []), ...(node.indexers || []), ...(node.internalSlots || [])]; + + if (props.length) { + this.space(); + this.printJoin(props, node, { + addNewlines(leading) { + if (leading && !props[0]) return 1; + }, + + indent: true, + statement: true, + iterator: () => { + if (props.length !== 1 || node.inexact) { + this.tokenChar(44); + this.space(); + } + } + }); + this.space(); + } + + if (node.inexact) { + this.indent(); + this.token("..."); + + if (props.length) { + this.newline(); + } + + this.dedent(); + } + + if (node.exact) { + this.token("|}"); + } else { + this.tokenChar(125); + } +} + +function ObjectTypeInternalSlot(node) { + if (node.static) { + this.word("static"); + this.space(); + } + + this.tokenChar(91); + this.tokenChar(91); + this.print(node.id, node); + this.tokenChar(93); + this.tokenChar(93); + if (node.optional) this.tokenChar(63); + + if (!node.method) { + this.tokenChar(58); + this.space(); + } + + this.print(node.value, node); +} + +function ObjectTypeCallProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + + this.print(node.value, node); +} + +function ObjectTypeIndexer(node) { + if (node.static) { + this.word("static"); + this.space(); + } + + this._variance(node); + + this.tokenChar(91); + + if (node.id) { + this.print(node.id, node); + this.tokenChar(58); + this.space(); + } + + this.print(node.key, node); + this.tokenChar(93); + this.tokenChar(58); + this.space(); + this.print(node.value, node); +} + +function ObjectTypeProperty(node) { + if (node.proto) { + this.word("proto"); + this.space(); + } + + if (node.static) { + this.word("static"); + this.space(); + } + + if (node.kind === "get" || node.kind === "set") { + this.word(node.kind); + this.space(); + } + + this._variance(node); + + this.print(node.key, node); + if (node.optional) this.tokenChar(63); + + if (!node.method) { + this.tokenChar(58); + this.space(); + } + + this.print(node.value, node); +} + +function ObjectTypeSpreadProperty(node) { + this.token("..."); + this.print(node.argument, node); +} + +function QualifiedTypeIdentifier(node) { + this.print(node.qualification, node); + this.tokenChar(46); + this.print(node.id, node); +} + +function SymbolTypeAnnotation() { + this.word("symbol"); +} + +function orSeparator() { + this.space(); + this.tokenChar(124); + this.space(); +} + +function UnionTypeAnnotation(node) { + this.printJoin(node.types, node, { + separator: orSeparator + }); +} + +function TypeCastExpression(node) { + this.tokenChar(40); + this.print(node.expression, node); + this.print(node.typeAnnotation, node); + this.tokenChar(41); +} + +function Variance(node) { + if (node.kind === "plus") { + this.tokenChar(43); + } else { + this.tokenChar(45); + } +} + +function VoidTypeAnnotation() { + this.word("void"); +} + +function IndexedAccessType(node) { + this.print(node.objectType, node, true); + this.tokenChar(91); + this.print(node.indexType, node); + this.tokenChar(93); +} + +function OptionalIndexedAccessType(node) { + this.print(node.objectType, node); + + if (node.optional) { + this.token("?."); + } + + this.tokenChar(91); + this.print(node.indexType, node); + this.tokenChar(93); +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/index.js b/node_modules/@babel/generator/lib/generators/index.js new file mode 100644 index 0000000..8820db0 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/index.js @@ -0,0 +1,148 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _templateLiterals = require("./template-literals"); + +Object.keys(_templateLiterals).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _templateLiterals[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _templateLiterals[key]; + } + }); +}); + +var _expressions = require("./expressions"); + +Object.keys(_expressions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _expressions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _expressions[key]; + } + }); +}); + +var _statements = require("./statements"); + +Object.keys(_statements).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _statements[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _statements[key]; + } + }); +}); + +var _classes = require("./classes"); + +Object.keys(_classes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _classes[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _classes[key]; + } + }); +}); + +var _methods = require("./methods"); + +Object.keys(_methods).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _methods[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _methods[key]; + } + }); +}); + +var _modules = require("./modules"); + +Object.keys(_modules).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _modules[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _modules[key]; + } + }); +}); + +var _types = require("./types"); + +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + } + }); +}); + +var _flow = require("./flow"); + +Object.keys(_flow).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _flow[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _flow[key]; + } + }); +}); + +var _base = require("./base"); + +Object.keys(_base).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _base[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _base[key]; + } + }); +}); + +var _jsx = require("./jsx"); + +Object.keys(_jsx).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _jsx[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _jsx[key]; + } + }); +}); + +var _typescript = require("./typescript"); + +Object.keys(_typescript).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _typescript[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _typescript[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/jsx.js b/node_modules/@babel/generator/lib/generators/jsx.js new file mode 100644 index 0000000..c7932f8 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/jsx.js @@ -0,0 +1,145 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.JSXAttribute = JSXAttribute; +exports.JSXClosingElement = JSXClosingElement; +exports.JSXClosingFragment = JSXClosingFragment; +exports.JSXElement = JSXElement; +exports.JSXEmptyExpression = JSXEmptyExpression; +exports.JSXExpressionContainer = JSXExpressionContainer; +exports.JSXFragment = JSXFragment; +exports.JSXIdentifier = JSXIdentifier; +exports.JSXMemberExpression = JSXMemberExpression; +exports.JSXNamespacedName = JSXNamespacedName; +exports.JSXOpeningElement = JSXOpeningElement; +exports.JSXOpeningFragment = JSXOpeningFragment; +exports.JSXSpreadAttribute = JSXSpreadAttribute; +exports.JSXSpreadChild = JSXSpreadChild; +exports.JSXText = JSXText; + +function JSXAttribute(node) { + this.print(node.name, node); + + if (node.value) { + this.tokenChar(61); + this.print(node.value, node); + } +} + +function JSXIdentifier(node) { + this.word(node.name); +} + +function JSXNamespacedName(node) { + this.print(node.namespace, node); + this.tokenChar(58); + this.print(node.name, node); +} + +function JSXMemberExpression(node) { + this.print(node.object, node); + this.tokenChar(46); + this.print(node.property, node); +} + +function JSXSpreadAttribute(node) { + this.tokenChar(123); + this.token("..."); + this.print(node.argument, node); + this.tokenChar(125); +} + +function JSXExpressionContainer(node) { + this.tokenChar(123); + this.print(node.expression, node); + this.tokenChar(125); +} + +function JSXSpreadChild(node) { + this.tokenChar(123); + this.token("..."); + this.print(node.expression, node); + this.tokenChar(125); +} + +function JSXText(node) { + const raw = this.getPossibleRaw(node); + + if (raw !== undefined) { + this.token(raw, true); + } else { + this.token(node.value, true); + } +} + +function JSXElement(node) { + const open = node.openingElement; + this.print(open, node); + if (open.selfClosing) return; + this.indent(); + + for (const child of node.children) { + this.print(child, node); + } + + this.dedent(); + this.print(node.closingElement, node); +} + +function spaceSeparator() { + this.space(); +} + +function JSXOpeningElement(node) { + this.tokenChar(60); + this.print(node.name, node); + this.print(node.typeParameters, node); + + if (node.attributes.length > 0) { + this.space(); + this.printJoin(node.attributes, node, { + separator: spaceSeparator + }); + } + + if (node.selfClosing) { + this.space(); + this.token("/>"); + } else { + this.tokenChar(62); + } +} + +function JSXClosingElement(node) { + this.token(""); + this.space(); + this.print(node.body, node); +} + +function hasTypesOrComments(node, param) { + var _param$leadingComment, _param$trailingCommen; + + return !!(node.typeParameters || node.returnType || node.predicate || param.typeAnnotation || param.optional || (_param$leadingComment = param.leadingComments) != null && _param$leadingComment.length || (_param$trailingCommen = param.trailingComments) != null && _param$trailingCommen.length); +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/modules.js b/node_modules/@babel/generator/lib/generators/modules.js new file mode 100644 index 0000000..a61d421 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/modules.js @@ -0,0 +1,245 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExportAllDeclaration = ExportAllDeclaration; +exports.ExportDefaultDeclaration = ExportDefaultDeclaration; +exports.ExportDefaultSpecifier = ExportDefaultSpecifier; +exports.ExportNamedDeclaration = ExportNamedDeclaration; +exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; +exports.ExportSpecifier = ExportSpecifier; +exports.ImportAttribute = ImportAttribute; +exports.ImportDeclaration = ImportDeclaration; +exports.ImportDefaultSpecifier = ImportDefaultSpecifier; +exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; +exports.ImportSpecifier = ImportSpecifier; + +var _t = require("@babel/types"); + +const { + isClassDeclaration, + isExportDefaultSpecifier, + isExportNamespaceSpecifier, + isImportDefaultSpecifier, + isImportNamespaceSpecifier, + isStatement +} = _t; + +function ImportSpecifier(node) { + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } + + this.print(node.imported, node); + + if (node.local && node.local.name !== node.imported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); + } +} + +function ImportDefaultSpecifier(node) { + this.print(node.local, node); +} + +function ExportDefaultSpecifier(node) { + this.print(node.exported, node); +} + +function ExportSpecifier(node) { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + this.print(node.local, node); + + if (node.exported && node.local.name !== node.exported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } +} + +function ExportNamespaceSpecifier(node) { + this.tokenChar(42); + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); +} + +function ExportAllDeclaration(node) { + this.word("export"); + this.space(); + + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + this.tokenChar(42); + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.printAssertions(node); + this.semicolon(); +} + +function ExportNamedDeclaration(node) { + { + if (this.format.decoratorsBeforeExport && isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); + } + } + this.word("export"); + this.space(); + + if (node.declaration) { + const declar = node.declaration; + this.print(declar, node); + if (!isStatement(declar)) this.semicolon(); + } else { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + const specifiers = node.specifiers.slice(0); + let hasSpecial = false; + + for (;;) { + const first = specifiers[0]; + + if (isExportDefaultSpecifier(first) || isExportNamespaceSpecifier(first)) { + hasSpecial = true; + this.print(specifiers.shift(), node); + + if (specifiers.length) { + this.tokenChar(44); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length || !specifiers.length && !hasSpecial) { + this.tokenChar(123); + + if (specifiers.length) { + this.space(); + this.printList(specifiers, node); + this.space(); + } + + this.tokenChar(125); + } + + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.printAssertions(node); + } + + this.semicolon(); + } +} + +function ExportDefaultDeclaration(node) { + { + if (this.format.decoratorsBeforeExport && isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); + } + } + this.word("export"); + this.space(); + this.word("default"); + this.space(); + const declar = node.declaration; + this.print(declar, node); + if (!isStatement(declar)) this.semicolon(); +} + +function ImportDeclaration(node) { + this.word("import"); + this.space(); + const isTypeKind = node.importKind === "type" || node.importKind === "typeof"; + + if (isTypeKind) { + this.word(node.importKind); + this.space(); + } + + const specifiers = node.specifiers.slice(0); + const hasSpecifiers = !!specifiers.length; + + while (hasSpecifiers) { + const first = specifiers[0]; + + if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) { + this.print(specifiers.shift(), node); + + if (specifiers.length) { + this.tokenChar(44); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length) { + this.tokenChar(123); + this.space(); + this.printList(specifiers, node); + this.space(); + this.tokenChar(125); + } else if (isTypeKind && !hasSpecifiers) { + this.tokenChar(123); + this.tokenChar(125); + } + + if (hasSpecifiers || isTypeKind) { + this.space(); + this.word("from"); + this.space(); + } + + this.print(node.source, node); + this.printAssertions(node); + { + var _node$attributes; + + if ((_node$attributes = node.attributes) != null && _node$attributes.length) { + this.space(); + this.word("with"); + this.space(); + this.printList(node.attributes, node); + } + } + this.semicolon(); +} + +function ImportAttribute(node) { + this.print(node.key); + this.tokenChar(58); + this.space(); + this.print(node.value); +} + +function ImportNamespaceSpecifier(node) { + this.tokenChar(42); + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/statements.js b/node_modules/@babel/generator/lib/generators/statements.js new file mode 100644 index 0000000..33de998 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/statements.js @@ -0,0 +1,340 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BreakStatement = BreakStatement; +exports.CatchClause = CatchClause; +exports.ContinueStatement = ContinueStatement; +exports.DebuggerStatement = DebuggerStatement; +exports.DoWhileStatement = DoWhileStatement; +exports.ForOfStatement = exports.ForInStatement = void 0; +exports.ForStatement = ForStatement; +exports.IfStatement = IfStatement; +exports.LabeledStatement = LabeledStatement; +exports.ReturnStatement = ReturnStatement; +exports.SwitchCase = SwitchCase; +exports.SwitchStatement = SwitchStatement; +exports.ThrowStatement = ThrowStatement; +exports.TryStatement = TryStatement; +exports.VariableDeclaration = VariableDeclaration; +exports.VariableDeclarator = VariableDeclarator; +exports.WhileStatement = WhileStatement; +exports.WithStatement = WithStatement; + +var _t = require("@babel/types"); + +const { + isFor, + isForStatement, + isIfStatement, + isStatement +} = _t; + +function WithStatement(node) { + this.word("with"); + this.space(); + this.tokenChar(40); + this.print(node.object, node); + this.tokenChar(41); + this.printBlock(node); +} + +function IfStatement(node) { + this.word("if"); + this.space(); + this.tokenChar(40); + this.print(node.test, node); + this.tokenChar(41); + this.space(); + const needsBlock = node.alternate && isIfStatement(getLastStatement(node.consequent)); + + if (needsBlock) { + this.tokenChar(123); + this.newline(); + this.indent(); + } + + this.printAndIndentOnComments(node.consequent, node); + + if (needsBlock) { + this.dedent(); + this.newline(); + this.tokenChar(125); + } + + if (node.alternate) { + if (this.endsWith(125)) this.space(); + this.word("else"); + this.space(); + this.printAndIndentOnComments(node.alternate, node); + } +} + +function getLastStatement(statement) { + const { + body + } = statement; + + if (isStatement(body) === false) { + return statement; + } + + return getLastStatement(body); +} + +function ForStatement(node) { + this.word("for"); + this.space(); + this.tokenChar(40); + this.inForStatementInitCounter++; + this.print(node.init, node); + this.inForStatementInitCounter--; + this.tokenChar(59); + + if (node.test) { + this.space(); + this.print(node.test, node); + } + + this.tokenChar(59); + + if (node.update) { + this.space(); + this.print(node.update, node); + } + + this.tokenChar(41); + this.printBlock(node); +} + +function WhileStatement(node) { + this.word("while"); + this.space(); + this.tokenChar(40); + this.print(node.test, node); + this.tokenChar(41); + this.printBlock(node); +} + +function ForXStatement(node) { + this.word("for"); + this.space(); + const isForOf = node.type === "ForOfStatement"; + + if (isForOf && node.await) { + this.word("await"); + this.space(); + } + + this.tokenChar(40); + this.print(node.left, node); + this.space(); + this.word(isForOf ? "of" : "in"); + this.space(); + this.print(node.right, node); + this.tokenChar(41); + this.printBlock(node); +} + +const ForInStatement = ForXStatement; +exports.ForInStatement = ForInStatement; +const ForOfStatement = ForXStatement; +exports.ForOfStatement = ForOfStatement; + +function DoWhileStatement(node) { + this.word("do"); + this.space(); + this.print(node.body, node); + this.space(); + this.word("while"); + this.space(); + this.tokenChar(40); + this.print(node.test, node); + this.tokenChar(41); + this.semicolon(); +} + +function printStatementAfterKeyword(printer, node, parent, isLabel) { + if (node) { + printer.space(); + printer.printTerminatorless(node, parent, isLabel); + } + + printer.semicolon(); +} + +function BreakStatement(node) { + this.word("break"); + printStatementAfterKeyword(this, node.label, node, true); +} + +function ContinueStatement(node) { + this.word("continue"); + printStatementAfterKeyword(this, node.label, node, true); +} + +function ReturnStatement(node) { + this.word("return"); + printStatementAfterKeyword(this, node.argument, node, false); +} + +function ThrowStatement(node) { + this.word("throw"); + printStatementAfterKeyword(this, node.argument, node, false); +} + +function LabeledStatement(node) { + this.print(node.label, node); + this.tokenChar(58); + this.space(); + this.print(node.body, node); +} + +function TryStatement(node) { + this.word("try"); + this.space(); + this.print(node.block, node); + this.space(); + + if (node.handlers) { + this.print(node.handlers[0], node); + } else { + this.print(node.handler, node); + } + + if (node.finalizer) { + this.space(); + this.word("finally"); + this.space(); + this.print(node.finalizer, node); + } +} + +function CatchClause(node) { + this.word("catch"); + this.space(); + + if (node.param) { + this.tokenChar(40); + this.print(node.param, node); + this.print(node.param.typeAnnotation, node); + this.tokenChar(41); + this.space(); + } + + this.print(node.body, node); +} + +function SwitchStatement(node) { + this.word("switch"); + this.space(); + this.tokenChar(40); + this.print(node.discriminant, node); + this.tokenChar(41); + this.space(); + this.tokenChar(123); + this.printSequence(node.cases, node, { + indent: true, + + addNewlines(leading, cas) { + if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + } + + }); + this.tokenChar(125); +} + +function SwitchCase(node) { + if (node.test) { + this.word("case"); + this.space(); + this.print(node.test, node); + this.tokenChar(58); + } else { + this.word("default"); + this.tokenChar(58); + } + + if (node.consequent.length) { + this.newline(); + this.printSequence(node.consequent, node, { + indent: true + }); + } +} + +function DebuggerStatement() { + this.word("debugger"); + this.semicolon(); +} + +function variableDeclarationIndent() { + this.tokenChar(44); + this.newline(); + + if (this.endsWith(10)) { + for (let i = 0; i < 4; i++) this.space(true); + } +} + +function constDeclarationIndent() { + this.tokenChar(44); + this.newline(); + + if (this.endsWith(10)) { + for (let i = 0; i < 6; i++) this.space(true); + } +} + +function VariableDeclaration(node, parent) { + if (node.declare) { + this.word("declare"); + this.space(); + } + + this.word(node.kind); + this.space(); + let hasInits = false; + + if (!isFor(parent)) { + for (const declar of node.declarations) { + if (declar.init) { + hasInits = true; + } + } + } + + let separator; + + if (hasInits) { + separator = node.kind === "const" ? constDeclarationIndent : variableDeclarationIndent; + } + + this.printList(node.declarations, node, { + separator + }); + + if (isFor(parent)) { + if (isForStatement(parent)) { + if (parent.init === node) return; + } else { + if (parent.left === node) return; + } + } + + this.semicolon(); +} + +function VariableDeclarator(node) { + this.print(node.id, node); + if (node.definite) this.tokenChar(33); + this.print(node.id.typeAnnotation, node); + + if (node.init) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.init, node); + } +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/template-literals.js b/node_modules/@babel/generator/lib/generators/template-literals.js new file mode 100644 index 0000000..21c17df --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/template-literals.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TaggedTemplateExpression = TaggedTemplateExpression; +exports.TemplateElement = TemplateElement; +exports.TemplateLiteral = TemplateLiteral; + +function TaggedTemplateExpression(node) { + this.print(node.tag, node); + this.print(node.typeParameters, node); + this.print(node.quasi, node); +} + +function TemplateElement(node, parent) { + const isFirst = parent.quasis[0] === node; + const isLast = parent.quasis[parent.quasis.length - 1] === node; + const value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); + this.token(value, true); +} + +function TemplateLiteral(node) { + const quasis = node.quasis; + + for (let i = 0; i < quasis.length; i++) { + this.print(quasis[i], node); + + if (i + 1 < quasis.length) { + this.print(node.expressions[i], node); + } + } +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/types.js b/node_modules/@babel/generator/lib/generators/types.js new file mode 100644 index 0000000..b955f93 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/types.js @@ -0,0 +1,276 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArgumentPlaceholder = ArgumentPlaceholder; +exports.ArrayPattern = exports.ArrayExpression = ArrayExpression; +exports.BigIntLiteral = BigIntLiteral; +exports.BooleanLiteral = BooleanLiteral; +exports.DecimalLiteral = DecimalLiteral; +exports.Identifier = Identifier; +exports.NullLiteral = NullLiteral; +exports.NumericLiteral = NumericLiteral; +exports.ObjectPattern = exports.ObjectExpression = ObjectExpression; +exports.ObjectMethod = ObjectMethod; +exports.ObjectProperty = ObjectProperty; +exports.PipelineBareFunction = PipelineBareFunction; +exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference; +exports.PipelineTopicExpression = PipelineTopicExpression; +exports.RecordExpression = RecordExpression; +exports.RegExpLiteral = RegExpLiteral; +exports.SpreadElement = exports.RestElement = RestElement; +exports.StringLiteral = StringLiteral; +exports.TopicReference = TopicReference; +exports.TupleExpression = TupleExpression; + +var _t = require("@babel/types"); + +var _jsesc = require("jsesc"); + +const { + isAssignmentPattern, + isIdentifier +} = _t; + +function Identifier(node) { + this.exactSource(node.loc, () => { + this.word(node.name); + }); +} + +function ArgumentPlaceholder() { + this.tokenChar(63); +} + +function RestElement(node) { + this.token("..."); + this.print(node.argument, node); +} + +function ObjectExpression(node) { + const props = node.properties; + this.tokenChar(123); + this.printInnerComments(node); + + if (props.length) { + this.space(); + this.printList(props, node, { + indent: true, + statement: true + }); + this.space(); + } + + this.tokenChar(125); +} + +function ObjectMethod(node) { + this.printJoin(node.decorators, node); + + this._methodHead(node); + + this.space(); + this.print(node.body, node); +} + +function ObjectProperty(node) { + this.printJoin(node.decorators, node); + + if (node.computed) { + this.tokenChar(91); + this.print(node.key, node); + this.tokenChar(93); + } else { + if (isAssignmentPattern(node.value) && isIdentifier(node.key) && node.key.name === node.value.left.name) { + this.print(node.value, node); + return; + } + + this.print(node.key, node); + + if (node.shorthand && isIdentifier(node.key) && isIdentifier(node.value) && node.key.name === node.value.name) { + return; + } + } + + this.tokenChar(58); + this.space(); + this.print(node.value, node); +} + +function ArrayExpression(node) { + const elems = node.elements; + const len = elems.length; + this.tokenChar(91); + this.printInnerComments(node); + + for (let i = 0; i < elems.length; i++) { + const elem = elems[i]; + + if (elem) { + if (i > 0) this.space(); + this.print(elem, node); + if (i < len - 1) this.tokenChar(44); + } else { + this.tokenChar(44); + } + } + + this.tokenChar(93); +} + +function RecordExpression(node) { + const props = node.properties; + let startToken; + let endToken; + + if (this.format.recordAndTupleSyntaxType === "bar") { + startToken = "{|"; + endToken = "|}"; + } else if (this.format.recordAndTupleSyntaxType === "hash") { + startToken = "#{"; + endToken = "}"; + } else { + throw new Error(`The "recordAndTupleSyntaxType" generator option must be "bar" or "hash" (${JSON.stringify(this.format.recordAndTupleSyntaxType)} received).`); + } + + this.token(startToken); + this.printInnerComments(node); + + if (props.length) { + this.space(); + this.printList(props, node, { + indent: true, + statement: true + }); + this.space(); + } + + this.token(endToken); +} + +function TupleExpression(node) { + const elems = node.elements; + const len = elems.length; + let startToken; + let endToken; + + if (this.format.recordAndTupleSyntaxType === "bar") { + startToken = "[|"; + endToken = "|]"; + } else if (this.format.recordAndTupleSyntaxType === "hash") { + startToken = "#["; + endToken = "]"; + } else { + throw new Error(`${this.format.recordAndTupleSyntaxType} is not a valid recordAndTuple syntax type`); + } + + this.token(startToken); + this.printInnerComments(node); + + for (let i = 0; i < elems.length; i++) { + const elem = elems[i]; + + if (elem) { + if (i > 0) this.space(); + this.print(elem, node); + if (i < len - 1) this.tokenChar(44); + } + } + + this.token(endToken); +} + +function RegExpLiteral(node) { + this.word(`/${node.pattern}/${node.flags}`); +} + +function BooleanLiteral(node) { + this.word(node.value ? "true" : "false"); +} + +function NullLiteral() { + this.word("null"); +} + +function NumericLiteral(node) { + const raw = this.getPossibleRaw(node); + const opts = this.format.jsescOption; + const value = node.value + ""; + + if (opts.numbers) { + this.number(_jsesc(node.value, opts)); + } else if (raw == null) { + this.number(value); + } else if (this.format.minified) { + this.number(raw.length < value.length ? raw : value); + } else { + this.number(raw); + } +} + +function StringLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.token(raw); + return; + } + + const val = _jsesc(node.value, Object.assign(this.format.jsescOption, this.format.jsonCompatibleStrings && { + json: true + })); + + return this.token(val); +} + +function BigIntLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.word(raw); + return; + } + + this.word(node.value + "n"); +} + +function DecimalLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.word(raw); + return; + } + + this.word(node.value + "m"); +} + +const validTopicTokenSet = new Set(["^^", "@@", "^", "%", "#"]); + +function TopicReference() { + const { + topicToken + } = this.format; + + if (validTopicTokenSet.has(topicToken)) { + this.token(topicToken); + } else { + const givenTopicTokenJSON = JSON.stringify(topicToken); + const validTopics = Array.from(validTopicTokenSet, v => JSON.stringify(v)); + throw new Error(`The "topicToken" generator option must be one of ` + `${validTopics.join(", ")} (${givenTopicTokenJSON} received instead).`); + } +} + +function PipelineTopicExpression(node) { + this.print(node.expression, node); +} + +function PipelineBareFunction(node) { + this.print(node.callee, node); +} + +function PipelinePrimaryTopicReference() { + this.tokenChar(35); +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/typescript.js b/node_modules/@babel/generator/lib/generators/typescript.js new file mode 100644 index 0000000..c5b71f3 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/typescript.js @@ -0,0 +1,833 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TSAnyKeyword = TSAnyKeyword; +exports.TSArrayType = TSArrayType; +exports.TSAsExpression = TSAsExpression; +exports.TSBigIntKeyword = TSBigIntKeyword; +exports.TSBooleanKeyword = TSBooleanKeyword; +exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; +exports.TSConditionalType = TSConditionalType; +exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; +exports.TSConstructorType = TSConstructorType; +exports.TSDeclareFunction = TSDeclareFunction; +exports.TSDeclareMethod = TSDeclareMethod; +exports.TSEnumDeclaration = TSEnumDeclaration; +exports.TSEnumMember = TSEnumMember; +exports.TSExportAssignment = TSExportAssignment; +exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; +exports.TSExternalModuleReference = TSExternalModuleReference; +exports.TSFunctionType = TSFunctionType; +exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; +exports.TSImportType = TSImportType; +exports.TSIndexSignature = TSIndexSignature; +exports.TSIndexedAccessType = TSIndexedAccessType; +exports.TSInferType = TSInferType; +exports.TSInstantiationExpression = TSInstantiationExpression; +exports.TSInterfaceBody = TSInterfaceBody; +exports.TSInterfaceDeclaration = TSInterfaceDeclaration; +exports.TSIntersectionType = TSIntersectionType; +exports.TSIntrinsicKeyword = TSIntrinsicKeyword; +exports.TSLiteralType = TSLiteralType; +exports.TSMappedType = TSMappedType; +exports.TSMethodSignature = TSMethodSignature; +exports.TSModuleBlock = TSModuleBlock; +exports.TSModuleDeclaration = TSModuleDeclaration; +exports.TSNamedTupleMember = TSNamedTupleMember; +exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; +exports.TSNeverKeyword = TSNeverKeyword; +exports.TSNonNullExpression = TSNonNullExpression; +exports.TSNullKeyword = TSNullKeyword; +exports.TSNumberKeyword = TSNumberKeyword; +exports.TSObjectKeyword = TSObjectKeyword; +exports.TSOptionalType = TSOptionalType; +exports.TSParameterProperty = TSParameterProperty; +exports.TSParenthesizedType = TSParenthesizedType; +exports.TSPropertySignature = TSPropertySignature; +exports.TSQualifiedName = TSQualifiedName; +exports.TSRestType = TSRestType; +exports.TSStringKeyword = TSStringKeyword; +exports.TSSymbolKeyword = TSSymbolKeyword; +exports.TSThisType = TSThisType; +exports.TSTupleType = TSTupleType; +exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; +exports.TSTypeAnnotation = TSTypeAnnotation; +exports.TSTypeAssertion = TSTypeAssertion; +exports.TSTypeLiteral = TSTypeLiteral; +exports.TSTypeOperator = TSTypeOperator; +exports.TSTypeParameter = TSTypeParameter; +exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; +exports.TSTypePredicate = TSTypePredicate; +exports.TSTypeQuery = TSTypeQuery; +exports.TSTypeReference = TSTypeReference; +exports.TSUndefinedKeyword = TSUndefinedKeyword; +exports.TSUnionType = TSUnionType; +exports.TSUnknownKeyword = TSUnknownKeyword; +exports.TSVoidKeyword = TSVoidKeyword; +exports.tsPrintClassMemberModifiers = tsPrintClassMemberModifiers; +exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType; +exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName; +exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase; +exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody; + +function TSTypeAnnotation(node) { + this.tokenChar(58); + this.space(); + if (node.optional) this.tokenChar(63); + this.print(node.typeAnnotation, node); +} + +function TSTypeParameterInstantiation(node, parent) { + this.tokenChar(60); + this.printList(node.params, node, {}); + + if (parent.type === "ArrowFunctionExpression" && node.params.length === 1) { + this.tokenChar(44); + } + + this.tokenChar(62); +} + +function TSTypeParameter(node) { + if (node.in) { + this.word("in"); + this.space(); + } + + if (node.out) { + this.word("out"); + this.space(); + } + + this.word(node.name); + + if (node.constraint) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.constraint, node); + } + + if (node.default) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.default, node); + } +} + +function TSParameterProperty(node) { + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } + + if (node.readonly) { + this.word("readonly"); + this.space(); + } + + this._param(node.parameter); +} + +function TSDeclareFunction(node) { + if (node.declare) { + this.word("declare"); + this.space(); + } + + this._functionHead(node); + + this.tokenChar(59); +} + +function TSDeclareMethod(node) { + this._classMethodHead(node); + + this.tokenChar(59); +} + +function TSQualifiedName(node) { + this.print(node.left, node); + this.tokenChar(46); + this.print(node.right, node); +} + +function TSCallSignatureDeclaration(node) { + this.tsPrintSignatureDeclarationBase(node); + this.tokenChar(59); +} + +function TSConstructSignatureDeclaration(node) { + this.word("new"); + this.space(); + this.tsPrintSignatureDeclarationBase(node); + this.tokenChar(59); +} + +function TSPropertySignature(node) { + const { + readonly, + initializer + } = node; + + if (readonly) { + this.word("readonly"); + this.space(); + } + + this.tsPrintPropertyOrMethodName(node); + this.print(node.typeAnnotation, node); + + if (initializer) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(initializer, node); + } + + this.tokenChar(59); +} + +function tsPrintPropertyOrMethodName(node) { + if (node.computed) { + this.tokenChar(91); + } + + this.print(node.key, node); + + if (node.computed) { + this.tokenChar(93); + } + + if (node.optional) { + this.tokenChar(63); + } +} + +function TSMethodSignature(node) { + const { + kind + } = node; + + if (kind === "set" || kind === "get") { + this.word(kind); + this.space(); + } + + this.tsPrintPropertyOrMethodName(node); + this.tsPrintSignatureDeclarationBase(node); + this.tokenChar(59); +} + +function TSIndexSignature(node) { + const { + readonly, + static: isStatic + } = node; + + if (isStatic) { + this.word("static"); + this.space(); + } + + if (readonly) { + this.word("readonly"); + this.space(); + } + + this.tokenChar(91); + + this._parameters(node.parameters, node); + + this.tokenChar(93); + this.print(node.typeAnnotation, node); + this.tokenChar(59); +} + +function TSAnyKeyword() { + this.word("any"); +} + +function TSBigIntKeyword() { + this.word("bigint"); +} + +function TSUnknownKeyword() { + this.word("unknown"); +} + +function TSNumberKeyword() { + this.word("number"); +} + +function TSObjectKeyword() { + this.word("object"); +} + +function TSBooleanKeyword() { + this.word("boolean"); +} + +function TSStringKeyword() { + this.word("string"); +} + +function TSSymbolKeyword() { + this.word("symbol"); +} + +function TSVoidKeyword() { + this.word("void"); +} + +function TSUndefinedKeyword() { + this.word("undefined"); +} + +function TSNullKeyword() { + this.word("null"); +} + +function TSNeverKeyword() { + this.word("never"); +} + +function TSIntrinsicKeyword() { + this.word("intrinsic"); +} + +function TSThisType() { + this.word("this"); +} + +function TSFunctionType(node) { + this.tsPrintFunctionOrConstructorType(node); +} + +function TSConstructorType(node) { + if (node.abstract) { + this.word("abstract"); + this.space(); + } + + this.word("new"); + this.space(); + this.tsPrintFunctionOrConstructorType(node); +} + +function tsPrintFunctionOrConstructorType(node) { + const { + typeParameters + } = node; + const parameters = node.parameters; + this.print(typeParameters, node); + this.tokenChar(40); + + this._parameters(parameters, node); + + this.tokenChar(41); + this.space(); + this.token("=>"); + this.space(); + const returnType = node.typeAnnotation; + this.print(returnType.typeAnnotation, node); +} + +function TSTypeReference(node) { + this.print(node.typeName, node, true); + this.print(node.typeParameters, node, true); +} + +function TSTypePredicate(node) { + if (node.asserts) { + this.word("asserts"); + this.space(); + } + + this.print(node.parameterName); + + if (node.typeAnnotation) { + this.space(); + this.word("is"); + this.space(); + this.print(node.typeAnnotation.typeAnnotation); + } +} + +function TSTypeQuery(node) { + this.word("typeof"); + this.space(); + this.print(node.exprName); + + if (node.typeParameters) { + this.print(node.typeParameters, node); + } +} + +function TSTypeLiteral(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.members, node); +} + +function tsPrintTypeLiteralOrInterfaceBody(members, node) { + tsPrintBraced(this, members, node); +} + +function tsPrintBraced(printer, members, node) { + printer.token("{"); + + if (members.length) { + printer.indent(); + printer.newline(); + + for (const member of members) { + printer.print(member, node); + printer.newline(); + } + + printer.dedent(); + printer.rightBrace(); + } else { + printer.token("}"); + } +} + +function TSArrayType(node) { + this.print(node.elementType, node, true); + this.token("[]"); +} + +function TSTupleType(node) { + this.tokenChar(91); + this.printList(node.elementTypes, node); + this.tokenChar(93); +} + +function TSOptionalType(node) { + this.print(node.typeAnnotation, node); + this.tokenChar(63); +} + +function TSRestType(node) { + this.token("..."); + this.print(node.typeAnnotation, node); +} + +function TSNamedTupleMember(node) { + this.print(node.label, node); + if (node.optional) this.tokenChar(63); + this.tokenChar(58); + this.space(); + this.print(node.elementType, node); +} + +function TSUnionType(node) { + tsPrintUnionOrIntersectionType(this, node, "|"); +} + +function TSIntersectionType(node) { + tsPrintUnionOrIntersectionType(this, node, "&"); +} + +function tsPrintUnionOrIntersectionType(printer, node, sep) { + printer.printJoin(node.types, node, { + separator() { + this.space(); + this.token(sep); + this.space(); + } + + }); +} + +function TSConditionalType(node) { + this.print(node.checkType); + this.space(); + this.word("extends"); + this.space(); + this.print(node.extendsType); + this.space(); + this.tokenChar(63); + this.space(); + this.print(node.trueType); + this.space(); + this.tokenChar(58); + this.space(); + this.print(node.falseType); +} + +function TSInferType(node) { + this.token("infer"); + this.space(); + this.print(node.typeParameter); +} + +function TSParenthesizedType(node) { + this.tokenChar(40); + this.print(node.typeAnnotation, node); + this.tokenChar(41); +} + +function TSTypeOperator(node) { + this.word(node.operator); + this.space(); + this.print(node.typeAnnotation, node); +} + +function TSIndexedAccessType(node) { + this.print(node.objectType, node, true); + this.tokenChar(91); + this.print(node.indexType, node); + this.tokenChar(93); +} + +function TSMappedType(node) { + const { + nameType, + optional, + readonly, + typeParameter + } = node; + this.tokenChar(123); + this.space(); + + if (readonly) { + tokenIfPlusMinus(this, readonly); + this.word("readonly"); + this.space(); + } + + this.tokenChar(91); + this.word(typeParameter.name); + this.space(); + this.word("in"); + this.space(); + this.print(typeParameter.constraint, typeParameter); + + if (nameType) { + this.space(); + this.word("as"); + this.space(); + this.print(nameType, node); + } + + this.tokenChar(93); + + if (optional) { + tokenIfPlusMinus(this, optional); + this.tokenChar(63); + } + + this.tokenChar(58); + this.space(); + this.print(node.typeAnnotation, node); + this.space(); + this.tokenChar(125); +} + +function tokenIfPlusMinus(self, tok) { + if (tok !== true) { + self.token(tok); + } +} + +function TSLiteralType(node) { + this.print(node.literal, node); +} + +function TSExpressionWithTypeArguments(node) { + this.print(node.expression, node); + this.print(node.typeParameters, node); +} + +function TSInterfaceDeclaration(node) { + const { + declare, + id, + typeParameters, + extends: extendz, + body + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + this.word("interface"); + this.space(); + this.print(id, node); + this.print(typeParameters, node); + + if (extendz != null && extendz.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(extendz, node); + } + + this.space(); + this.print(body, node); +} + +function TSInterfaceBody(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.body, node); +} + +function TSTypeAliasDeclaration(node) { + const { + declare, + id, + typeParameters, + typeAnnotation + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + this.word("type"); + this.space(); + this.print(id, node); + this.print(typeParameters, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(typeAnnotation, node); + this.tokenChar(59); +} + +function TSAsExpression(node) { + const { + expression, + typeAnnotation + } = node; + this.print(expression, node); + this.space(); + this.word("as"); + this.space(); + this.print(typeAnnotation, node); +} + +function TSTypeAssertion(node) { + const { + typeAnnotation, + expression + } = node; + this.tokenChar(60); + this.print(typeAnnotation, node); + this.tokenChar(62); + this.space(); + this.print(expression, node); +} + +function TSInstantiationExpression(node) { + this.print(node.expression, node); + this.print(node.typeParameters, node); +} + +function TSEnumDeclaration(node) { + const { + declare, + const: isConst, + id, + members + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + if (isConst) { + this.word("const"); + this.space(); + } + + this.word("enum"); + this.space(); + this.print(id, node); + this.space(); + tsPrintBraced(this, members, node); +} + +function TSEnumMember(node) { + const { + id, + initializer + } = node; + this.print(id, node); + + if (initializer) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(initializer, node); + } + + this.tokenChar(44); +} + +function TSModuleDeclaration(node) { + const { + declare, + id + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + if (!node.global) { + this.word(id.type === "Identifier" ? "namespace" : "module"); + this.space(); + } + + this.print(id, node); + + if (!node.body) { + this.tokenChar(59); + return; + } + + let body = node.body; + + while (body.type === "TSModuleDeclaration") { + this.tokenChar(46); + this.print(body.id, body); + body = body.body; + } + + this.space(); + this.print(body, node); +} + +function TSModuleBlock(node) { + tsPrintBraced(this, node.body, node); +} + +function TSImportType(node) { + const { + argument, + qualifier, + typeParameters + } = node; + this.word("import"); + this.tokenChar(40); + this.print(argument, node); + this.tokenChar(41); + + if (qualifier) { + this.tokenChar(46); + this.print(qualifier, node); + } + + if (typeParameters) { + this.print(typeParameters, node); + } +} + +function TSImportEqualsDeclaration(node) { + const { + isExport, + id, + moduleReference + } = node; + + if (isExport) { + this.word("export"); + this.space(); + } + + this.word("import"); + this.space(); + this.print(id, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(moduleReference, node); + this.tokenChar(59); +} + +function TSExternalModuleReference(node) { + this.token("require("); + this.print(node.expression, node); + this.tokenChar(41); +} + +function TSNonNullExpression(node) { + this.print(node.expression, node); + this.tokenChar(33); +} + +function TSExportAssignment(node) { + this.word("export"); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.expression, node); + this.tokenChar(59); +} + +function TSNamespaceExportDeclaration(node) { + this.word("export"); + this.space(); + this.word("as"); + this.space(); + this.word("namespace"); + this.space(); + this.print(node.id, node); +} + +function tsPrintSignatureDeclarationBase(node) { + const { + typeParameters + } = node; + const parameters = node.parameters; + this.print(typeParameters, node); + this.tokenChar(40); + + this._parameters(parameters, node); + + this.tokenChar(41); + const returnType = node.typeAnnotation; + this.print(returnType, node); +} + +function tsPrintClassMemberModifiers(node) { + const isField = node.type === "ClassAccessorProperty" || node.type === "ClassProperty"; + + if (isField && node.declare) { + this.word("declare"); + this.space(); + } + + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } + + if (node.static) { + this.word("static"); + this.space(); + } + + if (node.override) { + this.word("override"); + this.space(); + } + + if (node.abstract) { + this.word("abstract"); + this.space(); + } + + if (isField && node.readonly) { + this.word("readonly"); + this.space(); + } +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/index.js b/node_modules/@babel/generator/lib/index.js new file mode 100644 index 0000000..374e36f --- /dev/null +++ b/node_modules/@babel/generator/lib/index.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CodeGenerator = void 0; +exports.default = generate; + +var _sourceMap = require("./source-map"); + +var _printer = require("./printer"); + +class Generator extends _printer.default { + constructor(ast, opts = {}, code) { + const format = normalizeOptions(code, opts); + const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; + super(format, map); + this.ast = void 0; + this.ast = ast; + } + + generate() { + return super.generate(this.ast); + } + +} + +function normalizeOptions(code, opts) { + const format = { + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + shouldPrintComment: opts.shouldPrintComment, + retainLines: opts.retainLines, + retainFunctionParens: opts.retainFunctionParens, + comments: opts.comments == null || opts.comments, + compact: opts.compact, + minified: opts.minified, + concise: opts.concise, + indent: { + adjustMultilineComment: true, + style: " ", + base: 0 + }, + jsescOption: Object.assign({ + quotes: "double", + wrap: true, + minimal: false + }, opts.jsescOption), + recordAndTupleSyntaxType: opts.recordAndTupleSyntaxType, + topicToken: opts.topicToken + }; + { + format.decoratorsBeforeExport = !!opts.decoratorsBeforeExport; + format.jsonCompatibleStrings = opts.jsonCompatibleStrings; + } + + if (format.minified) { + format.compact = true; + + format.shouldPrintComment = format.shouldPrintComment || (() => format.comments); + } else { + format.shouldPrintComment = format.shouldPrintComment || (value => format.comments || value.includes("@license") || value.includes("@preserve")); + } + + if (format.compact === "auto") { + format.compact = code.length > 500000; + + if (format.compact) { + console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`); + } + } + + if (format.compact) { + format.indent.adjustMultilineComment = false; + } + + return format; +} + +class CodeGenerator { + constructor(ast, opts, code) { + this._generator = void 0; + this._generator = new Generator(ast, opts, code); + } + + generate() { + return this._generator.generate(); + } + +} + +exports.CodeGenerator = CodeGenerator; + +function generate(ast, opts, code) { + const gen = new Generator(ast, opts, code); + return gen.generate(); +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/index.js b/node_modules/@babel/generator/lib/node/index.js new file mode 100644 index 0000000..cdb1bfb --- /dev/null +++ b/node_modules/@babel/generator/lib/node/index.js @@ -0,0 +1,99 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.needsParens = needsParens; +exports.needsWhitespace = needsWhitespace; +exports.needsWhitespaceAfter = needsWhitespaceAfter; +exports.needsWhitespaceBefore = needsWhitespaceBefore; + +var whitespace = require("./whitespace"); + +var parens = require("./parentheses"); + +var _t = require("@babel/types"); + +const { + FLIPPED_ALIAS_KEYS, + isCallExpression, + isExpressionStatement, + isMemberExpression, + isNewExpression +} = _t; + +function expandAliases(obj) { + const newObj = {}; + + function add(type, func) { + const fn = newObj[type]; + newObj[type] = fn ? function (node, parent, stack) { + const result = fn(node, parent, stack); + return result == null ? func(node, parent, stack) : result; + } : func; + } + + for (const type of Object.keys(obj)) { + const aliases = FLIPPED_ALIAS_KEYS[type]; + + if (aliases) { + for (const alias of aliases) { + add(alias, obj[type]); + } + } else { + add(type, obj[type]); + } + } + + return newObj; +} + +const expandedParens = expandAliases(parens); +const expandedWhitespaceNodes = expandAliases(whitespace.nodes); + +function find(obj, node, parent, printStack) { + const fn = obj[node.type]; + return fn ? fn(node, parent, printStack) : null; +} + +function isOrHasCallExpression(node) { + if (isCallExpression(node)) { + return true; + } + + return isMemberExpression(node) && isOrHasCallExpression(node.object); +} + +function needsWhitespace(node, parent, type) { + if (!node) return false; + + if (isExpressionStatement(node)) { + node = node.expression; + } + + const flag = find(expandedWhitespaceNodes, node, parent); + + if (typeof flag === "number") { + return (flag & type) !== 0; + } + + return false; +} + +function needsWhitespaceBefore(node, parent) { + return needsWhitespace(node, parent, 1); +} + +function needsWhitespaceAfter(node, parent) { + return needsWhitespace(node, parent, 2); +} + +function needsParens(node, parent, printStack) { + if (!parent) return false; + + if (isNewExpression(parent) && parent.callee === node) { + if (isOrHasCallExpression(node)) return true; + } + + return find(expandedParens, node, parent, printStack); +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/parentheses.js b/node_modules/@babel/generator/lib/node/parentheses.js new file mode 100644 index 0000000..42a4253 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/parentheses.js @@ -0,0 +1,346 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArrowFunctionExpression = ArrowFunctionExpression; +exports.AssignmentExpression = AssignmentExpression; +exports.Binary = Binary; +exports.BinaryExpression = BinaryExpression; +exports.ClassExpression = ClassExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.DoExpression = DoExpression; +exports.FunctionExpression = FunctionExpression; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.Identifier = Identifier; +exports.LogicalExpression = LogicalExpression; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +exports.ObjectExpression = ObjectExpression; +exports.OptionalIndexedAccessType = OptionalIndexedAccessType; +exports.OptionalCallExpression = exports.OptionalMemberExpression = OptionalMemberExpression; +exports.SequenceExpression = SequenceExpression; +exports.TSAsExpression = TSAsExpression; +exports.TSInferType = TSInferType; +exports.TSInstantiationExpression = TSInstantiationExpression; +exports.TSTypeAssertion = TSTypeAssertion; +exports.TSIntersectionType = exports.TSUnionType = TSUnionType; +exports.UnaryLike = UnaryLike; +exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.UpdateExpression = UpdateExpression; +exports.AwaitExpression = exports.YieldExpression = YieldExpression; + +var _t = require("@babel/types"); + +const { + isArrayTypeAnnotation, + isArrowFunctionExpression, + isAssignmentExpression, + isAwaitExpression, + isBinary, + isBinaryExpression, + isUpdateExpression, + isCallExpression, + isClass, + isClassExpression, + isConditional, + isConditionalExpression, + isExportDeclaration, + isExportDefaultDeclaration, + isExpressionStatement, + isFor, + isForInStatement, + isForOfStatement, + isForStatement, + isFunctionExpression, + isIfStatement, + isIndexedAccessType, + isIntersectionTypeAnnotation, + isLogicalExpression, + isMemberExpression, + isNewExpression, + isNullableTypeAnnotation, + isObjectPattern, + isOptionalCallExpression, + isOptionalMemberExpression, + isReturnStatement, + isSequenceExpression, + isSwitchStatement, + isTSArrayType, + isTSAsExpression, + isTSInstantiationExpression, + isTSIntersectionType, + isTSNonNullExpression, + isTSOptionalType, + isTSRestType, + isTSTypeAssertion, + isTSUnionType, + isTaggedTemplateExpression, + isThrowStatement, + isTypeAnnotation, + isUnaryLike, + isUnionTypeAnnotation, + isVariableDeclarator, + isWhileStatement, + isYieldExpression +} = _t; +const PRECEDENCE = { + "||": 0, + "??": 0, + "|>": 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 +}; + +const isClassExtendsClause = (node, parent) => isClass(parent, { + superClass: node +}); + +const hasPostfixPart = (node, parent) => (isMemberExpression(parent) || isOptionalMemberExpression(parent)) && parent.object === node || (isCallExpression(parent) || isOptionalCallExpression(parent) || isNewExpression(parent)) && parent.callee === node || isTaggedTemplateExpression(parent) && parent.tag === node || isTSNonNullExpression(parent); + +function NullableTypeAnnotation(node, parent) { + return isArrayTypeAnnotation(parent); +} + +function FunctionTypeAnnotation(node, parent, printStack) { + if (printStack.length < 3) return; + return isUnionTypeAnnotation(parent) || isIntersectionTypeAnnotation(parent) || isArrayTypeAnnotation(parent) || isTypeAnnotation(parent) && isArrowFunctionExpression(printStack[printStack.length - 3]); +} + +function UpdateExpression(node, parent) { + return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent); +} + +function ObjectExpression(node, parent, printStack) { + return isFirstInContext(printStack, 1 | 2); +} + +function DoExpression(node, parent, printStack) { + return !node.async && isFirstInContext(printStack, 1); +} + +function Binary(node, parent) { + if (node.operator === "**" && isBinaryExpression(parent, { + operator: "**" + })) { + return parent.left === node; + } + + if (isClassExtendsClause(node, parent)) { + return true; + } + + if (hasPostfixPart(node, parent) || isUnaryLike(parent) || isAwaitExpression(parent)) { + return true; + } + + if (isBinary(parent)) { + const parentOp = parent.operator; + const parentPos = PRECEDENCE[parentOp]; + const nodeOp = node.operator; + const nodePos = PRECEDENCE[nodeOp]; + + if (parentPos === nodePos && parent.right === node && !isLogicalExpression(parent) || parentPos > nodePos) { + return true; + } + } +} + +function UnionTypeAnnotation(node, parent) { + return isArrayTypeAnnotation(parent) || isNullableTypeAnnotation(parent) || isIntersectionTypeAnnotation(parent) || isUnionTypeAnnotation(parent); +} + +function OptionalIndexedAccessType(node, parent) { + return isIndexedAccessType(parent, { + objectType: node + }); +} + +function TSAsExpression() { + return true; +} + +function TSTypeAssertion() { + return true; +} + +function TSUnionType(node, parent) { + return isTSArrayType(parent) || isTSOptionalType(parent) || isTSIntersectionType(parent) || isTSUnionType(parent) || isTSRestType(parent); +} + +function TSInferType(node, parent) { + return isTSArrayType(parent) || isTSOptionalType(parent); +} + +function TSInstantiationExpression(node, parent) { + return (isCallExpression(parent) || isOptionalCallExpression(parent) || isNewExpression(parent) || isTSInstantiationExpression(parent)) && !!parent.typeParameters; +} + +function BinaryExpression(node, parent) { + return node.operator === "in" && (isVariableDeclarator(parent) || isFor(parent)); +} + +function SequenceExpression(node, parent) { + if (isForStatement(parent) || isThrowStatement(parent) || isReturnStatement(parent) || isIfStatement(parent) && parent.test === node || isWhileStatement(parent) && parent.test === node || isForInStatement(parent) && parent.right === node || isSwitchStatement(parent) && parent.discriminant === node || isExpressionStatement(parent) && parent.expression === node) { + return false; + } + + return true; +} + +function YieldExpression(node, parent) { + return isBinary(parent) || isUnaryLike(parent) || hasPostfixPart(node, parent) || isAwaitExpression(parent) && isYieldExpression(node) || isConditionalExpression(parent) && node === parent.test || isClassExtendsClause(node, parent); +} + +function ClassExpression(node, parent, printStack) { + return isFirstInContext(printStack, 1 | 4); +} + +function UnaryLike(node, parent) { + return hasPostfixPart(node, parent) || isBinaryExpression(parent, { + operator: "**", + left: node + }) || isClassExtendsClause(node, parent); +} + +function FunctionExpression(node, parent, printStack) { + return isFirstInContext(printStack, 1 | 4); +} + +function ArrowFunctionExpression(node, parent) { + return isExportDeclaration(parent) || ConditionalExpression(node, parent); +} + +function ConditionalExpression(node, parent) { + if (isUnaryLike(parent) || isBinary(parent) || isConditionalExpression(parent, { + test: node + }) || isAwaitExpression(parent) || isTSTypeAssertion(parent) || isTSAsExpression(parent)) { + return true; + } + + return UnaryLike(node, parent); +} + +function OptionalMemberExpression(node, parent) { + return isCallExpression(parent, { + callee: node + }) || isMemberExpression(parent, { + object: node + }); +} + +function AssignmentExpression(node, parent) { + if (isObjectPattern(node.left)) { + return true; + } else { + return ConditionalExpression(node, parent); + } +} + +function LogicalExpression(node, parent) { + switch (node.operator) { + case "||": + if (!isLogicalExpression(parent)) return false; + return parent.operator === "??" || parent.operator === "&&"; + + case "&&": + return isLogicalExpression(parent, { + operator: "??" + }); + + case "??": + return isLogicalExpression(parent) && parent.operator !== "??"; + } +} + +function Identifier(node, parent, printStack) { + var _node$extra; + + if ((_node$extra = node.extra) != null && _node$extra.parenthesized && isAssignmentExpression(parent, { + left: node + }) && (isFunctionExpression(parent.right) || isClassExpression(parent.right)) && parent.right.id == null) { + return true; + } + + if (node.name === "let") { + const isFollowedByBracket = isMemberExpression(parent, { + object: node, + computed: true + }) || isOptionalMemberExpression(parent, { + object: node, + computed: true, + optional: false + }); + return isFirstInContext(printStack, isFollowedByBracket ? 1 | 8 | 16 | 32 : 32); + } + + return node.name === "async" && isForOfStatement(parent) && node === parent.left; +} + +function isFirstInContext(printStack, checkParam) { + const expressionStatement = checkParam & 1; + const arrowBody = checkParam & 2; + const exportDefault = checkParam & 4; + const forHead = checkParam & 8; + const forInHead = checkParam & 16; + const forOfHead = checkParam & 32; + let i = printStack.length - 1; + if (i <= 0) return; + let node = printStack[i]; + i--; + let parent = printStack[i]; + + while (i >= 0) { + if (expressionStatement && isExpressionStatement(parent, { + expression: node + }) || exportDefault && isExportDefaultDeclaration(parent, { + declaration: node + }) || arrowBody && isArrowFunctionExpression(parent, { + body: node + }) || forHead && isForStatement(parent, { + init: node + }) || forInHead && isForInStatement(parent, { + left: node + }) || forOfHead && isForOfStatement(parent, { + left: node + })) { + return true; + } + + if (i > 0 && (hasPostfixPart(node, parent) && !isNewExpression(parent) || isSequenceExpression(parent) && parent.expressions[0] === node || isUpdateExpression(parent) && !parent.prefix || isConditional(parent, { + test: node + }) || isBinary(parent, { + left: node + }) || isAssignmentExpression(parent, { + left: node + }))) { + node = parent; + i--; + parent = printStack[i]; + } else { + return false; + } + } + + return false; +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/whitespace.js b/node_modules/@babel/generator/lib/node/whitespace.js new file mode 100644 index 0000000..60dd7be --- /dev/null +++ b/node_modules/@babel/generator/lib/node/whitespace.js @@ -0,0 +1,174 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nodes = void 0; + +var _t = require("@babel/types"); + +const { + FLIPPED_ALIAS_KEYS, + isArrayExpression, + isAssignmentExpression, + isBinary, + isBlockStatement, + isCallExpression, + isFunction, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isOptionalCallExpression, + isOptionalMemberExpression, + isStringLiteral +} = _t; + +function crawlInternal(node, state) { + if (!node) return state; + + if (isMemberExpression(node) || isOptionalMemberExpression(node)) { + crawlInternal(node.object, state); + if (node.computed) crawlInternal(node.property, state); + } else if (isBinary(node) || isAssignmentExpression(node)) { + crawlInternal(node.left, state); + crawlInternal(node.right, state); + } else if (isCallExpression(node) || isOptionalCallExpression(node)) { + state.hasCall = true; + crawlInternal(node.callee, state); + } else if (isFunction(node)) { + state.hasFunction = true; + } else if (isIdentifier(node)) { + state.hasHelper = state.hasHelper || node.callee && isHelper(node.callee); + } + + return state; +} + +function crawl(node) { + return crawlInternal(node, { + hasCall: false, + hasFunction: false, + hasHelper: false + }); +} + +function isHelper(node) { + if (!node) return false; + + if (isMemberExpression(node)) { + return isHelper(node.object) || isHelper(node.property); + } else if (isIdentifier(node)) { + return node.name === "require" || node.name.charCodeAt(0) === 95; + } else if (isCallExpression(node)) { + return isHelper(node.callee); + } else if (isBinary(node) || isAssignmentExpression(node)) { + return isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); + } else { + return false; + } +} + +function isType(node) { + return isLiteral(node) || isObjectExpression(node) || isArrayExpression(node) || isIdentifier(node) || isMemberExpression(node); +} + +const nodes = { + AssignmentExpression(node) { + const state = crawl(node.right); + + if (state.hasCall && state.hasHelper || state.hasFunction) { + return state.hasFunction ? 1 | 2 : 2; + } + }, + + SwitchCase(node, parent) { + return (!!node.consequent.length || parent.cases[0] === node ? 1 : 0) | (!node.consequent.length && parent.cases[parent.cases.length - 1] === node ? 2 : 0); + }, + + LogicalExpression(node) { + if (isFunction(node.left) || isFunction(node.right)) { + return 2; + } + }, + + Literal(node) { + if (isStringLiteral(node) && node.value === "use strict") { + return 2; + } + }, + + CallExpression(node) { + if (isFunction(node.callee) || isHelper(node)) { + return 1 | 2; + } + }, + + OptionalCallExpression(node) { + if (isFunction(node.callee)) { + return 1 | 2; + } + }, + + VariableDeclaration(node) { + for (let i = 0; i < node.declarations.length; i++) { + const declar = node.declarations[i]; + let enabled = isHelper(declar.id) && !isType(declar.init); + + if (!enabled && declar.init) { + const state = crawl(declar.init); + enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; + } + + if (enabled) { + return 1 | 2; + } + } + }, + + IfStatement(node) { + if (isBlockStatement(node.consequent)) { + return 1 | 2; + } + } + +}; +exports.nodes = nodes; + +nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) { + if (parent.properties[0] === node) { + return 1; + } +}; + +nodes.ObjectTypeCallProperty = function (node, parent) { + var _parent$properties; + + if (parent.callProperties[0] === node && !((_parent$properties = parent.properties) != null && _parent$properties.length)) { + return 1; + } +}; + +nodes.ObjectTypeIndexer = function (node, parent) { + var _parent$properties2, _parent$callPropertie; + + if (parent.indexers[0] === node && !((_parent$properties2 = parent.properties) != null && _parent$properties2.length) && !((_parent$callPropertie = parent.callProperties) != null && _parent$callPropertie.length)) { + return 1; + } +}; + +nodes.ObjectTypeInternalSlot = function (node, parent) { + var _parent$properties3, _parent$callPropertie2, _parent$indexers; + + if (parent.internalSlots[0] === node && !((_parent$properties3 = parent.properties) != null && _parent$properties3.length) && !((_parent$callPropertie2 = parent.callProperties) != null && _parent$callPropertie2.length) && !((_parent$indexers = parent.indexers) != null && _parent$indexers.length)) { + return 1; + } +}; + +[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function ([type, amounts]) { + [type].concat(FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { + const ret = amounts ? 1 | 2 : 0; + + nodes[type] = () => ret; + }); +}); \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/printer.js b/node_modules/@babel/generator/lib/printer.js new file mode 100644 index 0000000..8d33734 --- /dev/null +++ b/node_modules/@babel/generator/lib/printer.js @@ -0,0 +1,614 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _buffer = require("./buffer"); + +var n = require("./node"); + +var generatorFunctions = require("./generators"); + +const SCIENTIFIC_NOTATION = /e/i; +const ZERO_DECIMAL_INTEGER = /\.0+$/; +const NON_DECIMAL_LITERAL = /^0[box]/; +const PURE_ANNOTATION_RE = /^\s*[@#]__PURE__\s*$/; +const { + needsParens, + needsWhitespaceAfter, + needsWhitespaceBefore +} = n; + +class Printer { + constructor(format, map) { + this.inForStatementInitCounter = 0; + this._printStack = []; + this._indent = 0; + this._indentChar = 0; + this._indentRepeat = 0; + this._insideAux = false; + this._parenPushNewlineState = null; + this._noLineTerminator = false; + this._printAuxAfterOnNextUserNode = false; + this._printedComments = new Set(); + this._endsWithInteger = false; + this._endsWithWord = false; + this.format = format; + this._buf = new _buffer.default(map); + this._indentChar = format.indent.style.charCodeAt(0); + this._indentRepeat = format.indent.style.length; + } + + generate(ast) { + this.print(ast); + + this._maybeAddAuxComment(); + + return this._buf.get(); + } + + indent() { + if (this.format.compact || this.format.concise) return; + this._indent++; + } + + dedent() { + if (this.format.compact || this.format.concise) return; + this._indent--; + } + + semicolon(force = false) { + this._maybeAddAuxComment(); + + if (force) { + this._appendChar(59); + } else { + this._queue(59); + } + } + + rightBrace() { + if (this.format.minified) { + this._buf.removeLastSemicolon(); + } + + this.tokenChar(125); + } + + space(force = false) { + if (this.format.compact) return; + + if (force) { + this._space(); + } else if (this._buf.hasContent()) { + const lastCp = this.getLastChar(); + + if (lastCp !== 32 && lastCp !== 10) { + this._space(); + } + } + } + + word(str) { + if (this._endsWithWord || str.charCodeAt(0) === 47 && this.endsWith(47)) { + this._space(); + } + + this._maybeAddAuxComment(); + + this._append(str, false); + + this._endsWithWord = true; + } + + number(str) { + this.word(str); + this._endsWithInteger = Number.isInteger(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== 46; + } + + token(str, maybeNewline = false) { + const lastChar = this.getLastChar(); + const strFirst = str.charCodeAt(0); + + if (lastChar === 33 && str === "--" || strFirst === 43 && lastChar === 43 || strFirst === 45 && lastChar === 45 || strFirst === 46 && this._endsWithInteger) { + this._space(); + } + + this._maybeAddAuxComment(); + + this._append(str, maybeNewline); + } + + tokenChar(char) { + const lastChar = this.getLastChar(); + + if (char === 43 && lastChar === 43 || char === 45 && lastChar === 45 || char === 46 && this._endsWithInteger) { + this._space(); + } + + this._maybeAddAuxComment(); + + this._appendChar(char); + } + + newline(i = 1) { + if (this.format.retainLines || this.format.compact) return; + + if (this.format.concise) { + this.space(); + return; + } + + const charBeforeNewline = this.endsWithCharAndNewline(); + if (charBeforeNewline === 10) return; + + if (charBeforeNewline === 123 || charBeforeNewline === 58) { + i--; + } + + if (i <= 0) return; + + for (let j = 0; j < i; j++) { + this._newline(); + } + } + + endsWith(char) { + return this.getLastChar() === char; + } + + getLastChar() { + return this._buf.getLastChar(); + } + + endsWithCharAndNewline() { + return this._buf.endsWithCharAndNewline(); + } + + removeTrailingNewline() { + this._buf.removeTrailingNewline(); + } + + exactSource(loc, cb) { + this._catchUp("start", loc); + + this._buf.exactSource(loc, cb); + } + + source(prop, loc) { + this._catchUp(prop, loc); + + this._buf.source(prop, loc); + } + + withSource(prop, loc, cb) { + this._catchUp(prop, loc); + + this._buf.withSource(prop, loc, cb); + } + + _space() { + this._queue(32); + } + + _newline() { + this._queue(10); + } + + _append(str, maybeNewline) { + this._maybeAddParen(str); + + this._maybeIndent(str.charCodeAt(0)); + + this._buf.append(str, maybeNewline); + + this._endsWithWord = false; + this._endsWithInteger = false; + } + + _appendChar(char) { + this._maybeAddParenChar(char); + + this._maybeIndent(char); + + this._buf.appendChar(char); + + this._endsWithWord = false; + this._endsWithInteger = false; + } + + _queue(char) { + this._maybeAddParenChar(char); + + this._maybeIndent(char); + + this._buf.queue(char); + + this._endsWithWord = false; + this._endsWithInteger = false; + } + + _maybeIndent(firstChar) { + if (this._indent && firstChar !== 10 && this.endsWith(10)) { + this._buf.queueIndentation(this._indentChar, this._getIndent()); + } + } + + _maybeAddParenChar(char) { + const parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + + if (char === 32) { + return; + } + + if (char !== 10) { + this._parenPushNewlineState = null; + return; + } + + this.tokenChar(40); + this.indent(); + parenPushNewlineState.printed = true; + } + + _maybeAddParen(str) { + const parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + const len = str.length; + let i; + + for (i = 0; i < len && str.charCodeAt(i) === 32; i++) continue; + + if (i === len) { + return; + } + + const cha = str.charCodeAt(i); + + if (cha !== 10) { + if (cha !== 47 || i + 1 === len) { + this._parenPushNewlineState = null; + return; + } + + const chaPost = str.charCodeAt(i + 1); + + if (chaPost === 42) { + if (PURE_ANNOTATION_RE.test(str.slice(i + 2, len - 2))) { + return; + } + } else if (chaPost !== 47) { + this._parenPushNewlineState = null; + return; + } + } + + this.tokenChar(40); + this.indent(); + parenPushNewlineState.printed = true; + } + + _catchUp(prop, loc) { + if (!this.format.retainLines) return; + const pos = loc ? loc[prop] : null; + + if ((pos == null ? void 0 : pos.line) != null) { + const count = pos.line - this._buf.getCurrentLine(); + + for (let i = 0; i < count; i++) { + this._newline(); + } + } + } + + _getIndent() { + return this._indentRepeat * this._indent; + } + + printTerminatorless(node, parent, isLabel) { + if (isLabel) { + this._noLineTerminator = true; + this.print(node, parent); + this._noLineTerminator = false; + } else { + const terminatorState = { + printed: false + }; + this._parenPushNewlineState = terminatorState; + this.print(node, parent); + + if (terminatorState.printed) { + this.dedent(); + this.newline(); + this.tokenChar(41); + } + } + } + + print(node, parent, noLineTerminator) { + if (!node) return; + const nodeType = node.type; + const format = this.format; + const oldConcise = format.concise; + + if (node._compact) { + format.concise = true; + } + + const printMethod = this[nodeType]; + + if (printMethod === undefined) { + throw new ReferenceError(`unknown node of type ${JSON.stringify(nodeType)} with constructor ${JSON.stringify(node.constructor.name)}`); + } + + this._printStack.push(node); + + const oldInAux = this._insideAux; + this._insideAux = node.loc == undefined; + + this._maybeAddAuxComment(this._insideAux && !oldInAux); + + let shouldPrintParens; + + if (format.retainFunctionParens && nodeType === "FunctionExpression" && node.extra && node.extra.parenthesized) { + shouldPrintParens = true; + } else { + shouldPrintParens = needsParens(node, parent, this._printStack); + } + + if (shouldPrintParens) this.tokenChar(40); + + this._printLeadingComments(node); + + const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc; + this.withSource("start", loc, printMethod.bind(this, node, parent)); + + if (noLineTerminator && !this._noLineTerminator) { + this._noLineTerminator = true; + + this._printTrailingComments(node); + + this._noLineTerminator = false; + } else { + this._printTrailingComments(node); + } + + if (shouldPrintParens) this.tokenChar(41); + + this._printStack.pop(); + + format.concise = oldConcise; + this._insideAux = oldInAux; + } + + _maybeAddAuxComment(enteredPositionlessNode) { + if (enteredPositionlessNode) this._printAuxBeforeComment(); + if (!this._insideAux) this._printAuxAfterComment(); + } + + _printAuxBeforeComment() { + if (this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = true; + const comment = this.format.auxiliaryCommentBefore; + + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } + } + + _printAuxAfterComment() { + if (!this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = false; + const comment = this.format.auxiliaryCommentAfter; + + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } + } + + getPossibleRaw(node) { + const extra = node.extra; + + if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { + return extra.raw; + } + } + + printJoin(nodes, parent, opts = {}) { + if (!(nodes != null && nodes.length)) return; + if (opts.indent) this.indent(); + const newlineOpts = { + addNewlines: opts.addNewlines + }; + const len = nodes.length; + + for (let i = 0; i < len; i++) { + const node = nodes[i]; + if (!node) continue; + if (opts.statement) this._printNewline(true, node, parent, newlineOpts); + this.print(node, parent); + + if (opts.iterator) { + opts.iterator(node, i); + } + + if (opts.separator && i < len - 1) { + opts.separator.call(this); + } + + if (opts.statement) this._printNewline(false, node, parent, newlineOpts); + } + + if (opts.indent) this.dedent(); + } + + printAndIndentOnComments(node, parent) { + const indent = node.leadingComments && node.leadingComments.length > 0; + if (indent) this.indent(); + this.print(node, parent); + if (indent) this.dedent(); + } + + printBlock(parent) { + const node = parent.body; + + if (node.type !== "EmptyStatement") { + this.space(); + } + + this.print(node, parent); + } + + _printTrailingComments(node) { + this._printComments(this._getComments(false, node)); + } + + _printLeadingComments(node) { + this._printComments(this._getComments(true, node), true); + } + + printInnerComments(node, indent = true) { + var _node$innerComments; + + if (!((_node$innerComments = node.innerComments) != null && _node$innerComments.length)) return; + if (indent) this.indent(); + + this._printComments(node.innerComments); + + if (indent) this.dedent(); + } + + printSequence(nodes, parent, opts = {}) { + opts.statement = true; + return this.printJoin(nodes, parent, opts); + } + + printList(items, parent, opts = {}) { + if (opts.separator == null) { + opts.separator = commaSeparator; + } + + return this.printJoin(items, parent, opts); + } + + _printNewline(leading, node, parent, opts) { + if (this.format.retainLines || this.format.compact) return; + + if (this.format.concise) { + this.space(); + return; + } + + let lines = 0; + + if (this._buf.hasContent()) { + if (!leading) lines++; + if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; + const needs = leading ? needsWhitespaceBefore : needsWhitespaceAfter; + if (needs(node, parent)) lines++; + } + + this.newline(Math.min(2, lines)); + } + + _getComments(leading, node) { + return node && (leading ? node.leadingComments : node.trailingComments) || null; + } + + _printComment(comment, skipNewLines) { + if (comment.ignore) return; + if (this._printedComments.has(comment)) return; + if (!this.format.shouldPrintComment(comment.value)) return; + + this._printedComments.add(comment); + + const isBlockComment = comment.type === "CommentBlock"; + const printNewLines = isBlockComment && !skipNewLines && !this._noLineTerminator; + if (printNewLines && this._buf.hasContent()) this.newline(1); + const lastCharCode = this.getLastChar(); + + if (lastCharCode !== 91 && lastCharCode !== 123) { + this.space(); + } + + let val; + let maybeNewline = false; + + if (isBlockComment) { + val = `/*${comment.value}*/`; + + if (this.format.indent.adjustMultilineComment) { + var _comment$loc; + + const offset = (_comment$loc = comment.loc) == null ? void 0 : _comment$loc.start.column; + + if (offset) { + const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); + val = val.replace(newlineRegex, "\n"); + } + + const indentSize = Math.max(this._getIndent(), this.format.retainLines ? 0 : this._buf.getCurrentColumn()); + val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); + maybeNewline = true; + } + } else if (!this._noLineTerminator) { + val = `//${comment.value}\n`; + maybeNewline = true; + } else { + val = `/*${comment.value}*/`; + } + + if (this.endsWith(47)) this._space(); + this.withSource("start", comment.loc, this._append.bind(this, val, maybeNewline)); + if (printNewLines) this.newline(1); + } + + _printComments(comments, inlinePureAnnotation) { + if (!(comments != null && comments.length)) return; + + if (inlinePureAnnotation && comments.length === 1 && PURE_ANNOTATION_RE.test(comments[0].value)) { + this._printComment(comments[0], this._buf.hasContent() && !this.endsWith(10)); + } else { + for (const comment of comments) { + this._printComment(comment); + } + } + } + + printAssertions(node) { + var _node$assertions; + + if ((_node$assertions = node.assertions) != null && _node$assertions.length) { + this.space(); + this.word("assert"); + this.space(); + this.tokenChar(123); + this.space(); + this.printList(node.assertions, node); + this.space(); + this.tokenChar(125); + } + } + +} + +Object.assign(Printer.prototype, generatorFunctions); +{ + Printer.prototype.Noop = function Noop() {}; +} +var _default = Printer; +exports.default = _default; + +function commaSeparator() { + this.tokenChar(44); + this.space(); +} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/source-map.js b/node_modules/@babel/generator/lib/source-map.js new file mode 100644 index 0000000..e611778 --- /dev/null +++ b/node_modules/@babel/generator/lib/source-map.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _genMapping = require("@jridgewell/gen-mapping"); + +class SourceMap { + constructor(opts, code) { + var _opts$sourceFileName; + + this._map = void 0; + this._rawMappings = void 0; + this._sourceFileName = void 0; + this._lastGenLine = 0; + this._lastSourceLine = 0; + this._lastSourceColumn = 0; + const map = this._map = new _genMapping.GenMapping({ + sourceRoot: opts.sourceRoot + }); + this._sourceFileName = (_opts$sourceFileName = opts.sourceFileName) == null ? void 0 : _opts$sourceFileName.replace(/\\/g, "/"); + this._rawMappings = undefined; + + if (typeof code === "string") { + (0, _genMapping.setSourceContent)(map, this._sourceFileName, code); + } else if (typeof code === "object") { + Object.keys(code).forEach(sourceFileName => { + (0, _genMapping.setSourceContent)(map, sourceFileName.replace(/\\/g, "/"), code[sourceFileName]); + }); + } + } + + get() { + return (0, _genMapping.toEncodedMap)(this._map); + } + + getDecoded() { + return (0, _genMapping.toDecodedMap)(this._map); + } + + getRawMappings() { + return this._rawMappings || (this._rawMappings = (0, _genMapping.allMappings)(this._map)); + } + + mark(generated, line, column, identifierName, filename) { + this._rawMappings = undefined; + (0, _genMapping.maybeAddMapping)(this._map, { + name: identifierName, + generated, + source: line == null ? undefined : (filename == null ? void 0 : filename.replace(/\\/g, "/")) || this._sourceFileName, + original: line == null ? undefined : { + line: line, + column: column + } + }); + } + +} + +exports.default = SourceMap; \ No newline at end of file diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/LICENSE b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/LICENSE new file mode 100644 index 0000000..352f071 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/README.md b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/README.md new file mode 100644 index 0000000..4066cdb --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/README.md @@ -0,0 +1,227 @@ +# @jridgewell/gen-mapping + +> Generate source maps + +`gen-mapping` allows you to generate a source map during transpilation or minification. +With a source map, you're able to trace the original location in the source file, either in Chrome's +DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping]. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This +provides the same `addMapping` and `setSourceContent` API. + +## Installation + +```sh +npm install @jridgewell/gen-mapping +``` + +## Usage + +```typescript +import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping'; + +const map = new GenMapping({ + file: 'output.js', + sourceRoot: 'https://example.com/', +}); + +setSourceContent(map, 'input.js', `function foo() {}`); + +addMapping(map, { + // Lines start at line 1, columns at column 0. + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +addMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 9 }, + name: 'foo', +}); + +assert.deepEqual(toDecodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: [ + [ [0, 0, 0, 0], [9, 0, 0, 9, 0] ] + ], +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: 'AAAA,SAASA', +}); +``` + +### Smaller Sourcemaps + +Not everything needs to be added to a sourcemap, and needless markings can cause signficantly +larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will +intelligently determine if this marking adds useful information. If not, the marking will be +skipped. + +```typescript +import { maybeAddMapping } from '@jridgewell/gen-mapping'; + +const map = new GenMapping(); + +// Adding a sourceless marking at the beginning of a line isn't useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, +}); + +// Adding a new source marking is useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +// But adding another marking pointing to the exact same original location isn't, even if the +// generated column changed. +maybeAddMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + names: [], + sources: ['input.js'], + sourcesContent: [null], + mappings: 'AAAA', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +Memory Usage: +gen-mapping: addSegment 5852872 bytes +gen-mapping: addMapping 7716042 bytes +source-map-js 6143250 bytes +source-map-0.6.1 6124102 bytes +source-map-0.8.0 6121173 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 441 ops/sec ±2.07% (90 runs sampled) +gen-mapping: addMapping x 350 ops/sec ±2.40% (86 runs sampled) +source-map-js: addMapping x 169 ops/sec ±2.42% (80 runs sampled) +source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled) +source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled) +gen-mapping: encoded output x 663 ops/sec ±0.22% (98 runs sampled) +source-map-js: encoded output x 197 ops/sec ±0.45% (84 runs sampled) +source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled) +source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +babel.min.js.map +Memory Usage: +gen-mapping: addSegment 37578063 bytes +gen-mapping: addMapping 37212897 bytes +source-map-js 47638527 bytes +source-map-0.6.1 47690503 bytes +source-map-0.8.0 47470188 bytes +Smallest memory usage is gen-mapping: addMapping + +Adding speed: +gen-mapping: addSegment x 31.05 ops/sec ±8.31% (43 runs sampled) +gen-mapping: addMapping x 29.83 ops/sec ±7.36% (51 runs sampled) +source-map-js: addMapping x 20.73 ops/sec ±6.22% (38 runs sampled) +source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled) +source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled) +gen-mapping: encoded output x 95.15 ops/sec ±2.98% (72 runs sampled) +source-map-js: encoded output x 15.20 ops/sec ±7.41% (33 runs sampled) +source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled) +source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +preact.js.map +Memory Usage: +gen-mapping: addSegment 416247 bytes +gen-mapping: addMapping 419824 bytes +source-map-js 1024619 bytes +source-map-0.6.1 1146004 bytes +source-map-0.8.0 1113250 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 13,755 ops/sec ±0.15% (98 runs sampled) +gen-mapping: addMapping x 13,013 ops/sec ±0.11% (101 runs sampled) +source-map-js: addMapping x 4,564 ops/sec ±0.21% (98 runs sampled) +source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled) +source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled) +gen-mapping: encoded output x 14,368 ops/sec ±4.07% (82 runs sampled) +source-map-js: encoded output x 5,261 ops/sec ±0.21% (99 runs sampled) +source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled) +source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +react.js.map +Memory Usage: +gen-mapping: addSegment 975096 bytes +gen-mapping: addMapping 1102981 bytes +source-map-js 2918836 bytes +source-map-0.6.1 2885435 bytes +source-map-0.8.0 2874336 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 4,772 ops/sec ±0.15% (100 runs sampled) +gen-mapping: addMapping x 4,456 ops/sec ±0.13% (97 runs sampled) +source-map-js: addMapping x 1,618 ops/sec ±0.24% (97 runs sampled) +source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled) +source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled) +gen-mapping: encoded output x 5,421 ops/sec ±1.60% (89 runs sampled) +source-map-js: encoded output x 2,113 ops/sec ±1.81% (98 runs sampled) +source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled) +source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled) +Fastest is gen-mapping: decoded output +``` + +[source-map]: https://www.npmjs.com/package/source-map +[trace-mapping]: https://github.com/jridgewell/trace-mapping diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs new file mode 100644 index 0000000..5aeb5cc --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs @@ -0,0 +1,230 @@ +import { SetArray, put } from '@jridgewell/set-array'; +import { encode } from '@jridgewell/sourcemap-codec'; +import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping'; + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +const NO_NAME = -1; +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +let addSegment; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +let addMapping; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +let maybeAddSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +let maybeAddMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +let setSourceContent; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toDecodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toEncodedMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +let fromMap; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +let allMappings; +// This split declaration is only so that terser can elminiate the static initialization block. +let addSegmentInternal; +/** + * Provides the state to generate a sourcemap. + */ +class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } +} +(() => { + addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + addMapping = (map, mapping) => { + return addMappingInternal(false, map, mapping); + }; + maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); + }; + setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[put(sources, source)] = content; + }; + toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + toEncodedMap = (map) => { + const decoded = toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) }); + }; + allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; + fromMap = (input) => { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(gen._names, map.names); + putAll(gen._sources, map.sources); + gen._sourcesContent = map.sourcesContent || map.sources.map(() => null); + gen._mappings = decodedMappings(map); + return gen; + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + }; +})(); +function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; +} +function putAll(strarr, array) { + for (let i = 0; i < array.length; i++) + put(strarr, array[i]); +} +function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + const s = source; + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content); +} + +export { GenMapping, addMapping, addSegment, allMappings, fromMap, maybeAddMapping, maybeAddSegment, setSourceContent, toDecodedMap, toEncodedMap }; +//# sourceMappingURL=gen-mapping.mjs.map diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map new file mode 100644 index 0000000..2fee0cd --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.mjs","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n ): void;\n};\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport let maybeAddSegment: typeof addSegment;\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport let maybeAddMapping: typeof addMapping;\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toDecodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toEncodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport let fromMap: (input: SourceMapInput) => GenMapping;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nlet addSegmentInternal: (\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n) => void;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n maybeAddSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n addMapping = (map, mapping) => {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n };\n\n maybeAddMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n toDecodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: file || undefined,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n toEncodedMap = (map) => {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n\n fromMap = (input) => {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(gen._names, map.names);\n putAll(gen._sources, map.sources as string[]);\n gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n gen._mappings = decodedMappings(map) as GenMapping['_mappings'];\n\n return gen;\n };\n\n // Internal helpers\n addSegmentInternal = (\n skipable,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(strarr: SetArray, array: string[]) {\n for (let i = 0; i < array.length; i++) put(strarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n const s: string = source;\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n s,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":[],"mappings":";;;;AAWO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC;;ACQ5B,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;AAEnB;;;AAGG;AACQ,IAAA,WA+BT;AAEF;;;AAGG;AACQ,IAAA,WA+BT;AAEF;;;;AAIG;AACQ,IAAA,gBAAmC;AAE9C;;;;AAIG;AACQ,IAAA,gBAAmC;AAE9C;;AAEG;AACQ,IAAA,iBAAoF;AAE/F;;;AAGG;AACQ,IAAA,aAAoD;AAE/D;;;AAGG;AACQ,IAAA,aAAoD;AAE/D;;AAEG;AACQ,IAAA,QAA+C;AAE1D;;;AAGG;AACQ,IAAA,YAA4C;AAEvD;AACA,IAAI,kBAUK,CAAC;AAEV;;AAEG;MACU,UAAU,CAAA;AAQrB,IAAA,WAAA,CAAY,EAAE,IAAI,EAAE,UAAU,KAAc,EAAE,EAAA;AAPtC,QAAA,IAAA,CAAA,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;AACxB,QAAA,IAAA,CAAA,QAAQ,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC1B,IAAe,CAAA,eAAA,GAAsB,EAAE,CAAC;QACxC,IAAS,CAAA,SAAA,GAAyB,EAAE,CAAC;AAK3C,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACjB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;KAC9B;AA2KF,CAAA;AAzKC,CAAA,MAAA;AACE,IAAA,UAAU,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,KAAI;QACxF,OAAO,kBAAkB,CACvB,KAAK,EACL,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,CACR,CAAC;AACJ,KAAC,CAAC;AAEF,IAAA,eAAe,GAAG,CAChB,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,KACL;QACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,CACR,CAAC;AACJ,KAAC,CAAC;AAEF,IAAA,UAAU,GAAG,CAAC,GAAG,EAAE,OAAO,KAAI;QAC5B,OAAO,kBAAkB,CAAC,KAAK,EAAE,GAAG,EAAE,OAAmD,CAAC,CAAC;AAC7F,KAAC,CAAC;AAEF,IAAA,eAAe,GAAG,CAAC,GAAG,EAAE,OAAO,KAAI;QACjC,OAAO,kBAAkB,CAAC,IAAI,EAAE,GAAG,EAAE,OAAmD,CAAC,CAAC;AAC5F,KAAC,CAAC;IAEF,gBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,KAAI;QAC1C,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;QACnE,cAAc,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC;AACjD,KAAC,CAAC;AAEF,IAAA,YAAY,GAAG,CAAC,GAAG,KAAI;QACrB,MAAM,EACJ,IAAI,EACJ,UAAU,EACV,SAAS,EAAE,QAAQ,EACnB,QAAQ,EAAE,OAAO,EACjB,eAAe,EAAE,cAAc,EAC/B,MAAM,EAAE,KAAK,GACd,GAAG,GAAG,CAAC;QACR,qBAAqB,CAAC,QAAQ,CAAC,CAAC;QAEhC,OAAO;AACL,YAAA,OAAO,EAAE,CAAC;YACV,IAAI,EAAE,IAAI,IAAI,SAAS;YACvB,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,UAAU,EAAE,UAAU,IAAI,SAAS;YACnC,OAAO,EAAE,OAAO,CAAC,KAAK;YACtB,cAAc;YACd,QAAQ;SACT,CAAC;AACJ,KAAC,CAAC;AAEF,IAAA,YAAY,GAAG,CAAC,GAAG,KAAI;AACrB,QAAA,MAAM,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;QAClC,OACK,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,EAAA,EAAA,OAAO,CACV,EAAA,EAAA,QAAQ,EAAE,MAAM,CAAC,OAAO,CAAC,QAAgC,CAAC,EAC1D,CAAA,CAAA;AACJ,KAAC,CAAC;AAEF,IAAA,WAAW,GAAG,CAAC,GAAG,KAAI;QACpB,MAAM,GAAG,GAAc,EAAE,CAAC;AAC1B,QAAA,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC;AAEtE,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACxC,YAAA,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AACzB,YAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACpC,gBAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAEpB,gBAAA,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;gBACvD,IAAI,MAAM,GAAuB,SAAS,CAAC;gBAC3C,IAAI,QAAQ,GAAoB,SAAS,CAAC;gBAC1C,IAAI,IAAI,GAAuB,SAAS,CAAC;AAEzC,gBAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;oBACpB,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC;AAC3C,oBAAA,QAAQ,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;AAEtE,oBAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;wBAAE,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC;AAC5D,iBAAA;AAED,gBAAA,GAAG,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAa,CAAC,CAAC;AAC5D,aAAA;AACF,SAAA;AAED,QAAA,OAAO,GAAG,CAAC;AACb,KAAC,CAAC;AAEF,IAAA,OAAO,GAAG,CAAC,KAAK,KAAI;AAClB,QAAA,MAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC;AAChC,QAAA,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC;QAE3E,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;QAC9B,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,OAAmB,CAAC,CAAC;AAC9C,QAAA,GAAG,CAAC,eAAe,GAAG,GAAG,CAAC,cAAc,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;AACxE,QAAA,GAAG,CAAC,SAAS,GAAG,eAAe,CAAC,GAAG,CAA4B,CAAC;AAEhE,QAAA,OAAO,GAAG,CAAC;AACb,KAAC,CAAC;;IAGF,kBAAkB,GAAG,CACnB,QAAQ,EACR,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,KACL;AACF,QAAA,MAAM,EACJ,SAAS,EAAE,QAAQ,EACnB,QAAQ,EAAE,OAAO,EACjB,eAAe,EAAE,cAAc,EAC/B,MAAM,EAAE,KAAK,GACd,GAAG,GAAG,CAAC;QACR,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QACxC,MAAM,KAAK,GAAG,cAAc,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QAE9C,IAAI,CAAC,MAAM,EAAE;AACX,YAAA,IAAI,QAAQ,IAAI,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC;gBAAE,OAAO;YACpD,OAAO,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;AACzC,SAAA;QAOD,MAAM,YAAY,GAAG,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAC1C,QAAA,MAAM,UAAU,GAAG,IAAI,GAAG,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC;AACrD,QAAA,IAAI,YAAY,KAAK,cAAc,CAAC,MAAM;YAAE,cAAc,CAAC,YAAY,CAAC,GAAG,OAAO,KAAP,IAAA,IAAA,OAAO,KAAP,KAAA,CAAA,GAAA,OAAO,GAAI,IAAI,CAAC;AAE3F,QAAA,IAAI,QAAQ,IAAI,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,EAAE;YAC3F,OAAO;AACR,SAAA;AAED,QAAA,OAAO,MAAM,CACX,IAAI,EACJ,KAAK,EACL,IAAI;cACA,CAAC,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC;cAC/D,CAAC,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,CACxD,CAAC;AACJ,KAAC,CAAC;AACJ,CAAC,GAAA,CAAA;AAOH,SAAS,OAAO,CAAC,QAA8B,EAAE,KAAa,EAAA;AAC5D,IAAA,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE,EAAE;AAC7C,QAAA,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AAClB,KAAA;AACD,IAAA,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC;AAED,SAAS,cAAc,CAAC,IAAwB,EAAE,SAAiB,EAAA;AACjE,IAAA,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC;AACxB,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE;AAC3C,QAAA,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACxB,QAAA,IAAI,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC;YAAE,MAAM;AACzC,KAAA;AACD,IAAA,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,MAAM,CAAI,KAAU,EAAE,KAAa,EAAE,KAAQ,EAAA;AACpD,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;QACzC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACzB,KAAA;AACD,IAAA,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;AACvB,CAAC;AAED,SAAS,qBAAqB,CAAC,QAA8B,EAAA;AAC3D,IAAA,MAAM,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC;IAC5B,IAAI,GAAG,GAAG,MAAM,CAAC;AACjB,IAAA,KAAK,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC1C,QAAA,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC;YAAE,MAAM;AACnC,KAAA;IACD,IAAI,GAAG,GAAG,MAAM;AAAE,QAAA,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;AAC1C,CAAC;AAED,SAAS,MAAM,CAAC,MAAgB,EAAE,KAAe,EAAA;AAC/C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,cAAc,CAAC,IAAwB,EAAE,KAAa,EAAA;;;IAG7D,IAAI,KAAK,KAAK,CAAC;AAAE,QAAA,OAAO,IAAI,CAAC;IAE7B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;;;;AAI7B,IAAA,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,UAAU,CACjB,IAAwB,EACxB,KAAa,EACb,YAAoB,EACpB,UAAkB,EAClB,YAAoB,EACpB,UAAkB,EAAA;;IAGlB,IAAI,KAAK,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK,CAAC;IAE9B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;;AAG7B,IAAA,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK,CAAC;;;AAIpC,IAAA,QACE,YAAY,KAAK,IAAI,CAAC,aAAa,CAAC;AACpC,QAAA,UAAU,KAAK,IAAI,CAAC,WAAW,CAAC;AAChC,QAAA,YAAY,KAAK,IAAI,CAAC,aAAa,CAAC;QACpC,UAAU,MAAM,IAAI,CAAC,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC,EAChE;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,QAAiB,EACjB,GAAe,EACf,OAMC,EAAA;AAED,IAAA,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAC/D,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,CACL,CAAC;AACH,KAAA;IACD,MAAM,CAAC,GAAW,MAAM,CAAC;AAEzB,IAAA,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,CAAC,EACD,QAAQ,CAAC,IAAI,GAAG,CAAC,EACjB,QAAQ,CAAC,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;AACJ;;;;"} \ No newline at end of file diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js new file mode 100644 index 0000000..d9fcf5c --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js @@ -0,0 +1,236 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/set-array'), require('@jridgewell/sourcemap-codec'), require('@jridgewell/trace-mapping')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/set-array', '@jridgewell/sourcemap-codec', '@jridgewell/trace-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.genMapping = {}, global.setArray, global.sourcemapCodec, global.traceMapping)); +})(this, (function (exports, setArray, sourcemapCodec, traceMapping) { 'use strict'; + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + + const NO_NAME = -1; + /** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ + exports.addSegment = void 0; + /** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ + exports.addMapping = void 0; + /** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ + exports.maybeAddSegment = void 0; + /** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ + exports.maybeAddMapping = void 0; + /** + * Adds/removes the content of the source file to the source map. + */ + exports.setSourceContent = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.toDecodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.toEncodedMap = void 0; + /** + * Constructs a new GenMapping, using the already present mappings of the input. + */ + exports.fromMap = void 0; + /** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ + exports.allMappings = void 0; + // This split declaration is only so that terser can elminiate the static initialization block. + let addSegmentInternal; + /** + * Provides the state to generate a sourcemap. + */ + class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new setArray.SetArray(); + this._sources = new setArray.SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } + } + (() => { + exports.addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + exports.maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + exports.addMapping = (map, mapping) => { + return addMappingInternal(false, map, mapping); + }; + exports.maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); + }; + exports.setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[setArray.put(sources, source)] = content; + }; + exports.toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + exports.toEncodedMap = (map) => { + const decoded = exports.toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: sourcemapCodec.encode(decoded.mappings) }); + }; + exports.allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; + exports.fromMap = (input) => { + const map = new traceMapping.TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(gen._names, map.names); + putAll(gen._sources, map.sources); + gen._sourcesContent = map.sourcesContent || map.sources.map(() => null); + gen._mappings = traceMapping.decodedMappings(map); + return gen; + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = setArray.put(sources, source); + const namesIndex = name ? setArray.put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + }; + })(); + function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; + } + function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; + } + function putAll(strarr, array) { + for (let i = 0; i < array.length; i++) + setArray.put(strarr, array[i]); + } + function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; + } + function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); + } + function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + const s = source; + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content); + } + + exports.GenMapping = GenMapping; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=gen-mapping.umd.js.map diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map new file mode 100644 index 0000000..7cc8d14 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.umd.js","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n ): void;\n};\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport let maybeAddSegment: typeof addSegment;\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport let maybeAddMapping: typeof addMapping;\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toDecodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toEncodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport let fromMap: (input: SourceMapInput) => GenMapping;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nlet addSegmentInternal: (\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n) => void;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n maybeAddSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n addMapping = (map, mapping) => {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n };\n\n maybeAddMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n toDecodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: file || undefined,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n toEncodedMap = (map) => {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n\n fromMap = (input) => {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(gen._names, map.names);\n putAll(gen._sources, map.sources as string[]);\n gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n gen._mappings = decodedMappings(map) as GenMapping['_mappings'];\n\n return gen;\n };\n\n // Internal helpers\n addSegmentInternal = (\n skipable,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(strarr: SetArray, array: string[]) {\n for (let i = 0; i < array.length; i++) put(strarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n const s: string = source;\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n s,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":["addSegment","addMapping","maybeAddSegment","maybeAddMapping","setSourceContent","toDecodedMap","toEncodedMap","fromMap","allMappings","SetArray","put","encode","TraceMap","decodedMappings"],"mappings":";;;;;;IAWO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC;;ICQ5B,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;IAEnB;;;IAGG;AACQA,gCA+BT;IAEF;;;IAGG;AACQC,gCA+BT;IAEF;;;;IAIG;AACQC,qCAAmC;IAE9C;;;;IAIG;AACQC,qCAAmC;IAE9C;;IAEG;AACQC,sCAAoF;IAE/F;;;IAGG;AACQC,kCAAoD;IAE/D;;;IAGG;AACQC,kCAAoD;IAE/D;;IAEG;AACQC,6BAA+C;IAE1D;;;IAGG;AACQC,iCAA4C;IAEvD;IACA,IAAI,kBAUK,CAAC;IAEV;;IAEG;UACU,UAAU,CAAA;IAQrB,IAAA,WAAA,CAAY,EAAE,IAAI,EAAE,UAAU,KAAc,EAAE,EAAA;IAPtC,QAAA,IAAA,CAAA,MAAM,GAAG,IAAIC,iBAAQ,EAAE,CAAC;IACxB,QAAA,IAAA,CAAA,QAAQ,GAAG,IAAIA,iBAAQ,EAAE,CAAC;YAC1B,IAAe,CAAA,eAAA,GAAsB,EAAE,CAAC;YACxC,IAAS,CAAA,SAAA,GAAyB,EAAE,CAAC;IAK3C,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACjB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;SAC9B;IA2KF,CAAA;IAzKC,CAAA,MAAA;IACE,IAAAT,kBAAU,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,KAAI;YACxF,OAAO,kBAAkB,CACvB,KAAK,EACL,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,CACR,CAAC;IACJ,KAAC,CAAC;IAEF,IAAAE,uBAAe,GAAG,CAChB,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,KACL;YACF,OAAO,kBAAkB,CACvB,IAAI,EACJ,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,CACR,CAAC;IACJ,KAAC,CAAC;IAEF,IAAAD,kBAAU,GAAG,CAAC,GAAG,EAAE,OAAO,KAAI;YAC5B,OAAO,kBAAkB,CAAC,KAAK,EAAE,GAAG,EAAE,OAAmD,CAAC,CAAC;IAC7F,KAAC,CAAC;IAEF,IAAAE,uBAAe,GAAG,CAAC,GAAG,EAAE,OAAO,KAAI;YACjC,OAAO,kBAAkB,CAAC,IAAI,EAAE,GAAG,EAAE,OAAmD,CAAC,CAAC;IAC5F,KAAC,CAAC;QAEFC,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,KAAI;YAC1C,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,GAAG,CAAC;YACnE,cAAc,CAACM,YAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC;IACjD,KAAC,CAAC;IAEF,IAAAL,oBAAY,GAAG,CAAC,GAAG,KAAI;YACrB,MAAM,EACJ,IAAI,EACJ,UAAU,EACV,SAAS,EAAE,QAAQ,EACnB,QAAQ,EAAE,OAAO,EACjB,eAAe,EAAE,cAAc,EAC/B,MAAM,EAAE,KAAK,GACd,GAAG,GAAG,CAAC;YACR,qBAAqB,CAAC,QAAQ,CAAC,CAAC;YAEhC,OAAO;IACL,YAAA,OAAO,EAAE,CAAC;gBACV,IAAI,EAAE,IAAI,IAAI,SAAS;gBACvB,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,UAAU,EAAE,UAAU,IAAI,SAAS;gBACnC,OAAO,EAAE,OAAO,CAAC,KAAK;gBACtB,cAAc;gBACd,QAAQ;aACT,CAAC;IACJ,KAAC,CAAC;IAEF,IAAAC,oBAAY,GAAG,CAAC,GAAG,KAAI;IACrB,QAAA,MAAM,OAAO,GAAGD,oBAAY,CAAC,GAAG,CAAC,CAAC;YAClC,OACK,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,EAAA,EAAA,OAAO,CACV,EAAA,EAAA,QAAQ,EAAEM,qBAAM,CAAC,OAAO,CAAC,QAAgC,CAAC,EAC1D,CAAA,CAAA;IACJ,KAAC,CAAC;IAEF,IAAAH,mBAAW,GAAG,CAAC,GAAG,KAAI;YACpB,MAAM,GAAG,GAAc,EAAE,CAAC;IAC1B,QAAA,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC;IAEtE,QAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACxC,YAAA,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IACzB,YAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACpC,gBAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IAEpB,gBAAA,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;oBACvD,IAAI,MAAM,GAAuB,SAAS,CAAC;oBAC3C,IAAI,QAAQ,GAAoB,SAAS,CAAC;oBAC1C,IAAI,IAAI,GAAuB,SAAS,CAAC;IAEzC,gBAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;wBACpB,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC;IAC3C,oBAAA,QAAQ,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;IAEtE,oBAAA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;4BAAE,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC;IAC5D,iBAAA;IAED,gBAAA,GAAG,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAa,CAAC,CAAC;IAC5D,aAAA;IACF,SAAA;IAED,QAAA,OAAO,GAAG,CAAC;IACb,KAAC,CAAC;IAEF,IAAAD,eAAO,GAAG,CAAC,KAAK,KAAI;IAClB,QAAA,MAAM,GAAG,GAAG,IAAIK,qBAAQ,CAAC,KAAK,CAAC,CAAC;IAChC,QAAA,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC;YAE3E,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;YAC9B,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,OAAmB,CAAC,CAAC;IAC9C,QAAA,GAAG,CAAC,eAAe,GAAG,GAAG,CAAC,cAAc,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;IACxE,QAAA,GAAG,CAAC,SAAS,GAAGC,4BAAe,CAAC,GAAG,CAA4B,CAAC;IAEhE,QAAA,OAAO,GAAG,CAAC;IACb,KAAC,CAAC;;QAGF,kBAAkB,GAAG,CACnB,QAAQ,EACR,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,OAAO,KACL;IACF,QAAA,MAAM,EACJ,SAAS,EAAE,QAAQ,EACnB,QAAQ,EAAE,OAAO,EACjB,eAAe,EAAE,cAAc,EAC/B,MAAM,EAAE,KAAK,GACd,GAAG,GAAG,CAAC;YACR,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,KAAK,GAAG,cAAc,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;YAE9C,IAAI,CAAC,MAAM,EAAE;IACX,YAAA,IAAI,QAAQ,IAAI,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC;oBAAE,OAAO;gBACpD,OAAO,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;IACzC,SAAA;YAOD,MAAM,YAAY,GAAGH,YAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC1C,QAAA,MAAM,UAAU,GAAG,IAAI,GAAGA,YAAG,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC;IACrD,QAAA,IAAI,YAAY,KAAK,cAAc,CAAC,MAAM;gBAAE,cAAc,CAAC,YAAY,CAAC,GAAG,OAAO,KAAP,IAAA,IAAA,OAAO,KAAP,KAAA,CAAA,GAAA,OAAO,GAAI,IAAI,CAAC;IAE3F,QAAA,IAAI,QAAQ,IAAI,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,EAAE;gBAC3F,OAAO;IACR,SAAA;IAED,QAAA,OAAO,MAAM,CACX,IAAI,EACJ,KAAK,EACL,IAAI;kBACA,CAAC,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC;kBAC/D,CAAC,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,CACxD,CAAC;IACJ,KAAC,CAAC;IACJ,CAAC,GAAA,CAAA;IAOH,SAAS,OAAO,CAAC,QAA8B,EAAE,KAAa,EAAA;IAC5D,IAAA,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE,EAAE;IAC7C,QAAA,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;IAClB,KAAA;IACD,IAAA,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IAED,SAAS,cAAc,CAAC,IAAwB,EAAE,SAAiB,EAAA;IACjE,IAAA,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC;IACxB,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE;IAC3C,QAAA,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACxB,QAAA,IAAI,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC;gBAAE,MAAM;IACzC,KAAA;IACD,IAAA,OAAO,KAAK,CAAC;IACf,CAAC;IAED,SAAS,MAAM,CAAI,KAAU,EAAE,KAAa,EAAE,KAAQ,EAAA;IACpD,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YACzC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IACzB,KAAA;IACD,IAAA,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;IACvB,CAAC;IAED,SAAS,qBAAqB,CAAC,QAA8B,EAAA;IAC3D,IAAA,MAAM,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC;QAC5B,IAAI,GAAG,GAAG,MAAM,CAAC;IACjB,IAAA,KAAK,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;IAC1C,QAAA,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM;IACnC,KAAA;QACD,IAAI,GAAG,GAAG,MAAM;IAAE,QAAA,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC;IAC1C,CAAC;IAED,SAAS,MAAM,CAAC,MAAgB,EAAE,KAAe,EAAA;IAC/C,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;YAAEA,YAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,CAAC;IAED,SAAS,cAAc,CAAC,IAAwB,EAAE,KAAa,EAAA;;;QAG7D,IAAI,KAAK,KAAK,CAAC;IAAE,QAAA,OAAO,IAAI,CAAC;QAE7B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;;;;IAI7B,IAAA,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;IAC3B,CAAC;IAED,SAAS,UAAU,CACjB,IAAwB,EACxB,KAAa,EACb,YAAoB,EACpB,UAAkB,EAClB,YAAoB,EACpB,UAAkB,EAAA;;QAGlB,IAAI,KAAK,KAAK,CAAC;IAAE,QAAA,OAAO,KAAK,CAAC;QAE9B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;;IAG7B,IAAA,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;IAAE,QAAA,OAAO,KAAK,CAAC;;;IAIpC,IAAA,QACE,YAAY,KAAK,IAAI,CAAC,aAAa,CAAC;IACpC,QAAA,UAAU,KAAK,IAAI,CAAC,WAAW,CAAC;IAChC,QAAA,YAAY,KAAK,IAAI,CAAC,aAAa,CAAC;YACpC,UAAU,MAAM,IAAI,CAAC,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC,EAChE;IACJ,CAAC;IAED,SAAS,kBAAkB,CACzB,QAAiB,EACjB,GAAe,EACf,OAMC,EAAA;IAED,IAAA,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAC/D,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,CACL,CAAC;IACH,KAAA;QACD,MAAM,CAAC,GAAW,MAAM,CAAC;IAEzB,IAAA,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,CAAC,EACD,QAAQ,CAAC,IAAI,GAAG,CAAC,EACjB,QAAQ,CAAC,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;IACJ;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts new file mode 100644 index 0000000..d510d74 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts @@ -0,0 +1,90 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export declare type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare let addSegment: { + (map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +}; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare let addMapping: { + (map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; + }): void; +}; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare let maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare let maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare let setSourceContent: (map: GenMapping, source: string, content: string | null) => void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let toDecodedMap: (map: GenMapping) => DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let toEncodedMap: (map: GenMapping) => EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare let fromMap: (input: SourceMapInput) => GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare let allMappings: (map: GenMapping) => Mapping[]; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..e187ba9 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,12 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..b309c81 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts @@ -0,0 +1,35 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export declare type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/package.json b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/package.json new file mode 100644 index 0000000..bc0ee90 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/package.json @@ -0,0 +1,114 @@ +{ + "_from": "@jridgewell/gen-mapping@^0.3.2", + "_id": "@jridgewell/gen-mapping@0.3.2", + "_inBundle": false, + "_integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", + "_location": "/@babel/generator/@jridgewell/gen-mapping", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@jridgewell/gen-mapping@^0.3.2", + "name": "@jridgewell/gen-mapping", + "escapedName": "@jridgewell%2fgen-mapping", + "scope": "@jridgewell", + "rawSpec": "^0.3.2", + "saveSpec": null, + "fetchSpec": "^0.3.2" + }, + "_requiredBy": [ + "/@babel/generator" + ], + "_resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", + "_shasum": "c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9", + "_spec": "@jridgewell/gen-mapping@^0.3.2", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/generator", + "author": { + "name": "Justin Ridgewell", + "email": "justin@ridgewell.name" + }, + "bugs": { + "url": "https://github.com/jridgewell/gen-mapping/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "deprecated": false, + "description": "Generate source maps", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/mocha": "9.1.1", + "@types/node": "17.0.29", + "@typescript-eslint/eslint-plugin": "5.21.0", + "@typescript-eslint/parser": "5.21.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "mocha": "9.2.2", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "typescript": "4.6.3" + }, + "engines": { + "node": ">=6.0.0" + }, + "exports": { + ".": [ + { + "types": "./dist/types/gen-mapping.d.ts", + "browser": "./dist/gen-mapping.umd.js", + "require": "./dist/gen-mapping.umd.js", + "import": "./dist/gen-mapping.mjs" + }, + "./dist/gen-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist", + "src" + ], + "homepage": "https://github.com/jridgewell/gen-mapping#readme", + "keywords": [ + "source", + "map" + ], + "license": "MIT", + "main": "dist/gen-mapping.umd.js", + "module": "dist/gen-mapping.mjs", + "name": "@jridgewell/gen-mapping", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/gen-mapping.git" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "pretest": "run-s build:rollup", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:coverage", + "test:coverage": "c8 mocha", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:watch": "run-p 'build:rollup -- --watch' 'test:only -- --watch'" + }, + "typings": "dist/types/gen-mapping.d.ts", + "version": "0.3.2" +} diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts new file mode 100644 index 0000000..601c745 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts @@ -0,0 +1,458 @@ +import { SetArray, put } from '@jridgewell/set-array'; +import { encode } from '@jridgewell/sourcemap-codec'; +import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping'; + +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, +} from './sourcemap-segment'; + +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { SourceMapSegment } from './sourcemap-segment'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; + +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; + +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; + +const NO_NAME = -1; + +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export let addSegment: { + ( + map: GenMapping, + genLine: number, + genColumn: number, + source?: null, + sourceLine?: null, + sourceColumn?: null, + name?: null, + content?: null, + ): void; + ( + map: GenMapping, + genLine: number, + genColumn: number, + source: string, + sourceLine: number, + sourceColumn: number, + name?: null, + content?: string | null, + ): void; + ( + map: GenMapping, + genLine: number, + genColumn: number, + source: string, + sourceLine: number, + sourceColumn: number, + name: string, + content?: string | null, + ): void; +}; + +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export let addMapping: { + ( + map: GenMapping, + mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; + }, + ): void; + ( + map: GenMapping, + mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; + }, + ): void; + ( + map: GenMapping, + mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; + }, + ): void; +}; + +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export let maybeAddSegment: typeof addSegment; + +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export let maybeAddMapping: typeof addMapping; + +/** + * Adds/removes the content of the source file to the source map. + */ +export let setSourceContent: (map: GenMapping, source: string, content: string | null) => void; + +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export let toDecodedMap: (map: GenMapping) => DecodedSourceMap; + +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export let toEncodedMap: (map: GenMapping) => EncodedSourceMap; + +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export let fromMap: (input: SourceMapInput) => GenMapping; + +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export let allMappings: (map: GenMapping) => Mapping[]; + +// This split declaration is only so that terser can elminiate the static initialization block. +let addSegmentInternal: ( + skipable: boolean, + map: GenMapping, + genLine: number, + genColumn: number, + source: S, + sourceLine: S extends string ? number : null | undefined, + sourceColumn: S extends string ? number : null | undefined, + name: S extends string ? string | null | undefined : null | undefined, + content: S extends string ? string | null | undefined : null | undefined, +) => void; + +/** + * Provides the state to generate a sourcemap. + */ +export class GenMapping { + private _names = new SetArray(); + private _sources = new SetArray(); + private _sourcesContent: (string | null)[] = []; + private _mappings: SourceMapSegment[][] = []; + declare file: string | null | undefined; + declare sourceRoot: string | null | undefined; + + constructor({ file, sourceRoot }: Options = {}) { + this.file = file; + this.sourceRoot = sourceRoot; + } + + static { + addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal( + false, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ); + }; + + maybeAddSegment = ( + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ) => { + return addSegmentInternal( + true, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ); + }; + + addMapping = (map, mapping) => { + return addMappingInternal(false, map, mapping as Parameters[2]); + }; + + maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping as Parameters[2]); + }; + + setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[put(sources, source)] = content; + }; + + toDecodedMap = (map) => { + const { + file, + sourceRoot, + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + } = map; + removeEmptyFinalLines(mappings); + + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + + toEncodedMap = (map) => { + const decoded = toDecodedMap(map); + return { + ...decoded, + mappings: encode(decoded.mappings as SourceMapSegment[][]), + }; + }; + + allMappings = (map) => { + const out: Mapping[] = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + + const generated = { line: i + 1, column: seg[COLUMN] }; + let source: string | undefined = undefined; + let original: Pos | undefined = undefined; + let name: string | undefined = undefined; + + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + + if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; + } + + out.push({ generated, source, original, name } as Mapping); + } + } + + return out; + }; + + fromMap = (input) => { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + + putAll(gen._names, map.names); + putAll(gen._sources, map.sources as string[]); + gen._sourcesContent = map.sourcesContent || map.sources.map(() => null); + gen._mappings = decodedMappings(map) as GenMapping['_mappings']; + + return gen; + }; + + // Internal helpers + addSegmentInternal = ( + skipable, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ) => { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + + if (!source) { + if (skipable && skipSourceless(line, index)) return; + return insert(line, index, [genColumn]); + } + + // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source + // isn't nullish. + assert(sourceLine); + assert(sourceColumn); + + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null; + + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + + return insert( + line, + index, + name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn], + ); + }; + } +} + +function assert(_val: unknown): asserts _val is T { + // noop. +} + +function getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; +} + +function getColumnIndex(line: SourceMapSegment[], genColumn: number): number { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) break; + } + return index; +} + +function insert(array: T[], index: number, value: T) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} + +function removeEmptyFinalLines(mappings: SourceMapSegment[][]) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) break; + } + if (len < length) mappings.length = len; +} + +function putAll(strarr: SetArray, array: string[]) { + for (let i = 0; i < array.length; i++) put(strarr, array[i]); +} + +function skipSourceless(line: SourceMapSegment[], index: number): boolean { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) return true; + + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} + +function skipSource( + line: SourceMapSegment[], + index: number, + sourcesIndex: number, + sourceLine: number, + sourceColumn: number, + namesIndex: number, +): boolean { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) return false; + + const prev = line[index - 1]; + + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) return false; + + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return ( + sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME) + ); +} + +function addMappingInternal( + skipable: boolean, + map: GenMapping, + mapping: { + generated: Pos; + source: S; + original: S extends string ? Pos : null | undefined; + name: S extends string ? string | null | undefined : null | undefined; + content: S extends string ? string | null | undefined : null | undefined; + }, +) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + null, + null, + null, + null, + null, + ); + } + const s: string = source; + assert(original); + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + s, + original.line - 1, + original.column, + name, + content, + ); +} diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts new file mode 100644 index 0000000..fb296dd --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts @@ -0,0 +1,16 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; + +export type SourceMapSegment = + | [GeneratedColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +export const COLUMN = 0; +export const SOURCES_INDEX = 1; +export const SOURCE_LINE = 2; +export const SOURCE_COLUMN = 3; +export const NAMES_INDEX = 4; diff --git a/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/types.ts b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/types.ts new file mode 100644 index 0000000..dd11331 --- /dev/null +++ b/node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping/src/types.ts @@ -0,0 +1,43 @@ +import type { SourceMapSegment } from './sourcemap-segment'; + +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; +} + +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} + +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} + +export interface Pos { + line: number; + column: number; +} + +export type Mapping = + | { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; + } + | { + generated: Pos; + source: string; + original: Pos; + name: string; + } + | { + generated: Pos; + source: string; + original: Pos; + name: undefined; + }; diff --git a/node_modules/@babel/generator/package.json b/node_modules/@babel/generator/package.json new file mode 100644 index 0000000..17d7519 --- /dev/null +++ b/node_modules/@babel/generator/package.json @@ -0,0 +1,74 @@ +{ + "_from": "@babel/generator@^7.18.13", + "_id": "@babel/generator@7.18.13", + "_inBundle": false, + "_integrity": "sha512-CkPg8ySSPuHTYPJYo7IRALdqyjM9HCbt/3uOBEFbzyGVP6Mn8bwFPB0jX6982JVNBlYzM1nnPkfjuXSOPtQeEQ==", + "_location": "/@babel/generator", + "_phantomChildren": { + "@jridgewell/set-array": "1.1.2", + "@jridgewell/sourcemap-codec": "1.4.14", + "@jridgewell/trace-mapping": "0.3.15" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/generator@^7.18.13", + "name": "@babel/generator", + "escapedName": "@babel%2fgenerator", + "scope": "@babel", + "rawSpec": "^7.18.13", + "saveSpec": null, + "fetchSpec": "^7.18.13" + }, + "_requiredBy": [ + "/@babel/core", + "/@babel/traverse", + "/jest-snapshot" + ], + "_resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.18.13.tgz", + "_shasum": "59550cbb9ae79b8def15587bdfbaa388c4abf212", + "_spec": "@babel/generator@^7.18.13", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/core", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20generator%22+is%3Aopen" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/types": "^7.18.13", + "@jridgewell/gen-mapping": "^0.3.2", + "jsesc": "^2.5.1" + }, + "deprecated": false, + "description": "Turns an AST into code.", + "devDependencies": { + "@babel/helper-fixtures": "^7.18.6", + "@babel/parser": "^7.18.13", + "@jridgewell/trace-mapping": "^0.3.8", + "@types/jsesc": "^2.5.0", + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "files": [ + "lib" + ], + "homepage": "https://babel.dev/docs/en/next/babel-generator", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/generator", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-generator" + }, + "type": "commonjs", + "version": "7.18.13" +} diff --git a/node_modules/@babel/helper-compilation-targets/LICENSE b/node_modules/@babel/helper-compilation-targets/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-compilation-targets/README.md b/node_modules/@babel/helper-compilation-targets/README.md new file mode 100644 index 0000000..29f043b --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/README.md @@ -0,0 +1,19 @@ +# @babel/helper-compilation-targets + +> Helper functions on Babel compilation targets + +See our website [@babel/helper-compilation-targets](https://babeljs.io/docs/en/babel-helper-compilation-targets) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-compilation-targets +``` + +or using yarn: + +```sh +yarn add @babel/helper-compilation-targets +``` diff --git a/node_modules/@babel/helper-compilation-targets/lib/debug.js b/node_modules/@babel/helper-compilation-targets/lib/debug.js new file mode 100644 index 0000000..4e05fdd --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/lib/debug.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getInclusionReasons = getInclusionReasons; + +var _semver = require("semver"); + +var _pretty = require("./pretty"); + +var _utils = require("./utils"); + +function getInclusionReasons(item, targetVersions, list) { + const minVersions = list[item] || {}; + return Object.keys(targetVersions).reduce((result, env) => { + const minVersion = (0, _utils.getLowestImplementedVersion)(minVersions, env); + const targetVersion = targetVersions[env]; + + if (!minVersion) { + result[env] = (0, _pretty.prettifyVersion)(targetVersion); + } else { + const minIsUnreleased = (0, _utils.isUnreleasedVersion)(minVersion, env); + const targetIsUnreleased = (0, _utils.isUnreleasedVersion)(targetVersion, env); + + if (!targetIsUnreleased && (minIsUnreleased || _semver.lt(targetVersion.toString(), (0, _utils.semverify)(minVersion)))) { + result[env] = (0, _pretty.prettifyVersion)(targetVersion); + } + } + + return result; + }, {}); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-compilation-targets/lib/filter-items.js b/node_modules/@babel/helper-compilation-targets/lib/filter-items.js new file mode 100644 index 0000000..f47f605 --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/lib/filter-items.js @@ -0,0 +1,88 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = filterItems; +exports.isRequired = isRequired; +exports.targetsSupported = targetsSupported; + +var _semver = require("semver"); + +var _plugins = require("@babel/compat-data/plugins"); + +var _utils = require("./utils"); + +function targetsSupported(target, support) { + const targetEnvironments = Object.keys(target); + + if (targetEnvironments.length === 0) { + return false; + } + + const unsupportedEnvironments = targetEnvironments.filter(environment => { + const lowestImplementedVersion = (0, _utils.getLowestImplementedVersion)(support, environment); + + if (!lowestImplementedVersion) { + return true; + } + + const lowestTargetedVersion = target[environment]; + + if ((0, _utils.isUnreleasedVersion)(lowestTargetedVersion, environment)) { + return false; + } + + if ((0, _utils.isUnreleasedVersion)(lowestImplementedVersion, environment)) { + return true; + } + + if (!_semver.valid(lowestTargetedVersion.toString())) { + throw new Error(`Invalid version passed for target "${environment}": "${lowestTargetedVersion}". ` + "Versions must be in semver format (major.minor.patch)"); + } + + return _semver.gt((0, _utils.semverify)(lowestImplementedVersion), lowestTargetedVersion.toString()); + }); + return unsupportedEnvironments.length === 0; +} + +function isRequired(name, targets, { + compatData = _plugins, + includes, + excludes +} = {}) { + if (excludes != null && excludes.has(name)) return false; + if (includes != null && includes.has(name)) return true; + return !targetsSupported(targets, compatData[name]); +} + +function filterItems(list, includes, excludes, targets, defaultIncludes, defaultExcludes, pluginSyntaxMap) { + const result = new Set(); + const options = { + compatData: list, + includes, + excludes + }; + + for (const item in list) { + if (isRequired(item, targets, options)) { + result.add(item); + } else if (pluginSyntaxMap) { + const shippedProposalsSyntax = pluginSyntaxMap.get(item); + + if (shippedProposalsSyntax) { + result.add(shippedProposalsSyntax); + } + } + } + + if (defaultIncludes) { + defaultIncludes.forEach(item => !excludes.has(item) && result.add(item)); + } + + if (defaultExcludes) { + defaultExcludes.forEach(item => !includes.has(item) && result.delete(item)); + } + + return result; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-compilation-targets/lib/index.js b/node_modules/@babel/helper-compilation-targets/lib/index.js new file mode 100644 index 0000000..1a39ee4 --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/lib/index.js @@ -0,0 +1,250 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "TargetNames", { + enumerable: true, + get: function () { + return _options.TargetNames; + } +}); +exports.default = getTargets; +Object.defineProperty(exports, "filterItems", { + enumerable: true, + get: function () { + return _filterItems.default; + } +}); +Object.defineProperty(exports, "getInclusionReasons", { + enumerable: true, + get: function () { + return _debug.getInclusionReasons; + } +}); +exports.isBrowsersQueryValid = isBrowsersQueryValid; +Object.defineProperty(exports, "isRequired", { + enumerable: true, + get: function () { + return _filterItems.isRequired; + } +}); +Object.defineProperty(exports, "prettifyTargets", { + enumerable: true, + get: function () { + return _pretty.prettifyTargets; + } +}); +Object.defineProperty(exports, "unreleasedLabels", { + enumerable: true, + get: function () { + return _targets.unreleasedLabels; + } +}); + +var _browserslist = require("browserslist"); + +var _helperValidatorOption = require("@babel/helper-validator-option"); + +var _nativeModules = require("@babel/compat-data/native-modules"); + +var _utils = require("./utils"); + +var _targets = require("./targets"); + +var _options = require("./options"); + +var _pretty = require("./pretty"); + +var _debug = require("./debug"); + +var _filterItems = require("./filter-items"); + +const ESM_SUPPORT = _nativeModules["es6.module"]; +const v = new _helperValidatorOption.OptionValidator("@babel/helper-compilation-targets"); + +function validateTargetNames(targets) { + const validTargets = Object.keys(_options.TargetNames); + + for (const target of Object.keys(targets)) { + if (!(target in _options.TargetNames)) { + throw new Error(v.formatMessage(`'${target}' is not a valid target +- Did you mean '${(0, _helperValidatorOption.findSuggestion)(target, validTargets)}'?`)); + } + } + + return targets; +} + +function isBrowsersQueryValid(browsers) { + return typeof browsers === "string" || Array.isArray(browsers) && browsers.every(b => typeof b === "string"); +} + +function validateBrowsers(browsers) { + v.invariant(browsers === undefined || isBrowsersQueryValid(browsers), `'${String(browsers)}' is not a valid browserslist query`); + return browsers; +} + +function getLowestVersions(browsers) { + return browsers.reduce((all, browser) => { + const [browserName, browserVersion] = browser.split(" "); + const target = _targets.browserNameMap[browserName]; + + if (!target) { + return all; + } + + try { + const splitVersion = browserVersion.split("-")[0].toLowerCase(); + const isSplitUnreleased = (0, _utils.isUnreleasedVersion)(splitVersion, target); + + if (!all[target]) { + all[target] = isSplitUnreleased ? splitVersion : (0, _utils.semverify)(splitVersion); + return all; + } + + const version = all[target]; + const isUnreleased = (0, _utils.isUnreleasedVersion)(version, target); + + if (isUnreleased && isSplitUnreleased) { + all[target] = (0, _utils.getLowestUnreleased)(version, splitVersion, target); + } else if (isUnreleased) { + all[target] = (0, _utils.semverify)(splitVersion); + } else if (!isUnreleased && !isSplitUnreleased) { + const parsedBrowserVersion = (0, _utils.semverify)(splitVersion); + all[target] = (0, _utils.semverMin)(version, parsedBrowserVersion); + } + } catch (e) {} + + return all; + }, {}); +} + +function outputDecimalWarning(decimalTargets) { + if (!decimalTargets.length) { + return; + } + + console.warn("Warning, the following targets are using a decimal version:\n"); + decimalTargets.forEach(({ + target, + value + }) => console.warn(` ${target}: ${value}`)); + console.warn(` +We recommend using a string for minor/patch versions to avoid numbers like 6.10 +getting parsed as 6.1, which can lead to unexpected behavior. +`); +} + +function semverifyTarget(target, value) { + try { + return (0, _utils.semverify)(value); + } catch (error) { + throw new Error(v.formatMessage(`'${value}' is not a valid value for 'targets.${target}'.`)); + } +} + +function nodeTargetParser(value) { + const parsed = value === true || value === "current" ? process.versions.node : semverifyTarget("node", value); + return ["node", parsed]; +} + +function defaultTargetParser(target, value) { + const version = (0, _utils.isUnreleasedVersion)(value, target) ? value.toLowerCase() : semverifyTarget(target, value); + return [target, version]; +} + +function generateTargets(inputTargets) { + const input = Object.assign({}, inputTargets); + delete input.esmodules; + delete input.browsers; + return input; +} + +function resolveTargets(queries, env) { + const resolved = _browserslist(queries, { + mobileToDesktop: true, + env + }); + + return getLowestVersions(resolved); +} + +function getTargets(inputTargets = {}, options = {}) { + var _browsers, _browsers2; + + let { + browsers, + esmodules + } = inputTargets; + const { + configPath = "." + } = options; + validateBrowsers(browsers); + const input = generateTargets(inputTargets); + let targets = validateTargetNames(input); + const shouldParseBrowsers = !!browsers; + const hasTargets = shouldParseBrowsers || Object.keys(targets).length > 0; + const shouldSearchForConfig = !options.ignoreBrowserslistConfig && !hasTargets; + + if (!browsers && shouldSearchForConfig) { + browsers = _browserslist.loadConfig({ + config: options.configFile, + path: configPath, + env: options.browserslistEnv + }); + + if (browsers == null) { + { + browsers = []; + } + } + } + + if (esmodules && (esmodules !== "intersect" || !((_browsers = browsers) != null && _browsers.length))) { + browsers = Object.keys(ESM_SUPPORT).map(browser => `${browser} >= ${ESM_SUPPORT[browser]}`).join(", "); + esmodules = false; + } + + if ((_browsers2 = browsers) != null && _browsers2.length) { + const queryBrowsers = resolveTargets(browsers, options.browserslistEnv); + + if (esmodules === "intersect") { + for (const browser of Object.keys(queryBrowsers)) { + const version = queryBrowsers[browser]; + const esmSupportVersion = ESM_SUPPORT[browser]; + + if (esmSupportVersion) { + queryBrowsers[browser] = (0, _utils.getHighestUnreleased)(version, (0, _utils.semverify)(esmSupportVersion), browser); + } else { + delete queryBrowsers[browser]; + } + } + } + + targets = Object.assign(queryBrowsers, targets); + } + + const result = {}; + const decimalWarnings = []; + + for (const target of Object.keys(targets).sort()) { + const value = targets[target]; + + if (typeof value === "number" && value % 1 !== 0) { + decimalWarnings.push({ + target, + value + }); + } + + const [parsedTarget, parsedValue] = target === "node" ? nodeTargetParser(value) : defaultTargetParser(target, value); + + if (parsedValue) { + result[parsedTarget] = parsedValue; + } + } + + outputDecimalWarning(decimalWarnings); + return result; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-compilation-targets/lib/options.js b/node_modules/@babel/helper-compilation-targets/lib/options.js new file mode 100644 index 0000000..cbf4de0 --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/lib/options.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TargetNames = void 0; +const TargetNames = { + node: "node", + chrome: "chrome", + opera: "opera", + edge: "edge", + firefox: "firefox", + safari: "safari", + ie: "ie", + ios: "ios", + android: "android", + electron: "electron", + samsung: "samsung", + rhino: "rhino" +}; +exports.TargetNames = TargetNames; \ No newline at end of file diff --git a/node_modules/@babel/helper-compilation-targets/lib/pretty.js b/node_modules/@babel/helper-compilation-targets/lib/pretty.js new file mode 100644 index 0000000..88df640 --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/lib/pretty.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.prettifyTargets = prettifyTargets; +exports.prettifyVersion = prettifyVersion; + +var _semver = require("semver"); + +var _targets = require("./targets"); + +function prettifyVersion(version) { + if (typeof version !== "string") { + return version; + } + + const parts = [_semver.major(version)]; + + const minor = _semver.minor(version); + + const patch = _semver.patch(version); + + if (minor || patch) { + parts.push(minor); + } + + if (patch) { + parts.push(patch); + } + + return parts.join("."); +} + +function prettifyTargets(targets) { + return Object.keys(targets).reduce((results, target) => { + let value = targets[target]; + const unreleasedLabel = _targets.unreleasedLabels[target]; + + if (typeof value === "string" && unreleasedLabel !== value) { + value = prettifyVersion(value); + } + + results[target] = value; + return results; + }, {}); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-compilation-targets/lib/targets.js b/node_modules/@babel/helper-compilation-targets/lib/targets.js new file mode 100644 index 0000000..3cbaeac --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/lib/targets.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unreleasedLabels = exports.browserNameMap = void 0; +const unreleasedLabels = { + safari: "tp" +}; +exports.unreleasedLabels = unreleasedLabels; +const browserNameMap = { + and_chr: "chrome", + and_ff: "firefox", + android: "android", + chrome: "chrome", + edge: "edge", + firefox: "firefox", + ie: "ie", + ie_mob: "ie", + ios_saf: "ios", + node: "node", + op_mob: "opera", + opera: "opera", + safari: "safari", + samsung: "samsung" +}; +exports.browserNameMap = browserNameMap; \ No newline at end of file diff --git a/node_modules/@babel/helper-compilation-targets/lib/types.js b/node_modules/@babel/helper-compilation-targets/lib/types.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@babel/helper-compilation-targets/lib/utils.js b/node_modules/@babel/helper-compilation-targets/lib/utils.js new file mode 100644 index 0000000..e14e7f9 --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/lib/utils.js @@ -0,0 +1,72 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getHighestUnreleased = getHighestUnreleased; +exports.getLowestImplementedVersion = getLowestImplementedVersion; +exports.getLowestUnreleased = getLowestUnreleased; +exports.isUnreleasedVersion = isUnreleasedVersion; +exports.semverMin = semverMin; +exports.semverify = semverify; + +var _semver = require("semver"); + +var _helperValidatorOption = require("@babel/helper-validator-option"); + +var _targets = require("./targets"); + +const versionRegExp = /^(\d+|\d+.\d+)$/; +const v = new _helperValidatorOption.OptionValidator("@babel/helper-compilation-targets"); + +function semverMin(first, second) { + return first && _semver.lt(first, second) ? first : second; +} + +function semverify(version) { + if (typeof version === "string" && _semver.valid(version)) { + return version; + } + + v.invariant(typeof version === "number" || typeof version === "string" && versionRegExp.test(version), `'${version}' is not a valid version`); + const split = version.toString().split("."); + + while (split.length < 3) { + split.push("0"); + } + + return split.join("."); +} + +function isUnreleasedVersion(version, env) { + const unreleasedLabel = _targets.unreleasedLabels[env]; + return !!unreleasedLabel && unreleasedLabel === version.toString().toLowerCase(); +} + +function getLowestUnreleased(a, b, env) { + const unreleasedLabel = _targets.unreleasedLabels[env]; + + if (a === unreleasedLabel) { + return b; + } + + if (b === unreleasedLabel) { + return a; + } + + return semverMin(a, b); +} + +function getHighestUnreleased(a, b, env) { + return getLowestUnreleased(a, b, env) === a ? b : a; +} + +function getLowestImplementedVersion(plugin, environment) { + const result = plugin[environment]; + + if (!result && environment === "android") { + return plugin.chrome; + } + + return result; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-compilation-targets/package.json b/node_modules/@babel/helper-compilation-targets/package.json new file mode 100644 index 0000000..82729ba --- /dev/null +++ b/node_modules/@babel/helper-compilation-targets/package.json @@ -0,0 +1,75 @@ +{ + "_from": "@babel/helper-compilation-targets@^7.18.9", + "_id": "@babel/helper-compilation-targets@7.18.9", + "_inBundle": false, + "_integrity": "sha512-tzLCyVmqUiFlcFoAPLA/gL9TeYrF61VLNtb+hvkuVaB5SUjW7jcfrglBIX1vUIoT7CLP3bBlIMeyEsIl2eFQNg==", + "_location": "/@babel/helper-compilation-targets", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-compilation-targets@^7.18.9", + "name": "@babel/helper-compilation-targets", + "escapedName": "@babel%2fhelper-compilation-targets", + "scope": "@babel", + "rawSpec": "^7.18.9", + "saveSpec": null, + "fetchSpec": "^7.18.9" + }, + "_requiredBy": [ + "/@babel/core" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.18.9.tgz", + "_shasum": "69e64f57b524cde3e5ff6cc5a9f4a387ee5563bf", + "_spec": "@babel/helper-compilation-targets@^7.18.9", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/core", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/compat-data": "^7.18.8", + "@babel/helper-validator-option": "^7.18.6", + "browserslist": "^4.20.2", + "semver": "^6.3.0" + }, + "deprecated": false, + "description": "Helper functions on Babel compilation targets", + "devDependencies": { + "@babel/core": "^7.18.9", + "@babel/helper-plugin-test-runner": "^7.18.6", + "@types/semver": "^5.5.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "homepage": "https://github.com/babel/babel#readme", + "keywords": [ + "babel", + "babel-plugin" + ], + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-compilation-targets", + "peerDependencies": { + "@babel/core": "^7.0.0" + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-compilation-targets" + }, + "type": "commonjs", + "version": "7.18.9" +} diff --git a/node_modules/@babel/helper-environment-visitor/LICENSE b/node_modules/@babel/helper-environment-visitor/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-environment-visitor/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-environment-visitor/README.md b/node_modules/@babel/helper-environment-visitor/README.md new file mode 100644 index 0000000..ec74ac3 --- /dev/null +++ b/node_modules/@babel/helper-environment-visitor/README.md @@ -0,0 +1,19 @@ +# @babel/helper-environment-visitor + +> Helper visitor to only visit nodes in the current 'this' context + +See our website [@babel/helper-environment-visitor](https://babeljs.io/docs/en/babel-helper-environment-visitor) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/helper-environment-visitor +``` + +or using yarn: + +```sh +yarn add @babel/helper-environment-visitor --dev +``` diff --git a/node_modules/@babel/helper-environment-visitor/lib/index.js b/node_modules/@babel/helper-environment-visitor/lib/index.js new file mode 100644 index 0000000..bf1a303 --- /dev/null +++ b/node_modules/@babel/helper-environment-visitor/lib/index.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.requeueComputedKeyAndDecorators = requeueComputedKeyAndDecorators; +exports.skipAllButComputedKey = skipAllButComputedKey; + +function skipAllButComputedKey(path) { + path.skip(); + + if (path.node.computed) { + path.context.maybeQueue(path.get("key")); + } +} + +function requeueComputedKeyAndDecorators(path) { + const { + context, + node + } = path; + + if (node.computed) { + context.maybeQueue(path.get("key")); + } + + if (node.decorators) { + for (const decorator of path.get("decorators")) { + context.maybeQueue(decorator); + } + } +} + +const visitor = { + FunctionParent(path) { + if (path.isArrowFunctionExpression()) { + return; + } else { + path.skip(); + + if (path.isMethod()) { + requeueComputedKeyAndDecorators(path); + } + } + }, + + Property(path) { + if (path.isObjectProperty()) { + return; + } + + path.skip(); + requeueComputedKeyAndDecorators(path); + } + +}; +var _default = visitor; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@babel/helper-environment-visitor/package.json b/node_modules/@babel/helper-environment-visitor/package.json new file mode 100644 index 0000000..2a1ec8b --- /dev/null +++ b/node_modules/@babel/helper-environment-visitor/package.json @@ -0,0 +1,62 @@ +{ + "_from": "@babel/helper-environment-visitor@^7.18.9", + "_id": "@babel/helper-environment-visitor@7.18.9", + "_inBundle": false, + "_integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "_location": "/@babel/helper-environment-visitor", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-environment-visitor@^7.18.9", + "name": "@babel/helper-environment-visitor", + "escapedName": "@babel%2fhelper-environment-visitor", + "scope": "@babel", + "rawSpec": "^7.18.9", + "saveSpec": null, + "fetchSpec": "^7.18.9" + }, + "_requiredBy": [ + "/@babel/helper-module-transforms", + "/@babel/traverse" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", + "_shasum": "0c0cee9b35d2ca190478756865bb3528422f51be", + "_spec": "@babel/helper-environment-visitor@^7.18.9", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/helper-module-transforms", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Helper visitor to only visit nodes in the current 'this' context", + "devDependencies": { + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" + }, + "engines": { + "node": ">=6.9.0" + }, + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-environment-visitor", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-environment-visitor", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-environment-visitor" + }, + "type": "commonjs", + "version": "7.18.9" +} diff --git a/node_modules/@babel/helper-function-name/LICENSE b/node_modules/@babel/helper-function-name/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-function-name/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-function-name/README.md b/node_modules/@babel/helper-function-name/README.md new file mode 100644 index 0000000..1e490ae --- /dev/null +++ b/node_modules/@babel/helper-function-name/README.md @@ -0,0 +1,19 @@ +# @babel/helper-function-name + +> Helper function to change the property 'name' of every function + +See our website [@babel/helper-function-name](https://babeljs.io/docs/en/babel-helper-function-name) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-function-name +``` + +or using yarn: + +```sh +yarn add @babel/helper-function-name +``` diff --git a/node_modules/@babel/helper-function-name/lib/index.js b/node_modules/@babel/helper-function-name/lib/index.js new file mode 100644 index 0000000..2ad7316 --- /dev/null +++ b/node_modules/@babel/helper-function-name/lib/index.js @@ -0,0 +1,199 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +var _template = require("@babel/template"); + +var _t = require("@babel/types"); + +const { + NOT_LOCAL_BINDING, + cloneNode, + identifier, + isAssignmentExpression, + isAssignmentPattern, + isFunction, + isIdentifier, + isLiteral, + isNullLiteral, + isObjectMethod, + isObjectProperty, + isRegExpLiteral, + isRestElement, + isTemplateLiteral, + isVariableDeclarator, + toBindingIdentifierName +} = _t; + +function getFunctionArity(node) { + const count = node.params.findIndex(param => isAssignmentPattern(param) || isRestElement(param)); + return count === -1 ? node.params.length : count; +} + +const buildPropertyMethodAssignmentWrapper = _template.default.statement(` + (function (FUNCTION_KEY) { + function FUNCTION_ID() { + return FUNCTION_KEY.apply(this, arguments); + } + + FUNCTION_ID.toString = function () { + return FUNCTION_KEY.toString(); + } + + return FUNCTION_ID; + })(FUNCTION) +`); + +const buildGeneratorPropertyMethodAssignmentWrapper = _template.default.statement(` + (function (FUNCTION_KEY) { + function* FUNCTION_ID() { + return yield* FUNCTION_KEY.apply(this, arguments); + } + + FUNCTION_ID.toString = function () { + return FUNCTION_KEY.toString(); + }; + + return FUNCTION_ID; + })(FUNCTION) +`); + +const visitor = { + "ReferencedIdentifier|BindingIdentifier"(path, state) { + if (path.node.name !== state.name) return; + const localDeclar = path.scope.getBindingIdentifier(state.name); + if (localDeclar !== state.outerDeclar) return; + state.selfReference = true; + path.stop(); + } + +}; + +function getNameFromLiteralId(id) { + if (isNullLiteral(id)) { + return "null"; + } + + if (isRegExpLiteral(id)) { + return `_${id.pattern}_${id.flags}`; + } + + if (isTemplateLiteral(id)) { + return id.quasis.map(quasi => quasi.value.raw).join(""); + } + + if (id.value !== undefined) { + return id.value + ""; + } + + return ""; +} + +function wrap(state, method, id, scope) { + if (state.selfReference) { + if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { + scope.rename(id.name); + } else { + if (!isFunction(method)) return; + let build = buildPropertyMethodAssignmentWrapper; + + if (method.generator) { + build = buildGeneratorPropertyMethodAssignmentWrapper; + } + + const template = build({ + FUNCTION: method, + FUNCTION_ID: id, + FUNCTION_KEY: scope.generateUidIdentifier(id.name) + }).expression; + const params = template.callee.body.body[0].params; + + for (let i = 0, len = getFunctionArity(method); i < len; i++) { + params.push(scope.generateUidIdentifier("x")); + } + + return template; + } + } + + method.id = id; + scope.getProgramParent().references[id.name] = true; +} + +function visit(node, name, scope) { + const state = { + selfAssignment: false, + selfReference: false, + outerDeclar: scope.getBindingIdentifier(name), + name: name + }; + const binding = scope.getOwnBinding(name); + + if (binding) { + if (binding.kind === "param") { + state.selfReference = true; + } else {} + } else if (state.outerDeclar || scope.hasGlobal(name)) { + scope.traverse(node, visitor, state); + } + + return state; +} + +function _default({ + node, + parent, + scope, + id +}, localBinding = false, supportUnicodeId = false) { + if (node.id) return; + + if ((isObjectProperty(parent) || isObjectMethod(parent, { + kind: "method" + })) && (!parent.computed || isLiteral(parent.key))) { + id = parent.key; + } else if (isVariableDeclarator(parent)) { + id = parent.id; + + if (isIdentifier(id) && !localBinding) { + const binding = scope.parent.getBinding(id.name); + + if (binding && binding.constant && scope.getBinding(id.name) === binding) { + node.id = cloneNode(id); + node.id[NOT_LOCAL_BINDING] = true; + return; + } + } + } else if (isAssignmentExpression(parent, { + operator: "=" + })) { + id = parent.left; + } else if (!id) { + return; + } + + let name; + + if (id && isLiteral(id)) { + name = getNameFromLiteralId(id); + } else if (id && isIdentifier(id)) { + name = id.name; + } + + if (name === undefined) { + return; + } + + if (!supportUnicodeId && isFunction(node) && /[\uD800-\uDFFF]/.test(name)) { + return; + } + + name = toBindingIdentifierName(name); + const newId = identifier(name); + newId[NOT_LOCAL_BINDING] = true; + const state = visit(node, name, scope); + return wrap(state, node, newId, scope) || node; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-function-name/package.json b/node_modules/@babel/helper-function-name/package.json new file mode 100644 index 0000000..2e13596 --- /dev/null +++ b/node_modules/@babel/helper-function-name/package.json @@ -0,0 +1,57 @@ +{ + "_from": "@babel/helper-function-name@^7.18.9", + "_id": "@babel/helper-function-name@7.18.9", + "_inBundle": false, + "_integrity": "sha512-fJgWlZt7nxGksJS9a0XdSaI4XvpExnNIgRP+rVefWh5U7BL8pPuir6SJUmFKRfjWQ51OtWSzwOxhaH/EBWWc0A==", + "_location": "/@babel/helper-function-name", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-function-name@^7.18.9", + "name": "@babel/helper-function-name", + "escapedName": "@babel%2fhelper-function-name", + "scope": "@babel", + "rawSpec": "^7.18.9", + "saveSpec": null, + "fetchSpec": "^7.18.9" + }, + "_requiredBy": [ + "/@babel/traverse" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.18.9.tgz", + "_shasum": "940e6084a55dee867d33b4e487da2676365e86b0", + "_spec": "@babel/helper-function-name@^7.18.9", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/traverse", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/template": "^7.18.6", + "@babel/types": "^7.18.9" + }, + "deprecated": false, + "description": "Helper function to change the property 'name' of every function", + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-function-name", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-function-name", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-function-name" + }, + "type": "commonjs", + "version": "7.18.9" +} diff --git a/node_modules/@babel/helper-hoist-variables/LICENSE b/node_modules/@babel/helper-hoist-variables/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-hoist-variables/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-hoist-variables/README.md b/node_modules/@babel/helper-hoist-variables/README.md new file mode 100644 index 0000000..ef87821 --- /dev/null +++ b/node_modules/@babel/helper-hoist-variables/README.md @@ -0,0 +1,19 @@ +# @babel/helper-hoist-variables + +> Helper function to hoist variables + +See our website [@babel/helper-hoist-variables](https://babeljs.io/docs/en/babel-helper-hoist-variables) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-hoist-variables +``` + +or using yarn: + +```sh +yarn add @babel/helper-hoist-variables +``` diff --git a/node_modules/@babel/helper-hoist-variables/lib/index.js b/node_modules/@babel/helper-hoist-variables/lib/index.js new file mode 100644 index 0000000..31fb847 --- /dev/null +++ b/node_modules/@babel/helper-hoist-variables/lib/index.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = hoistVariables; + +var _t = require("@babel/types"); + +const { + assignmentExpression, + expressionStatement, + identifier +} = _t; +const visitor = { + Scope(path, state) { + if (state.kind === "let") path.skip(); + }, + + FunctionParent(path) { + path.skip(); + }, + + VariableDeclaration(path, state) { + if (state.kind && path.node.kind !== state.kind) return; + const nodes = []; + const declarations = path.get("declarations"); + let firstId; + + for (const declar of declarations) { + firstId = declar.node.id; + + if (declar.node.init) { + nodes.push(expressionStatement(assignmentExpression("=", declar.node.id, declar.node.init))); + } + + for (const name of Object.keys(declar.getBindingIdentifiers())) { + state.emit(identifier(name), name, declar.node.init !== null); + } + } + + if (path.parentPath.isFor({ + left: path.node + })) { + path.replaceWith(firstId); + } else { + path.replaceWithMultiple(nodes); + } + } + +}; + +function hoistVariables(path, emit, kind = "var") { + path.traverse(visitor, { + kind, + emit + }); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-hoist-variables/package.json b/node_modules/@babel/helper-hoist-variables/package.json new file mode 100644 index 0000000..cdb9032 --- /dev/null +++ b/node_modules/@babel/helper-hoist-variables/package.json @@ -0,0 +1,60 @@ +{ + "TODO": "The @babel/traverse dependency is only needed for the NodePath TS type. We can consider exporting it from @babel/core.", + "_from": "@babel/helper-hoist-variables@^7.18.6", + "_id": "@babel/helper-hoist-variables@7.18.6", + "_inBundle": false, + "_integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "_location": "/@babel/helper-hoist-variables", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-hoist-variables@^7.18.6", + "name": "@babel/helper-hoist-variables", + "escapedName": "@babel%2fhelper-hoist-variables", + "scope": "@babel", + "rawSpec": "^7.18.6", + "saveSpec": null, + "fetchSpec": "^7.18.6" + }, + "_requiredBy": [ + "/@babel/traverse" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", + "_shasum": "d4d2c8fb4baeaa5c68b99cc8245c56554f926678", + "_spec": "@babel/helper-hoist-variables@^7.18.6", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/traverse", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/types": "^7.18.6" + }, + "deprecated": false, + "description": "Helper function to hoist variables", + "devDependencies": { + "@babel/traverse": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-hoist-variables", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-hoist-variables", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-hoist-variables" + }, + "type": "commonjs", + "version": "7.18.6" +} diff --git a/node_modules/@babel/helper-module-imports/LICENSE b/node_modules/@babel/helper-module-imports/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-module-imports/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-module-imports/README.md b/node_modules/@babel/helper-module-imports/README.md new file mode 100644 index 0000000..933c5b7 --- /dev/null +++ b/node_modules/@babel/helper-module-imports/README.md @@ -0,0 +1,19 @@ +# @babel/helper-module-imports + +> Babel helper functions for inserting module loads + +See our website [@babel/helper-module-imports](https://babeljs.io/docs/en/babel-helper-module-imports) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-module-imports +``` + +or using yarn: + +```sh +yarn add @babel/helper-module-imports +``` diff --git a/node_modules/@babel/helper-module-imports/lib/import-builder.js b/node_modules/@babel/helper-module-imports/lib/import-builder.js new file mode 100644 index 0000000..907f6fd --- /dev/null +++ b/node_modules/@babel/helper-module-imports/lib/import-builder.js @@ -0,0 +1,164 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _assert = require("assert"); + +var _t = require("@babel/types"); + +const { + callExpression, + cloneNode, + expressionStatement, + identifier, + importDeclaration, + importDefaultSpecifier, + importNamespaceSpecifier, + importSpecifier, + memberExpression, + stringLiteral, + variableDeclaration, + variableDeclarator +} = _t; + +class ImportBuilder { + constructor(importedSource, scope, hub) { + this._statements = []; + this._resultName = null; + this._importedSource = void 0; + this._scope = scope; + this._hub = hub; + this._importedSource = importedSource; + } + + done() { + return { + statements: this._statements, + resultName: this._resultName + }; + } + + import() { + this._statements.push(importDeclaration([], stringLiteral(this._importedSource))); + + return this; + } + + require() { + this._statements.push(expressionStatement(callExpression(identifier("require"), [stringLiteral(this._importedSource)]))); + + return this; + } + + namespace(name = "namespace") { + const local = this._scope.generateUidIdentifier(name); + + const statement = this._statements[this._statements.length - 1]; + + _assert(statement.type === "ImportDeclaration"); + + _assert(statement.specifiers.length === 0); + + statement.specifiers = [importNamespaceSpecifier(local)]; + this._resultName = cloneNode(local); + return this; + } + + default(name) { + const id = this._scope.generateUidIdentifier(name); + + const statement = this._statements[this._statements.length - 1]; + + _assert(statement.type === "ImportDeclaration"); + + _assert(statement.specifiers.length === 0); + + statement.specifiers = [importDefaultSpecifier(id)]; + this._resultName = cloneNode(id); + return this; + } + + named(name, importName) { + if (importName === "default") return this.default(name); + + const id = this._scope.generateUidIdentifier(name); + + const statement = this._statements[this._statements.length - 1]; + + _assert(statement.type === "ImportDeclaration"); + + _assert(statement.specifiers.length === 0); + + statement.specifiers = [importSpecifier(id, identifier(importName))]; + this._resultName = cloneNode(id); + return this; + } + + var(name) { + const id = this._scope.generateUidIdentifier(name); + + let statement = this._statements[this._statements.length - 1]; + + if (statement.type !== "ExpressionStatement") { + _assert(this._resultName); + + statement = expressionStatement(this._resultName); + + this._statements.push(statement); + } + + this._statements[this._statements.length - 1] = variableDeclaration("var", [variableDeclarator(id, statement.expression)]); + this._resultName = cloneNode(id); + return this; + } + + defaultInterop() { + return this._interop(this._hub.addHelper("interopRequireDefault")); + } + + wildcardInterop() { + return this._interop(this._hub.addHelper("interopRequireWildcard")); + } + + _interop(callee) { + const statement = this._statements[this._statements.length - 1]; + + if (statement.type === "ExpressionStatement") { + statement.expression = callExpression(callee, [statement.expression]); + } else if (statement.type === "VariableDeclaration") { + _assert(statement.declarations.length === 1); + + statement.declarations[0].init = callExpression(callee, [statement.declarations[0].init]); + } else { + _assert.fail("Unexpected type."); + } + + return this; + } + + prop(name) { + const statement = this._statements[this._statements.length - 1]; + + if (statement.type === "ExpressionStatement") { + statement.expression = memberExpression(statement.expression, identifier(name)); + } else if (statement.type === "VariableDeclaration") { + _assert(statement.declarations.length === 1); + + statement.declarations[0].init = memberExpression(statement.declarations[0].init, identifier(name)); + } else { + _assert.fail("Unexpected type:" + statement.type); + } + + return this; + } + + read(name) { + this._resultName = memberExpression(this._resultName, identifier(name)); + } + +} + +exports.default = ImportBuilder; \ No newline at end of file diff --git a/node_modules/@babel/helper-module-imports/lib/import-injector.js b/node_modules/@babel/helper-module-imports/lib/import-injector.js new file mode 100644 index 0000000..cb3bf59 --- /dev/null +++ b/node_modules/@babel/helper-module-imports/lib/import-injector.js @@ -0,0 +1,280 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _assert = require("assert"); + +var _t = require("@babel/types"); + +var _importBuilder = require("./import-builder"); + +var _isModule = require("./is-module"); + +const { + numericLiteral, + sequenceExpression +} = _t; + +class ImportInjector { + constructor(path, importedSource, opts) { + this._defaultOpts = { + importedSource: null, + importedType: "commonjs", + importedInterop: "babel", + importingInterop: "babel", + ensureLiveReference: false, + ensureNoContext: false, + importPosition: "before" + }; + const programPath = path.find(p => p.isProgram()); + this._programPath = programPath; + this._programScope = programPath.scope; + this._hub = programPath.hub; + this._defaultOpts = this._applyDefaults(importedSource, opts, true); + } + + addDefault(importedSourceIn, opts) { + return this.addNamed("default", importedSourceIn, opts); + } + + addNamed(importName, importedSourceIn, opts) { + _assert(typeof importName === "string"); + + return this._generateImport(this._applyDefaults(importedSourceIn, opts), importName); + } + + addNamespace(importedSourceIn, opts) { + return this._generateImport(this._applyDefaults(importedSourceIn, opts), null); + } + + addSideEffect(importedSourceIn, opts) { + return this._generateImport(this._applyDefaults(importedSourceIn, opts), void 0); + } + + _applyDefaults(importedSource, opts, isInit = false) { + let newOpts; + + if (typeof importedSource === "string") { + newOpts = Object.assign({}, this._defaultOpts, { + importedSource + }, opts); + } else { + _assert(!opts, "Unexpected secondary arguments."); + + newOpts = Object.assign({}, this._defaultOpts, importedSource); + } + + if (!isInit && opts) { + if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint; + if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist; + } + + return newOpts; + } + + _generateImport(opts, importName) { + const isDefault = importName === "default"; + const isNamed = !!importName && !isDefault; + const isNamespace = importName === null; + const { + importedSource, + importedType, + importedInterop, + importingInterop, + ensureLiveReference, + ensureNoContext, + nameHint, + importPosition, + blockHoist + } = opts; + let name = nameHint || importName; + const isMod = (0, _isModule.default)(this._programPath); + const isModuleForNode = isMod && importingInterop === "node"; + const isModuleForBabel = isMod && importingInterop === "babel"; + + if (importPosition === "after" && !isMod) { + throw new Error(`"importPosition": "after" is only supported in modules`); + } + + const builder = new _importBuilder.default(importedSource, this._programScope, this._hub); + + if (importedType === "es6") { + if (!isModuleForNode && !isModuleForBabel) { + throw new Error("Cannot import an ES6 module from CommonJS"); + } + + builder.import(); + + if (isNamespace) { + builder.namespace(nameHint || importedSource); + } else if (isDefault || isNamed) { + builder.named(name, importName); + } + } else if (importedType !== "commonjs") { + throw new Error(`Unexpected interopType "${importedType}"`); + } else if (importedInterop === "babel") { + if (isModuleForNode) { + name = name !== "default" ? name : importedSource; + const es6Default = `${importedSource}$es6Default`; + builder.import(); + + if (isNamespace) { + builder.default(es6Default).var(name || importedSource).wildcardInterop(); + } else if (isDefault) { + if (ensureLiveReference) { + builder.default(es6Default).var(name || importedSource).defaultInterop().read("default"); + } else { + builder.default(es6Default).var(name).defaultInterop().prop(importName); + } + } else if (isNamed) { + builder.default(es6Default).read(importName); + } + } else if (isModuleForBabel) { + builder.import(); + + if (isNamespace) { + builder.namespace(name || importedSource); + } else if (isDefault || isNamed) { + builder.named(name, importName); + } + } else { + builder.require(); + + if (isNamespace) { + builder.var(name || importedSource).wildcardInterop(); + } else if ((isDefault || isNamed) && ensureLiveReference) { + if (isDefault) { + name = name !== "default" ? name : importedSource; + builder.var(name).read(importName); + builder.defaultInterop(); + } else { + builder.var(importedSource).read(importName); + } + } else if (isDefault) { + builder.var(name).defaultInterop().prop(importName); + } else if (isNamed) { + builder.var(name).prop(importName); + } + } + } else if (importedInterop === "compiled") { + if (isModuleForNode) { + builder.import(); + + if (isNamespace) { + builder.default(name || importedSource); + } else if (isDefault || isNamed) { + builder.default(importedSource).read(name); + } + } else if (isModuleForBabel) { + builder.import(); + + if (isNamespace) { + builder.namespace(name || importedSource); + } else if (isDefault || isNamed) { + builder.named(name, importName); + } + } else { + builder.require(); + + if (isNamespace) { + builder.var(name || importedSource); + } else if (isDefault || isNamed) { + if (ensureLiveReference) { + builder.var(importedSource).read(name); + } else { + builder.prop(importName).var(name); + } + } + } + } else if (importedInterop === "uncompiled") { + if (isDefault && ensureLiveReference) { + throw new Error("No live reference for commonjs default"); + } + + if (isModuleForNode) { + builder.import(); + + if (isNamespace) { + builder.default(name || importedSource); + } else if (isDefault) { + builder.default(name); + } else if (isNamed) { + builder.default(importedSource).read(name); + } + } else if (isModuleForBabel) { + builder.import(); + + if (isNamespace) { + builder.default(name || importedSource); + } else if (isDefault) { + builder.default(name); + } else if (isNamed) { + builder.named(name, importName); + } + } else { + builder.require(); + + if (isNamespace) { + builder.var(name || importedSource); + } else if (isDefault) { + builder.var(name); + } else if (isNamed) { + if (ensureLiveReference) { + builder.var(importedSource).read(name); + } else { + builder.var(name).prop(importName); + } + } + } + } else { + throw new Error(`Unknown importedInterop "${importedInterop}".`); + } + + const { + statements, + resultName + } = builder.done(); + + this._insertStatements(statements, importPosition, blockHoist); + + if ((isDefault || isNamed) && ensureNoContext && resultName.type !== "Identifier") { + return sequenceExpression([numericLiteral(0), resultName]); + } + + return resultName; + } + + _insertStatements(statements, importPosition = "before", blockHoist = 3) { + const body = this._programPath.get("body"); + + if (importPosition === "after") { + for (let i = body.length - 1; i >= 0; i--) { + if (body[i].isImportDeclaration()) { + body[i].insertAfter(statements); + return; + } + } + } else { + statements.forEach(node => { + node._blockHoist = blockHoist; + }); + const targetPath = body.find(p => { + const val = p.node._blockHoist; + return Number.isFinite(val) && val < 4; + }); + + if (targetPath) { + targetPath.insertBefore(statements); + return; + } + } + + this._programPath.unshiftContainer("body", statements); + } + +} + +exports.default = ImportInjector; \ No newline at end of file diff --git a/node_modules/@babel/helper-module-imports/lib/index.js b/node_modules/@babel/helper-module-imports/lib/index.js new file mode 100644 index 0000000..a3d7921 --- /dev/null +++ b/node_modules/@babel/helper-module-imports/lib/index.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ImportInjector", { + enumerable: true, + get: function () { + return _importInjector.default; + } +}); +exports.addDefault = addDefault; +exports.addNamed = addNamed; +exports.addNamespace = addNamespace; +exports.addSideEffect = addSideEffect; +Object.defineProperty(exports, "isModule", { + enumerable: true, + get: function () { + return _isModule.default; + } +}); + +var _importInjector = require("./import-injector"); + +var _isModule = require("./is-module"); + +function addDefault(path, importedSource, opts) { + return new _importInjector.default(path).addDefault(importedSource, opts); +} + +function addNamed(path, name, importedSource, opts) { + return new _importInjector.default(path).addNamed(name, importedSource, opts); +} + +function addNamespace(path, importedSource, opts) { + return new _importInjector.default(path).addNamespace(importedSource, opts); +} + +function addSideEffect(path, importedSource, opts) { + return new _importInjector.default(path).addSideEffect(importedSource, opts); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-module-imports/lib/is-module.js b/node_modules/@babel/helper-module-imports/lib/is-module.js new file mode 100644 index 0000000..ad9e399 --- /dev/null +++ b/node_modules/@babel/helper-module-imports/lib/is-module.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isModule; + +function isModule(path) { + const { + sourceType + } = path.node; + + if (sourceType !== "module" && sourceType !== "script") { + throw path.buildCodeFrameError(`Unknown sourceType "${sourceType}", cannot transform.`); + } + + return path.node.sourceType === "module"; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-module-imports/package.json b/node_modules/@babel/helper-module-imports/package.json new file mode 100644 index 0000000..97b64fb --- /dev/null +++ b/node_modules/@babel/helper-module-imports/package.json @@ -0,0 +1,60 @@ +{ + "_from": "@babel/helper-module-imports@^7.18.6", + "_id": "@babel/helper-module-imports@7.18.6", + "_inBundle": false, + "_integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", + "_location": "/@babel/helper-module-imports", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-module-imports@^7.18.6", + "name": "@babel/helper-module-imports", + "escapedName": "@babel%2fhelper-module-imports", + "scope": "@babel", + "rawSpec": "^7.18.6", + "saveSpec": null, + "fetchSpec": "^7.18.6" + }, + "_requiredBy": [ + "/@babel/helper-module-transforms" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", + "_shasum": "1e3ebdbbd08aad1437b428c50204db13c5a3ca6e", + "_spec": "@babel/helper-module-imports@^7.18.6", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/helper-module-transforms", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/types": "^7.18.6" + }, + "deprecated": false, + "description": "Babel helper functions for inserting module loads", + "devDependencies": { + "@babel/core": "^7.18.6", + "@babel/traverse": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-module-imports", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-module-imports", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-module-imports" + }, + "type": "commonjs", + "version": "7.18.6" +} diff --git a/node_modules/@babel/helper-module-transforms/LICENSE b/node_modules/@babel/helper-module-transforms/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-module-transforms/README.md b/node_modules/@babel/helper-module-transforms/README.md new file mode 100644 index 0000000..c7b1a38 --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/README.md @@ -0,0 +1,19 @@ +# @babel/helper-module-transforms + +> Babel helper functions for implementing ES6 module transformations + +See our website [@babel/helper-module-transforms](https://babeljs.io/docs/en/babel-helper-module-transforms) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-module-transforms +``` + +or using yarn: + +```sh +yarn add @babel/helper-module-transforms +``` diff --git a/node_modules/@babel/helper-module-transforms/lib/get-module-name.js b/node_modules/@babel/helper-module-transforms/lib/get-module-name.js new file mode 100644 index 0000000..87c2b83 --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/lib/get-module-name.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = getModuleName; +{ + const originalGetModuleName = getModuleName; + + exports.default = getModuleName = function getModuleName(rootOpts, pluginOpts) { + var _pluginOpts$moduleId, _pluginOpts$moduleIds, _pluginOpts$getModule, _pluginOpts$moduleRoo; + + return originalGetModuleName(rootOpts, { + moduleId: (_pluginOpts$moduleId = pluginOpts.moduleId) != null ? _pluginOpts$moduleId : rootOpts.moduleId, + moduleIds: (_pluginOpts$moduleIds = pluginOpts.moduleIds) != null ? _pluginOpts$moduleIds : rootOpts.moduleIds, + getModuleId: (_pluginOpts$getModule = pluginOpts.getModuleId) != null ? _pluginOpts$getModule : rootOpts.getModuleId, + moduleRoot: (_pluginOpts$moduleRoo = pluginOpts.moduleRoot) != null ? _pluginOpts$moduleRoo : rootOpts.moduleRoot + }); + }; +} + +function getModuleName(rootOpts, pluginOpts) { + const { + filename, + filenameRelative = filename, + sourceRoot = pluginOpts.moduleRoot + } = rootOpts; + const { + moduleId, + moduleIds = !!moduleId, + getModuleId, + moduleRoot = sourceRoot + } = pluginOpts; + if (!moduleIds) return null; + + if (moduleId != null && !getModuleId) { + return moduleId; + } + + let moduleName = moduleRoot != null ? moduleRoot + "/" : ""; + + if (filenameRelative) { + const sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : ""; + moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, ""); + } + + moduleName = moduleName.replace(/\\/g, "/"); + + if (getModuleId) { + return getModuleId(moduleName) || moduleName; + } else { + return moduleName; + } +} \ No newline at end of file diff --git a/node_modules/@babel/helper-module-transforms/lib/index.js b/node_modules/@babel/helper-module-transforms/lib/index.js new file mode 100644 index 0000000..9a4b68d --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/lib/index.js @@ -0,0 +1,424 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildNamespaceInitStatements = buildNamespaceInitStatements; +exports.ensureStatementsHoisted = ensureStatementsHoisted; +Object.defineProperty(exports, "getModuleName", { + enumerable: true, + get: function () { + return _getModuleName.default; + } +}); +Object.defineProperty(exports, "hasExports", { + enumerable: true, + get: function () { + return _normalizeAndLoadMetadata.hasExports; + } +}); +Object.defineProperty(exports, "isModule", { + enumerable: true, + get: function () { + return _helperModuleImports.isModule; + } +}); +Object.defineProperty(exports, "isSideEffectImport", { + enumerable: true, + get: function () { + return _normalizeAndLoadMetadata.isSideEffectImport; + } +}); +exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader; +Object.defineProperty(exports, "rewriteThis", { + enumerable: true, + get: function () { + return _rewriteThis.default; + } +}); +exports.wrapInterop = wrapInterop; + +var _assert = require("assert"); + +var _t = require("@babel/types"); + +var _template = require("@babel/template"); + +var _helperModuleImports = require("@babel/helper-module-imports"); + +var _rewriteThis = require("./rewrite-this"); + +var _rewriteLiveReferences = require("./rewrite-live-references"); + +var _normalizeAndLoadMetadata = require("./normalize-and-load-metadata"); + +var _getModuleName = require("./get-module-name"); + +const { + booleanLiteral, + callExpression, + cloneNode, + directive, + directiveLiteral, + expressionStatement, + identifier, + isIdentifier, + memberExpression, + stringLiteral, + valueToNode, + variableDeclaration, + variableDeclarator +} = _t; + +function rewriteModuleStatementsAndPrepareHeader(path, { + loose, + exportName, + strict, + allowTopLevelThis, + strictMode, + noInterop, + importInterop = noInterop ? "none" : "babel", + lazy, + esNamespaceOnly, + filename, + constantReexports = loose, + enumerableModuleMeta = loose, + noIncompleteNsImportDetection +}) { + (0, _normalizeAndLoadMetadata.validateImportInteropOption)(importInterop); + + _assert((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script"); + + path.node.sourceType = "script"; + const meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, { + importInterop, + initializeReexports: constantReexports, + lazy, + esNamespaceOnly, + filename + }); + + if (!allowTopLevelThis) { + (0, _rewriteThis.default)(path); + } + + (0, _rewriteLiveReferences.default)(path, meta); + + if (strictMode !== false) { + const hasStrict = path.node.directives.some(directive => { + return directive.value.value === "use strict"; + }); + + if (!hasStrict) { + path.unshiftContainer("directives", directive(directiveLiteral("use strict"))); + } + } + + const headers = []; + + if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) { + headers.push(buildESModuleHeader(meta, enumerableModuleMeta)); + } + + const nameList = buildExportNameListDeclaration(path, meta); + + if (nameList) { + meta.exportNameListName = nameList.name; + headers.push(nameList.statement); + } + + headers.push(...buildExportInitializationStatements(path, meta, constantReexports, noIncompleteNsImportDetection)); + return { + meta, + headers + }; +} + +function ensureStatementsHoisted(statements) { + statements.forEach(header => { + header._blockHoist = 3; + }); +} + +function wrapInterop(programPath, expr, type) { + if (type === "none") { + return null; + } + + if (type === "node-namespace") { + return callExpression(programPath.hub.addHelper("interopRequireWildcard"), [expr, booleanLiteral(true)]); + } else if (type === "node-default") { + return null; + } + + let helper; + + if (type === "default") { + helper = "interopRequireDefault"; + } else if (type === "namespace") { + helper = "interopRequireWildcard"; + } else { + throw new Error(`Unknown interop: ${type}`); + } + + return callExpression(programPath.hub.addHelper(helper), [expr]); +} + +function buildNamespaceInitStatements(metadata, sourceMetadata, constantReexports = false) { + const statements = []; + let srcNamespace = identifier(sourceMetadata.name); + if (sourceMetadata.lazy) srcNamespace = callExpression(srcNamespace, []); + + for (const localName of sourceMetadata.importsNamespace) { + if (localName === sourceMetadata.name) continue; + statements.push(_template.default.statement`var NAME = SOURCE;`({ + NAME: localName, + SOURCE: cloneNode(srcNamespace) + })); + } + + if (constantReexports) { + statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, true)); + } + + for (const exportName of sourceMetadata.reexportNamespace) { + statements.push((sourceMetadata.lazy ? _template.default.statement` + Object.defineProperty(EXPORTS, "NAME", { + enumerable: true, + get: function() { + return NAMESPACE; + } + }); + ` : _template.default.statement`EXPORTS.NAME = NAMESPACE;`)({ + EXPORTS: metadata.exportName, + NAME: exportName, + NAMESPACE: cloneNode(srcNamespace) + })); + } + + if (sourceMetadata.reexportAll) { + const statement = buildNamespaceReexport(metadata, cloneNode(srcNamespace), constantReexports); + statement.loc = sourceMetadata.reexportAll.loc; + statements.push(statement); + } + + return statements; +} + +const ReexportTemplate = { + constant: _template.default.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`, + constantComputed: _template.default.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`, + spec: _template.default.statement` + Object.defineProperty(EXPORTS, "EXPORT_NAME", { + enumerable: true, + get: function() { + return NAMESPACE_IMPORT; + }, + }); + ` +}; + +const buildReexportsFromMeta = (meta, metadata, constantReexports) => { + const namespace = metadata.lazy ? callExpression(identifier(metadata.name), []) : identifier(metadata.name); + const { + stringSpecifiers + } = meta; + return Array.from(metadata.reexports, ([exportName, importName]) => { + let NAMESPACE_IMPORT = cloneNode(namespace); + + if (importName === "default" && metadata.interop === "node-default") {} else if (stringSpecifiers.has(importName)) { + NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, stringLiteral(importName), true); + } else { + NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, identifier(importName)); + } + + const astNodes = { + EXPORTS: meta.exportName, + EXPORT_NAME: exportName, + NAMESPACE_IMPORT + }; + + if (constantReexports || isIdentifier(NAMESPACE_IMPORT)) { + if (stringSpecifiers.has(exportName)) { + return ReexportTemplate.constantComputed(astNodes); + } else { + return ReexportTemplate.constant(astNodes); + } + } else { + return ReexportTemplate.spec(astNodes); + } + }); +}; + +function buildESModuleHeader(metadata, enumerableModuleMeta = false) { + return (enumerableModuleMeta ? _template.default.statement` + EXPORTS.__esModule = true; + ` : _template.default.statement` + Object.defineProperty(EXPORTS, "__esModule", { + value: true, + }); + `)({ + EXPORTS: metadata.exportName + }); +} + +function buildNamespaceReexport(metadata, namespace, constantReexports) { + return (constantReexports ? _template.default.statement` + Object.keys(NAMESPACE).forEach(function(key) { + if (key === "default" || key === "__esModule") return; + VERIFY_NAME_LIST; + if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return; + + EXPORTS[key] = NAMESPACE[key]; + }); + ` : _template.default.statement` + Object.keys(NAMESPACE).forEach(function(key) { + if (key === "default" || key === "__esModule") return; + VERIFY_NAME_LIST; + if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return; + + Object.defineProperty(EXPORTS, key, { + enumerable: true, + get: function() { + return NAMESPACE[key]; + }, + }); + }); + `)({ + NAMESPACE: namespace, + EXPORTS: metadata.exportName, + VERIFY_NAME_LIST: metadata.exportNameListName ? (0, _template.default)` + if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return; + `({ + EXPORTS_LIST: metadata.exportNameListName + }) : null + }); +} + +function buildExportNameListDeclaration(programPath, metadata) { + const exportedVars = Object.create(null); + + for (const data of metadata.local.values()) { + for (const name of data.names) { + exportedVars[name] = true; + } + } + + let hasReexport = false; + + for (const data of metadata.source.values()) { + for (const exportName of data.reexports.keys()) { + exportedVars[exportName] = true; + } + + for (const exportName of data.reexportNamespace) { + exportedVars[exportName] = true; + } + + hasReexport = hasReexport || !!data.reexportAll; + } + + if (!hasReexport || Object.keys(exportedVars).length === 0) return null; + const name = programPath.scope.generateUidIdentifier("exportNames"); + delete exportedVars.default; + return { + name: name.name, + statement: variableDeclaration("var", [variableDeclarator(name, valueToNode(exportedVars))]) + }; +} + +function buildExportInitializationStatements(programPath, metadata, constantReexports = false, noIncompleteNsImportDetection = false) { + const initStatements = []; + + for (const [localName, data] of metadata.local) { + if (data.kind === "import") {} else if (data.kind === "hoisted") { + initStatements.push([data.names[0], buildInitStatement(metadata, data.names, identifier(localName))]); + } else if (!noIncompleteNsImportDetection) { + for (const exportName of data.names) { + initStatements.push([exportName, null]); + } + } + } + + for (const data of metadata.source.values()) { + if (!constantReexports) { + const reexportsStatements = buildReexportsFromMeta(metadata, data, false); + const reexports = [...data.reexports.keys()]; + + for (let i = 0; i < reexportsStatements.length; i++) { + initStatements.push([reexports[i], reexportsStatements[i]]); + } + } + + if (!noIncompleteNsImportDetection) { + for (const exportName of data.reexportNamespace) { + initStatements.push([exportName, null]); + } + } + } + + initStatements.sort(([a], [b]) => { + if (a < b) return -1; + if (b < a) return 1; + return 0; + }); + const results = []; + + if (noIncompleteNsImportDetection) { + for (const [, initStatement] of initStatements) { + results.push(initStatement); + } + } else { + const chunkSize = 100; + + for (let i = 0; i < initStatements.length; i += chunkSize) { + let uninitializedExportNames = []; + + for (let j = 0; j < chunkSize && i + j < initStatements.length; j++) { + const [exportName, initStatement] = initStatements[i + j]; + + if (initStatement !== null) { + if (uninitializedExportNames.length > 0) { + results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode())); + uninitializedExportNames = []; + } + + results.push(initStatement); + } else { + uninitializedExportNames.push(exportName); + } + } + + if (uninitializedExportNames.length > 0) { + results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode())); + } + } + } + + return results; +} + +const InitTemplate = { + computed: _template.default.expression`EXPORTS["NAME"] = VALUE`, + default: _template.default.expression`EXPORTS.NAME = VALUE` +}; + +function buildInitStatement(metadata, exportNames, initExpr) { + const { + stringSpecifiers, + exportName: EXPORTS + } = metadata; + return expressionStatement(exportNames.reduce((acc, exportName) => { + const params = { + EXPORTS, + NAME: exportName, + VALUE: acc + }; + + if (stringSpecifiers.has(exportName)) { + return InitTemplate.computed(params); + } else { + return InitTemplate.default(params); + } + }, initExpr)); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-module-transforms/lib/normalize-and-load-metadata.js b/node_modules/@babel/helper-module-transforms/lib/normalize-and-load-metadata.js new file mode 100644 index 0000000..5187a30 --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/lib/normalize-and-load-metadata.js @@ -0,0 +1,401 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeModuleAndLoadMetadata; +exports.hasExports = hasExports; +exports.isSideEffectImport = isSideEffectImport; +exports.validateImportInteropOption = validateImportInteropOption; + +var _path = require("path"); + +var _helperValidatorIdentifier = require("@babel/helper-validator-identifier"); + +var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration"); + +function hasExports(metadata) { + return metadata.hasExports; +} + +function isSideEffectImport(source) { + return source.imports.size === 0 && source.importsNamespace.size === 0 && source.reexports.size === 0 && source.reexportNamespace.size === 0 && !source.reexportAll; +} + +function validateImportInteropOption(importInterop) { + if (typeof importInterop !== "function" && importInterop !== "none" && importInterop !== "babel" && importInterop !== "node") { + throw new Error(`.importInterop must be one of "none", "babel", "node", or a function returning one of those values (received ${importInterop}).`); + } + + return importInterop; +} + +function resolveImportInterop(importInterop, source, filename) { + if (typeof importInterop === "function") { + return validateImportInteropOption(importInterop(source, filename)); + } + + return importInterop; +} + +function normalizeModuleAndLoadMetadata(programPath, exportName, { + importInterop, + initializeReexports = false, + lazy = false, + esNamespaceOnly = false, + filename +}) { + if (!exportName) { + exportName = programPath.scope.generateUidIdentifier("exports").name; + } + + const stringSpecifiers = new Set(); + nameAnonymousExports(programPath); + const { + local, + source, + hasExports + } = getModuleMetadata(programPath, { + initializeReexports, + lazy + }, stringSpecifiers); + removeModuleDeclarations(programPath); + + for (const [, metadata] of source) { + if (metadata.importsNamespace.size > 0) { + metadata.name = metadata.importsNamespace.values().next().value; + } + + const resolvedInterop = resolveImportInterop(importInterop, metadata.source, filename); + + if (resolvedInterop === "none") { + metadata.interop = "none"; + } else if (resolvedInterop === "node" && metadata.interop === "namespace") { + metadata.interop = "node-namespace"; + } else if (resolvedInterop === "node" && metadata.interop === "default") { + metadata.interop = "node-default"; + } else if (esNamespaceOnly && metadata.interop === "namespace") { + metadata.interop = "default"; + } + } + + return { + exportName, + exportNameListName: null, + hasExports, + local, + source, + stringSpecifiers + }; +} + +function getExportSpecifierName(path, stringSpecifiers) { + if (path.isIdentifier()) { + return path.node.name; + } else if (path.isStringLiteral()) { + const stringValue = path.node.value; + + if (!(0, _helperValidatorIdentifier.isIdentifierName)(stringValue)) { + stringSpecifiers.add(stringValue); + } + + return stringValue; + } else { + throw new Error(`Expected export specifier to be either Identifier or StringLiteral, got ${path.node.type}`); + } +} + +function assertExportSpecifier(path) { + if (path.isExportSpecifier()) { + return; + } else if (path.isExportNamespaceSpecifier()) { + throw path.buildCodeFrameError("Export namespace should be first transformed by `@babel/plugin-proposal-export-namespace-from`."); + } else { + throw path.buildCodeFrameError("Unexpected export specifier type"); + } +} + +function getModuleMetadata(programPath, { + lazy, + initializeReexports +}, stringSpecifiers) { + const localData = getLocalExportMetadata(programPath, initializeReexports, stringSpecifiers); + const sourceData = new Map(); + + const getData = sourceNode => { + const source = sourceNode.value; + let data = sourceData.get(source); + + if (!data) { + data = { + name: programPath.scope.generateUidIdentifier((0, _path.basename)(source, (0, _path.extname)(source))).name, + interop: "none", + loc: null, + imports: new Map(), + importsNamespace: new Set(), + reexports: new Map(), + reexportNamespace: new Set(), + reexportAll: null, + lazy: false, + source + }; + sourceData.set(source, data); + } + + return data; + }; + + let hasExports = false; + programPath.get("body").forEach(child => { + if (child.isImportDeclaration()) { + const data = getData(child.node.source); + if (!data.loc) data.loc = child.node.loc; + child.get("specifiers").forEach(spec => { + if (spec.isImportDefaultSpecifier()) { + const localName = spec.get("local").node.name; + data.imports.set(localName, "default"); + const reexport = localData.get(localName); + + if (reexport) { + localData.delete(localName); + reexport.names.forEach(name => { + data.reexports.set(name, "default"); + }); + } + } else if (spec.isImportNamespaceSpecifier()) { + const localName = spec.get("local").node.name; + data.importsNamespace.add(localName); + const reexport = localData.get(localName); + + if (reexport) { + localData.delete(localName); + reexport.names.forEach(name => { + data.reexportNamespace.add(name); + }); + } + } else if (spec.isImportSpecifier()) { + const importName = getExportSpecifierName(spec.get("imported"), stringSpecifiers); + const localName = spec.get("local").node.name; + data.imports.set(localName, importName); + const reexport = localData.get(localName); + + if (reexport) { + localData.delete(localName); + reexport.names.forEach(name => { + data.reexports.set(name, importName); + }); + } + } + }); + } else if (child.isExportAllDeclaration()) { + hasExports = true; + const data = getData(child.node.source); + if (!data.loc) data.loc = child.node.loc; + data.reexportAll = { + loc: child.node.loc + }; + } else if (child.isExportNamedDeclaration() && child.node.source) { + hasExports = true; + const data = getData(child.node.source); + if (!data.loc) data.loc = child.node.loc; + child.get("specifiers").forEach(spec => { + assertExportSpecifier(spec); + const importName = getExportSpecifierName(spec.get("local"), stringSpecifiers); + const exportName = getExportSpecifierName(spec.get("exported"), stringSpecifiers); + data.reexports.set(exportName, importName); + + if (exportName === "__esModule") { + throw spec.get("exported").buildCodeFrameError('Illegal export "__esModule".'); + } + }); + } else if (child.isExportNamedDeclaration() || child.isExportDefaultDeclaration()) { + hasExports = true; + } + }); + + for (const metadata of sourceData.values()) { + let needsDefault = false; + let needsNamed = false; + + if (metadata.importsNamespace.size > 0) { + needsDefault = true; + needsNamed = true; + } + + if (metadata.reexportAll) { + needsNamed = true; + } + + for (const importName of metadata.imports.values()) { + if (importName === "default") needsDefault = true;else needsNamed = true; + } + + for (const importName of metadata.reexports.values()) { + if (importName === "default") needsDefault = true;else needsNamed = true; + } + + if (needsDefault && needsNamed) { + metadata.interop = "namespace"; + } else if (needsDefault) { + metadata.interop = "default"; + } + } + + for (const [source, metadata] of sourceData) { + if (lazy !== false && !(isSideEffectImport(metadata) || metadata.reexportAll)) { + if (lazy === true) { + metadata.lazy = !/\./.test(source); + } else if (Array.isArray(lazy)) { + metadata.lazy = lazy.indexOf(source) !== -1; + } else if (typeof lazy === "function") { + metadata.lazy = lazy(source); + } else { + throw new Error(`.lazy must be a boolean, string array, or function`); + } + } + } + + return { + hasExports, + local: localData, + source: sourceData + }; +} + +function getLocalExportMetadata(programPath, initializeReexports, stringSpecifiers) { + const bindingKindLookup = new Map(); + programPath.get("body").forEach(child => { + let kind; + + if (child.isImportDeclaration()) { + kind = "import"; + } else { + if (child.isExportDefaultDeclaration()) { + child = child.get("declaration"); + } + + if (child.isExportNamedDeclaration()) { + if (child.node.declaration) { + child = child.get("declaration"); + } else if (initializeReexports && child.node.source && child.get("source").isStringLiteral()) { + child.get("specifiers").forEach(spec => { + assertExportSpecifier(spec); + bindingKindLookup.set(spec.get("local").node.name, "block"); + }); + return; + } + } + + if (child.isFunctionDeclaration()) { + kind = "hoisted"; + } else if (child.isClassDeclaration()) { + kind = "block"; + } else if (child.isVariableDeclaration({ + kind: "var" + })) { + kind = "var"; + } else if (child.isVariableDeclaration()) { + kind = "block"; + } else { + return; + } + } + + Object.keys(child.getOuterBindingIdentifiers()).forEach(name => { + bindingKindLookup.set(name, kind); + }); + }); + const localMetadata = new Map(); + + const getLocalMetadata = idPath => { + const localName = idPath.node.name; + let metadata = localMetadata.get(localName); + + if (!metadata) { + const kind = bindingKindLookup.get(localName); + + if (kind === undefined) { + throw idPath.buildCodeFrameError(`Exporting local "${localName}", which is not declared.`); + } + + metadata = { + names: [], + kind + }; + localMetadata.set(localName, metadata); + } + + return metadata; + }; + + programPath.get("body").forEach(child => { + if (child.isExportNamedDeclaration() && (initializeReexports || !child.node.source)) { + if (child.node.declaration) { + const declaration = child.get("declaration"); + const ids = declaration.getOuterBindingIdentifierPaths(); + Object.keys(ids).forEach(name => { + if (name === "__esModule") { + throw declaration.buildCodeFrameError('Illegal export "__esModule".'); + } + + getLocalMetadata(ids[name]).names.push(name); + }); + } else { + child.get("specifiers").forEach(spec => { + const local = spec.get("local"); + const exported = spec.get("exported"); + const localMetadata = getLocalMetadata(local); + const exportName = getExportSpecifierName(exported, stringSpecifiers); + + if (exportName === "__esModule") { + throw exported.buildCodeFrameError('Illegal export "__esModule".'); + } + + localMetadata.names.push(exportName); + }); + } + } else if (child.isExportDefaultDeclaration()) { + const declaration = child.get("declaration"); + + if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration()) { + getLocalMetadata(declaration.get("id")).names.push("default"); + } else { + throw declaration.buildCodeFrameError("Unexpected default expression export."); + } + } + }); + return localMetadata; +} + +function nameAnonymousExports(programPath) { + programPath.get("body").forEach(child => { + if (!child.isExportDefaultDeclaration()) return; + (0, _helperSplitExportDeclaration.default)(child); + }); +} + +function removeModuleDeclarations(programPath) { + programPath.get("body").forEach(child => { + if (child.isImportDeclaration()) { + child.remove(); + } else if (child.isExportNamedDeclaration()) { + if (child.node.declaration) { + child.node.declaration._blockHoist = child.node._blockHoist; + child.replaceWith(child.node.declaration); + } else { + child.remove(); + } + } else if (child.isExportDefaultDeclaration()) { + const declaration = child.get("declaration"); + + if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration()) { + declaration._blockHoist = child.node._blockHoist; + child.replaceWith(declaration); + } else { + throw declaration.buildCodeFrameError("Unexpected default expression export."); + } + } else if (child.isExportAllDeclaration()) { + child.remove(); + } + }); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-module-transforms/lib/rewrite-live-references.js b/node_modules/@babel/helper-module-transforms/lib/rewrite-live-references.js new file mode 100644 index 0000000..7ef6a46 --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/lib/rewrite-live-references.js @@ -0,0 +1,412 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rewriteLiveReferences; + +var _assert = require("assert"); + +var _t = require("@babel/types"); + +var _template = require("@babel/template"); + +var _helperSimpleAccess = require("@babel/helper-simple-access"); + +const { + assignmentExpression, + callExpression, + cloneNode, + expressionStatement, + getOuterBindingIdentifiers, + identifier, + isMemberExpression, + isVariableDeclaration, + jsxIdentifier, + jsxMemberExpression, + memberExpression, + numericLiteral, + sequenceExpression, + stringLiteral, + variableDeclaration, + variableDeclarator +} = _t; + +function isInType(path) { + do { + switch (path.parent.type) { + case "TSTypeAnnotation": + case "TSTypeAliasDeclaration": + case "TSTypeReference": + case "TypeAnnotation": + case "TypeAlias": + return true; + + case "ExportSpecifier": + return path.parentPath.parent.exportKind === "type"; + + default: + if (path.parentPath.isStatement() || path.parentPath.isExpression()) { + return false; + } + + } + } while (path = path.parentPath); +} + +function rewriteLiveReferences(programPath, metadata) { + const imported = new Map(); + const exported = new Map(); + + const requeueInParent = path => { + programPath.requeue(path); + }; + + for (const [source, data] of metadata.source) { + for (const [localName, importName] of data.imports) { + imported.set(localName, [source, importName, null]); + } + + for (const localName of data.importsNamespace) { + imported.set(localName, [source, null, localName]); + } + } + + for (const [local, data] of metadata.local) { + let exportMeta = exported.get(local); + + if (!exportMeta) { + exportMeta = []; + exported.set(local, exportMeta); + } + + exportMeta.push(...data.names); + } + + const rewriteBindingInitVisitorState = { + metadata, + requeueInParent, + scope: programPath.scope, + exported + }; + programPath.traverse(rewriteBindingInitVisitor, rewriteBindingInitVisitorState); + (0, _helperSimpleAccess.default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]), false); + const rewriteReferencesVisitorState = { + seen: new WeakSet(), + metadata, + requeueInParent, + scope: programPath.scope, + imported, + exported, + buildImportReference: ([source, importName, localName], identNode) => { + const meta = metadata.source.get(source); + + if (localName) { + if (meta.lazy) { + identNode = callExpression(identNode, []); + } + + return identNode; + } + + let namespace = identifier(meta.name); + if (meta.lazy) namespace = callExpression(namespace, []); + + if (importName === "default" && meta.interop === "node-default") { + return namespace; + } + + const computed = metadata.stringSpecifiers.has(importName); + return memberExpression(namespace, computed ? stringLiteral(importName) : identifier(importName), computed); + } + }; + programPath.traverse(rewriteReferencesVisitor, rewriteReferencesVisitorState); +} + +const rewriteBindingInitVisitor = { + Scope(path) { + path.skip(); + }, + + ClassDeclaration(path) { + const { + requeueInParent, + exported, + metadata + } = this; + const { + id + } = path.node; + if (!id) throw new Error("Expected class to have a name"); + const localName = id.name; + const exportNames = exported.get(localName) || []; + + if (exportNames.length > 0) { + const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName), path.scope)); + statement._blockHoist = path.node._blockHoist; + requeueInParent(path.insertAfter(statement)[0]); + } + }, + + VariableDeclaration(path) { + const { + requeueInParent, + exported, + metadata + } = this; + Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => { + const exportNames = exported.get(localName) || []; + + if (exportNames.length > 0) { + const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName), path.scope)); + statement._blockHoist = path.node._blockHoist; + requeueInParent(path.insertAfter(statement)[0]); + } + }); + } + +}; + +const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr, scope) => { + const exportsObjectName = metadata.exportName; + + for (let currentScope = scope; currentScope != null; currentScope = currentScope.parent) { + if (currentScope.hasOwnBinding(exportsObjectName)) { + currentScope.rename(exportsObjectName); + } + } + + return (exportNames || []).reduce((expr, exportName) => { + const { + stringSpecifiers + } = metadata; + const computed = stringSpecifiers.has(exportName); + return assignmentExpression("=", memberExpression(identifier(exportsObjectName), computed ? stringLiteral(exportName) : identifier(exportName), computed), expr); + }, localExpr); +}; + +const buildImportThrow = localName => { + return _template.default.expression.ast` + (function() { + throw new Error('"' + '${localName}' + '" is read-only.'); + })() + `; +}; + +const rewriteReferencesVisitor = { + ReferencedIdentifier(path) { + const { + seen, + buildImportReference, + scope, + imported, + requeueInParent + } = this; + if (seen.has(path.node)) return; + seen.add(path.node); + const localName = path.node.name; + const importData = imported.get(localName); + + if (importData) { + if (isInType(path)) { + throw path.buildCodeFrameError(`Cannot transform the imported binding "${localName}" since it's also used in a type annotation. ` + `Please strip type annotations using @babel/preset-typescript or @babel/preset-flow.`); + } + + const localBinding = path.scope.getBinding(localName); + const rootBinding = scope.getBinding(localName); + if (rootBinding !== localBinding) return; + const ref = buildImportReference(importData, path.node); + ref.loc = path.node.loc; + + if ((path.parentPath.isCallExpression({ + callee: path.node + }) || path.parentPath.isOptionalCallExpression({ + callee: path.node + }) || path.parentPath.isTaggedTemplateExpression({ + tag: path.node + })) && isMemberExpression(ref)) { + path.replaceWith(sequenceExpression([numericLiteral(0), ref])); + } else if (path.isJSXIdentifier() && isMemberExpression(ref)) { + const { + object, + property + } = ref; + path.replaceWith(jsxMemberExpression(jsxIdentifier(object.name), jsxIdentifier(property.name))); + } else { + path.replaceWith(ref); + } + + requeueInParent(path); + path.skip(); + } + }, + + UpdateExpression(path) { + const { + scope, + seen, + imported, + exported, + requeueInParent, + buildImportReference + } = this; + if (seen.has(path.node)) return; + seen.add(path.node); + const arg = path.get("argument"); + if (arg.isMemberExpression()) return; + const update = path.node; + + if (arg.isIdentifier()) { + const localName = arg.node.name; + + if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { + return; + } + + const exportedNames = exported.get(localName); + const importData = imported.get(localName); + + if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) { + if (importData) { + path.replaceWith(assignmentExpression(update.operator[0] + "=", buildImportReference(importData, arg.node), buildImportThrow(localName))); + } else if (update.prefix) { + path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, cloneNode(update), path.scope)); + } else { + const ref = scope.generateDeclaredUidIdentifier(localName); + path.replaceWith(sequenceExpression([assignmentExpression("=", cloneNode(ref), cloneNode(update)), buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName), path.scope), cloneNode(ref)])); + } + } + } + + requeueInParent(path); + path.skip(); + }, + + AssignmentExpression: { + exit(path) { + const { + scope, + seen, + imported, + exported, + requeueInParent, + buildImportReference + } = this; + if (seen.has(path.node)) return; + seen.add(path.node); + const left = path.get("left"); + if (left.isMemberExpression()) return; + + if (left.isIdentifier()) { + const localName = left.node.name; + + if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { + return; + } + + const exportedNames = exported.get(localName); + const importData = imported.get(localName); + + if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) { + _assert(path.node.operator === "=", "Path was not simplified"); + + const assignment = path.node; + + if (importData) { + assignment.left = buildImportReference(importData, left.node); + assignment.right = sequenceExpression([assignment.right, buildImportThrow(localName)]); + } + + path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment, path.scope)); + requeueInParent(path); + } + } else { + const ids = left.getOuterBindingIdentifiers(); + const programScopeIds = Object.keys(ids).filter(localName => scope.getBinding(localName) === path.scope.getBinding(localName)); + const id = programScopeIds.find(localName => imported.has(localName)); + + if (id) { + path.node.right = sequenceExpression([path.node.right, buildImportThrow(id)]); + } + + const items = []; + programScopeIds.forEach(localName => { + const exportedNames = exported.get(localName) || []; + + if (exportedNames.length > 0) { + items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName), path.scope)); + } + }); + + if (items.length > 0) { + let node = sequenceExpression(items); + + if (path.parentPath.isExpressionStatement()) { + node = expressionStatement(node); + node._blockHoist = path.parentPath.node._blockHoist; + } + + const statement = path.insertAfter(node)[0]; + requeueInParent(statement); + } + } + } + + }, + + "ForOfStatement|ForInStatement"(path) { + const { + scope, + node + } = path; + const { + left + } = node; + const { + exported, + imported, + scope: programScope + } = this; + + if (!isVariableDeclaration(left)) { + let didTransformExport = false, + importConstViolationName; + const loopBodyScope = path.get("body").scope; + + for (const name of Object.keys(getOuterBindingIdentifiers(left))) { + if (programScope.getBinding(name) === scope.getBinding(name)) { + if (exported.has(name)) { + didTransformExport = true; + + if (loopBodyScope.hasOwnBinding(name)) { + loopBodyScope.rename(name); + } + } + + if (imported.has(name) && !importConstViolationName) { + importConstViolationName = name; + } + } + } + + if (!didTransformExport && !importConstViolationName) { + return; + } + + path.ensureBlock(); + const bodyPath = path.get("body"); + const newLoopId = scope.generateUidIdentifierBasedOnNode(left); + path.get("left").replaceWith(variableDeclaration("let", [variableDeclarator(cloneNode(newLoopId))])); + scope.registerDeclaration(path.get("left")); + + if (didTransformExport) { + bodyPath.unshiftContainer("body", expressionStatement(assignmentExpression("=", left, newLoopId))); + } + + if (importConstViolationName) { + bodyPath.unshiftContainer("body", expressionStatement(buildImportThrow(importConstViolationName))); + } + } + } + +}; \ No newline at end of file diff --git a/node_modules/@babel/helper-module-transforms/lib/rewrite-this.js b/node_modules/@babel/helper-module-transforms/lib/rewrite-this.js new file mode 100644 index 0000000..9165539 --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/lib/rewrite-this.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rewriteThis; + +var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor"); + +var _traverse = require("@babel/traverse"); + +var _t = require("@babel/types"); + +const { + numericLiteral, + unaryExpression +} = _t; + +function rewriteThis(programPath) { + (0, _traverse.default)(programPath.node, Object.assign({}, rewriteThisVisitor, { + noScope: true + })); +} + +const rewriteThisVisitor = _traverse.default.visitors.merge([_helperEnvironmentVisitor.default, { + ThisExpression(path) { + path.replaceWith(unaryExpression("void", numericLiteral(0), true)); + } + +}]); \ No newline at end of file diff --git a/node_modules/@babel/helper-module-transforms/package.json b/node_modules/@babel/helper-module-transforms/package.json new file mode 100644 index 0000000..df3b9a6 --- /dev/null +++ b/node_modules/@babel/helper-module-transforms/package.json @@ -0,0 +1,63 @@ +{ + "_from": "@babel/helper-module-transforms@^7.18.9", + "_id": "@babel/helper-module-transforms@7.18.9", + "_inBundle": false, + "_integrity": "sha512-KYNqY0ICwfv19b31XzvmI/mfcylOzbLtowkw+mfvGPAQ3kfCnMLYbED3YecL5tPd8nAYFQFAd6JHp2LxZk/J1g==", + "_location": "/@babel/helper-module-transforms", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-module-transforms@^7.18.9", + "name": "@babel/helper-module-transforms", + "escapedName": "@babel%2fhelper-module-transforms", + "scope": "@babel", + "rawSpec": "^7.18.9", + "saveSpec": null, + "fetchSpec": "^7.18.9" + }, + "_requiredBy": [ + "/@babel/core" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.18.9.tgz", + "_shasum": "5a1079c005135ed627442df31a42887e80fcb712", + "_spec": "@babel/helper-module-transforms@^7.18.9", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/core", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-module-imports": "^7.18.6", + "@babel/helper-simple-access": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/helper-validator-identifier": "^7.18.6", + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" + }, + "deprecated": false, + "description": "Babel helper functions for implementing ES6 module transformations", + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-module-transforms", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-module-transforms", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-module-transforms" + }, + "type": "commonjs", + "version": "7.18.9" +} diff --git a/node_modules/@babel/helper-plugin-utils/LICENSE b/node_modules/@babel/helper-plugin-utils/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-plugin-utils/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-plugin-utils/README.md b/node_modules/@babel/helper-plugin-utils/README.md new file mode 100644 index 0000000..c17852d --- /dev/null +++ b/node_modules/@babel/helper-plugin-utils/README.md @@ -0,0 +1,19 @@ +# @babel/helper-plugin-utils + +> General utilities for plugins to use + +See our website [@babel/helper-plugin-utils](https://babeljs.io/docs/en/babel-helper-plugin-utils) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-plugin-utils +``` + +or using yarn: + +```sh +yarn add @babel/helper-plugin-utils +``` diff --git a/node_modules/@babel/helper-plugin-utils/lib/index.js b/node_modules/@babel/helper-plugin-utils/lib/index.js new file mode 100644 index 0000000..02df692 --- /dev/null +++ b/node_modules/@babel/helper-plugin-utils/lib/index.js @@ -0,0 +1,95 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.declare = declare; +exports.declarePreset = void 0; + +function declare(builder) { + return (api, options, dirname) => { + var _clonedApi2; + + let clonedApi; + + for (const name of Object.keys(apiPolyfills)) { + var _clonedApi; + + if (api[name]) continue; + clonedApi = (_clonedApi = clonedApi) != null ? _clonedApi : copyApiObject(api); + clonedApi[name] = apiPolyfills[name](clonedApi); + } + + return builder((_clonedApi2 = clonedApi) != null ? _clonedApi2 : api, options || {}, dirname); + }; +} + +const declarePreset = declare; +exports.declarePreset = declarePreset; +const apiPolyfills = { + assertVersion: api => range => { + throwVersionError(range, api.version); + }, + targets: () => () => { + return {}; + }, + assumption: () => () => { + return undefined; + } +}; + +function copyApiObject(api) { + let proto = null; + + if (typeof api.version === "string" && /^7\./.test(api.version)) { + proto = Object.getPrototypeOf(api); + + if (proto && (!has(proto, "version") || !has(proto, "transform") || !has(proto, "template") || !has(proto, "types"))) { + proto = null; + } + } + + return Object.assign({}, proto, api); +} + +function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function throwVersionError(range, version) { + if (typeof range === "number") { + if (!Number.isInteger(range)) { + throw new Error("Expected string or integer value."); + } + + range = `^${range}.0.0-0`; + } + + if (typeof range !== "string") { + throw new Error("Expected string or integer value."); + } + + const limit = Error.stackTraceLimit; + + if (typeof limit === "number" && limit < 25) { + Error.stackTraceLimit = 25; + } + + let err; + + if (version.slice(0, 2) === "7.") { + err = new Error(`Requires Babel "^7.0.0-beta.41", but was loaded with "${version}". ` + `You'll need to update your @babel/core version.`); + } else { + err = new Error(`Requires Babel "${range}", but was loaded with "${version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`); + } + + if (typeof limit === "number") { + Error.stackTraceLimit = limit; + } + + throw Object.assign(err, { + code: "BABEL_VERSION_UNSUPPORTED", + version, + range + }); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-plugin-utils/package.json b/node_modules/@babel/helper-plugin-utils/package.json new file mode 100644 index 0000000..985ac42 --- /dev/null +++ b/node_modules/@babel/helper-plugin-utils/package.json @@ -0,0 +1,67 @@ +{ + "_from": "@babel/helper-plugin-utils@^7.0.0", + "_id": "@babel/helper-plugin-utils@7.18.9", + "_inBundle": false, + "_integrity": "sha512-aBXPT3bmtLryXaoJLyYPXPlSD4p1ld9aYeR+sJNOZjJJGiOpb+fKfh3NkcCu7J54nUJwCERPBExCCpyCOHnu/w==", + "_location": "/@babel/helper-plugin-utils", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-plugin-utils@^7.0.0", + "name": "@babel/helper-plugin-utils", + "escapedName": "@babel%2fhelper-plugin-utils", + "scope": "@babel", + "rawSpec": "^7.0.0", + "saveSpec": null, + "fetchSpec": "^7.0.0" + }, + "_requiredBy": [ + "/@babel/plugin-syntax-async-generators", + "/@babel/plugin-syntax-bigint", + "/@babel/plugin-syntax-class-properties", + "/@babel/plugin-syntax-import-meta", + "/@babel/plugin-syntax-json-strings", + "/@babel/plugin-syntax-jsx", + "/@babel/plugin-syntax-logical-assignment-operators", + "/@babel/plugin-syntax-nullish-coalescing-operator", + "/@babel/plugin-syntax-numeric-separator", + "/@babel/plugin-syntax-object-rest-spread", + "/@babel/plugin-syntax-optional-catch-binding", + "/@babel/plugin-syntax-optional-chaining", + "/@babel/plugin-syntax-top-level-await", + "/@babel/plugin-syntax-typescript", + "/babel-plugin-istanbul" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.18.9.tgz", + "_shasum": "4b8aea3b069d8cb8a72cdfe28ddf5ceca695ef2f", + "_spec": "@babel/helper-plugin-utils@^7.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/babel-plugin-istanbul", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "General utilities for plugins to use", + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-plugin-utils", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-plugin-utils", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-plugin-utils" + }, + "type": "commonjs", + "version": "7.18.9" +} diff --git a/node_modules/@babel/helper-simple-access/LICENSE b/node_modules/@babel/helper-simple-access/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-simple-access/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-simple-access/README.md b/node_modules/@babel/helper-simple-access/README.md new file mode 100644 index 0000000..01aa70a --- /dev/null +++ b/node_modules/@babel/helper-simple-access/README.md @@ -0,0 +1,19 @@ +# @babel/helper-simple-access + +> Babel helper for ensuring that access to a given value is performed through simple accesses + +See our website [@babel/helper-simple-access](https://babeljs.io/docs/en/babel-helper-simple-access) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-simple-access +``` + +or using yarn: + +```sh +yarn add @babel/helper-simple-access +``` diff --git a/node_modules/@babel/helper-simple-access/lib/index.js b/node_modules/@babel/helper-simple-access/lib/index.js new file mode 100644 index 0000000..0f19aea --- /dev/null +++ b/node_modules/@babel/helper-simple-access/lib/index.js @@ -0,0 +1,100 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = simplifyAccess; + +var _t = require("@babel/types"); + +const { + LOGICAL_OPERATORS, + assignmentExpression, + binaryExpression, + cloneNode, + identifier, + logicalExpression, + numericLiteral, + sequenceExpression, + unaryExpression +} = _t; + +function simplifyAccess(path, bindingNames, includeUpdateExpression = true) { + path.traverse(simpleAssignmentVisitor, { + scope: path.scope, + bindingNames, + seen: new WeakSet(), + includeUpdateExpression + }); +} + +const simpleAssignmentVisitor = { + UpdateExpression: { + exit(path) { + const { + scope, + bindingNames, + includeUpdateExpression + } = this; + + if (!includeUpdateExpression) { + return; + } + + const arg = path.get("argument"); + if (!arg.isIdentifier()) return; + const localName = arg.node.name; + if (!bindingNames.has(localName)) return; + + if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { + return; + } + + if (path.parentPath.isExpressionStatement() && !path.isCompletionRecord()) { + const operator = path.node.operator == "++" ? "+=" : "-="; + path.replaceWith(assignmentExpression(operator, arg.node, numericLiteral(1))); + } else if (path.node.prefix) { + path.replaceWith(assignmentExpression("=", identifier(localName), binaryExpression(path.node.operator[0], unaryExpression("+", arg.node), numericLiteral(1)))); + } else { + const old = path.scope.generateUidIdentifierBasedOnNode(arg.node, "old"); + const varName = old.name; + path.scope.push({ + id: old + }); + const binary = binaryExpression(path.node.operator[0], identifier(varName), numericLiteral(1)); + path.replaceWith(sequenceExpression([assignmentExpression("=", identifier(varName), unaryExpression("+", arg.node)), assignmentExpression("=", cloneNode(arg.node), binary), identifier(varName)])); + } + } + + }, + AssignmentExpression: { + exit(path) { + const { + scope, + seen, + bindingNames + } = this; + if (path.node.operator === "=") return; + if (seen.has(path.node)) return; + seen.add(path.node); + const left = path.get("left"); + if (!left.isIdentifier()) return; + const localName = left.node.name; + if (!bindingNames.has(localName)) return; + + if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { + return; + } + + const operator = path.node.operator.slice(0, -1); + + if (LOGICAL_OPERATORS.includes(operator)) { + path.replaceWith(logicalExpression(operator, path.node.left, assignmentExpression("=", cloneNode(path.node.left), path.node.right))); + } else { + path.node.right = binaryExpression(operator, cloneNode(path.node.left), path.node.right); + path.node.operator = "="; + } + } + + } +}; \ No newline at end of file diff --git a/node_modules/@babel/helper-simple-access/package.json b/node_modules/@babel/helper-simple-access/package.json new file mode 100644 index 0000000..53811d2 --- /dev/null +++ b/node_modules/@babel/helper-simple-access/package.json @@ -0,0 +1,59 @@ +{ + "_from": "@babel/helper-simple-access@^7.18.6", + "_id": "@babel/helper-simple-access@7.18.6", + "_inBundle": false, + "_integrity": "sha512-iNpIgTgyAvDQpDj76POqg+YEt8fPxx3yaNBg3S30dxNKm2SWfYhD0TGrK/Eu9wHpUW63VQU894TsTg+GLbUa1g==", + "_location": "/@babel/helper-simple-access", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-simple-access@^7.18.6", + "name": "@babel/helper-simple-access", + "escapedName": "@babel%2fhelper-simple-access", + "scope": "@babel", + "rawSpec": "^7.18.6", + "saveSpec": null, + "fetchSpec": "^7.18.6" + }, + "_requiredBy": [ + "/@babel/helper-module-transforms" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.18.6.tgz", + "_shasum": "d6d8f51f4ac2978068df934b569f08f29788c7ea", + "_spec": "@babel/helper-simple-access@^7.18.6", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/helper-module-transforms", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/types": "^7.18.6" + }, + "deprecated": false, + "description": "Babel helper for ensuring that access to a given value is performed through simple accesses", + "devDependencies": { + "@babel/traverse": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-simple-access", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-simple-access", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-simple-access" + }, + "type": "commonjs", + "version": "7.18.6" +} diff --git a/node_modules/@babel/helper-split-export-declaration/LICENSE b/node_modules/@babel/helper-split-export-declaration/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-split-export-declaration/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-split-export-declaration/README.md b/node_modules/@babel/helper-split-export-declaration/README.md new file mode 100644 index 0000000..b76e8ef --- /dev/null +++ b/node_modules/@babel/helper-split-export-declaration/README.md @@ -0,0 +1,19 @@ +# @babel/helper-split-export-declaration + +> + +See our website [@babel/helper-split-export-declaration](https://babeljs.io/docs/en/babel-helper-split-export-declaration) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-split-export-declaration +``` + +or using yarn: + +```sh +yarn add @babel/helper-split-export-declaration +``` diff --git a/node_modules/@babel/helper-split-export-declaration/lib/index.js b/node_modules/@babel/helper-split-export-declaration/lib/index.js new file mode 100644 index 0000000..89cb62f --- /dev/null +++ b/node_modules/@babel/helper-split-export-declaration/lib/index.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = splitExportDeclaration; + +var _t = require("@babel/types"); + +const { + cloneNode, + exportNamedDeclaration, + exportSpecifier, + identifier, + variableDeclaration, + variableDeclarator +} = _t; + +function splitExportDeclaration(exportDeclaration) { + if (!exportDeclaration.isExportDeclaration() || exportDeclaration.isExportAllDeclaration()) { + throw new Error("Only default and named export declarations can be split."); + } + + if (exportDeclaration.isExportDefaultDeclaration()) { + const declaration = exportDeclaration.get("declaration"); + const standaloneDeclaration = declaration.isFunctionDeclaration() || declaration.isClassDeclaration(); + const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope; + let id = declaration.node.id; + let needBindingRegistration = false; + + if (!id) { + needBindingRegistration = true; + id = scope.generateUidIdentifier("default"); + + if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) { + declaration.node.id = cloneNode(id); + } + } + + const updatedDeclaration = standaloneDeclaration ? declaration.node : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]); + const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]); + exportDeclaration.insertAfter(updatedExportDeclaration); + exportDeclaration.replaceWith(updatedDeclaration); + + if (needBindingRegistration) { + scope.registerDeclaration(exportDeclaration); + } + + return exportDeclaration; + } else if (exportDeclaration.get("specifiers").length > 0) { + throw new Error("It doesn't make sense to split exported specifiers."); + } + + const declaration = exportDeclaration.get("declaration"); + const bindingIdentifiers = declaration.getOuterBindingIdentifiers(); + const specifiers = Object.keys(bindingIdentifiers).map(name => { + return exportSpecifier(identifier(name), identifier(name)); + }); + const aliasDeclar = exportNamedDeclaration(null, specifiers); + exportDeclaration.insertAfter(aliasDeclar); + exportDeclaration.replaceWith(declaration.node); + return exportDeclaration; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-split-export-declaration/package.json b/node_modules/@babel/helper-split-export-declaration/package.json new file mode 100644 index 0000000..f9c5183 --- /dev/null +++ b/node_modules/@babel/helper-split-export-declaration/package.json @@ -0,0 +1,57 @@ +{ + "_from": "@babel/helper-split-export-declaration@^7.18.6", + "_id": "@babel/helper-split-export-declaration@7.18.6", + "_inBundle": false, + "_integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "_location": "/@babel/helper-split-export-declaration", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-split-export-declaration@^7.18.6", + "name": "@babel/helper-split-export-declaration", + "escapedName": "@babel%2fhelper-split-export-declaration", + "scope": "@babel", + "rawSpec": "^7.18.6", + "saveSpec": null, + "fetchSpec": "^7.18.6" + }, + "_requiredBy": [ + "/@babel/helper-module-transforms", + "/@babel/traverse" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", + "_shasum": "7367949bc75b20c6d5a5d4a97bba2824ae8ef075", + "_spec": "@babel/helper-split-export-declaration@^7.18.6", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/helper-module-transforms", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/types": "^7.18.6" + }, + "deprecated": false, + "description": ">", + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-split-export-declaration", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-split-export-declaration", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-split-export-declaration" + }, + "type": "commonjs", + "version": "7.18.6" +} diff --git a/node_modules/@babel/helper-string-parser/LICENSE b/node_modules/@babel/helper-string-parser/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-string-parser/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-string-parser/README.md b/node_modules/@babel/helper-string-parser/README.md new file mode 100644 index 0000000..5a13b5f --- /dev/null +++ b/node_modules/@babel/helper-string-parser/README.md @@ -0,0 +1,19 @@ +# @babel/helper-string-parser + +> A utility package to parse strings + +See our website [@babel/helper-string-parser](https://babeljs.io/docs/en/babel-helper-string-parser) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-string-parser +``` + +or using yarn: + +```sh +yarn add @babel/helper-string-parser +``` diff --git a/node_modules/@babel/helper-string-parser/lib/index.js b/node_modules/@babel/helper-string-parser/lib/index.js new file mode 100644 index 0000000..737ce62 --- /dev/null +++ b/node_modules/@babel/helper-string-parser/lib/index.js @@ -0,0 +1,328 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.readCodePoint = readCodePoint; +exports.readInt = readInt; +exports.readStringContents = readStringContents; + +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; + +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; + +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let containsInvalid = false; + let chunkStart = pos; + const { + length + } = input; + + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + + const ch = input.charCodeAt(pos); + + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + + if (ch === 92) { + out += input.slice(chunkStart, pos); + let escaped; + ({ + ch: escaped, + pos, + lineStart, + curLine + } = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors)); + + if (escaped === null) { + containsInvalid = true; + } else { + out += escaped; + } + + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + + return { + pos, + str: out, + containsInvalid, + lineStart, + curLine + }; +} + +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + + return ch === (type === "double" ? 34 : 39); +} + +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + + const ch = input.charCodeAt(pos++); + + switch (ch) { + case 110: + return res("\n"); + + case 114: + return res("\r"); + + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + + case 116: + return res("\t"); + + case 98: + return res("\b"); + + case 118: + return res("\u000b"); + + case 102: + return res("\f"); + + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + + case 10: + lineStart = pos; + ++curLine; + + case 8232: + case 8233: + return res(""); + + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = input.slice(startPos, pos + 2).match(/^[0-7]+/); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + + return res(String.fromCharCode(octal)); + } + + return res(String.fromCharCode(ch)); + } +} + +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors)); + + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + + return { + code: n, + pos + }; +} + +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + + if (!allowNumSeparator) { + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + + ++pos; + continue; + } + + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + + if (val >= radix) { + if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + + ++pos; + total = total * radix + val; + } + + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + + return { + n: total, + pos + }; +} + +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + + return { + code, + pos + }; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-string-parser/package.json b/node_modules/@babel/helper-string-parser/package.json new file mode 100644 index 0000000..8010706 --- /dev/null +++ b/node_modules/@babel/helper-string-parser/package.json @@ -0,0 +1,60 @@ +{ + "_from": "@babel/helper-string-parser@^7.18.10", + "_id": "@babel/helper-string-parser@7.18.10", + "_inBundle": false, + "_integrity": "sha512-XtIfWmeNY3i4t7t4D2t02q50HvqHybPqW2ki1kosnvWCwuCMeo81Jf0gwr85jy/neUdg5XDdeFE/80DXiO+njw==", + "_location": "/@babel/helper-string-parser", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-string-parser@^7.18.10", + "name": "@babel/helper-string-parser", + "escapedName": "@babel%2fhelper-string-parser", + "scope": "@babel", + "rawSpec": "^7.18.10", + "saveSpec": null, + "fetchSpec": "^7.18.10" + }, + "_requiredBy": [ + "/@babel/types" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.18.10.tgz", + "_shasum": "181f22d28ebe1b3857fa575f5c290b1aaf659b56", + "_spec": "@babel/helper-string-parser@^7.18.10", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/types", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A utility package to parse strings", + "devDependencies": { + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-string-parser", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-string-parser", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-string-parser" + }, + "type": "commonjs", + "version": "7.18.10" +} diff --git a/node_modules/@babel/helper-validator-identifier/LICENSE b/node_modules/@babel/helper-validator-identifier/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-validator-identifier/README.md b/node_modules/@babel/helper-validator-identifier/README.md new file mode 100644 index 0000000..4f704c4 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/README.md @@ -0,0 +1,19 @@ +# @babel/helper-validator-identifier + +> Validate identifier/keywords name + +See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/en/babel-helper-validator-identifier) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-validator-identifier +``` + +or using yarn: + +```sh +yarn add @babel/helper-validator-identifier +``` diff --git a/node_modules/@babel/helper-validator-identifier/lib/identifier.js b/node_modules/@babel/helper-validator-identifier/lib/identifier.js new file mode 100644 index 0000000..cbade22 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/identifier.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIdentifierChar = isIdentifierChar; +exports.isIdentifierName = isIdentifierName; +exports.isIdentifierStart = isIdentifierStart; +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 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, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 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, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 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, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 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, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + +function isInAstralSet(code, set) { + let pos = 0x10000; + + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + + return false; +} + +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes); +} + +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} + +function isIdentifierName(name) { + let isFirst = true; + + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + + if (isFirst) { + isFirst = false; + + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + + return !isFirst; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/index.js b/node_modules/@babel/helper-validator-identifier/lib/index.js new file mode 100644 index 0000000..ca9decf --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/index.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } +}); +Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } +}); +Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } +}); +Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } +}); +Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } +}); +Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } +}); + +var _identifier = require("./identifier"); + +var _keyword = require("./keyword"); \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/lib/keyword.js b/node_modules/@babel/helper-validator-identifier/lib/keyword.js new file mode 100644 index 0000000..0939e9a --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/lib/keyword.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isKeyword = isKeyword; +exports.isReservedWord = isReservedWord; +exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; +exports.isStrictBindReservedWord = isStrictBindReservedWord; +exports.isStrictReservedWord = isStrictReservedWord; +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} + +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} + +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} + +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} + +function isKeyword(word) { + return keywords.has(word); +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-identifier/package.json b/node_modules/@babel/helper-validator-identifier/package.json new file mode 100644 index 0000000..460611b --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/package.json @@ -0,0 +1,63 @@ +{ + "_from": "@babel/helper-validator-identifier@^7.18.6", + "_id": "@babel/helper-validator-identifier@7.18.6", + "_inBundle": false, + "_integrity": "sha512-MmetCkz9ej86nJQV+sFCxoGGrUbU3q02kgLciwkrt9QqEB7cP39oKEY0PakknEO0Gu20SskMRi+AYZ3b1TpN9g==", + "_location": "/@babel/helper-validator-identifier", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-validator-identifier@^7.18.6", + "name": "@babel/helper-validator-identifier", + "escapedName": "@babel%2fhelper-validator-identifier", + "scope": "@babel", + "rawSpec": "^7.18.6", + "saveSpec": null, + "fetchSpec": "^7.18.6" + }, + "_requiredBy": [ + "/@babel/helper-module-transforms", + "/@babel/highlight", + "/@babel/types" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.18.6.tgz", + "_shasum": "9c97e30d31b2b8c72a1d08984f2ca9b574d7a076", + "_spec": "@babel/helper-validator-identifier@^7.18.6", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/highlight", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Validate identifier/keywords name", + "devDependencies": { + "@unicode/unicode-14.0.0": "^1.2.1", + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "homepage": "https://github.com/babel/babel#readme", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-validator-identifier", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-validator-identifier" + }, + "type": "commonjs", + "version": "7.18.6" +} diff --git a/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js b/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js new file mode 100644 index 0000000..f644d77 --- /dev/null +++ b/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js @@ -0,0 +1,75 @@ +"use strict"; + +// Always use the latest available version of Unicode! +// https://tc39.github.io/ecma262/#sec-conformance +const version = "14.0.0"; + +const start = require("@unicode/unicode-" + + version + + "/Binary_Property/ID_Start/code-points.js").filter(function (ch) { + return ch > 0x7f; +}); +let last = -1; +const cont = [0x200c, 0x200d].concat( + require("@unicode/unicode-" + + version + + "/Binary_Property/ID_Continue/code-points.js").filter(function (ch) { + return ch > 0x7f && search(start, ch, last + 1) == -1; + }) +); + +function search(arr, ch, starting) { + for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) { + if (arr[i] === ch) return i; + } + return -1; +} + +function pad(str, width) { + while (str.length < width) str = "0" + str; + return str; +} + +function esc(code) { + const hex = code.toString(16); + if (hex.length <= 2) return "\\x" + pad(hex, 2); + else return "\\u" + pad(hex, 4); +} + +function generate(chars) { + const astral = []; + let re = ""; + for (let i = 0, at = 0x10000; i < chars.length; i++) { + const from = chars[i]; + let to = from; + while (i < chars.length - 1 && chars[i + 1] == to + 1) { + i++; + to++; + } + if (to <= 0xffff) { + if (from == to) re += esc(from); + else if (from + 1 == to) re += esc(from) + esc(to); + else re += esc(from) + "-" + esc(to); + } else { + astral.push(from - at, to - from); + at = to; + } + } + return { nonASCII: re, astral: astral }; +} + +const startData = generate(start); +const contData = generate(cont); + +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";'); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";" +); +console.log("/* prettier-ignore */"); +console.log( + "const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";" +); diff --git a/node_modules/@babel/helper-validator-option/LICENSE b/node_modules/@babel/helper-validator-option/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helper-validator-option/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helper-validator-option/README.md b/node_modules/@babel/helper-validator-option/README.md new file mode 100644 index 0000000..94ab428 --- /dev/null +++ b/node_modules/@babel/helper-validator-option/README.md @@ -0,0 +1,19 @@ +# @babel/helper-validator-option + +> Validate plugin/preset options + +See our website [@babel/helper-validator-option](https://babeljs.io/docs/en/babel-helper-validator-option) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-validator-option +``` + +or using yarn: + +```sh +yarn add @babel/helper-validator-option +``` diff --git a/node_modules/@babel/helper-validator-option/lib/find-suggestion.js b/node_modules/@babel/helper-validator-option/lib/find-suggestion.js new file mode 100644 index 0000000..019ea93 --- /dev/null +++ b/node_modules/@babel/helper-validator-option/lib/find-suggestion.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findSuggestion = findSuggestion; +const { + min +} = Math; + +function levenshtein(a, b) { + let t = [], + u = [], + i, + j; + const m = a.length, + n = b.length; + + if (!m) { + return n; + } + + if (!n) { + return m; + } + + for (j = 0; j <= n; j++) { + t[j] = j; + } + + for (i = 1; i <= m; i++) { + for (u = [i], j = 1; j <= n; j++) { + u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : min(t[j - 1], t[j], u[j - 1]) + 1; + } + + t = u; + } + + return u[n]; +} + +function findSuggestion(str, arr) { + const distances = arr.map(el => levenshtein(el, str)); + return arr[distances.indexOf(min(...distances))]; +} \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-option/lib/index.js b/node_modules/@babel/helper-validator-option/lib/index.js new file mode 100644 index 0000000..8afe861 --- /dev/null +++ b/node_modules/@babel/helper-validator-option/lib/index.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "OptionValidator", { + enumerable: true, + get: function () { + return _validator.OptionValidator; + } +}); +Object.defineProperty(exports, "findSuggestion", { + enumerable: true, + get: function () { + return _findSuggestion.findSuggestion; + } +}); + +var _validator = require("./validator"); + +var _findSuggestion = require("./find-suggestion"); \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-option/lib/validator.js b/node_modules/@babel/helper-validator-option/lib/validator.js new file mode 100644 index 0000000..5b4bad1 --- /dev/null +++ b/node_modules/@babel/helper-validator-option/lib/validator.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OptionValidator = void 0; + +var _findSuggestion = require("./find-suggestion"); + +class OptionValidator { + constructor(descriptor) { + this.descriptor = descriptor; + } + + validateTopLevelOptions(options, TopLevelOptionShape) { + const validOptionNames = Object.keys(TopLevelOptionShape); + + for (const option of Object.keys(options)) { + if (!validOptionNames.includes(option)) { + throw new Error(this.formatMessage(`'${option}' is not a valid top-level option. +- Did you mean '${(0, _findSuggestion.findSuggestion)(option, validOptionNames)}'?`)); + } + } + } + + validateBooleanOption(name, value, defaultValue) { + if (value === undefined) { + return defaultValue; + } else { + this.invariant(typeof value === "boolean", `'${name}' option must be a boolean.`); + } + + return value; + } + + validateStringOption(name, value, defaultValue) { + if (value === undefined) { + return defaultValue; + } else { + this.invariant(typeof value === "string", `'${name}' option must be a string.`); + } + + return value; + } + + invariant(condition, message) { + if (!condition) { + throw new Error(this.formatMessage(message)); + } + } + + formatMessage(message) { + return `${this.descriptor}: ${message}`; + } + +} + +exports.OptionValidator = OptionValidator; \ No newline at end of file diff --git a/node_modules/@babel/helper-validator-option/package.json b/node_modules/@babel/helper-validator-option/package.json new file mode 100644 index 0000000..a5b1b13 --- /dev/null +++ b/node_modules/@babel/helper-validator-option/package.json @@ -0,0 +1,57 @@ +{ + "_from": "@babel/helper-validator-option@^7.18.6", + "_id": "@babel/helper-validator-option@7.18.6", + "_inBundle": false, + "_integrity": "sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw==", + "_location": "/@babel/helper-validator-option", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-validator-option@^7.18.6", + "name": "@babel/helper-validator-option", + "escapedName": "@babel%2fhelper-validator-option", + "scope": "@babel", + "rawSpec": "^7.18.6", + "saveSpec": null, + "fetchSpec": "^7.18.6" + }, + "_requiredBy": [ + "/@babel/helper-compilation-targets" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz", + "_shasum": "bf0d2b5a509b1f336099e4ff36e1a63aa5db4db8", + "_spec": "@babel/helper-validator-option@^7.18.6", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/helper-compilation-targets", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Validate plugin/preset options", + "engines": { + "node": ">=6.9.0" + }, + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "homepage": "https://github.com/babel/babel#readme", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helper-validator-option", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-validator-option" + }, + "type": "commonjs", + "version": "7.18.6" +} diff --git a/node_modules/@babel/helpers/LICENSE b/node_modules/@babel/helpers/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/helpers/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/helpers/README.md b/node_modules/@babel/helpers/README.md new file mode 100644 index 0000000..3b79dbf --- /dev/null +++ b/node_modules/@babel/helpers/README.md @@ -0,0 +1,19 @@ +# @babel/helpers + +> Collection of helper functions used by Babel transforms. + +See our website [@babel/helpers](https://babeljs.io/docs/en/babel-helpers) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/helpers +``` + +or using yarn: + +```sh +yarn add @babel/helpers --dev +``` diff --git a/node_modules/@babel/helpers/lib/helpers-generated.js b/node_modules/@babel/helpers/lib/helpers-generated.js new file mode 100644 index 0000000..29d2c5c --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers-generated.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _template = require("@babel/template"); + +function helper(minVersion, source) { + return Object.freeze({ + minVersion, + ast: () => _template.default.program.ast(source, { + preserveComments: true + }) + }); +} + +var _default = Object.freeze({ + applyDecs: helper("7.17.8", 'function createMetadataMethodsForProperty(metadataMap,kind,property,decoratorFinishedRef){return{getMetadata:function(key){assertNotFinished(decoratorFinishedRef,"getMetadata"),assertMetadataKey(key);var metadataForKey=metadataMap[key];if(void 0!==metadataForKey)if(1===kind){var pub=metadataForKey.public;if(void 0!==pub)return pub[property]}else if(2===kind){var priv=metadataForKey.private;if(void 0!==priv)return priv.get(property)}else if(Object.hasOwnProperty.call(metadataForKey,"constructor"))return metadataForKey.constructor},setMetadata:function(key,value){assertNotFinished(decoratorFinishedRef,"setMetadata"),assertMetadataKey(key);var metadataForKey=metadataMap[key];if(void 0===metadataForKey&&(metadataForKey=metadataMap[key]={}),1===kind){var pub=metadataForKey.public;void 0===pub&&(pub=metadataForKey.public={}),pub[property]=value}else if(2===kind){var priv=metadataForKey.priv;void 0===priv&&(priv=metadataForKey.private=new Map),priv.set(property,value)}else metadataForKey.constructor=value}}}function convertMetadataMapToFinal(obj,metadataMap){var parentMetadataMap=obj[Symbol.metadata||Symbol.for("Symbol.metadata")],metadataKeys=Object.getOwnPropertySymbols(metadataMap);if(0!==metadataKeys.length){for(var i=0;i=0;i--){var newInit;if(void 0!==(newValue=memberDec(decs[i],name,desc,metadataMap,initializers,kind,isStatic,isPrivate,value)))assertValidReturnValue(kind,newValue),0===kind?newInit=newValue:1===kind?(newInit=getInit(newValue),get=newValue.get||value.get,set=newValue.set||value.set,value={get:get,set:set}):value=newValue,void 0!==newInit&&(void 0===initializer?initializer=newInit:"function"==typeof initializer?initializer=[initializer,newInit]:initializer.push(newInit))}if(0===kind||1===kind){if(void 0===initializer)initializer=function(instance,init){return init};else if("function"!=typeof initializer){var ownInitializers=initializer;initializer=function(instance,init){for(var value=init,i=0;i3,isStatic=kind>=5;if(isStatic?(base=Class,metadataMap=staticMetadataMap,0!==(kind-=5)&&(initializers=staticInitializers=staticInitializers||[])):(base=Class.prototype,metadataMap=protoMetadataMap,0!==kind&&(initializers=protoInitializers=protoInitializers||[])),0!==kind&&!isPrivate){var existingNonFields=isStatic?existingStaticNonFields:existingProtoNonFields,existingKind=existingNonFields.get(name)||0;if(!0===existingKind||3===existingKind&&4!==kind||4===existingKind&&3!==kind)throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "+name);!existingKind&&kind>2?existingNonFields.set(name,kind):existingNonFields.set(name,!0)}applyMemberDec(ret,base,decInfo,name,kind,isStatic,isPrivate,metadataMap,initializers)}}pushInitializers(ret,protoInitializers),pushInitializers(ret,staticInitializers)}function pushInitializers(ret,initializers){initializers&&ret.push((function(instance){for(var i=0;i0){for(var initializers=[],newClass=targetClass,name=targetClass.name,i=classDecs.length-1;i>=0;i--){var decoratorFinishedRef={v:!1};try{var ctx=Object.assign({kind:"class",name:name,addInitializer:createAddInitializerMethod(initializers,decoratorFinishedRef)},createMetadataMethodsForProperty(metadataMap,0,name,decoratorFinishedRef)),nextNewClass=classDecs[i](newClass,ctx)}finally{decoratorFinishedRef.v=!0}void 0!==nextNewClass&&(assertValidReturnValue(10,nextNewClass),newClass=nextNewClass)}ret.push(newClass,(function(){for(var i=0;i1){for(var childArray=new Array(childrenLength),i=0;i=0;--i){var entry=this.tryEntries[i],record=entry.completion;if("root"===entry.tryLoc)return handle("end");if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc"),hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc)return this.complete(entry.completion,entry.afterLoc),resetTryEntry(entry),ContinueSentinel}},catch:function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if("throw"===record.type){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){return this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc},"next"===this.method&&(this.arg=undefined),ContinueSentinel}},exports}'), + typeof: helper("7.0.0-beta.0", 'export default function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}'), + wrapRegExp: helper("7.2.6", 'import setPrototypeOf from"setPrototypeOf";import inherits from"inherits";export default function _wrapRegExp(){_wrapRegExp=function(re,groups){return new BabelRegExp(re,void 0,groups)};var _super=RegExp.prototype,_groups=new WeakMap;function BabelRegExp(re,flags,groups){var _this=new RegExp(re,flags);return _groups.set(_this,groups||_groups.get(re)),setPrototypeOf(_this,BabelRegExp.prototype)}function buildGroups(result,re){var g=_groups.get(re);return Object.keys(g).reduce((function(groups,name){return groups[name]=result[g[name]],groups}),Object.create(null))}return inherits(BabelRegExp,RegExp),BabelRegExp.prototype.exec=function(str){var result=_super.exec.call(this,str);return result&&(result.groups=buildGroups(result,this)),result},BabelRegExp.prototype[Symbol.replace]=function(str,substitution){if("string"==typeof substitution){var groups=_groups.get(this);return _super[Symbol.replace].call(this,str,substitution.replace(/\\$<([^>]+)>/g,(function(_,name){return"$"+groups[name]})))}if("function"==typeof substitution){var _this=this;return _super[Symbol.replace].call(this,str,(function(){var args=arguments;return"object"!=typeof args[args.length-1]&&(args=[].slice.call(args)).push(buildGroups(args,_this)),substitution.apply(this,args)}))}return _super[Symbol.replace].call(this,str,substitution)},_wrapRegExp.apply(this,arguments)}') +}); + +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers.js b/node_modules/@babel/helpers/lib/helpers.js new file mode 100644 index 0000000..5002403 --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers.js @@ -0,0 +1,1961 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _template = require("@babel/template"); + +var _helpersGenerated = require("./helpers-generated"); + +const helpers = Object.assign({ + __proto__: null +}, _helpersGenerated.default); +var _default = helpers; +exports.default = _default; + +const helper = minVersion => tpl => ({ + minVersion, + ast: () => _template.default.program.ast(tpl) +}); + +helpers.AwaitValue = helper("7.0.0-beta.0")` + export default function _AwaitValue(value) { + this.wrapped = value; + } +`; +helpers.AsyncGenerator = helper("7.0.0-beta.0")` + import AwaitValue from "AwaitValue"; + + export default function AsyncGenerator(gen) { + var front, back; + + function send(key, arg) { + return new Promise(function (resolve, reject) { + var request = { + key: key, + arg: arg, + resolve: resolve, + reject: reject, + next: null, + }; + + if (back) { + back = back.next = request; + } else { + front = back = request; + resume(key, arg); + } + }); + } + + function resume(key, arg) { + try { + var result = gen[key](arg) + var value = result.value; + var wrappedAwait = value instanceof AwaitValue; + + Promise.resolve(wrappedAwait ? value.wrapped : value).then( + function (arg) { + if (wrappedAwait) { + resume(key === "return" ? "return" : "next", arg); + return + } + + settle(result.done ? "return" : "normal", arg); + }, + function (err) { resume("throw", err); }); + } catch (err) { + settle("throw", err); + } + } + + function settle(type, value) { + switch (type) { + case "return": + front.resolve({ value: value, done: true }); + break; + case "throw": + front.reject(value); + break; + default: + front.resolve({ value: value, done: false }); + break; + } + + front = front.next; + if (front) { + resume(front.key, front.arg); + } else { + back = null; + } + } + + this._invoke = send; + + // Hide "return" method if generator return is not supported + if (typeof gen.return !== "function") { + this.return = undefined; + } + } + + AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }; + + AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; + AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; + AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; +`; +helpers.wrapAsyncGenerator = helper("7.0.0-beta.0")` + import AsyncGenerator from "AsyncGenerator"; + + export default function _wrapAsyncGenerator(fn) { + return function () { + return new AsyncGenerator(fn.apply(this, arguments)); + }; + } +`; +helpers.awaitAsyncGenerator = helper("7.0.0-beta.0")` + import AwaitValue from "AwaitValue"; + + export default function _awaitAsyncGenerator(value) { + return new AwaitValue(value); + } +`; +helpers.asyncGeneratorDelegate = helper("7.0.0-beta.0")` + export default function _asyncGeneratorDelegate(inner, awaitWrap) { + var iter = {}, waiting = false; + + function pump(key, value) { + waiting = true; + value = new Promise(function (resolve) { resolve(inner[key](value)); }); + return { done: false, value: awaitWrap(value) }; + }; + + iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () { return this; }; + + iter.next = function (value) { + if (waiting) { + waiting = false; + return value; + } + return pump("next", value); + }; + + if (typeof inner.throw === "function") { + iter.throw = function (value) { + if (waiting) { + waiting = false; + throw value; + } + return pump("throw", value); + }; + } + + if (typeof inner.return === "function") { + iter.return = function (value) { + if (waiting) { + waiting = false; + return value; + } + return pump("return", value); + }; + } + + return iter; + } +`; +helpers.asyncToGenerator = helper("7.0.0-beta.0")` + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + + export default function _asyncToGenerator(fn) { + return function () { + var self = this, args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; + } +`; +helpers.classCallCheck = helper("7.0.0-beta.0")` + export default function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } +`; +helpers.createClass = helper("7.0.0-beta.0")` + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i ++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + export default function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } +`; +helpers.defineEnumerableProperties = helper("7.0.0-beta.0")` + export default function _defineEnumerableProperties(obj, descs) { + for (var key in descs) { + var desc = descs[key]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, key, desc); + } + + // Symbols are not enumerated over by for-in loops. If native + // Symbols are available, fetch all of the descs object's own + // symbol properties and define them on our target object too. + if (Object.getOwnPropertySymbols) { + var objectSymbols = Object.getOwnPropertySymbols(descs); + for (var i = 0; i < objectSymbols.length; i++) { + var sym = objectSymbols[i]; + var desc = descs[sym]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, sym, desc); + } + } + return obj; + } +`; +helpers.defaults = helper("7.0.0-beta.0")` + export default function _defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + return obj; + } +`; +helpers.defineProperty = helper("7.0.0-beta.0")` + export default function _defineProperty(obj, key, value) { + // Shortcircuit the slow defineProperty path when possible. + // We are trying to avoid issues where setters defined on the + // prototype cause side effects under the fast path of simple + // assignment. By checking for existence of the property with + // the in operator, we can optimize most of this overhead away. + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } +`; +helpers.extends = helper("7.0.0-beta.0")` + export default function _extends() { + _extends = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + + return _extends.apply(this, arguments); + } +`; +helpers.objectSpread = helper("7.0.0-beta.0")` + import defineProperty from "defineProperty"; + + export default function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = (arguments[i] != null) ? Object(arguments[i]) : {}; + var ownKeys = Object.keys(source); + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function(sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + ownKeys.forEach(function(key) { + defineProperty(target, key, source[key]); + }); + } + return target; + } +`; +helpers.inherits = helper("7.0.0-beta.0")` + import setPrototypeOf from "setPrototypeOf"; + + export default function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + // We can't use defineProperty to set the prototype in a single step because it + // doesn't work in Chrome <= 36. https://github.com/babel/babel/issues/14056 + // V8 bug: https://bugs.chromium.org/p/v8/issues/detail?id=3334 + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + Object.defineProperty(subClass, "prototype", { writable: false }); + if (superClass) setPrototypeOf(subClass, superClass); + } +`; +helpers.inheritsLoose = helper("7.0.0-beta.0")` + import setPrototypeOf from "setPrototypeOf"; + + export default function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); + } +`; +helpers.getPrototypeOf = helper("7.0.0-beta.0")` + export default function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf + ? Object.getPrototypeOf.bind() + : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } +`; +helpers.setPrototypeOf = helper("7.0.0-beta.0")` + export default function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf + ? Object.setPrototypeOf.bind() + : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } +`; +helpers.isNativeReflectConstruct = helper("7.9.0")` + export default function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + + // core-js@3 + if (Reflect.construct.sham) return false; + + // Proxy can't be polyfilled. Every browser implemented + // proxies before or at the same time as Reflect.construct, + // so if they support Proxy they also support Reflect.construct. + if (typeof Proxy === "function") return true; + + // Since Reflect.construct can't be properly polyfilled, some + // implementations (e.g. core-js@2) don't set the correct internal slots. + // Those polyfills don't allow us to subclass built-ins, so we need to + // use our fallback implementation. + try { + // If the internal slots aren't set, this throws an error similar to + // TypeError: this is not a Boolean object. + + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})); + return true; + } catch (e) { + return false; + } + } +`; +helpers.construct = helper("7.0.0-beta.0")` + import setPrototypeOf from "setPrototypeOf"; + import isNativeReflectConstruct from "isNativeReflectConstruct"; + + export default function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + _construct = Reflect.construct.bind(); + } else { + // NOTE: If Parent !== Class, the correct __proto__ is set *after* + // calling the constructor. + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + // Avoid issues with Class being present but undefined when it wasn't + // present in the original call. + return _construct.apply(null, arguments); + } +`; +helpers.isNativeFunction = helper("7.0.0-beta.0")` + export default function _isNativeFunction(fn) { + // Note: This function returns "true" for core-js functions. + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } +`; +helpers.wrapNativeSuper = helper("7.0.0-beta.0")` + import getPrototypeOf from "getPrototypeOf"; + import setPrototypeOf from "setPrototypeOf"; + import isNativeFunction from "isNativeFunction"; + import construct from "construct"; + + export default function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + _cache.set(Class, Wrapper); + } + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor) + } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true, + } + }); + + return setPrototypeOf(Wrapper, Class); + } + + return _wrapNativeSuper(Class) + } +`; +helpers.instanceof = helper("7.0.0-beta.0")` + export default function _instanceof(left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return !!right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } + } +`; +helpers.interopRequireDefault = helper("7.0.0-beta.0")` + export default function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } +`; +helpers.interopRequireWildcard = helper("7.14.0")` + function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); + } + + export default function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + + if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) { + return { default: obj } + } + + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; + } +`; +helpers.newArrowCheck = helper("7.0.0-beta.0")` + export default function _newArrowCheck(innerThis, boundThis) { + if (innerThis !== boundThis) { + throw new TypeError("Cannot instantiate an arrow function"); + } + } +`; +helpers.objectDestructuringEmpty = helper("7.0.0-beta.0")` + export default function _objectDestructuringEmpty(obj) { + if (obj == null) throw new TypeError("Cannot destructure undefined"); + } +`; +helpers.objectWithoutPropertiesLoose = helper("7.0.0-beta.0")` + export default function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; + } +`; +helpers.objectWithoutProperties = helper("7.0.0-beta.0")` + import objectWithoutPropertiesLoose from "objectWithoutPropertiesLoose"; + + export default function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + + return target; + } +`; +helpers.assertThisInitialized = helper("7.0.0-beta.0")` + export default function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self; + } +`; +helpers.possibleConstructorReturn = helper("7.0.0-beta.0")` + import assertThisInitialized from "assertThisInitialized"; + + export default function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + + return assertThisInitialized(self); + } +`; +helpers.createSuper = helper("7.9.0")` + import getPrototypeOf from "getPrototypeOf"; + import isNativeReflectConstruct from "isNativeReflectConstruct"; + import possibleConstructorReturn from "possibleConstructorReturn"; + + export default function _createSuper(Derived) { + var hasNativeReflectConstruct = isNativeReflectConstruct(); + + return function _createSuperInternal() { + var Super = getPrototypeOf(Derived), result; + if (hasNativeReflectConstruct) { + // NOTE: This doesn't work if this.__proto__.constructor has been modified. + var NewTarget = getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return possibleConstructorReturn(this, result); + } + } + `; +helpers.superPropBase = helper("7.0.0-beta.0")` + import getPrototypeOf from "getPrototypeOf"; + + export default function _superPropBase(object, property) { + // Yes, this throws if object is null to being with, that's on purpose. + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + return object; + } +`; +helpers.get = helper("7.0.0-beta.0")` + import superPropBase from "superPropBase"; + + export default function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get.bind(); + } else { + _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + + if (!base) return; + + var desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.get) { + // STEP 3. If receiver is not present, then set receiver to target. + return desc.get.call(arguments.length < 3 ? target : receiver); + } + + return desc.value; + }; + } + return _get.apply(this, arguments); + } +`; +helpers.set = helper("7.0.0-beta.0")` + import superPropBase from "superPropBase"; + import defineProperty from "defineProperty"; + + function set(target, property, value, receiver) { + if (typeof Reflect !== "undefined" && Reflect.set) { + set = Reflect.set; + } else { + set = function set(target, property, value, receiver) { + var base = superPropBase(target, property); + var desc; + + if (base) { + desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.set) { + desc.set.call(receiver, value); + return true; + } else if (!desc.writable) { + // Both getter and non-writable fall into this. + return false; + } + } + + // Without a super that defines the property, spec boils down to + // "define on receiver" for some reason. + desc = Object.getOwnPropertyDescriptor(receiver, property); + if (desc) { + if (!desc.writable) { + // Setter, getter, and non-writable fall into this. + return false; + } + + desc.value = value; + Object.defineProperty(receiver, property, desc); + } else { + // Avoid setters that may be defined on Sub's prototype, but not on + // the instance. + defineProperty(receiver, property, value); + } + + return true; + }; + } + + return set(target, property, value, receiver); + } + + export default function _set(target, property, value, receiver, isStrict) { + var s = set(target, property, value, receiver || target); + if (!s && isStrict) { + throw new Error('failed to set property'); + } + + return value; + } +`; +helpers.taggedTemplateLiteral = helper("7.0.0-beta.0")` + export default function _taggedTemplateLiteral(strings, raw) { + if (!raw) { raw = strings.slice(0); } + return Object.freeze(Object.defineProperties(strings, { + raw: { value: Object.freeze(raw) } + })); + } +`; +helpers.taggedTemplateLiteralLoose = helper("7.0.0-beta.0")` + export default function _taggedTemplateLiteralLoose(strings, raw) { + if (!raw) { raw = strings.slice(0); } + strings.raw = raw; + return strings; + } +`; +helpers.readOnlyError = helper("7.0.0-beta.0")` + export default function _readOnlyError(name) { + throw new TypeError("\\"" + name + "\\" is read-only"); + } +`; +helpers.writeOnlyError = helper("7.12.13")` + export default function _writeOnlyError(name) { + throw new TypeError("\\"" + name + "\\" is write-only"); + } +`; +helpers.classNameTDZError = helper("7.0.0-beta.0")` + export default function _classNameTDZError(name) { + throw new Error("Class \\"" + name + "\\" cannot be referenced in computed property keys."); + } +`; +helpers.temporalUndefined = helper("7.0.0-beta.0")` + // This function isn't mean to be called, but to be used as a reference. + // We can't use a normal object because it isn't hoisted. + export default function _temporalUndefined() {} +`; +helpers.tdz = helper("7.5.5")` + export default function _tdzError(name) { + throw new ReferenceError(name + " is not defined - temporal dead zone"); + } +`; +helpers.temporalRef = helper("7.0.0-beta.0")` + import undef from "temporalUndefined"; + import err from "tdz"; + + export default function _temporalRef(val, name) { + return val === undef ? err(name) : val; + } +`; +helpers.slicedToArray = helper("7.0.0-beta.0")` + import arrayWithHoles from "arrayWithHoles"; + import iterableToArrayLimit from "iterableToArrayLimit"; + import unsupportedIterableToArray from "unsupportedIterableToArray"; + import nonIterableRest from "nonIterableRest"; + + export default function _slicedToArray(arr, i) { + return ( + arrayWithHoles(arr) || + iterableToArrayLimit(arr, i) || + unsupportedIterableToArray(arr, i) || + nonIterableRest() + ); + } +`; +helpers.slicedToArrayLoose = helper("7.0.0-beta.0")` + import arrayWithHoles from "arrayWithHoles"; + import iterableToArrayLimitLoose from "iterableToArrayLimitLoose"; + import unsupportedIterableToArray from "unsupportedIterableToArray"; + import nonIterableRest from "nonIterableRest"; + + export default function _slicedToArrayLoose(arr, i) { + return ( + arrayWithHoles(arr) || + iterableToArrayLimitLoose(arr, i) || + unsupportedIterableToArray(arr, i) || + nonIterableRest() + ); + } +`; +helpers.toArray = helper("7.0.0-beta.0")` + import arrayWithHoles from "arrayWithHoles"; + import iterableToArray from "iterableToArray"; + import unsupportedIterableToArray from "unsupportedIterableToArray"; + import nonIterableRest from "nonIterableRest"; + + export default function _toArray(arr) { + return ( + arrayWithHoles(arr) || + iterableToArray(arr) || + unsupportedIterableToArray(arr) || + nonIterableRest() + ); + } +`; +helpers.toConsumableArray = helper("7.0.0-beta.0")` + import arrayWithoutHoles from "arrayWithoutHoles"; + import iterableToArray from "iterableToArray"; + import unsupportedIterableToArray from "unsupportedIterableToArray"; + import nonIterableSpread from "nonIterableSpread"; + + export default function _toConsumableArray(arr) { + return ( + arrayWithoutHoles(arr) || + iterableToArray(arr) || + unsupportedIterableToArray(arr) || + nonIterableSpread() + ); + } +`; +helpers.arrayWithoutHoles = helper("7.0.0-beta.0")` + import arrayLikeToArray from "arrayLikeToArray"; + + export default function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); + } +`; +helpers.arrayWithHoles = helper("7.0.0-beta.0")` + export default function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } +`; +helpers.maybeArrayLike = helper("7.9.0")` + import arrayLikeToArray from "arrayLikeToArray"; + + export default function _maybeArrayLike(next, arr, i) { + if (arr && !Array.isArray(arr) && typeof arr.length === "number") { + var len = arr.length; + return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); + } + return next(arr, i); + } +`; +helpers.iterableToArray = helper("7.0.0-beta.0")` + export default function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + } +`; +helpers.iterableToArrayLimit = helper("7.0.0-beta.0")` + export default function _iterableToArrayLimit(arr, i) { + // this is an expanded form of \`for...of\` that properly supports abrupt completions of + // iterators etc. variable names have been minimised to reduce the size of this massive + // helper. sometimes spec compliance is annoying :( + // + // _n = _iteratorNormalCompletion + // _d = _didIteratorError + // _e = _iteratorError + // _i = _iterator + // _s = _step + + var _i = arr == null ? null : (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); + if (_i == null) return; + + var _arr = []; + var _n = true; + var _d = false; + var _s, _e; + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + return _arr; + } +`; +helpers.iterableToArrayLimitLoose = helper("7.0.0-beta.0")` + export default function _iterableToArrayLimitLoose(arr, i) { + var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); + if (_i == null) return; + + var _arr = []; + for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) { + _arr.push(_step.value); + if (i && _arr.length === i) break; + } + return _arr; + } +`; +helpers.unsupportedIterableToArray = helper("7.9.0")` + import arrayLikeToArray from "arrayLikeToArray"; + + export default function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) + return arrayLikeToArray(o, minLen); + } +`; +helpers.arrayLikeToArray = helper("7.9.0")` + export default function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; + } +`; +helpers.nonIterableSpread = helper("7.0.0-beta.0")` + export default function _nonIterableSpread() { + throw new TypeError( + "Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." + ); + } +`; +helpers.nonIterableRest = helper("7.0.0-beta.0")` + export default function _nonIterableRest() { + throw new TypeError( + "Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." + ); + } +`; +helpers.createForOfIteratorHelper = helper("7.9.0")` + import unsupportedIterableToArray from "unsupportedIterableToArray"; + + // s: start (create the iterator) + // n: next + // e: error (called whenever something throws) + // f: finish (always called at the end) + + export default function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + + if (!it) { + // Fallback for engines without symbol support + if ( + Array.isArray(o) || + (it = unsupportedIterableToArray(o)) || + (allowArrayLike && o && typeof o.length === "number") + ) { + if (it) o = it; + var i = 0; + var F = function(){}; + return { + s: F, + n: function() { + if (i >= o.length) return { done: true }; + return { done: false, value: o[i++] }; + }, + e: function(e) { throw e; }, + f: F, + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var normalCompletion = true, didErr = false, err; + + return { + s: function() { + it = it.call(o); + }, + n: function() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function(e) { + didErr = true; + err = e; + }, + f: function() { + try { + if (!normalCompletion && it.return != null) it.return(); + } finally { + if (didErr) throw err; + } + } + }; + } +`; +helpers.createForOfIteratorHelperLoose = helper("7.9.0")` + import unsupportedIterableToArray from "unsupportedIterableToArray"; + + export default function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + + if (it) return (it = it.call(o)).next.bind(it); + + // Fallback for engines without symbol support + if ( + Array.isArray(o) || + (it = unsupportedIterableToArray(o)) || + (allowArrayLike && o && typeof o.length === "number") + ) { + if (it) o = it; + var i = 0; + return function() { + if (i >= o.length) return { done: true }; + return { done: false, value: o[i++] }; + } + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } +`; +helpers.skipFirstGeneratorNext = helper("7.0.0-beta.0")` + export default function _skipFirstGeneratorNext(fn) { + return function () { + var it = fn.apply(this, arguments); + it.next(); + return it; + } + } +`; +helpers.toPrimitive = helper("7.1.5")` + export default function _toPrimitive( + input, + hint /*: "default" | "string" | "number" | void */ + ) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } +`; +helpers.toPropertyKey = helper("7.1.5")` + import toPrimitive from "toPrimitive"; + + export default function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } +`; +helpers.initializerWarningHelper = helper("7.0.0-beta.0")` + export default function _initializerWarningHelper(descriptor, context){ + throw new Error( + 'Decorating class property failed. Please ensure that ' + + 'proposal-class-properties is enabled and runs after the decorators transform.' + ); + } +`; +helpers.initializerDefineProperty = helper("7.0.0-beta.0")` + export default function _initializerDefineProperty(target, property, descriptor, context){ + if (!descriptor) return; + + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0, + }); + } +`; +helpers.applyDecoratedDescriptor = helper("7.0.0-beta.0")` + export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context){ + var desc = {}; + Object.keys(descriptor).forEach(function(key){ + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + if ('value' in desc || desc.initializer){ + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function(desc, decorator){ + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0){ + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0){ + Object.defineProperty(target, property, desc); + desc = null; + } + + return desc; + } +`; +helpers.classPrivateFieldLooseKey = helper("7.0.0-beta.0")` + var id = 0; + export default function _classPrivateFieldKey(name) { + return "__private_" + (id++) + "_" + name; + } +`; +helpers.classPrivateFieldLooseBase = helper("7.0.0-beta.0")` + export default function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); + } + return receiver; + } +`; +helpers.classPrivateFieldGet = helper("7.0.0-beta.0")` + import classApplyDescriptorGet from "classApplyDescriptorGet"; + import classExtractFieldDescriptor from "classExtractFieldDescriptor"; + export default function _classPrivateFieldGet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); + return classApplyDescriptorGet(receiver, descriptor); + } +`; +helpers.classPrivateFieldSet = helper("7.0.0-beta.0")` + import classApplyDescriptorSet from "classApplyDescriptorSet"; + import classExtractFieldDescriptor from "classExtractFieldDescriptor"; + export default function _classPrivateFieldSet(receiver, privateMap, value) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; + } +`; +helpers.classPrivateFieldDestructureSet = helper("7.4.4")` + import classApplyDescriptorDestructureSet from "classApplyDescriptorDestructureSet"; + import classExtractFieldDescriptor from "classExtractFieldDescriptor"; + export default function _classPrivateFieldDestructureSet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); + } +`; +helpers.classExtractFieldDescriptor = helper("7.13.10")` + export default function _classExtractFieldDescriptor(receiver, privateMap, action) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to " + action + " private field on non-instance"); + } + return privateMap.get(receiver); + } +`; +helpers.classStaticPrivateFieldSpecGet = helper("7.0.2")` + import classApplyDescriptorGet from "classApplyDescriptorGet"; + import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; + import classCheckPrivateStaticFieldDescriptor from "classCheckPrivateStaticFieldDescriptor"; + export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "get"); + return classApplyDescriptorGet(receiver, descriptor); + } +`; +helpers.classStaticPrivateFieldSpecSet = helper("7.0.2")` + import classApplyDescriptorSet from "classApplyDescriptorSet"; + import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; + import classCheckPrivateStaticFieldDescriptor from "classCheckPrivateStaticFieldDescriptor"; + export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; + } +`; +helpers.classStaticPrivateMethodGet = helper("7.3.2")` + import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; + export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { + classCheckPrivateStaticAccess(receiver, classConstructor); + return method; + } +`; +helpers.classStaticPrivateMethodSet = helper("7.3.2")` + export default function _classStaticPrivateMethodSet() { + throw new TypeError("attempted to set read only static private field"); + } +`; +helpers.classApplyDescriptorGet = helper("7.13.10")` + export default function _classApplyDescriptorGet(receiver, descriptor) { + if (descriptor.get) { + return descriptor.get.call(receiver); + } + return descriptor.value; + } +`; +helpers.classApplyDescriptorSet = helper("7.13.10")` + export default function _classApplyDescriptorSet(receiver, descriptor, value) { + if (descriptor.set) { + descriptor.set.call(receiver, value); + } else { + if (!descriptor.writable) { + // This should only throw in strict mode, but class bodies are + // always strict and private fields can only be used inside + // class bodies. + throw new TypeError("attempted to set read only private field"); + } + descriptor.value = value; + } + } +`; +helpers.classApplyDescriptorDestructureSet = helper("7.13.10")` + export default function _classApplyDescriptorDestructureSet(receiver, descriptor) { + if (descriptor.set) { + if (!("__destrObj" in descriptor)) { + descriptor.__destrObj = { + set value(v) { + descriptor.set.call(receiver, v) + }, + }; + } + return descriptor.__destrObj; + } else { + if (!descriptor.writable) { + // This should only throw in strict mode, but class bodies are + // always strict and private fields can only be used inside + // class bodies. + throw new TypeError("attempted to set read only private field"); + } + + return descriptor; + } + } +`; +helpers.classStaticPrivateFieldDestructureSet = helper("7.13.10")` + import classApplyDescriptorDestructureSet from "classApplyDescriptorDestructureSet"; + import classCheckPrivateStaticAccess from "classCheckPrivateStaticAccess"; + import classCheckPrivateStaticFieldDescriptor from "classCheckPrivateStaticFieldDescriptor"; + export default function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); + } +`; +helpers.classCheckPrivateStaticAccess = helper("7.13.10")` + export default function _classCheckPrivateStaticAccess(receiver, classConstructor) { + if (receiver !== classConstructor) { + throw new TypeError("Private static access of wrong provenance"); + } + } +`; +helpers.classCheckPrivateStaticFieldDescriptor = helper("7.13.10")` + export default function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { + if (descriptor === undefined) { + throw new TypeError("attempted to " + action + " private static field before its declaration"); + } + } +`; +helpers.decorate = helper("7.1.5")` + import toArray from "toArray"; + import toPropertyKey from "toPropertyKey"; + + // These comments are stripped by @babel/template + /*:: + type PropertyDescriptor = + | { + value: any, + writable: boolean, + configurable: boolean, + enumerable: boolean, + } + | { + get?: () => any, + set?: (v: any) => void, + configurable: boolean, + enumerable: boolean, + }; + + type FieldDescriptor ={ + writable: boolean, + configurable: boolean, + enumerable: boolean, + }; + + type Placement = "static" | "prototype" | "own"; + type Key = string | symbol; // PrivateName is not supported yet. + + type ElementDescriptor = + | { + kind: "method", + key: Key, + placement: Placement, + descriptor: PropertyDescriptor + } + | { + kind: "field", + key: Key, + placement: Placement, + descriptor: FieldDescriptor, + initializer?: () => any, + }; + + // This is exposed to the user code + type ElementObjectInput = ElementDescriptor & { + [@@toStringTag]?: "Descriptor" + }; + + // This is exposed to the user code + type ElementObjectOutput = ElementDescriptor & { + [@@toStringTag]?: "Descriptor" + extras?: ElementDescriptor[], + finisher?: ClassFinisher, + }; + + // This is exposed to the user code + type ClassObject = { + [@@toStringTag]?: "Descriptor", + kind: "class", + elements: ElementDescriptor[], + }; + + type ElementDecorator = (descriptor: ElementObjectInput) => ?ElementObjectOutput; + type ClassDecorator = (descriptor: ClassObject) => ?ClassObject; + type ClassFinisher = (cl: Class) => Class; + + // Only used by Babel in the transform output, not part of the spec. + type ElementDefinition = + | { + kind: "method", + value: any, + key: Key, + static?: boolean, + decorators?: ElementDecorator[], + } + | { + kind: "field", + value: () => any, + key: Key, + static?: boolean, + decorators?: ElementDecorator[], + }; + + declare function ClassFactory(initialize: (instance: C) => void): { + F: Class, + d: ElementDefinition[] + } + + */ + + /*:: + // Various combinations with/without extras and with one or many finishers + + type ElementFinisherExtras = { + element: ElementDescriptor, + finisher?: ClassFinisher, + extras?: ElementDescriptor[], + }; + + type ElementFinishersExtras = { + element: ElementDescriptor, + finishers: ClassFinisher[], + extras: ElementDescriptor[], + }; + + type ElementsFinisher = { + elements: ElementDescriptor[], + finisher?: ClassFinisher, + }; + + type ElementsFinishers = { + elements: ElementDescriptor[], + finishers: ClassFinisher[], + }; + + */ + + /*:: + + type Placements = { + static: Key[], + prototype: Key[], + own: Key[], + }; + + */ + + // ClassDefinitionEvaluation (Steps 26-*) + export default function _decorate( + decorators /*: ClassDecorator[] */, + factory /*: ClassFactory */, + superClass /*: ?Class<*> */, + mixins /*: ?Array */, + ) /*: Class<*> */ { + var api = _getDecoratorsApi(); + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + api = mixins[i](api); + } + } + + var r = factory(function initialize(O) { + api.initializeInstanceElements(O, decorated.elements); + }, superClass); + var decorated = api.decorateClass( + _coalesceClassElements(r.d.map(_createElementDescriptor)), + decorators, + ); + + api.initializeClassElements(r.F, decorated.elements); + + return api.runClassFinishers(r.F, decorated.finishers); + } + + function _getDecoratorsApi() { + _getDecoratorsApi = function() { + return api; + }; + + var api = { + elementsDefinitionOrder: [["method"], ["field"]], + + // InitializeInstanceElements + initializeInstanceElements: function( + /*::*/ O /*: C */, + elements /*: ElementDescriptor[] */, + ) { + ["method", "field"].forEach(function(kind) { + elements.forEach(function(element /*: ElementDescriptor */) { + if (element.kind === kind && element.placement === "own") { + this.defineClassElement(O, element); + } + }, this); + }, this); + }, + + // InitializeClassElements + initializeClassElements: function( + /*::*/ F /*: Class */, + elements /*: ElementDescriptor[] */, + ) { + var proto = F.prototype; + + ["method", "field"].forEach(function(kind) { + elements.forEach(function(element /*: ElementDescriptor */) { + var placement = element.placement; + if ( + element.kind === kind && + (placement === "static" || placement === "prototype") + ) { + var receiver = placement === "static" ? F : proto; + this.defineClassElement(receiver, element); + } + }, this); + }, this); + }, + + // DefineClassElement + defineClassElement: function( + /*::*/ receiver /*: C | Class */, + element /*: ElementDescriptor */, + ) { + var descriptor /*: PropertyDescriptor */ = element.descriptor; + if (element.kind === "field") { + var initializer = element.initializer; + descriptor = { + enumerable: descriptor.enumerable, + writable: descriptor.writable, + configurable: descriptor.configurable, + value: initializer === void 0 ? void 0 : initializer.call(receiver), + }; + } + Object.defineProperty(receiver, element.key, descriptor); + }, + + // DecorateClass + decorateClass: function( + elements /*: ElementDescriptor[] */, + decorators /*: ClassDecorator[] */, + ) /*: ElementsFinishers */ { + var newElements /*: ElementDescriptor[] */ = []; + var finishers /*: ClassFinisher[] */ = []; + var placements /*: Placements */ = { + static: [], + prototype: [], + own: [], + }; + + elements.forEach(function(element /*: ElementDescriptor */) { + this.addElementPlacement(element, placements); + }, this); + + elements.forEach(function(element /*: ElementDescriptor */) { + if (!_hasDecorators(element)) return newElements.push(element); + + var elementFinishersExtras /*: ElementFinishersExtras */ = this.decorateElement( + element, + placements, + ); + newElements.push(elementFinishersExtras.element); + newElements.push.apply(newElements, elementFinishersExtras.extras); + finishers.push.apply(finishers, elementFinishersExtras.finishers); + }, this); + + if (!decorators) { + return { elements: newElements, finishers: finishers }; + } + + var result /*: ElementsFinishers */ = this.decorateConstructor( + newElements, + decorators, + ); + finishers.push.apply(finishers, result.finishers); + result.finishers = finishers; + + return result; + }, + + // AddElementPlacement + addElementPlacement: function( + element /*: ElementDescriptor */, + placements /*: Placements */, + silent /*: boolean */, + ) { + var keys = placements[element.placement]; + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + keys.push(element.key); + }, + + // DecorateElement + decorateElement: function( + element /*: ElementDescriptor */, + placements /*: Placements */, + ) /*: ElementFinishersExtras */ { + var extras /*: ElementDescriptor[] */ = []; + var finishers /*: ClassFinisher[] */ = []; + + for ( + var decorators = element.decorators, i = decorators.length - 1; + i >= 0; + i-- + ) { + // (inlined) RemoveElementPlacement + var keys = placements[element.placement]; + keys.splice(keys.indexOf(element.key), 1); + + var elementObject /*: ElementObjectInput */ = this.fromElementDescriptor( + element, + ); + var elementFinisherExtras /*: ElementFinisherExtras */ = this.toElementFinisherExtras( + (0, decorators[i])(elementObject) /*: ElementObjectOutput */ || + elementObject, + ); + + element = elementFinisherExtras.element; + this.addElementPlacement(element, placements); + + if (elementFinisherExtras.finisher) { + finishers.push(elementFinisherExtras.finisher); + } + + var newExtras /*: ElementDescriptor[] | void */ = + elementFinisherExtras.extras; + if (newExtras) { + for (var j = 0; j < newExtras.length; j++) { + this.addElementPlacement(newExtras[j], placements); + } + extras.push.apply(extras, newExtras); + } + } + + return { element: element, finishers: finishers, extras: extras }; + }, + + // DecorateConstructor + decorateConstructor: function( + elements /*: ElementDescriptor[] */, + decorators /*: ClassDecorator[] */, + ) /*: ElementsFinishers */ { + var finishers /*: ClassFinisher[] */ = []; + + for (var i = decorators.length - 1; i >= 0; i--) { + var obj /*: ClassObject */ = this.fromClassDescriptor(elements); + var elementsAndFinisher /*: ElementsFinisher */ = this.toClassDescriptor( + (0, decorators[i])(obj) /*: ClassObject */ || obj, + ); + + if (elementsAndFinisher.finisher !== undefined) { + finishers.push(elementsAndFinisher.finisher); + } + + if (elementsAndFinisher.elements !== undefined) { + elements = elementsAndFinisher.elements; + + for (var j = 0; j < elements.length - 1; j++) { + for (var k = j + 1; k < elements.length; k++) { + if ( + elements[j].key === elements[k].key && + elements[j].placement === elements[k].placement + ) { + throw new TypeError( + "Duplicated element (" + elements[j].key + ")", + ); + } + } + } + } + } + + return { elements: elements, finishers: finishers }; + }, + + // FromElementDescriptor + fromElementDescriptor: function( + element /*: ElementDescriptor */, + ) /*: ElementObject */ { + var obj /*: ElementObject */ = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor, + }; + + var desc = { + value: "Descriptor", + configurable: true, + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + + if (element.kind === "field") obj.initializer = element.initializer; + + return obj; + }, + + // ToElementDescriptors + toElementDescriptors: function( + elementObjects /*: ElementObject[] */, + ) /*: ElementDescriptor[] */ { + if (elementObjects === undefined) return; + return toArray(elementObjects).map(function(elementObject) { + var element = this.toElementDescriptor(elementObject); + this.disallowProperty(elementObject, "finisher", "An element descriptor"); + this.disallowProperty(elementObject, "extras", "An element descriptor"); + return element; + }, this); + }, + + // ToElementDescriptor + toElementDescriptor: function( + elementObject /*: ElementObject */, + ) /*: ElementDescriptor */ { + var kind = String(elementObject.kind); + if (kind !== "method" && kind !== "field") { + throw new TypeError( + 'An element descriptor\\'s .kind property must be either "method" or' + + ' "field", but a decorator created an element descriptor with' + + ' .kind "' + + kind + + '"', + ); + } + + var key = toPropertyKey(elementObject.key); + + var placement = String(elementObject.placement); + if ( + placement !== "static" && + placement !== "prototype" && + placement !== "own" + ) { + throw new TypeError( + 'An element descriptor\\'s .placement property must be one of "static",' + + ' "prototype" or "own", but a decorator created an element descriptor' + + ' with .placement "' + + placement + + '"', + ); + } + + var descriptor /*: PropertyDescriptor */ = elementObject.descriptor; + + this.disallowProperty(elementObject, "elements", "An element descriptor"); + + var element /*: ElementDescriptor */ = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor), + }; + + if (kind !== "field") { + this.disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + this.disallowProperty( + descriptor, + "get", + "The property descriptor of a field descriptor", + ); + this.disallowProperty( + descriptor, + "set", + "The property descriptor of a field descriptor", + ); + this.disallowProperty( + descriptor, + "value", + "The property descriptor of a field descriptor", + ); + + element.initializer = elementObject.initializer; + } + + return element; + }, + + toElementFinisherExtras: function( + elementObject /*: ElementObject */, + ) /*: ElementFinisherExtras */ { + var element /*: ElementDescriptor */ = this.toElementDescriptor( + elementObject, + ); + var finisher /*: ClassFinisher */ = _optionalCallableProperty( + elementObject, + "finisher", + ); + var extras /*: ElementDescriptors[] */ = this.toElementDescriptors( + elementObject.extras, + ); + + return { element: element, finisher: finisher, extras: extras }; + }, + + // FromClassDescriptor + fromClassDescriptor: function( + elements /*: ElementDescriptor[] */, + ) /*: ClassObject */ { + var obj = { + kind: "class", + elements: elements.map(this.fromElementDescriptor, this), + }; + + var desc = { value: "Descriptor", configurable: true }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + + return obj; + }, + + // ToClassDescriptor + toClassDescriptor: function( + obj /*: ClassObject */, + ) /*: ElementsFinisher */ { + var kind = String(obj.kind); + if (kind !== "class") { + throw new TypeError( + 'A class descriptor\\'s .kind property must be "class", but a decorator' + + ' created a class descriptor with .kind "' + + kind + + '"', + ); + } + + this.disallowProperty(obj, "key", "A class descriptor"); + this.disallowProperty(obj, "placement", "A class descriptor"); + this.disallowProperty(obj, "descriptor", "A class descriptor"); + this.disallowProperty(obj, "initializer", "A class descriptor"); + this.disallowProperty(obj, "extras", "A class descriptor"); + + var finisher = _optionalCallableProperty(obj, "finisher"); + var elements = this.toElementDescriptors(obj.elements); + + return { elements: elements, finisher: finisher }; + }, + + // RunClassFinishers + runClassFinishers: function( + constructor /*: Class<*> */, + finishers /*: ClassFinisher[] */, + ) /*: Class<*> */ { + for (var i = 0; i < finishers.length; i++) { + var newConstructor /*: ?Class<*> */ = (0, finishers[i])(constructor); + if (newConstructor !== undefined) { + // NOTE: This should check if IsConstructor(newConstructor) is false. + if (typeof newConstructor !== "function") { + throw new TypeError("Finishers must return a constructor."); + } + constructor = newConstructor; + } + } + return constructor; + }, + + disallowProperty: function(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } + } + }; + + return api; + } + + // ClassElementEvaluation + function _createElementDescriptor( + def /*: ElementDefinition */, + ) /*: ElementDescriptor */ { + var key = toPropertyKey(def.key); + + var descriptor /*: PropertyDescriptor */; + if (def.kind === "method") { + descriptor = { + value: def.value, + writable: true, + configurable: true, + enumerable: false, + }; + } else if (def.kind === "get") { + descriptor = { get: def.value, configurable: true, enumerable: false }; + } else if (def.kind === "set") { + descriptor = { set: def.value, configurable: true, enumerable: false }; + } else if (def.kind === "field") { + descriptor = { configurable: true, writable: true, enumerable: true }; + } + + var element /*: ElementDescriptor */ = { + kind: def.kind === "field" ? "field" : "method", + key: key, + placement: def.static + ? "static" + : def.kind === "field" + ? "own" + : "prototype", + descriptor: descriptor, + }; + if (def.decorators) element.decorators = def.decorators; + if (def.kind === "field") element.initializer = def.value; + + return element; + } + + // CoalesceGetterSetter + function _coalesceGetterSetter( + element /*: ElementDescriptor */, + other /*: ElementDescriptor */, + ) { + if (element.descriptor.get !== undefined) { + other.descriptor.get = element.descriptor.get; + } else { + other.descriptor.set = element.descriptor.set; + } + } + + // CoalesceClassElements + function _coalesceClassElements( + elements /*: ElementDescriptor[] */, + ) /*: ElementDescriptor[] */ { + var newElements /*: ElementDescriptor[] */ = []; + + var isSameElement = function( + other /*: ElementDescriptor */, + ) /*: boolean */ { + return ( + other.kind === "method" && + other.key === element.key && + other.placement === element.placement + ); + }; + + for (var i = 0; i < elements.length; i++) { + var element /*: ElementDescriptor */ = elements[i]; + var other /*: ElementDescriptor */; + + if ( + element.kind === "method" && + (other = newElements.find(isSameElement)) + ) { + if ( + _isDataDescriptor(element.descriptor) || + _isDataDescriptor(other.descriptor) + ) { + if (_hasDecorators(element) || _hasDecorators(other)) { + throw new ReferenceError( + "Duplicated methods (" + element.key + ") can't be decorated.", + ); + } + other.descriptor = element.descriptor; + } else { + if (_hasDecorators(element)) { + if (_hasDecorators(other)) { + throw new ReferenceError( + "Decorators can't be placed on different accessors with for " + + "the same property (" + + element.key + + ").", + ); + } + other.decorators = element.decorators; + } + _coalesceGetterSetter(element, other); + } + } else { + newElements.push(element); + } + } + + return newElements; + } + + function _hasDecorators(element /*: ElementDescriptor */) /*: boolean */ { + return element.decorators && element.decorators.length; + } + + function _isDataDescriptor(desc /*: PropertyDescriptor */) /*: boolean */ { + return ( + desc !== undefined && + !(desc.value === undefined && desc.writable === undefined) + ); + } + + function _optionalCallableProperty /*::*/( + obj /*: T */, + name /*: $Keys */, + ) /*: ?Function */ { + var value = obj[name]; + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + return value; + } + +`; +helpers.classPrivateMethodGet = helper("7.1.6")` + export default function _classPrivateMethodGet(receiver, privateSet, fn) { + if (!privateSet.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return fn; + } +`; +helpers.checkPrivateRedeclaration = helper("7.14.1")` + export default function _checkPrivateRedeclaration(obj, privateCollection) { + if (privateCollection.has(obj)) { + throw new TypeError("Cannot initialize the same private elements twice on an object"); + } + } +`; +helpers.classPrivateFieldInitSpec = helper("7.14.1")` + import checkPrivateRedeclaration from "checkPrivateRedeclaration"; + + export default function _classPrivateFieldInitSpec(obj, privateMap, value) { + checkPrivateRedeclaration(obj, privateMap); + privateMap.set(obj, value); + } +`; +helpers.classPrivateMethodInitSpec = helper("7.14.1")` + import checkPrivateRedeclaration from "checkPrivateRedeclaration"; + + export default function _classPrivateMethodInitSpec(obj, privateSet) { + checkPrivateRedeclaration(obj, privateSet); + privateSet.add(obj); + } +`; +{ + helpers.classPrivateMethodSet = helper("7.1.6")` + export default function _classPrivateMethodSet() { + throw new TypeError("attempted to reassign private method"); + } + `; +} +helpers.identity = helper("7.17.0")` + export default function _identity(x) { + return x; + } +`; \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers/applyDecs.js b/node_modules/@babel/helpers/lib/helpers/applyDecs.js new file mode 100644 index 0000000..8808a40 --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers/applyDecs.js @@ -0,0 +1,530 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = applyDecs; + +function createMetadataMethodsForProperty(metadataMap, kind, property, decoratorFinishedRef) { + return { + getMetadata: function (key) { + assertNotFinished(decoratorFinishedRef, "getMetadata"); + assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + if (metadataForKey === void 0) return void 0; + + if (kind === 1) { + var pub = metadataForKey.public; + + if (pub !== void 0) { + return pub[property]; + } + } else if (kind === 2) { + var priv = metadataForKey.private; + + if (priv !== void 0) { + return priv.get(property); + } + } else if (Object.hasOwnProperty.call(metadataForKey, "constructor")) { + return metadataForKey.constructor; + } + }, + setMetadata: function (key, value) { + assertNotFinished(decoratorFinishedRef, "setMetadata"); + assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + + if (metadataForKey === void 0) { + metadataForKey = metadataMap[key] = {}; + } + + if (kind === 1) { + var pub = metadataForKey.public; + + if (pub === void 0) { + pub = metadataForKey.public = {}; + } + + pub[property] = value; + } else if (kind === 2) { + var priv = metadataForKey.priv; + + if (priv === void 0) { + priv = metadataForKey.private = new Map(); + } + + priv.set(property, value); + } else { + metadataForKey.constructor = value; + } + } + }; +} + +function convertMetadataMapToFinal(obj, metadataMap) { + var parentMetadataMap = obj[Symbol.metadata || Symbol.for("Symbol.metadata")]; + var metadataKeys = Object.getOwnPropertySymbols(metadataMap); + if (metadataKeys.length === 0) return; + + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i]; + var metaForKey = metadataMap[key]; + var parentMetaForKey = parentMetadataMap ? parentMetadataMap[key] : null; + var pub = metaForKey.public; + var parentPub = parentMetaForKey ? parentMetaForKey.public : null; + + if (pub && parentPub) { + Object.setPrototypeOf(pub, parentPub); + } + + var priv = metaForKey.private; + + if (priv) { + var privArr = Array.from(priv.values()); + var parentPriv = parentMetaForKey ? parentMetaForKey.private : null; + + if (parentPriv) { + privArr = privArr.concat(parentPriv); + } + + metaForKey.private = privArr; + } + + if (parentMetaForKey) { + Object.setPrototypeOf(metaForKey, parentMetaForKey); + } + } + + if (parentMetadataMap) { + Object.setPrototypeOf(metadataMap, parentMetadataMap); + } + + obj[Symbol.metadata || Symbol.for("Symbol.metadata")] = metadataMap; +} + +function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function addInitializer(initializer) { + assertNotFinished(decoratorFinishedRef, "addInitializer"); + assertCallable(initializer, "An initializer"); + initializers.push(initializer); + }; +} + +function memberDec(dec, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + + switch (kind) { + case 1: + kindStr = "accessor"; + break; + + case 2: + kindStr = "method"; + break; + + case 3: + kindStr = "getter"; + break; + + case 4: + kindStr = "setter"; + break; + + default: + kindStr = "field"; + } + + var ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + isStatic: isStatic, + isPrivate: isPrivate + }; + var decoratorFinishedRef = { + v: false + }; + + if (kind !== 0) { + ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef); + } + + var metadataKind, metadataName; + + if (isPrivate) { + metadataKind = 2; + metadataName = Symbol(name); + var access = {}; + + if (kind === 0) { + access.get = desc.get; + access.set = desc.set; + } else if (kind === 2) { + access.get = function () { + return desc.value; + }; + } else { + if (kind === 1 || kind === 3) { + access.get = function () { + return desc.get.call(this); + }; + } + + if (kind === 1 || kind === 4) { + access.set = function (v) { + desc.set.call(this, v); + }; + } + } + + ctx.access = access; + } else { + metadataKind = 1; + metadataName = name; + } + + try { + return dec(value, Object.assign(ctx, createMetadataMethodsForProperty(metadataMap, metadataKind, metadataName, decoratorFinishedRef))); + } finally { + decoratorFinishedRef.v = true; + } +} + +function assertNotFinished(decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) { + throw new Error("attempted to call " + fnName + " after decoration was finished"); + } +} + +function assertMetadataKey(key) { + if (typeof key !== "symbol") { + throw new TypeError("Metadata keys must be symbols, received: " + key); + } +} + +function assertCallable(fn, hint) { + if (typeof fn !== "function") { + throw new TypeError(hint + " must be a function"); + } +} + +function assertValidReturnValue(kind, value) { + var type = typeof value; + + if (kind === 1) { + if (type !== "object" || value === null) { + throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + } + + if (value.get !== undefined) { + assertCallable(value.get, "accessor.get"); + } + + if (value.set !== undefined) { + assertCallable(value.set, "accessor.set"); + } + + if (value.init !== undefined) { + assertCallable(value.init, "accessor.init"); + } + + if (value.initializer !== undefined) { + assertCallable(value.initializer, "accessor.initializer"); + } + } else if (type !== "function") { + var hint; + + if (kind === 0) { + hint = "field"; + } else if (kind === 10) { + hint = "class"; + } else { + hint = "method"; + } + + throw new TypeError(hint + " decorators must return a function or void 0"); + } +} + +function getInit(desc) { + var initializer; + + if ((initializer = desc.init) == null && (initializer = desc.initializer) && typeof console !== "undefined") { + console.warn(".initializer has been renamed to .init as of March 2022"); + } + + return initializer; +} + +function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers) { + var decs = decInfo[0]; + var desc, initializer, value; + + if (isPrivate) { + if (kind === 0 || kind === 1) { + desc = { + get: decInfo[3], + set: decInfo[4] + }; + } else if (kind === 3) { + desc = { + get: decInfo[3] + }; + } else if (kind === 4) { + desc = { + set: decInfo[3] + }; + } else { + desc = { + value: decInfo[3] + }; + } + } else if (kind !== 0) { + desc = Object.getOwnPropertyDescriptor(base, name); + } + + if (kind === 1) { + value = { + get: desc.get, + set: desc.set + }; + } else if (kind === 2) { + value = desc.value; + } else if (kind === 3) { + value = desc.get; + } else if (kind === 4) { + value = desc.set; + } + + var newValue, get, set; + + if (typeof decs === "function") { + newValue = memberDec(decs, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value); + + if (newValue !== void 0) { + assertValidReturnValue(kind, newValue); + + if (kind === 0) { + initializer = newValue; + } else if (kind === 1) { + initializer = getInit(newValue); + get = newValue.get || value.get; + set = newValue.set || value.set; + value = { + get: get, + set: set + }; + } else { + value = newValue; + } + } + } else { + for (var i = decs.length - 1; i >= 0; i--) { + var dec = decs[i]; + newValue = memberDec(dec, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value); + + if (newValue !== void 0) { + assertValidReturnValue(kind, newValue); + var newInit; + + if (kind === 0) { + newInit = newValue; + } else if (kind === 1) { + newInit = getInit(newValue); + get = newValue.get || value.get; + set = newValue.set || value.set; + value = { + get: get, + set: set + }; + } else { + value = newValue; + } + + if (newInit !== void 0) { + if (initializer === void 0) { + initializer = newInit; + } else if (typeof initializer === "function") { + initializer = [initializer, newInit]; + } else { + initializer.push(newInit); + } + } + } + } + } + + if (kind === 0 || kind === 1) { + if (initializer === void 0) { + initializer = function (instance, init) { + return init; + }; + } else if (typeof initializer !== "function") { + var ownInitializers = initializer; + + initializer = function (instance, init) { + var value = init; + + for (var i = 0; i < ownInitializers.length; i++) { + value = ownInitializers[i].call(instance, value); + } + + return value; + }; + } else { + var originalInitializer = initializer; + + initializer = function (instance, init) { + return originalInitializer.call(instance, init); + }; + } + + ret.push(initializer); + } + + if (kind !== 0) { + if (kind === 1) { + desc.get = value.get; + desc.set = value.set; + } else if (kind === 2) { + desc.value = value; + } else if (kind === 3) { + desc.get = value; + } else if (kind === 4) { + desc.set = value; + } + + if (isPrivate) { + if (kind === 1) { + ret.push(function (instance, args) { + return value.get.call(instance, args); + }); + ret.push(function (instance, args) { + return value.set.call(instance, args); + }); + } else if (kind === 2) { + ret.push(value); + } else { + ret.push(function (instance, args) { + return value.call(instance, args); + }); + } + } else { + Object.defineProperty(base, name, desc); + } + } +} + +function applyMemberDecs(ret, Class, protoMetadataMap, staticMetadataMap, decInfos) { + var protoInitializers; + var staticInitializers; + var existingProtoNonFields = new Map(); + var existingStaticNonFields = new Map(); + + for (var i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (!Array.isArray(decInfo)) continue; + var kind = decInfo[1]; + var name = decInfo[2]; + var isPrivate = decInfo.length > 3; + var isStatic = kind >= 5; + var base; + var metadataMap; + var initializers; + + if (isStatic) { + base = Class; + metadataMap = staticMetadataMap; + kind = kind - 5; + + if (kind !== 0) { + staticInitializers = staticInitializers || []; + initializers = staticInitializers; + } + } else { + base = Class.prototype; + metadataMap = protoMetadataMap; + + if (kind !== 0) { + protoInitializers = protoInitializers || []; + initializers = protoInitializers; + } + } + + if (kind !== 0 && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields; + var existingKind = existingNonFields.get(name) || 0; + + if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) { + throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + } else if (!existingKind && kind > 2) { + existingNonFields.set(name, kind); + } else { + existingNonFields.set(name, true); + } + } + + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers); + } + + pushInitializers(ret, protoInitializers); + pushInitializers(ret, staticInitializers); +} + +function pushInitializers(ret, initializers) { + if (initializers) { + ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) { + initializers[i].call(instance); + } + + return instance; + }); + } +} + +function applyClassDecs(ret, targetClass, metadataMap, classDecs) { + if (classDecs.length > 0) { + var initializers = []; + var newClass = targetClass; + var name = targetClass.name; + + for (var i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: false + }; + + try { + var ctx = Object.assign({ + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }, createMetadataMethodsForProperty(metadataMap, 0, name, decoratorFinishedRef)); + var nextNewClass = classDecs[i](newClass, ctx); + } finally { + decoratorFinishedRef.v = true; + } + + if (nextNewClass !== undefined) { + assertValidReturnValue(10, nextNewClass); + newClass = nextNewClass; + } + } + + ret.push(newClass, function () { + for (var i = 0; i < initializers.length; i++) { + initializers[i].call(newClass); + } + }); + } +} + +function applyDecs(targetClass, memberDecs, classDecs) { + var ret = []; + var staticMetadataMap = {}; + var protoMetadataMap = {}; + applyMemberDecs(ret, targetClass, protoMetadataMap, staticMetadataMap, memberDecs); + convertMetadataMapToFinal(targetClass.prototype, protoMetadataMap); + applyClassDecs(ret, targetClass, staticMetadataMap, classDecs); + convertMetadataMapToFinal(targetClass, staticMetadataMap); + return ret; +} \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers/asyncIterator.js b/node_modules/@babel/helpers/lib/helpers/asyncIterator.js new file mode 100644 index 0000000..0a6d9de --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers/asyncIterator.js @@ -0,0 +1,81 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _asyncIterator; + +function _asyncIterator(iterable) { + var method, + async, + sync, + retry = 2; + + if (typeof Symbol !== "undefined") { + async = Symbol.asyncIterator; + sync = Symbol.iterator; + } + + while (retry--) { + if (async && (method = iterable[async]) != null) { + return method.call(iterable); + } + + if (sync && (method = iterable[sync]) != null) { + return new AsyncFromSyncIterator(method.call(iterable)); + } + + async = "@@asyncIterator"; + sync = "@@iterator"; + } + + throw new TypeError("Object is not async iterable"); +} + +function AsyncFromSyncIterator(s) { + AsyncFromSyncIterator = function (s) { + this.s = s; + this.n = s.next; + }; + + AsyncFromSyncIterator.prototype = { + s: null, + n: null, + next: function () { + return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); + }, + return: function (value) { + var ret = this.s.return; + + if (ret === undefined) { + return Promise.resolve({ + value: value, + done: true + }); + } + + return AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); + }, + throw: function (value) { + var thr = this.s.return; + if (thr === undefined) return Promise.reject(value); + return AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); + } + }; + + function AsyncFromSyncIteratorContinuation(r) { + if (Object(r) !== r) { + return Promise.reject(new TypeError(r + " is not an object.")); + } + + var done = r.done; + return Promise.resolve(r.value).then(function (value) { + return { + value: value, + done: done + }; + }); + } + + return new AsyncFromSyncIterator(s); +} \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers/jsx.js b/node_modules/@babel/helpers/lib/helpers/jsx.js new file mode 100644 index 0000000..68de168 --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers/jsx.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _createRawReactElement; +var REACT_ELEMENT_TYPE; + +function _createRawReactElement(type, props, key, children) { + if (!REACT_ELEMENT_TYPE) { + REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; + } + + var defaultProps = type && type.defaultProps; + var childrenLength = arguments.length - 3; + + if (!props && childrenLength !== 0) { + props = { + children: void 0 + }; + } + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = new Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 3]; + } + + props.children = childArray; + } + + if (props && defaultProps) { + for (var propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + } else if (!props) { + props = defaultProps || {}; + } + + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key === undefined ? null : "" + key, + ref: null, + props: props, + _owner: null + }; +} \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers/objectSpread2.js b/node_modules/@babel/helpers/lib/helpers/objectSpread2.js new file mode 100644 index 0000000..03db006 --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers/objectSpread2.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _objectSpread2; + +var _defineProperty = require("defineProperty"); + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers/regeneratorRuntime.js b/node_modules/@babel/helpers/lib/helpers/regeneratorRuntime.js new file mode 100644 index 0000000..225ca44 --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers/regeneratorRuntime.js @@ -0,0 +1,587 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _regeneratorRuntime; + +function _regeneratorRuntime() { + "use strict"; + + exports.default = _regeneratorRuntime = function () { + return exports; + }; + + var exports = {}; + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + + try { + define({}, ""); + } catch (err) { + define = function (obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + generator._invoke = makeInvokeMethod(innerFn, self, context); + return generator; + } + + exports.wrap = wrap; + + function tryCatch(fn, obj, arg) { + try { + return { + type: "normal", + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: "throw", + arg: err + }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + var ContinueSentinel = {}; + + function Generator() {} + + function GeneratorFunction() {} + + function GeneratorFunctionPrototype() {} + + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + + if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = GeneratorFunctionPrototype; + define(Gp, "constructor", GeneratorFunctionPrototype); + define(GeneratorFunctionPrototype, "constructor", GeneratorFunction); + GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); + + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + define(prototype, method, function (arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function (genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor ? ctor === GeneratorFunction || (ctor.displayName || ctor.name) === "GeneratorFunction" : false; + }; + + exports.mark = function (genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + + genFun.prototype = Object.create(Gp); + return genFun; + }; + + exports.awrap = function (arg) { + return { + __await: arg + }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + + if (value && typeof value === "object" && hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function (unwrapped) { + result.value = unwrapped; + resolve(result); + }, function (error) { + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } + + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }); + exports.AsyncIterator = AsyncIterator; + + exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); + return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + context.sent = context._sent = context.arg; + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + var record = tryCatch(innerFn, self, context); + + if (record.type === "normal") { + state = context.done ? GenStateCompleted : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + } else if (record.type === "throw") { + state = GenStateCompleted; + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + + if (method === undefined) { + context.delegate = null; + + if (context.method === "throw") { + if (delegate.iterator["return"]) { + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError("The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (!info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + context[delegate.resultName] = info.value; + context.next = delegate.nextLoc; + + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + } else { + return info; + } + + context.delegate = null; + return ContinueSentinel; + } + + defineIteratorMethods(Gp); + define(Gp, toStringTagSymbol, "Generator"); + define(Gp, iteratorSymbol, function () { + return this; + }); + define(Gp, "toString", function () { + return "[object Generator]"; + }); + + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + this.tryEntries = [{ + tryLoc: "root" + }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function (object) { + var keys = []; + + for (var key in object) { + keys.push(key); + } + + keys.reverse(); + return function next() { + while (keys.length) { + var key = keys.pop(); + + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + return next; + }; + + return next.next = next; + } + } + + return { + next: doneResult + }; + } + + exports.values = values; + + function doneResult() { + return { + value: undefined, + done: true + }; + } + + Context.prototype = { + constructor: Context, + reset: function (skipTempReset) { + this.prev = 0; + this.next = 0; + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + this.method = "next"; + this.arg = undefined; + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + stop: function () { + this.done = true; + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + dispatchException: function (exception) { + if (this.done) { + throw exception; + } + + var context = this; + + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + context.method = "next"; + context.arg = undefined; + } + + return !!caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + abrupt: function (type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + complete: function (record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + finish: function (finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + catch: function (tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + + return thrown; + } + } + + throw new Error("illegal catch attempt"); + }, + delegateYield: function (iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + return exports; +} \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers/typeof.js b/node_modules/@babel/helpers/lib/helpers/typeof.js new file mode 100644 index 0000000..b1a728b --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers/typeof.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _typeof; + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + exports.default = _typeof = function (obj) { + return typeof obj; + }; + } else { + exports.default = _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/helpers/wrapRegExp.js b/node_modules/@babel/helpers/lib/helpers/wrapRegExp.js new file mode 100644 index 0000000..6375b71 --- /dev/null +++ b/node_modules/@babel/helpers/lib/helpers/wrapRegExp.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _wrapRegExp; + +var _setPrototypeOf = require("setPrototypeOf"); + +var _inherits = require("inherits"); + +function _wrapRegExp() { + exports.default = _wrapRegExp = function (re, groups) { + return new BabelRegExp(re, undefined, groups); + }; + + var _super = RegExp.prototype; + + var _groups = new WeakMap(); + + function BabelRegExp(re, flags, groups) { + var _this = new RegExp(re, flags); + + _groups.set(_this, groups || _groups.get(re)); + + return _setPrototypeOf(_this, BabelRegExp.prototype); + } + + _inherits(BabelRegExp, RegExp); + + BabelRegExp.prototype.exec = function (str) { + var result = _super.exec.call(this, str); + + if (result) result.groups = buildGroups(result, this); + return result; + }; + + BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { + if (typeof substitution === "string") { + var groups = _groups.get(this); + + return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { + return "$" + groups[name]; + })); + } else if (typeof substitution === "function") { + var _this = this; + + return _super[Symbol.replace].call(this, str, function () { + var args = arguments; + + if (typeof args[args.length - 1] !== "object") { + args = [].slice.call(args); + args.push(buildGroups(args, _this)); + } + + return substitution.apply(this, args); + }); + } else { + return _super[Symbol.replace].call(this, str, substitution); + } + }; + + function buildGroups(result, re) { + var g = _groups.get(re); + + return Object.keys(g).reduce(function (groups, name) { + groups[name] = result[g[name]]; + return groups; + }, Object.create(null)); + } + + return _wrapRegExp.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/helpers/lib/index.js b/node_modules/@babel/helpers/lib/index.js new file mode 100644 index 0000000..511c6c5 --- /dev/null +++ b/node_modules/@babel/helpers/lib/index.js @@ -0,0 +1,290 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.ensure = ensure; +exports.get = get; +exports.getDependencies = getDependencies; +exports.list = void 0; +exports.minVersion = minVersion; + +var _traverse = require("@babel/traverse"); + +var _t = require("@babel/types"); + +var _helpers = require("./helpers"); + +const { + assignmentExpression, + cloneNode, + expressionStatement, + file, + identifier +} = _t; + +function makePath(path) { + const parts = []; + + for (; path.parentPath; path = path.parentPath) { + parts.push(path.key); + if (path.inList) parts.push(path.listKey); + } + + return parts.reverse().join("."); +} + +let FileClass = undefined; + +function getHelperMetadata(file) { + const globals = new Set(); + const localBindingNames = new Set(); + const dependencies = new Map(); + let exportName; + let exportPath; + const exportBindingAssignments = []; + const importPaths = []; + const importBindingsReferences = []; + const dependencyVisitor = { + ImportDeclaration(child) { + const name = child.node.source.value; + + if (!_helpers.default[name]) { + throw child.buildCodeFrameError(`Unknown helper ${name}`); + } + + if (child.get("specifiers").length !== 1 || !child.get("specifiers.0").isImportDefaultSpecifier()) { + throw child.buildCodeFrameError("Helpers can only import a default value"); + } + + const bindingIdentifier = child.node.specifiers[0].local; + dependencies.set(bindingIdentifier, name); + importPaths.push(makePath(child)); + }, + + ExportDefaultDeclaration(child) { + const decl = child.get("declaration"); + + if (!decl.isFunctionDeclaration() || !decl.node.id) { + throw decl.buildCodeFrameError("Helpers can only export named function declarations"); + } + + exportName = decl.node.id.name; + exportPath = makePath(child); + }, + + ExportAllDeclaration(child) { + throw child.buildCodeFrameError("Helpers can only export default"); + }, + + ExportNamedDeclaration(child) { + throw child.buildCodeFrameError("Helpers can only export default"); + }, + + Statement(child) { + if (child.isModuleDeclaration()) return; + child.skip(); + } + + }; + const referenceVisitor = { + Program(path) { + const bindings = path.scope.getAllBindings(); + Object.keys(bindings).forEach(name => { + if (name === exportName) return; + if (dependencies.has(bindings[name].identifier)) return; + localBindingNames.add(name); + }); + }, + + ReferencedIdentifier(child) { + const name = child.node.name; + const binding = child.scope.getBinding(name); + + if (!binding) { + globals.add(name); + } else if (dependencies.has(binding.identifier)) { + importBindingsReferences.push(makePath(child)); + } + }, + + AssignmentExpression(child) { + const left = child.get("left"); + if (!(exportName in left.getBindingIdentifiers())) return; + + if (!left.isIdentifier()) { + throw left.buildCodeFrameError("Only simple assignments to exports are allowed in helpers"); + } + + const binding = child.scope.getBinding(exportName); + + if (binding != null && binding.scope.path.isProgram()) { + exportBindingAssignments.push(makePath(child)); + } + } + + }; + (0, _traverse.default)(file.ast, dependencyVisitor, file.scope); + (0, _traverse.default)(file.ast, referenceVisitor, file.scope); + if (!exportPath) throw new Error("Helpers must have a default export."); + exportBindingAssignments.reverse(); + return { + globals: Array.from(globals), + localBindingNames: Array.from(localBindingNames), + dependencies, + exportBindingAssignments, + exportPath, + exportName, + importBindingsReferences, + importPaths + }; +} + +function permuteHelperAST(file, metadata, id, localBindings, getDependency) { + if (localBindings && !id) { + throw new Error("Unexpected local bindings for module-based helpers."); + } + + if (!id) return; + const { + localBindingNames, + dependencies, + exportBindingAssignments, + exportPath, + exportName, + importBindingsReferences, + importPaths + } = metadata; + const dependenciesRefs = {}; + dependencies.forEach((name, id) => { + dependenciesRefs[id.name] = typeof getDependency === "function" && getDependency(name) || id; + }); + const toRename = {}; + const bindings = new Set(localBindings || []); + localBindingNames.forEach(name => { + let newName = name; + + while (bindings.has(newName)) newName = "_" + newName; + + if (newName !== name) toRename[name] = newName; + }); + + if (id.type === "Identifier" && exportName !== id.name) { + toRename[exportName] = id.name; + } + + const { + path + } = file; + const exp = path.get(exportPath); + const imps = importPaths.map(p => path.get(p)); + const impsBindingRefs = importBindingsReferences.map(p => path.get(p)); + const decl = exp.get("declaration"); + + if (id.type === "Identifier") { + exp.replaceWith(decl); + } else if (id.type === "MemberExpression") { + exportBindingAssignments.forEach(assignPath => { + const assign = path.get(assignPath); + assign.replaceWith(assignmentExpression("=", id, assign.node)); + }); + exp.replaceWith(decl); + path.pushContainer("body", expressionStatement(assignmentExpression("=", id, identifier(exportName)))); + } else { + throw new Error("Unexpected helper format."); + } + + Object.keys(toRename).forEach(name => { + path.scope.rename(name, toRename[name]); + }); + + for (const path of imps) path.remove(); + + for (const path of impsBindingRefs) { + const node = cloneNode(dependenciesRefs[path.node.name]); + path.replaceWith(node); + } +} + +const helperData = Object.create(null); + +function loadHelper(name) { + if (!helperData[name]) { + const helper = _helpers.default[name]; + + if (!helper) { + throw Object.assign(new ReferenceError(`Unknown helper ${name}`), { + code: "BABEL_HELPER_UNKNOWN", + helper: name + }); + } + + const fn = () => { + { + if (!FileClass) { + const fakeFile = { + ast: file(helper.ast()), + path: null + }; + (0, _traverse.default)(fakeFile.ast, { + Program: path => (fakeFile.path = path).stop() + }); + return fakeFile; + } + } + return new FileClass({ + filename: `babel-helper://${name}` + }, { + ast: file(helper.ast()), + code: "[internal Babel helper code]", + inputMap: null + }); + }; + + let metadata = null; + helperData[name] = { + minVersion: helper.minVersion, + + build(getDependency, id, localBindings) { + const file = fn(); + metadata || (metadata = getHelperMetadata(file)); + permuteHelperAST(file, metadata, id, localBindings, getDependency); + return { + nodes: file.ast.program.body, + globals: metadata.globals + }; + }, + + getDependencies() { + metadata || (metadata = getHelperMetadata(fn())); + return Array.from(metadata.dependencies.values()); + } + + }; + } + + return helperData[name]; +} + +function get(name, getDependency, id, localBindings) { + return loadHelper(name).build(getDependency, id, localBindings); +} + +function minVersion(name) { + return loadHelper(name).minVersion; +} + +function getDependencies(name) { + return loadHelper(name).getDependencies(); +} + +function ensure(name, newFileClass) { + FileClass || (FileClass = newFileClass); + loadHelper(name); +} + +const list = Object.keys(_helpers.default).map(name => name.replace(/^_/, "")); +exports.list = list; +var _default = get; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/@babel/helpers/package.json b/node_modules/@babel/helpers/package.json new file mode 100644 index 0000000..a35a754 --- /dev/null +++ b/node_modules/@babel/helpers/package.json @@ -0,0 +1,65 @@ +{ + "_from": "@babel/helpers@^7.18.9", + "_id": "@babel/helpers@7.18.9", + "_inBundle": false, + "_integrity": "sha512-Jf5a+rbrLoR4eNdUmnFu8cN5eNJT6qdTdOg5IHIzq87WwyRw9PwguLFOWYgktN/60IP4fgDUawJvs7PjQIzELQ==", + "_location": "/@babel/helpers", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helpers@^7.18.9", + "name": "@babel/helpers", + "escapedName": "@babel%2fhelpers", + "scope": "@babel", + "rawSpec": "^7.18.9", + "saveSpec": null, + "fetchSpec": "^7.18.9" + }, + "_requiredBy": [ + "/@babel/core" + ], + "_resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.18.9.tgz", + "_shasum": "4bef3b893f253a1eced04516824ede94dcfe7ff9", + "_spec": "@babel/helpers@^7.18.9", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/core", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/template": "^7.18.6", + "@babel/traverse": "^7.18.9", + "@babel/types": "^7.18.9" + }, + "deprecated": false, + "description": "Collection of helper functions used by Babel transforms.", + "devDependencies": { + "@babel/generator": "^7.18.9", + "@babel/helper-plugin-test-runner": "^7.18.6", + "@babel/parser": "^7.18.9", + "regenerator-runtime": "^0.13.9", + "terser": "^5.9.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helpers", + "license": "MIT", + "main": "./lib/index.js", + "name": "@babel/helpers", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helpers" + }, + "type": "commonjs", + "version": "7.18.9" +} diff --git a/node_modules/@babel/helpers/scripts/generate-helpers.js b/node_modules/@babel/helpers/scripts/generate-helpers.js new file mode 100644 index 0000000..e0b3701 --- /dev/null +++ b/node_modules/@babel/helpers/scripts/generate-helpers.js @@ -0,0 +1,64 @@ +import fs from "fs"; +import { join } from "path"; +import { URL, fileURLToPath } from "url"; +import { minify } from "terser"; // eslint-disable-line import/no-extraneous-dependencies + +const HELPERS_FOLDER = new URL("../src/helpers", import.meta.url); +const IGNORED_FILES = new Set(["package.json"]); + +export default async function generateHelpers() { + let output = `/* + * This file is auto-generated! Do not modify it directly. + * To re-generate run 'yarn gulp generate-runtime-helpers' + */ + +import template from "@babel/template"; + +function helper(minVersion: string, source: string) { + return Object.freeze({ + minVersion, + ast: () => template.program.ast(source, { preserveComments: true }), + }) +} + +export default Object.freeze({ +`; + + for (const file of (await fs.promises.readdir(HELPERS_FOLDER)).sort()) { + if (IGNORED_FILES.has(file)) continue; + if (file.startsWith(".")) continue; // ignore e.g. vim swap files + + const [helperName] = file.split("."); + + const filePath = join(fileURLToPath(HELPERS_FOLDER), file); + if (!file.endsWith(".js")) { + console.error("ignoring", filePath); + continue; + } + + const fileContents = await fs.promises.readFile(filePath, "utf8"); + const minVersionMatch = fileContents.match( + /^\s*\/\*\s*@minVersion\s+(?\S+)\s*\*\/\s*$/m + ); + if (!minVersionMatch) { + throw new Error(`@minVersion number missing in ${filePath}`); + } + const { minVersion } = minVersionMatch.groups; + + const source = await minify(fileContents, { + mangle: false, + // The _typeof helper has a custom directive that we must keep + compress: { directives: false }, + }); + + output += `\ + ${JSON.stringify(helperName)}: helper( + ${JSON.stringify(minVersion)}, + ${JSON.stringify(source.code)}, + ), +`; + } + + output += "});"; + return output; +} diff --git a/node_modules/@babel/helpers/scripts/generate-regenerator-runtime.js b/node_modules/@babel/helpers/scripts/generate-regenerator-runtime.js new file mode 100644 index 0000000..b6bacf6 --- /dev/null +++ b/node_modules/@babel/helpers/scripts/generate-regenerator-runtime.js @@ -0,0 +1,64 @@ +/* eslint-disable import/no-extraneous-dependencies */ + +import fs from "fs"; +import { createRequire } from "module"; + +const [parse, generate] = await Promise.all([ + import("@babel/parser").then(ns => ns.parse), + import("@babel/generator").then(ns => ns.default.default || ns.default), +]).catch(error => + Promise.reject( + new Error( + "Before running generate-helpers.js you must compile @babel/parser and @babel/generator.", + { cause: error } + ) + ) +); + +const REGENERATOR_RUNTIME_IN_FILE = fs.readFileSync( + createRequire(import.meta.url).resolve("regenerator-runtime"), + "utf8" +); + +const MIN_VERSION = "7.18.0"; + +const HEADER = `/* @minVersion ${MIN_VERSION} */ +/* + * This file is auto-generated! Do not modify it directly. + * To re-generate, update the regenerator-runtime dependency of + * @babel/helpers and run 'yarn gulp generate-runtime-helpers'. + */ + +/* eslint-disable */ +`; + +const COPYRIGHT = `/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */`; + +export default function generateRegeneratorRuntimeHelper() { + const ast = parse(REGENERATOR_RUNTIME_IN_FILE, { sourceType: "script" }); + + const factoryFunction = ast.program.body[0].declarations[0].init.callee; + factoryFunction.type = "FunctionDeclaration"; + factoryFunction.id = { type: "Identifier", name: "_regeneratorRuntime" }; + factoryFunction.params = []; + factoryFunction.body.body.unshift( + ...stmts(` + ${COPYRIGHT} + _regeneratorRuntime = function () { return exports; }; + var exports = {}; + `) + ); + + const { code } = generate({ + type: "ExportDefaultDeclaration", + declaration: factoryFunction, + }); + + return HEADER + code; +} + +function stmts(code) { + return parse(`function _() { ${code} }`, { + sourceType: "script", + }).program.body[0].body.body; +} diff --git a/node_modules/@babel/helpers/scripts/package.json b/node_modules/@babel/helpers/scripts/package.json new file mode 100644 index 0000000..5ffd980 --- /dev/null +++ b/node_modules/@babel/helpers/scripts/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/node_modules/@babel/highlight/LICENSE b/node_modules/@babel/highlight/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/highlight/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/highlight/README.md b/node_modules/@babel/highlight/README.md new file mode 100644 index 0000000..f8887ad --- /dev/null +++ b/node_modules/@babel/highlight/README.md @@ -0,0 +1,19 @@ +# @babel/highlight + +> Syntax highlight JavaScript strings for output in terminals. + +See our website [@babel/highlight](https://babeljs.io/docs/en/babel-highlight) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/highlight +``` + +or using yarn: + +```sh +yarn add @babel/highlight --dev +``` diff --git a/node_modules/@babel/highlight/lib/index.js b/node_modules/@babel/highlight/lib/index.js new file mode 100644 index 0000000..856dfd9 --- /dev/null +++ b/node_modules/@babel/highlight/lib/index.js @@ -0,0 +1,116 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = highlight; +exports.getChalk = getChalk; +exports.shouldHighlight = shouldHighlight; + +var _jsTokens = require("js-tokens"); + +var _helperValidatorIdentifier = require("@babel/helper-validator-identifier"); + +var _chalk = require("chalk"); + +const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]); + +function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsxIdentifier: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; +} + +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; +const BRACKET = /^[()[\]{}]$/; +let tokenize; +{ + const JSX_TAG = /^[a-z][\w-]*$/i; + + const getTokenType = function (token, offset, text) { + if (token.type === "name") { + if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isStrictReservedWord)(token.value, true) || sometimesKeywords.has(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) == " colorize(str)).join("\n"); + } else { + highlighted += value; + } + } + + return highlighted; +} + +function shouldHighlight(options) { + return !!_chalk.supportsColor || options.forceColor; +} + +function getChalk(options) { + return options.forceColor ? new _chalk.constructor({ + enabled: true, + level: 1 + }) : _chalk; +} + +function highlight(code, options = {}) { + if (code !== "" && shouldHighlight(options)) { + const chalk = getChalk(options); + const defs = getDefs(chalk); + return highlightTokens(defs, code); + } else { + return code; + } +} \ No newline at end of file diff --git a/node_modules/@babel/highlight/node_modules/ansi-styles/index.js b/node_modules/@babel/highlight/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..90a871c --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/index.js @@ -0,0 +1,165 @@ +'use strict'; +const colorConvert = require('color-convert'); + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + 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], + + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/@babel/highlight/node_modules/ansi-styles/license b/node_modules/@babel/highlight/node_modules/ansi-styles/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/highlight/node_modules/ansi-styles/package.json b/node_modules/@babel/highlight/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..327a4c8 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/package.json @@ -0,0 +1,88 @@ +{ + "_from": "ansi-styles@^3.2.1", + "_id": "ansi-styles@3.2.1", + "_inBundle": false, + "_integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "_location": "/@babel/highlight/ansi-styles", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ansi-styles@^3.2.1", + "name": "ansi-styles", + "escapedName": "ansi-styles", + "rawSpec": "^3.2.1", + "saveSpec": null, + "fetchSpec": "^3.2.1" + }, + "_requiredBy": [ + "/@babel/highlight/chalk" + ], + "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "_shasum": "41fbb20243e50b12be0f04b8dedbf07520ce841d", + "_spec": "ansi-styles@^3.2.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/highlight/node_modules/chalk", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "ava": { + "require": "babel-polyfill" + }, + "bugs": { + "url": "https://github.com/chalk/ansi-styles/issues" + }, + "bundleDependencies": false, + "dependencies": { + "color-convert": "^1.9.0" + }, + "deprecated": false, + "description": "ANSI escape codes for styling strings in the terminal", + "devDependencies": { + "ava": "*", + "babel-polyfill": "^6.23.0", + "svg-term-cli": "^2.1.1", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/chalk/ansi-styles#readme", + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "name": "ansi-styles", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/ansi-styles.git" + }, + "scripts": { + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor", + "test": "xo && ava" + }, + "version": "3.2.1" +} diff --git a/node_modules/@babel/highlight/node_modules/ansi-styles/readme.md b/node_modules/@babel/highlight/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..3158e2d --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/ansi-styles/readme.md @@ -0,0 +1,147 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + + + + +## Install + +``` +$ npm install ansi-styles +``` + + +## Usage + +```js +const style = require('ansi-styles'); + +console.log(`${style.green.open}Hello world!${style.green.close}`); + + +// Color conversion between 16/256/truecolor +// NOTE: If conversion goes to 16 colors or 256 colors, the original color +// may be degraded to fit that color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); +console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); +console.log(style.color.ansi16m.hex('#ABCDEF') + 'Hello world!' + style.color.close); +``` + +## API + +Each style has an `open` and `close` property. + + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `gray` ("bright black") +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `style.modifier` +- `style.color` +- `style.bgColor` + +###### Example + +```js +console.log(style.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +console.log(style.codes.get(36)); +//=> 39 +``` + + +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) + +`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. + +To use these, call the associated conversion function with the intended output, for example: + +```js +style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code +style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code + +style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code +style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code + +style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code +style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code +``` + + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/node_modules/@babel/highlight/node_modules/chalk/index.js b/node_modules/@babel/highlight/node_modules/chalk/index.js new file mode 100644 index 0000000..1cc5fa8 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/index.js @@ -0,0 +1,228 @@ +'use strict'; +const escapeStringRegexp = require('escape-string-regexp'); +const ansiStyles = require('ansi-styles'); +const stdoutColor = require('supports-color').stdout; + +const template = require('./templates.js'); + +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); + +const styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = Chalk; + + return chalk.template; + } + + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} + +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} + +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, styles); + +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + + const self = this; + + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript diff --git a/node_modules/@babel/highlight/node_modules/chalk/index.js.flow b/node_modules/@babel/highlight/node_modules/chalk/index.js.flow new file mode 100644 index 0000000..622caaa --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/index.js.flow @@ -0,0 +1,93 @@ +// @flow strict + +type TemplateStringsArray = $ReadOnlyArray; + +export type Level = $Values<{ + None: 0, + Basic: 1, + Ansi256: 2, + TrueColor: 3 +}>; + +export type ChalkOptions = {| + enabled?: boolean, + level?: Level +|}; + +export type ColorSupport = {| + level: Level, + hasBasic: boolean, + has256: boolean, + has16m: boolean +|}; + +export interface Chalk { + (...text: string[]): string, + (text: TemplateStringsArray, ...placeholders: string[]): string, + constructor(options?: ChalkOptions): Chalk, + enabled: boolean, + level: Level, + rgb(r: number, g: number, b: number): Chalk, + hsl(h: number, s: number, l: number): Chalk, + hsv(h: number, s: number, v: number): Chalk, + hwb(h: number, w: number, b: number): Chalk, + bgHex(color: string): Chalk, + bgKeyword(color: string): Chalk, + bgRgb(r: number, g: number, b: number): Chalk, + bgHsl(h: number, s: number, l: number): Chalk, + bgHsv(h: number, s: number, v: number): Chalk, + bgHwb(h: number, w: number, b: number): Chalk, + hex(color: string): Chalk, + keyword(color: string): Chalk, + + +reset: Chalk, + +bold: Chalk, + +dim: Chalk, + +italic: Chalk, + +underline: Chalk, + +inverse: Chalk, + +hidden: Chalk, + +strikethrough: Chalk, + + +visible: Chalk, + + +black: Chalk, + +red: Chalk, + +green: Chalk, + +yellow: Chalk, + +blue: Chalk, + +magenta: Chalk, + +cyan: Chalk, + +white: Chalk, + +gray: Chalk, + +grey: Chalk, + +blackBright: Chalk, + +redBright: Chalk, + +greenBright: Chalk, + +yellowBright: Chalk, + +blueBright: Chalk, + +magentaBright: Chalk, + +cyanBright: Chalk, + +whiteBright: Chalk, + + +bgBlack: Chalk, + +bgRed: Chalk, + +bgGreen: Chalk, + +bgYellow: Chalk, + +bgBlue: Chalk, + +bgMagenta: Chalk, + +bgCyan: Chalk, + +bgWhite: Chalk, + +bgBlackBright: Chalk, + +bgRedBright: Chalk, + +bgGreenBright: Chalk, + +bgYellowBright: Chalk, + +bgBlueBright: Chalk, + +bgMagentaBright: Chalk, + +bgCyanBright: Chalk, + +bgWhiteBrigh: Chalk, + + supportsColor: ColorSupport +}; + +declare module.exports: Chalk; diff --git a/node_modules/@babel/highlight/node_modules/chalk/license b/node_modules/@babel/highlight/node_modules/chalk/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/highlight/node_modules/chalk/package.json b/node_modules/@babel/highlight/node_modules/chalk/package.json new file mode 100644 index 0000000..af08ff3 --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/package.json @@ -0,0 +1,103 @@ +{ + "_from": "chalk@^2.0.0", + "_id": "chalk@2.4.2", + "_inBundle": false, + "_integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "_location": "/@babel/highlight/chalk", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "chalk@^2.0.0", + "name": "chalk", + "escapedName": "chalk", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/@babel/highlight" + ], + "_resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "_shasum": "cd42541677a54333cf541a49108c1432b44c9424", + "_spec": "chalk@^2.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/highlight", + "bugs": { + "url": "https://github.com/chalk/chalk/issues" + }, + "bundleDependencies": false, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "deprecated": false, + "description": "Terminal string styling done right", + "devDependencies": { + "ava": "*", + "coveralls": "^3.0.0", + "execa": "^0.9.0", + "flow-bin": "^0.68.0", + "import-fresh": "^2.0.0", + "matcha": "^0.7.0", + "nyc": "^11.0.2", + "resolve-from": "^4.0.0", + "typescript": "^2.5.3", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js", + "templates.js", + "types/index.d.ts", + "index.js.flow" + ], + "homepage": "https://github.com/chalk/chalk#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "name": "chalk", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/chalk.git" + }, + "scripts": { + "bench": "matcha benchmark.js", + "coveralls": "nyc report --reporter=text-lcov | coveralls", + "test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava" + }, + "types": "types/index.d.ts", + "version": "2.4.2", + "xo": { + "envs": [ + "node", + "mocha" + ], + "ignores": [ + "test/_flow.js" + ] + } +} diff --git a/node_modules/@babel/highlight/node_modules/chalk/readme.md b/node_modules/@babel/highlight/node_modules/chalk/readme.md new file mode 100644 index 0000000..d298e2c --- /dev/null +++ b/node_modules/@babel/highlight/node_modules/chalk/readme.md @@ -0,0 +1,314 @@ +

+
+
+ Chalk +
+
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs) + +### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0) + + + + +## Highlights + +- Expressive API +- Highly performant +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~23,000 packages](https://www.npmjs.com/browse/depended/chalk) as of December 31, 2017 + + +## Install + +```console +$ npm install chalk +``` + +
+ + + + +## Usage + +```js +const chalk = require('chalk'); + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +const chalk = require('chalk'); +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// ES2015 tagged template literal +log(chalk` +CPU: {red ${cpu.totalPercent}%} +RAM: {green ${ram.used / ram.total * 100}%} +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.keyword('orange')('Yay for orange colored text!')); +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +const chalk = require('chalk'); + +const error = chalk.bold.red; +const warning = chalk.keyword('orange'); + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + + +## API + +### chalk.` or + + `; +} + +function headerTemplate(details) { + function metricsTemplate({ pct, covered, total }, kind) { + return ` +
+ ${pct}% + ${kind} + ${covered}/${total} +
+ `; + } + + function skipTemplate(metrics) { + const statements = metrics.statements.skipped; + const branches = metrics.branches.skipped; + const functions = metrics.functions.skipped; + + const countLabel = (c, label, plural) => + c === 0 ? [] : `${c} ${label}${c === 1 ? '' : plural}`; + const skips = [].concat( + countLabel(statements, 'statement', 's'), + countLabel(functions, 'function', 's'), + countLabel(branches, 'branch', 'es') + ); + + if (skips.length === 0) { + return ''; + } + + return ` +
+ ${skips.join(', ')} + Ignored      +
+ `; + } + + return ` + + +${htmlHead(details)} + +
+
+

${details.pathHtml}

+
+ ${metricsTemplate(details.metrics.statements, 'Statements')} + ${metricsTemplate(details.metrics.branches, 'Branches')} + ${metricsTemplate(details.metrics.functions, 'Functions')} + ${metricsTemplate(details.metrics.lines, 'Lines')} + ${skipTemplate(details.metrics)} +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+ `; +} + +function footerTemplate(details) { + return ` +
+
+ + + + + + + + `; +} + +function detailTemplate(data) { + const lineNumbers = new Array(data.maxLines).fill().map((_, i) => i + 1); + const lineLink = num => + `${num}`; + const lineCount = line => + `${line.hits}`; + + /* This is rendered in a `
`, need control of all whitespace. */
+    return [
+        '',
+        `${lineNumbers
+            .map(lineLink)
+            .join('\n')}`,
+        `${data.lineCoverage
+            .map(lineCount)
+            .join('\n')}`,
+        `
${data.annotatedCode.join(
+            '\n'
+        )}
`, + '' + ].join(''); +} +const summaryTableHeader = [ + '
', + '', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '', + '', + '' +].join('\n'); + +function summaryLineTemplate(details) { + const { reportClasses, metrics, file, output } = details; + const percentGraph = pct => { + if (!isFinite(pct)) { + return ''; + } + + const cls = ['cover-fill']; + if (pct === 100) { + cls.push('cover-full'); + } + + pct = Math.floor(pct); + return [ + `
`, + `
` + ].join(''); + }; + const summaryType = (type, showGraph = false) => { + const info = metrics[type]; + const reportClass = reportClasses[type]; + const result = [ + ``, + `` + ]; + if (showGraph) { + result.unshift( + `` + ); + } + + return result; + }; + + return [] + .concat( + '', + ``, + summaryType('statements', true), + summaryType('branches'), + summaryType('functions'), + summaryType('lines'), + '\n' + ) + .join('\n\t'); +} + +const summaryTableFooter = ['', '
FileStatementsBranchesFunctionsLines
${info.pct}%${info.covered}/${info.total}`, + `
${percentGraph(info.pct)}
`, + `
${html.escape(file)}
', '
'].join('\n'); +const emptyClasses = { + statements: 'empty', + lines: 'empty', + functions: 'empty', + branches: 'empty' +}; + +const standardLinkMapper = { + getPath(node) { + if (typeof node === 'string') { + return node; + } + let filePath = node.getQualifiedName(); + if (node.isSummary()) { + if (filePath !== '') { + filePath += '/index.html'; + } else { + filePath = 'index.html'; + } + } else { + filePath += '.html'; + } + return filePath; + }, + + relativePath(source, target) { + const targetPath = this.getPath(target); + const sourcePath = path.dirname(this.getPath(source)); + return path.posix.relative(sourcePath, targetPath); + }, + + assetPath(node, name) { + return this.relativePath(this.getPath(node), name); + } +}; + +function fixPct(metrics) { + Object.keys(emptyClasses).forEach(key => { + metrics[key].pct = 0; + }); + return metrics; +} + +class HtmlReport extends ReportBase { + constructor(opts) { + super(); + + this.verbose = opts.verbose; + this.linkMapper = opts.linkMapper || standardLinkMapper; + this.subdir = opts.subdir || ''; + this.date = new Date().toISOString(); + this.skipEmpty = opts.skipEmpty; + } + + getBreadcrumbHtml(node) { + let parent = node.getParent(); + const nodePath = []; + + while (parent) { + nodePath.push(parent); + parent = parent.getParent(); + } + + const linkPath = nodePath.map(ancestor => { + const target = this.linkMapper.relativePath(node, ancestor); + const name = ancestor.getRelativeName() || 'All files'; + return '' + name + ''; + }); + + linkPath.reverse(); + return linkPath.length > 0 + ? linkPath.join(' / ') + ' ' + node.getRelativeName() + : 'All files'; + } + + fillTemplate(node, templateData, context) { + const linkMapper = this.linkMapper; + const summary = node.getCoverageSummary(); + templateData.entity = node.getQualifiedName() || 'All files'; + templateData.metrics = summary; + templateData.reportClass = context.classForPercent( + 'statements', + summary.statements.pct + ); + templateData.pathHtml = this.getBreadcrumbHtml(node); + templateData.base = { + css: linkMapper.assetPath(node, 'base.css') + }; + templateData.sorter = { + js: linkMapper.assetPath(node, 'sorter.js'), + image: linkMapper.assetPath(node, 'sort-arrow-sprite.png') + }; + templateData.blockNavigation = { + js: linkMapper.assetPath(node, 'block-navigation.js') + }; + templateData.prettify = { + js: linkMapper.assetPath(node, 'prettify.js'), + css: linkMapper.assetPath(node, 'prettify.css') + }; + templateData.favicon = linkMapper.assetPath(node, 'favicon.png'); + } + + getTemplateData() { + return { datetime: this.date }; + } + + getWriter(context) { + if (!this.subdir) { + return context.writer; + } + return context.writer.writerForDir(this.subdir); + } + + onStart(root, context) { + const assetHeaders = { + '.js': '/* eslint-disable */\n' + }; + + ['.', 'vendor'].forEach(subdir => { + const writer = this.getWriter(context); + const srcDir = path.resolve(__dirname, 'assets', subdir); + fs.readdirSync(srcDir).forEach(f => { + const resolvedSource = path.resolve(srcDir, f); + const resolvedDestination = '.'; + const stat = fs.statSync(resolvedSource); + let dest; + + if (stat.isFile()) { + dest = resolvedDestination + '/' + f; + if (this.verbose) { + console.log('Write asset: ' + dest); + } + writer.copyFile( + resolvedSource, + dest, + assetHeaders[path.extname(f)] + ); + } + }); + }); + } + + onSummary(node, context) { + const linkMapper = this.linkMapper; + const templateData = this.getTemplateData(); + const children = node.getChildren(); + const skipEmpty = this.skipEmpty; + + this.fillTemplate(node, templateData, context); + const cw = this.getWriter(context).writeFile(linkMapper.getPath(node)); + cw.write(headerTemplate(templateData)); + cw.write(summaryTableHeader); + children.forEach(child => { + const metrics = child.getCoverageSummary(); + const isEmpty = metrics.isEmpty(); + if (skipEmpty && isEmpty) { + return; + } + const reportClasses = isEmpty + ? emptyClasses + : { + statements: context.classForPercent( + 'statements', + metrics.statements.pct + ), + lines: context.classForPercent( + 'lines', + metrics.lines.pct + ), + functions: context.classForPercent( + 'functions', + metrics.functions.pct + ), + branches: context.classForPercent( + 'branches', + metrics.branches.pct + ) + }; + const data = { + metrics: isEmpty ? fixPct(metrics) : metrics, + reportClasses, + file: child.getRelativeName(), + output: linkMapper.relativePath(node, child) + }; + cw.write(summaryLineTemplate(data) + '\n'); + }); + cw.write(summaryTableFooter); + cw.write(footerTemplate(templateData)); + cw.close(); + } + + onDetail(node, context) { + const linkMapper = this.linkMapper; + const templateData = this.getTemplateData(); + + this.fillTemplate(node, templateData, context); + const cw = this.getWriter(context).writeFile(linkMapper.getPath(node)); + cw.write(headerTemplate(templateData)); + cw.write('
\n');
+        cw.write(detailTemplate(annotator(node.getFileCoverage(), context)));
+        cw.write('
\n'); + cw.write(footerTemplate(templateData)); + cw.close(); + } +} + +module.exports = HtmlReport; diff --git a/node_modules/istanbul-reports/lib/html/insertion-text.js b/node_modules/istanbul-reports/lib/html/insertion-text.js new file mode 100644 index 0000000..6f80642 --- /dev/null +++ b/node_modules/istanbul-reports/lib/html/insertion-text.js @@ -0,0 +1,114 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +function InsertionText(text, consumeBlanks) { + this.text = text; + this.origLength = text.length; + this.offsets = []; + this.consumeBlanks = consumeBlanks; + this.startPos = this.findFirstNonBlank(); + this.endPos = this.findLastNonBlank(); +} + +const WHITE_RE = /[ \f\n\r\t\v\u00A0\u2028\u2029]/; + +InsertionText.prototype = { + findFirstNonBlank() { + let pos = -1; + const text = this.text; + const len = text.length; + let i; + for (i = 0; i < len; i += 1) { + if (!text.charAt(i).match(WHITE_RE)) { + pos = i; + break; + } + } + return pos; + }, + findLastNonBlank() { + const text = this.text; + const len = text.length; + let pos = text.length + 1; + let i; + for (i = len - 1; i >= 0; i -= 1) { + if (!text.charAt(i).match(WHITE_RE)) { + pos = i; + break; + } + } + return pos; + }, + originalLength() { + return this.origLength; + }, + + insertAt(col, str, insertBefore, consumeBlanks) { + consumeBlanks = + typeof consumeBlanks === 'undefined' + ? this.consumeBlanks + : consumeBlanks; + col = col > this.originalLength() ? this.originalLength() : col; + col = col < 0 ? 0 : col; + + if (consumeBlanks) { + if (col <= this.startPos) { + col = 0; + } + if (col > this.endPos) { + col = this.origLength; + } + } + + const len = str.length; + const offset = this.findOffset(col, len, insertBefore); + const realPos = col + offset; + const text = this.text; + this.text = text.substring(0, realPos) + str + text.substring(realPos); + return this; + }, + + findOffset(pos, len, insertBefore) { + const offsets = this.offsets; + let offsetObj; + let cumulativeOffset = 0; + let i; + + for (i = 0; i < offsets.length; i += 1) { + offsetObj = offsets[i]; + if ( + offsetObj.pos < pos || + (offsetObj.pos === pos && !insertBefore) + ) { + cumulativeOffset += offsetObj.len; + } + if (offsetObj.pos >= pos) { + break; + } + } + if (offsetObj && offsetObj.pos === pos) { + offsetObj.len += len; + } else { + offsets.splice(i, 0, { pos, len }); + } + return cumulativeOffset; + }, + + wrap(startPos, startText, endPos, endText, consumeBlanks) { + this.insertAt(startPos, startText, true, consumeBlanks); + this.insertAt(endPos, endText, false, consumeBlanks); + return this; + }, + + wrapLine(startText, endText) { + this.wrap(0, startText, this.originalLength(), endText); + }, + + toString() { + return this.text; + } +}; + +module.exports = InsertionText; diff --git a/node_modules/istanbul-reports/lib/json-summary/index.js b/node_modules/istanbul-reports/lib/json-summary/index.js new file mode 100644 index 0000000..318a47f --- /dev/null +++ b/node_modules/istanbul-reports/lib/json-summary/index.js @@ -0,0 +1,56 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class JsonSummaryReport extends ReportBase { + constructor(opts) { + super(); + + this.file = opts.file || 'coverage-summary.json'; + this.contentWriter = null; + this.first = true; + } + + onStart(root, context) { + this.contentWriter = context.writer.writeFile(this.file); + this.contentWriter.write('{'); + } + + writeSummary(filePath, sc) { + const cw = this.contentWriter; + if (this.first) { + this.first = false; + } else { + cw.write(','); + } + cw.write(JSON.stringify(filePath)); + cw.write(': '); + cw.write(JSON.stringify(sc)); + cw.println(''); + } + + onSummary(node) { + if (!node.isRoot()) { + return; + } + this.writeSummary('total', node.getCoverageSummary()); + } + + onDetail(node) { + this.writeSummary( + node.getFileCoverage().path, + node.getCoverageSummary() + ); + } + + onEnd() { + const cw = this.contentWriter; + cw.println('}'); + cw.close(); + } +} + +module.exports = JsonSummaryReport; diff --git a/node_modules/istanbul-reports/lib/json/index.js b/node_modules/istanbul-reports/lib/json/index.js new file mode 100644 index 0000000..bcae6ae --- /dev/null +++ b/node_modules/istanbul-reports/lib/json/index.js @@ -0,0 +1,44 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class JsonReport extends ReportBase { + constructor(opts) { + super(); + + this.file = opts.file || 'coverage-final.json'; + this.first = true; + } + + onStart(root, context) { + this.contentWriter = context.writer.writeFile(this.file); + this.contentWriter.write('{'); + } + + onDetail(node) { + const fc = node.getFileCoverage(); + const key = fc.path; + const cw = this.contentWriter; + + if (this.first) { + this.first = false; + } else { + cw.write(','); + } + cw.write(JSON.stringify(key)); + cw.write(': '); + cw.write(JSON.stringify(fc)); + cw.println(''); + } + + onEnd() { + const cw = this.contentWriter; + cw.println('}'); + cw.close(); + } +} + +module.exports = JsonReport; diff --git a/node_modules/istanbul-reports/lib/lcov/index.js b/node_modules/istanbul-reports/lib/lcov/index.js new file mode 100644 index 0000000..383c202 --- /dev/null +++ b/node_modules/istanbul-reports/lib/lcov/index.js @@ -0,0 +1,33 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const { ReportBase } = require('istanbul-lib-report'); +const LcovOnlyReport = require('../lcovonly'); +const HtmlReport = require('../html'); + +class LcovReport extends ReportBase { + constructor(opts) { + super(); + this.lcov = new LcovOnlyReport({ file: 'lcov.info', ...opts }); + this.html = new HtmlReport({ subdir: 'lcov-report' }); + } +} + +['Start', 'End', 'Summary', 'SummaryEnd', 'Detail'].forEach(what => { + const meth = 'on' + what; + LcovReport.prototype[meth] = function(...args) { + const lcov = this.lcov; + const html = this.html; + + if (lcov[meth]) { + lcov[meth](...args); + } + if (html[meth]) { + html[meth](...args); + } + }; +}); + +module.exports = LcovReport; diff --git a/node_modules/istanbul-reports/lib/lcovonly/index.js b/node_modules/istanbul-reports/lib/lcovonly/index.js new file mode 100644 index 0000000..0720e46 --- /dev/null +++ b/node_modules/istanbul-reports/lib/lcovonly/index.js @@ -0,0 +1,77 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class LcovOnlyReport extends ReportBase { + constructor(opts) { + super(); + opts = opts || {}; + this.file = opts.file || 'lcov.info'; + this.projectRoot = opts.projectRoot || process.cwd(); + this.contentWriter = null; + } + + onStart(root, context) { + this.contentWriter = context.writer.writeFile(this.file); + } + + onDetail(node) { + const fc = node.getFileCoverage(); + const writer = this.contentWriter; + const functions = fc.f; + const functionMap = fc.fnMap; + const lines = fc.getLineCoverage(); + const branches = fc.b; + const branchMap = fc.branchMap; + const summary = node.getCoverageSummary(); + const path = require('path'); + + writer.println('TN:'); + const fileName = path.relative(this.projectRoot, fc.path); + writer.println('SF:' + fileName); + + Object.values(functionMap).forEach(meta => { + // Some versions of the instrumenter in the wild populate 'loc' + // but not 'decl': + const decl = meta.decl || meta.loc; + writer.println('FN:' + [decl.start.line, meta.name].join(',')); + }); + writer.println('FNF:' + summary.functions.total); + writer.println('FNH:' + summary.functions.covered); + + Object.entries(functionMap).forEach(([key, meta]) => { + const stats = functions[key]; + writer.println('FNDA:' + [stats, meta.name].join(',')); + }); + + Object.entries(lines).forEach(entry => { + writer.println('DA:' + entry.join(',')); + }); + writer.println('LF:' + summary.lines.total); + writer.println('LH:' + summary.lines.covered); + + Object.entries(branches).forEach(([key, branchArray]) => { + const meta = branchMap[key]; + if (meta) { + const { line } = meta.loc.start; + branchArray.forEach((b, i) => { + writer.println('BRDA:' + [line, key, i, b].join(',')); + }); + } else { + console.warn('Missing coverage entries in', fileName, key); + } + }); + writer.println('BRF:' + summary.branches.total); + writer.println('BRH:' + summary.branches.covered); + writer.println('end_of_record'); + } + + onEnd() { + this.contentWriter.close(); + } +} + +module.exports = LcovOnlyReport; diff --git a/node_modules/istanbul-reports/lib/none/index.js b/node_modules/istanbul-reports/lib/none/index.js new file mode 100644 index 0000000..81c1408 --- /dev/null +++ b/node_modules/istanbul-reports/lib/none/index.js @@ -0,0 +1,10 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const { ReportBase } = require('istanbul-lib-report'); + +class NoneReport extends ReportBase {} + +module.exports = NoneReport; diff --git a/node_modules/istanbul-reports/lib/teamcity/index.js b/node_modules/istanbul-reports/lib/teamcity/index.js new file mode 100644 index 0000000..2bca26a --- /dev/null +++ b/node_modules/istanbul-reports/lib/teamcity/index.js @@ -0,0 +1,67 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class TeamcityReport extends ReportBase { + constructor(opts) { + super(); + + opts = opts || {}; + this.file = opts.file || null; + this.blockName = opts.blockName || 'Code Coverage Summary'; + } + + onStart(node, context) { + const metrics = node.getCoverageSummary(); + const cw = context.writer.writeFile(this.file); + + cw.println(''); + cw.println("##teamcity[blockOpened name='" + this.blockName + "']"); + + //Statements Covered + cw.println( + lineForKey(metrics.statements.covered, 'CodeCoverageAbsBCovered') + ); + cw.println( + lineForKey(metrics.statements.total, 'CodeCoverageAbsBTotal') + ); + + //Branches Covered + cw.println( + lineForKey(metrics.branches.covered, 'CodeCoverageAbsRCovered') + ); + cw.println(lineForKey(metrics.branches.total, 'CodeCoverageAbsRTotal')); + + //Functions Covered + cw.println( + lineForKey(metrics.functions.covered, 'CodeCoverageAbsMCovered') + ); + cw.println( + lineForKey(metrics.functions.total, 'CodeCoverageAbsMTotal') + ); + + //Lines Covered + cw.println( + lineForKey(metrics.lines.covered, 'CodeCoverageAbsLCovered') + ); + cw.println(lineForKey(metrics.lines.total, 'CodeCoverageAbsLTotal')); + + cw.println("##teamcity[blockClosed name='" + this.blockName + "']"); + cw.close(); + } +} + +function lineForKey(value, teamcityVar) { + return ( + "##teamcity[buildStatisticValue key='" + + teamcityVar + + "' value='" + + value + + "']" + ); +} + +module.exports = TeamcityReport; diff --git a/node_modules/istanbul-reports/lib/text-lcov/index.js b/node_modules/istanbul-reports/lib/text-lcov/index.js new file mode 100644 index 0000000..847aedf --- /dev/null +++ b/node_modules/istanbul-reports/lib/text-lcov/index.js @@ -0,0 +1,17 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const LcovOnly = require('../lcovonly'); + +class TextLcov extends LcovOnly { + constructor(opts) { + super({ + ...opts, + file: '-' + }); + } +} + +module.exports = TextLcov; diff --git a/node_modules/istanbul-reports/lib/text-summary/index.js b/node_modules/istanbul-reports/lib/text-summary/index.js new file mode 100644 index 0000000..a9e6eab --- /dev/null +++ b/node_modules/istanbul-reports/lib/text-summary/index.js @@ -0,0 +1,62 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class TextSummaryReport extends ReportBase { + constructor(opts) { + super(); + + opts = opts || {}; + this.file = opts.file || null; + } + + onStart(node, context) { + const summary = node.getCoverageSummary(); + const cw = context.writer.writeFile(this.file); + const printLine = function(key) { + const str = lineForKey(summary, key); + const clazz = context.classForPercent(key, summary[key].pct); + cw.println(cw.colorize(str, clazz)); + }; + + cw.println(''); + cw.println( + '=============================== Coverage summary ===============================' + ); + printLine('statements'); + printLine('branches'); + printLine('functions'); + printLine('lines'); + cw.println( + '================================================================================' + ); + cw.close(); + } +} + +function lineForKey(summary, key) { + const metrics = summary[key]; + + key = key.substring(0, 1).toUpperCase() + key.substring(1); + if (key.length < 12) { + key += ' '.substring(0, 12 - key.length); + } + const result = [ + key, + ':', + metrics.pct + '%', + '(', + metrics.covered + '/' + metrics.total, + ')' + ].join(' '); + const skipped = metrics.skipped; + if (skipped > 0) { + return result + ', ' + skipped + ' ignored'; + } + return result; +} + +module.exports = TextSummaryReport; diff --git a/node_modules/istanbul-reports/lib/text/index.js b/node_modules/istanbul-reports/lib/text/index.js new file mode 100644 index 0000000..c28cedb --- /dev/null +++ b/node_modules/istanbul-reports/lib/text/index.js @@ -0,0 +1,298 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE + file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +const NAME_COL = 4; +const PCT_COLS = 7; +const MISSING_COL = 17; +const TAB_SIZE = 1; +const DELIM = ' | '; + +function padding(num, ch) { + let str = ''; + let i; + ch = ch || ' '; + for (i = 0; i < num; i += 1) { + str += ch; + } + return str; +} + +function fill(str, width, right, tabs) { + tabs = tabs || 0; + str = String(str); + + const leadingSpaces = tabs * TAB_SIZE; + const remaining = width - leadingSpaces; + const leader = padding(leadingSpaces); + let fmtStr = ''; + + if (remaining > 0) { + const strlen = str.length; + let fillStr; + + if (remaining >= strlen) { + fillStr = padding(remaining - strlen); + } else { + fillStr = '...'; + const length = remaining - fillStr.length; + + str = str.substring(strlen - length); + right = true; + } + fmtStr = right ? fillStr + str : str + fillStr; + } + + return leader + fmtStr; +} + +function formatName(name, maxCols, level) { + return fill(name, maxCols, false, level); +} + +function formatPct(pct, width) { + return fill(pct, width || PCT_COLS, true, 0); +} + +function nodeMissing(node) { + if (node.isSummary()) { + return ''; + } + + const metrics = node.getCoverageSummary(); + const isEmpty = metrics.isEmpty(); + const lines = isEmpty ? 0 : metrics.lines.pct; + + let coveredLines; + + const fileCoverage = node.getFileCoverage(); + if (lines === 100) { + const branches = fileCoverage.getBranchCoverageByLine(); + coveredLines = Object.entries(branches).map(([key, { coverage }]) => [ + key, + coverage === 100 + ]); + } else { + coveredLines = Object.entries(fileCoverage.getLineCoverage()); + } + + let newRange = true; + const ranges = coveredLines + .reduce((acum, [line, hit]) => { + if (hit) newRange = true; + else { + line = parseInt(line); + if (newRange) { + acum.push([line]); + newRange = false; + } else acum[acum.length - 1][1] = line; + } + + return acum; + }, []) + .map(range => { + const { length } = range; + + if (length === 1) return range[0]; + + return `${range[0]}-${range[1]}`; + }); + + return [].concat(...ranges).join(','); +} + +function nodeName(node) { + return node.getRelativeName() || 'All files'; +} + +function depthFor(node) { + let ret = 0; + node = node.getParent(); + while (node) { + ret += 1; + node = node.getParent(); + } + return ret; +} + +function nullDepthFor() { + return 0; +} + +function findWidth(node, context, nodeExtractor, depthFor = nullDepthFor) { + let last = 0; + function compareWidth(node) { + last = Math.max( + last, + TAB_SIZE * depthFor(node) + nodeExtractor(node).length + ); + } + const visitor = { + onSummary: compareWidth, + onDetail: compareWidth + }; + node.visit(context.getVisitor(visitor)); + return last; +} + +function makeLine(nameWidth, missingWidth) { + const name = padding(nameWidth, '-'); + const pct = padding(PCT_COLS, '-'); + const elements = []; + + elements.push(name); + elements.push(pct); + elements.push(padding(PCT_COLS + 1, '-')); + elements.push(pct); + elements.push(pct); + elements.push(padding(missingWidth, '-')); + return elements.join(DELIM.replace(/ /g, '-')) + '-'; +} + +function tableHeader(maxNameCols, missingWidth) { + const elements = []; + elements.push(formatName('File', maxNameCols, 0)); + elements.push(formatPct('% Stmts')); + elements.push(formatPct('% Branch', PCT_COLS + 1)); + elements.push(formatPct('% Funcs')); + elements.push(formatPct('% Lines')); + elements.push(formatName('Uncovered Line #s', missingWidth)); + return elements.join(DELIM) + ' '; +} + +function isFull(metrics) { + return ( + metrics.statements.pct === 100 && + metrics.branches.pct === 100 && + metrics.functions.pct === 100 && + metrics.lines.pct === 100 + ); +} + +function tableRow( + node, + context, + colorizer, + maxNameCols, + level, + skipEmpty, + skipFull, + missingWidth +) { + const name = nodeName(node); + const metrics = node.getCoverageSummary(); + const isEmpty = metrics.isEmpty(); + if (skipEmpty && isEmpty) { + return ''; + } + if (skipFull && isFull(metrics)) { + return ''; + } + + const mm = { + statements: isEmpty ? 0 : metrics.statements.pct, + branches: isEmpty ? 0 : metrics.branches.pct, + functions: isEmpty ? 0 : metrics.functions.pct, + lines: isEmpty ? 0 : metrics.lines.pct + }; + const colorize = isEmpty + ? function(str) { + return str; + } + : function(str, key) { + return colorizer(str, context.classForPercent(key, mm[key])); + }; + const elements = []; + + elements.push(colorize(formatName(name, maxNameCols, level), 'statements')); + elements.push(colorize(formatPct(mm.statements), 'statements')); + elements.push(colorize(formatPct(mm.branches, PCT_COLS + 1), 'branches')); + elements.push(colorize(formatPct(mm.functions), 'functions')); + elements.push(colorize(formatPct(mm.lines), 'lines')); + elements.push( + colorizer( + formatName(nodeMissing(node), missingWidth), + mm.lines === 100 ? 'medium' : 'low' + ) + ); + + return elements.join(DELIM) + ' '; +} + +class TextReport extends ReportBase { + constructor(opts) { + super(opts); + + opts = opts || {}; + const { maxCols } = opts; + + this.file = opts.file || null; + this.maxCols = maxCols != null ? maxCols : process.stdout.columns || 80; + this.cw = null; + this.skipEmpty = opts.skipEmpty; + this.skipFull = opts.skipFull; + } + + onStart(root, context) { + this.cw = context.writer.writeFile(this.file); + this.nameWidth = Math.max( + NAME_COL, + findWidth(root, context, nodeName, depthFor) + ); + this.missingWidth = Math.max( + MISSING_COL, + findWidth(root, context, nodeMissing) + ); + + if (this.maxCols > 0) { + const pct_cols = DELIM.length + 4 * (PCT_COLS + DELIM.length) + 2; + + const maxRemaining = this.maxCols - (pct_cols + MISSING_COL); + if (this.nameWidth > maxRemaining) { + this.nameWidth = maxRemaining; + this.missingWidth = MISSING_COL; + } else if (this.nameWidth < maxRemaining) { + const maxRemaining = this.maxCols - (this.nameWidth + pct_cols); + if (this.missingWidth > maxRemaining) { + this.missingWidth = maxRemaining; + } + } + } + const line = makeLine(this.nameWidth, this.missingWidth); + this.cw.println(line); + this.cw.println(tableHeader(this.nameWidth, this.missingWidth)); + this.cw.println(line); + } + + onSummary(node, context) { + const nodeDepth = depthFor(node); + const row = tableRow( + node, + context, + this.cw.colorize.bind(this.cw), + this.nameWidth, + nodeDepth, + this.skipEmpty, + this.skipFull, + this.missingWidth + ); + if (row) { + this.cw.println(row); + } + } + + onDetail(node, context) { + return this.onSummary(node, context); + } + + onEnd() { + this.cw.println(makeLine(this.nameWidth, this.missingWidth)); + this.cw.close(); + } +} + +module.exports = TextReport; diff --git a/node_modules/istanbul-reports/package.json b/node_modules/istanbul-reports/package.json new file mode 100644 index 0000000..45008ac --- /dev/null +++ b/node_modules/istanbul-reports/package.json @@ -0,0 +1,88 @@ +{ + "_from": "istanbul-reports@^3.1.3", + "_id": "istanbul-reports@3.1.5", + "_inBundle": false, + "_integrity": "sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==", + "_location": "/istanbul-reports", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "istanbul-reports@^3.1.3", + "name": "istanbul-reports", + "escapedName": "istanbul-reports", + "rawSpec": "^3.1.3", + "saveSpec": null, + "fetchSpec": "^3.1.3" + }, + "_requiredBy": [ + "/@jest/reporters" + ], + "_resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.5.tgz", + "_shasum": "cc9a6ab25cb25659810e4785ed9d9fb742578bae", + "_spec": "istanbul-reports@^3.1.3", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/reporters", + "author": { + "name": "Krishnan Anantheswaran", + "email": "kananthmail-github@yahoo.com" + }, + "bugs": { + "url": "https://github.com/istanbuljs/istanbuljs/issues" + }, + "bundleDependencies": false, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "deprecated": false, + "description": "istanbul reports", + "devDependencies": { + "@babel/core": "^7.7.5", + "@babel/preset-env": "^7.7.5", + "@babel/preset-react": "^7.7.4", + "babel-loader": "^8.0.6", + "chai": "^4.2.0", + "is-windows": "^1.0.2", + "istanbul-lib-coverage": "^3.0.0", + "mocha": "^6.2.2", + "nyc": "^15.0.0-beta.2", + "react": "^16.12.0", + "react-dom": "^16.12.0", + "webpack": "^4.41.2", + "webpack-cli": "^3.3.10" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://istanbul.js.org/", + "keywords": [ + "istanbul", + "reports" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "name": "istanbul-reports", + "nyc": { + "exclude": [ + "lib/html/assets/**", + "lib/html-spa/assets/**", + "lib/html-spa/rollup.config.js", + "test/**" + ] + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git", + "directory": "packages/istanbul-reports" + }, + "scripts": { + "prepare": "webpack --config lib/html-spa/webpack.config.js --mode production", + "prepare:watch": "webpack --config lib/html-spa/webpack.config.js --watch --mode development", + "test": "nyc mocha --recursive" + }, + "version": "3.1.5" +} diff --git a/node_modules/jest-changed-files/LICENSE b/node_modules/jest-changed-files/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-changed-files/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-changed-files/README.md b/node_modules/jest-changed-files/README.md new file mode 100644 index 0000000..d0c8539 --- /dev/null +++ b/node_modules/jest-changed-files/README.md @@ -0,0 +1,63 @@ +# jest-changed-files + +A module used internally by Jest to check which files have changed since you last committed in git or hg. + +## Install + +```sh +$ npm install --save jest-changed-files +``` + +## API + +### `getChangedFilesForRoots(roots: >, options: ?object): Promise` + +Get the list of files and repos that have changed since the last commit. + +#### Parameters + +roots: Array of string paths gathered from [jest roots](https://jestjs.io/docs/configuration#roots-arraystring). + +options: Object literal with keys + +- lastCommit: boolean +- withAncestor: boolean + +### findRepos(roots: >): Promise + +Get a set of git and hg repositories. + +#### Parameters + +roots: Array of string paths gathered from [jest roots](https://jestjs.io/docs/configuration#roots-arraystring). + +## Usage + +```javascript +import {getChangedFilesForRoots} from 'jest-changed-files'; + +getChangedFilesForRoots(['/path/to/test'], { + lastCommit: true, + withAncestor: true, +}).then(files => { + /* + { + repos: [], + changedFiles: [] + } + */ +}); +``` + +```javascript +import {findRepos} from 'jest-changed-files'; + +findRepos(['/path/to/test']).then(repos => { + /* + { + git: Set, + hg: Set + } + */ +}); +``` diff --git a/node_modules/jest-changed-files/build/git.d.ts b/node_modules/jest-changed-files/build/git.d.ts new file mode 100644 index 0000000..498733b --- /dev/null +++ b/node_modules/jest-changed-files/build/git.d.ts @@ -0,0 +1,10 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +import type { SCMAdapter } from './types'; +declare const adapter: SCMAdapter; +export default adapter; diff --git a/node_modules/jest-changed-files/build/git.js b/node_modules/jest-changed-files/build/git.js new file mode 100644 index 0000000..01005d0 --- /dev/null +++ b/node_modules/jest-changed-files/build/git.js @@ -0,0 +1,174 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _execa() { + const data = _interopRequireDefault(require('execa')); + + _execa = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const findChangedFilesUsingCommand = async (args, cwd) => { + let result; + + try { + result = await (0, _execa().default)('git', args, { + cwd + }); + } catch (e) { + // TODO: Should we keep the original `message`? + e.message = e.stderr; + throw e; + } + + return result.stdout + .split('\n') + .filter(s => s !== '') + .map(changedPath => path().resolve(cwd, changedPath)); +}; + +const adapter = { + findChangedFiles: async (cwd, options) => { + const changedSince = options.withAncestor ? 'HEAD^' : options.changedSince; + const includePaths = (options.includePaths ?? []).map(absoluteRoot => + path().normalize(path().relative(cwd, absoluteRoot)) + ); + + if (options.lastCommit) { + return findChangedFilesUsingCommand( + ['show', '--name-only', '--pretty=format:', 'HEAD', '--'].concat( + includePaths + ), + cwd + ); + } + + if (changedSince) { + const [committed, staged, unstaged] = await Promise.all([ + findChangedFilesUsingCommand( + ['diff', '--name-only', `${changedSince}...HEAD`, '--'].concat( + includePaths + ), + cwd + ), + findChangedFilesUsingCommand( + ['diff', '--cached', '--name-only', '--'].concat(includePaths), + cwd + ), + findChangedFilesUsingCommand( + [ + 'ls-files', + '--other', + '--modified', + '--exclude-standard', + '--' + ].concat(includePaths), + cwd + ) + ]); + return [...committed, ...staged, ...unstaged]; + } + + const [staged, unstaged] = await Promise.all([ + findChangedFilesUsingCommand( + ['diff', '--cached', '--name-only', '--'].concat(includePaths), + cwd + ), + findChangedFilesUsingCommand( + [ + 'ls-files', + '--other', + '--modified', + '--exclude-standard', + '--' + ].concat(includePaths), + cwd + ) + ]); + return [...staged, ...unstaged]; + }, + getRoot: async cwd => { + const options = ['rev-parse', '--show-cdup']; + + try { + const result = await (0, _execa().default)('git', options, { + cwd + }); + return path().resolve(cwd, result.stdout); + } catch { + return null; + } + } +}; +var _default = adapter; +exports.default = _default; diff --git a/node_modules/jest-changed-files/build/hg.d.ts b/node_modules/jest-changed-files/build/hg.d.ts new file mode 100644 index 0000000..498733b --- /dev/null +++ b/node_modules/jest-changed-files/build/hg.d.ts @@ -0,0 +1,10 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +import type { SCMAdapter } from './types'; +declare const adapter: SCMAdapter; +export default adapter; diff --git a/node_modules/jest-changed-files/build/hg.js b/node_modules/jest-changed-files/build/hg.js new file mode 100644 index 0000000..8ee624b --- /dev/null +++ b/node_modules/jest-changed-files/build/hg.js @@ -0,0 +1,127 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _execa() { + const data = _interopRequireDefault(require('execa')); + + _execa = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const env = {...process.env, HGPLAIN: '1'}; +const adapter = { + findChangedFiles: async (cwd, options) => { + const includePaths = options.includePaths ?? []; + const args = ['status', '-amnu']; + + if (options.withAncestor) { + args.push('--rev', 'first(min(!public() & ::.)^+.^)'); + } else if (options.changedSince) { + args.push('--rev', `ancestor(., ${options.changedSince})`); + } else if (options.lastCommit === true) { + args.push('--change', '.'); + } + + args.push(...includePaths); + let result; + + try { + result = await (0, _execa().default)('hg', args, { + cwd, + env + }); + } catch (e) { + // TODO: Should we keep the original `message`? + e.message = e.stderr; + throw e; + } + + return result.stdout + .split('\n') + .filter(s => s !== '') + .map(changedPath => path().resolve(cwd, changedPath)); + }, + getRoot: async cwd => { + try { + const result = await (0, _execa().default)('hg', ['root'], { + cwd, + env + }); + return result.stdout; + } catch { + return null; + } + } +}; +var _default = adapter; +exports.default = _default; diff --git a/node_modules/jest-changed-files/build/index.d.ts b/node_modules/jest-changed-files/build/index.d.ts new file mode 100644 index 0000000..9dc1e76 --- /dev/null +++ b/node_modules/jest-changed-files/build/index.d.ts @@ -0,0 +1,35 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare type ChangedFiles = { + repos: Repos; + changedFiles: Paths; +}; + +export declare type ChangedFilesPromise = Promise; + +export declare const findRepos: (roots: Array) => Promise; + +export declare const getChangedFilesForRoots: ( + roots: Array, + options: Options, +) => ChangedFilesPromise; + +declare type Options = { + lastCommit?: boolean; + withAncestor?: boolean; + changedSince?: string; + includePaths?: Array; +}; + +declare type Paths = Set; + +declare type Repos = { + git: Paths; + hg: Paths; +}; + +export {}; diff --git a/node_modules/jest-changed-files/build/index.js b/node_modules/jest-changed-files/build/index.js new file mode 100644 index 0000000..8c81c00 --- /dev/null +++ b/node_modules/jest-changed-files/build/index.js @@ -0,0 +1,86 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getChangedFilesForRoots = exports.findRepos = void 0; + +function _pLimit() { + const data = _interopRequireDefault(require('p-limit')); + + _pLimit = function () { + return data; + }; + + return data; +} + +var _git = _interopRequireDefault(require('./git')); + +var _hg = _interopRequireDefault(require('./hg')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +function notEmpty(value) { + return value != null; +} // This is an arbitrary number. The main goal is to prevent projects with +// many roots (50+) from spawning too many processes at once. + +const mutex = (0, _pLimit().default)(5); + +const findGitRoot = dir => mutex(() => _git.default.getRoot(dir)); + +const findHgRoot = dir => mutex(() => _hg.default.getRoot(dir)); + +const getChangedFilesForRoots = async (roots, options) => { + const repos = await findRepos(roots); + const changedFilesOptions = { + includePaths: roots, + ...options + }; + const gitPromises = Array.from(repos.git).map(repo => + _git.default.findChangedFiles(repo, changedFilesOptions) + ); + const hgPromises = Array.from(repos.hg).map(repo => + _hg.default.findChangedFiles(repo, changedFilesOptions) + ); + const changedFiles = ( + await Promise.all(gitPromises.concat(hgPromises)) + ).reduce((allFiles, changedFilesInTheRepo) => { + for (const file of changedFilesInTheRepo) { + allFiles.add(file); + } + + return allFiles; + }, new Set()); + return { + changedFiles, + repos + }; +}; + +exports.getChangedFilesForRoots = getChangedFilesForRoots; + +const findRepos = async roots => { + const gitRepos = await Promise.all( + roots.reduce((promises, root) => promises.concat(findGitRoot(root)), []) + ); + const hgRepos = await Promise.all( + roots.reduce((promises, root) => promises.concat(findHgRoot(root)), []) + ); + return { + git: new Set(gitRepos.filter(notEmpty)), + hg: new Set(hgRepos.filter(notEmpty)) + }; +}; + +exports.findRepos = findRepos; diff --git a/node_modules/jest-changed-files/build/types.d.ts b/node_modules/jest-changed-files/build/types.d.ts new file mode 100644 index 0000000..fc290d4 --- /dev/null +++ b/node_modules/jest-changed-files/build/types.d.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare type Options = { + lastCommit?: boolean; + withAncestor?: boolean; + changedSince?: string; + includePaths?: Array; +}; +declare type Paths = Set; +export declare type Repos = { + git: Paths; + hg: Paths; +}; +export declare type ChangedFiles = { + repos: Repos; + changedFiles: Paths; +}; +export declare type ChangedFilesPromise = Promise; +export declare type SCMAdapter = { + findChangedFiles: (cwd: string, options: Options) => Promise>; + getRoot: (cwd: string) => Promise; +}; +export {}; diff --git a/node_modules/jest-changed-files/build/types.js b/node_modules/jest-changed-files/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-changed-files/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-changed-files/node_modules/p-limit/index.d.ts b/node_modules/jest-changed-files/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..f348d7f --- /dev/null +++ b/node_modules/jest-changed-files/node_modules/p-limit/index.d.ts @@ -0,0 +1,42 @@ +declare namespace pLimit { + interface Limit { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + } +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +declare function pLimit(concurrency: number): pLimit.Limit; + +export = pLimit; diff --git a/node_modules/jest-changed-files/node_modules/p-limit/index.js b/node_modules/jest-changed-files/node_modules/p-limit/index.js new file mode 100644 index 0000000..c2ae52d --- /dev/null +++ b/node_modules/jest-changed-files/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +'use strict'; +const Queue = require('yocto-queue'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +module.exports = pLimit; diff --git a/node_modules/jest-changed-files/node_modules/p-limit/license b/node_modules/jest-changed-files/node_modules/p-limit/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/jest-changed-files/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jest-changed-files/node_modules/p-limit/package.json b/node_modules/jest-changed-files/node_modules/p-limit/package.json new file mode 100644 index 0000000..14fe4a4 --- /dev/null +++ b/node_modules/jest-changed-files/node_modules/p-limit/package.json @@ -0,0 +1,84 @@ +{ + "_from": "p-limit@^3.1.0", + "_id": "p-limit@3.1.0", + "_inBundle": false, + "_integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "_location": "/jest-changed-files/p-limit", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "p-limit@^3.1.0", + "name": "p-limit", + "escapedName": "p-limit", + "rawSpec": "^3.1.0", + "saveSpec": null, + "fetchSpec": "^3.1.0" + }, + "_requiredBy": [ + "/jest-changed-files" + ], + "_resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "_shasum": "e1daccbe78d0d1388ca18c64fea38e3e57e3706b", + "_spec": "p-limit@^3.1.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-changed-files", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/p-limit/issues" + }, + "bundleDependencies": false, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "deprecated": false, + "description": "Run multiple promise-returning & async functions with limited concurrency", + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.4.0", + "in-range": "^2.0.0", + "random-int": "^2.0.1", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/p-limit#readme", + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "license": "MIT", + "name": "p-limit", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/p-limit.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "3.1.0" +} diff --git a/node_modules/jest-changed-files/node_modules/p-limit/readme.md b/node_modules/jest-changed-files/node_modules/p-limit/readme.md new file mode 100644 index 0000000..b283c1e --- /dev/null +++ b/node_modules/jest-changed-files/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/jest-changed-files/package.json b/node_modules/jest-changed-files/package.json new file mode 100644 index 0000000..bac67b8 --- /dev/null +++ b/node_modules/jest-changed-files/package.json @@ -0,0 +1,62 @@ +{ + "_from": "jest-changed-files@^29.0.0", + "_id": "jest-changed-files@29.0.0", + "_inBundle": false, + "_integrity": "sha512-28/iDMDrUpGoCitTURuDqUzWQoWmOmOKOFST1mi2lwh62X4BFf6khgH3uSuo1e49X/UDjuApAj3w0wLOex4VPQ==", + "_location": "/jest-changed-files", + "_phantomChildren": { + "yocto-queue": "0.1.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-changed-files@^29.0.0", + "name": "jest-changed-files", + "escapedName": "jest-changed-files", + "rawSpec": "^29.0.0", + "saveSpec": null, + "fetchSpec": "^29.0.0" + }, + "_requiredBy": [ + "/@jest/core" + ], + "_resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.0.0.tgz", + "_shasum": "aa238eae42d9372a413dd9a8dadc91ca1806dce0", + "_spec": "jest-changed-files@^29.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "execa": "^5.0.0", + "p-limit": "^3.1.0" + }, + "deprecated": false, + "description": "A module used internally by Jest to check which files have changed since you last committed in git or hg.", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "75006e46c76f6fda14bbc0548f86edb2ba087cd2", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-changed-files", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-changed-files" + }, + "types": "./build/index.d.ts", + "version": "29.0.0" +} diff --git a/node_modules/jest-circus/LICENSE b/node_modules/jest-circus/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-circus/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-circus/README.md b/node_modules/jest-circus/README.md new file mode 100644 index 0000000..67305ed --- /dev/null +++ b/node_modules/jest-circus/README.md @@ -0,0 +1,65 @@ +[type-definitions]: https://github.com/facebook/jest/blob/main/packages/jest-types/src/Circus.ts + +

+ + +

jest-circus

+

The next-gen test runner for Jest

+

+ +## Overview + +Circus is a flux-based test runner for Jest that is fast, maintainable, and simple to extend. + +Circus allows you to bind to events via an optional event handler on any [custom environment](https://jestjs.io/docs/configuration#testenvironment-string). See the [type definitions][type-definitions] for more information on the events and state data currently available. + +```js +import {Event, State} from 'jest-circus'; +import NodeEnvironment from 'jest-environment-node'; + +class MyCustomEnvironment extends NodeEnvironment { + //... + + async handleTestEvent(event: Event, state: State) { + if (event.name === 'test_start') { + // ... + } + } +} +``` + +Mutating event or state data is currently unsupported and may cause unexpected behavior or break in a future release without warning. New events, event data, and/or state data will not be considered a breaking change and may be added in any minor release. + +Note, that `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled. **However, there are a few events that do not conform to this rule, namely**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions][type-definitions]). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. + +## Installation + +> Note: As of Jest 27, `jest-circus` is the default test runner, so you do not have to install it to use it. + +Install `jest-circus` using yarn: + +```bash +yarn add --dev jest-circus +``` + +Or via npm: + +```bash +npm install --save-dev jest-circus +``` + +## Configure + +Configure Jest to use `jest-circus` via the [`testRunner`](https://jestjs.io/docs/configuration#testrunner-string) option: + +```json +{ + "testRunner": "jest-circus/runner" +} +``` + +Or via CLI: + +```bash +jest --testRunner='jest-circus/runner' +``` diff --git a/node_modules/jest-circus/build/eventHandler.js b/node_modules/jest-circus/build/eventHandler.js new file mode 100644 index 0000000..235003c --- /dev/null +++ b/node_modules/jest-circus/build/eventHandler.js @@ -0,0 +1,314 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _globalErrorHandlers = require('./globalErrorHandlers'); + +var _types = require('./types'); + +var _utils = require('./utils'); + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestNow = globalThis[Symbol.for('jest-native-now')] || globalThis.Date.now; + +const eventHandler = (event, state) => { + switch (event.name) { + case 'include_test_location_in_result': { + state.includeTestLocationInResult = true; + break; + } + + case 'hook_start': { + event.hook.seenDone = false; + break; + } + + case 'start_describe_definition': { + const {blockName, mode} = event; + const {currentDescribeBlock, currentlyRunningTest} = state; + + if (currentlyRunningTest) { + currentlyRunningTest.errors.push( + new Error( + `Cannot nest a describe inside a test. Describe block "${blockName}" cannot run because it is nested within "${currentlyRunningTest.name}".` + ) + ); + break; + } + + const describeBlock = (0, _utils.makeDescribe)( + blockName, + currentDescribeBlock, + mode + ); + currentDescribeBlock.children.push(describeBlock); + state.currentDescribeBlock = describeBlock; + break; + } + + case 'finish_describe_definition': { + const {currentDescribeBlock} = state; + (0, _utils.invariant)( + currentDescribeBlock, + 'currentDescribeBlock must be there' + ); + + if (!(0, _utils.describeBlockHasTests)(currentDescribeBlock)) { + currentDescribeBlock.hooks.forEach(hook => { + hook.asyncError.message = `Invalid: ${hook.type}() may not be used in a describe block containing no tests.`; + state.unhandledErrors.push(hook.asyncError); + }); + } // pass mode of currentDescribeBlock to tests + // but do not when there is already a single test with "only" mode + + const shouldPassMode = !( + currentDescribeBlock.mode === 'only' && + currentDescribeBlock.children.some( + child => child.type === 'test' && child.mode === 'only' + ) + ); + + if (shouldPassMode) { + currentDescribeBlock.children.forEach(child => { + if (child.type === 'test' && !child.mode) { + child.mode = currentDescribeBlock.mode; + } + }); + } + + if ( + !state.hasFocusedTests && + currentDescribeBlock.mode !== 'skip' && + currentDescribeBlock.children.some( + child => child.type === 'test' && child.mode === 'only' + ) + ) { + state.hasFocusedTests = true; + } + + if (currentDescribeBlock.parent) { + state.currentDescribeBlock = currentDescribeBlock.parent; + } + + break; + } + + case 'add_hook': { + const {currentDescribeBlock, currentlyRunningTest, hasStarted} = state; + const {asyncError, fn, hookType: type, timeout} = event; + + if (currentlyRunningTest) { + currentlyRunningTest.errors.push( + new Error( + `Hooks cannot be defined inside tests. Hook of type "${type}" is nested within "${currentlyRunningTest.name}".` + ) + ); + break; + } else if (hasStarted) { + state.unhandledErrors.push( + new Error( + 'Cannot add a hook after tests have started running. Hooks must be defined synchronously.' + ) + ); + break; + } + + const parent = currentDescribeBlock; + currentDescribeBlock.hooks.push({ + asyncError, + fn, + parent, + seenDone: false, + timeout, + type + }); + break; + } + + case 'add_test': { + const {currentDescribeBlock, currentlyRunningTest, hasStarted} = state; + const { + asyncError, + fn, + mode, + testName: name, + timeout, + concurrent, + failing + } = event; + + if (currentlyRunningTest) { + currentlyRunningTest.errors.push( + new Error( + `Tests cannot be nested. Test "${name}" cannot run because it is nested within "${currentlyRunningTest.name}".` + ) + ); + break; + } else if (hasStarted) { + state.unhandledErrors.push( + new Error( + 'Cannot add a test after tests have started running. Tests must be defined synchronously.' + ) + ); + break; + } + + const test = (0, _utils.makeTest)( + fn, + mode, + concurrent, + name, + currentDescribeBlock, + timeout, + asyncError, + failing + ); + + if (currentDescribeBlock.mode !== 'skip' && test.mode === 'only') { + state.hasFocusedTests = true; + } + + currentDescribeBlock.children.push(test); + currentDescribeBlock.tests.push(test); + break; + } + + case 'hook_failure': { + const {test, describeBlock, error, hook} = event; + const {asyncError, type} = hook; + + if (type === 'beforeAll') { + (0, _utils.invariant)(describeBlock, 'always present for `*All` hooks'); + (0, _utils.addErrorToEachTestUnderDescribe)( + describeBlock, + error, + asyncError + ); + } else if (type === 'afterAll') { + // Attaching `afterAll` errors to each test makes execution flow + // too complicated, so we'll consider them to be global. + state.unhandledErrors.push([error, asyncError]); + } else { + (0, _utils.invariant)(test, 'always present for `*Each` hooks'); + test.errors.push([error, asyncError]); + } + + break; + } + + case 'test_skip': { + event.test.status = 'skip'; + break; + } + + case 'test_todo': { + event.test.status = 'todo'; + break; + } + + case 'test_done': { + event.test.duration = (0, _utils.getTestDuration)(event.test); + event.test.status = 'done'; + state.currentlyRunningTest = null; + break; + } + + case 'test_start': { + state.currentlyRunningTest = event.test; + event.test.startedAt = jestNow(); + event.test.invocations += 1; + break; + } + + case 'test_fn_start': { + event.test.seenDone = false; + break; + } + + case 'test_fn_failure': { + const { + error, + test: {asyncError} + } = event; + event.test.errors.push([error, asyncError]); + break; + } + + case 'test_retry': { + const logErrorsBeforeRetry = // eslint-disable-next-line no-restricted-globals + global[_types.LOG_ERRORS_BEFORE_RETRY] || false; + + if (logErrorsBeforeRetry) { + event.test.retryReasons.push(...event.test.errors); + } + + event.test.errors = []; + break; + } + + case 'run_start': { + state.hasStarted = true; + /* eslint-disable no-restricted-globals */ + + global[_types.TEST_TIMEOUT_SYMBOL] && + (state.testTimeout = global[_types.TEST_TIMEOUT_SYMBOL]); + /* eslint-enable */ + + break; + } + + case 'run_finish': { + break; + } + + case 'setup': { + // Uncaught exception handlers should be defined on the parent process + // object. If defined on the VM's process object they just no op and let + // the parent process crash. It might make sense to return a `dispatch` + // function to the parent process and register handlers there instead, but + // i'm not sure if this is works. For now i just replicated whatever + // jasmine was doing -- dabramov + state.parentProcess = event.parentProcess; + (0, _utils.invariant)(state.parentProcess); + state.originalGlobalErrorHandlers = (0, + _globalErrorHandlers.injectGlobalErrorHandlers)(state.parentProcess); + + if (event.testNamePattern) { + state.testNamePattern = new RegExp(event.testNamePattern, 'i'); + } + + break; + } + + case 'teardown': { + (0, _utils.invariant)(state.originalGlobalErrorHandlers); + (0, _utils.invariant)(state.parentProcess); + (0, _globalErrorHandlers.restoreGlobalErrorHandlers)( + state.parentProcess, + state.originalGlobalErrorHandlers + ); + break; + } + + case 'error': { + // It's very likely for long-running async tests to throw errors. In this + // case we want to catch them and fail the current test. At the same time + // there's a possibility that one test sets a long timeout, that will + // eventually throw after this test finishes but during some other test + // execution, which will result in one test's error failing another test. + // In any way, it should be possible to track where the error was thrown + // from. + state.currentlyRunningTest + ? state.currentlyRunningTest.errors.push(event.error) + : state.unhandledErrors.push(event.error); + break; + } + } +}; + +var _default = eventHandler; +exports.default = _default; diff --git a/node_modules/jest-circus/build/formatNodeAssertErrors.js b/node_modules/jest-circus/build/formatNodeAssertErrors.js new file mode 100644 index 0000000..2fd3af2 --- /dev/null +++ b/node_modules/jest-circus/build/formatNodeAssertErrors.js @@ -0,0 +1,202 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _assert = require('assert'); + +var _chalk = _interopRequireDefault(require('chalk')); + +var _jestMatcherUtils = require('jest-matcher-utils'); + +var _prettyFormat = require('pretty-format'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const assertOperatorsMap = { + '!=': 'notEqual', + '!==': 'notStrictEqual', + '==': 'equal', + '===': 'strictEqual' +}; +const humanReadableOperators = { + deepEqual: 'to deeply equal', + deepStrictEqual: 'to deeply and strictly equal', + equal: 'to be equal', + notDeepEqual: 'not to deeply equal', + notDeepStrictEqual: 'not to deeply and strictly equal', + notEqual: 'to not be equal', + notStrictEqual: 'not be strictly equal', + strictEqual: 'to strictly be equal' +}; + +const formatNodeAssertErrors = (event, state) => { + if (event.name === 'test_done') { + event.test.errors = event.test.errors.map(errors => { + let error; + + if (Array.isArray(errors)) { + const [originalError, asyncError] = errors; + + if (originalError == null) { + error = asyncError; + } else if (!originalError.stack) { + error = asyncError; + error.message = originalError.message + ? originalError.message + : `thrown: ${(0, _prettyFormat.format)(originalError, { + maxDepth: 3 + })}`; + } else { + error = originalError; + } + } else { + error = errors; + } + + return isAssertionError(error) + ? { + message: assertionErrorMessage(error, { + expand: state.expand + }) + } + : errors; + }); + } +}; + +const getOperatorName = (operator, stack) => { + if (typeof operator === 'string') { + return assertOperatorsMap[operator] || operator; + } + + if (stack.match('.doesNotThrow')) { + return 'doesNotThrow'; + } + + if (stack.match('.throws')) { + return 'throws'; + } + + return ''; +}; + +const operatorMessage = operator => { + const niceOperatorName = getOperatorName(operator, ''); + const humanReadableOperator = humanReadableOperators[niceOperatorName]; + return typeof operator === 'string' + ? `${humanReadableOperator || niceOperatorName} to:\n` + : ''; +}; + +const assertThrowingMatcherHint = operatorName => + operatorName + ? _chalk.default.dim('assert') + + _chalk.default.dim(`.${operatorName}(`) + + _chalk.default.red('function') + + _chalk.default.dim(')') + : ''; + +const assertMatcherHint = (operator, operatorName, expected) => { + let message = ''; + + if (operator === '==' && expected === true) { + message = + _chalk.default.dim('assert') + + _chalk.default.dim('(') + + _chalk.default.red('received') + + _chalk.default.dim(')'); + } else if (operatorName) { + message = + _chalk.default.dim('assert') + + _chalk.default.dim(`.${operatorName}(`) + + _chalk.default.red('received') + + _chalk.default.dim(', ') + + _chalk.default.green('expected') + + _chalk.default.dim(')'); + } + + return message; +}; + +function assertionErrorMessage(error, options) { + const {expected, actual, generatedMessage, message, operator, stack} = error; + const diffString = (0, _jestMatcherUtils.diff)(expected, actual, options); + const hasCustomMessage = !generatedMessage; + const operatorName = getOperatorName(operator, stack); + const trimmedStack = stack + .replace(message, '') + .replace(/AssertionError(.*)/g, ''); + + if (operatorName === 'doesNotThrow') { + return ( + // eslint-disable-next-line prefer-template + buildHintString(assertThrowingMatcherHint(operatorName)) + + _chalk.default.reset('Expected the function not to throw an error.\n') + + _chalk.default.reset('Instead, it threw:\n') + + ` ${(0, _jestMatcherUtils.printReceived)(actual)}` + + _chalk.default.reset( + hasCustomMessage ? `\n\nMessage:\n ${message}` : '' + ) + + trimmedStack + ); + } + + if (operatorName === 'throws') { + return ( + buildHintString(assertThrowingMatcherHint(operatorName)) + + _chalk.default.reset('Expected the function to throw an error.\n') + + _chalk.default.reset("But it didn't throw anything.") + + _chalk.default.reset( + hasCustomMessage ? `\n\nMessage:\n ${message}` : '' + ) + + trimmedStack + ); + } + + if (operatorName === 'fail') { + return ( + buildHintString(assertMatcherHint(operator, operatorName, expected)) + + _chalk.default.reset(hasCustomMessage ? `Message:\n ${message}` : '') + + trimmedStack + ); + } + + return ( + // eslint-disable-next-line prefer-template + buildHintString(assertMatcherHint(operator, operatorName, expected)) + + _chalk.default.reset(`Expected value ${operatorMessage(operator)}`) + + ` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + + _chalk.default.reset('Received:\n') + + ` ${(0, _jestMatcherUtils.printReceived)(actual)}` + + _chalk.default.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + + trimmedStack + ); +} + +function isAssertionError(error) { + return ( + error && + (error instanceof _assert.AssertionError || + error.name === _assert.AssertionError.name || + error.code === 'ERR_ASSERTION') + ); +} + +function buildHintString(hint) { + return hint ? `${hint}\n\n` : ''; +} + +var _default = formatNodeAssertErrors; +exports.default = _default; diff --git a/node_modules/jest-circus/build/globalErrorHandlers.js b/node_modules/jest-circus/build/globalErrorHandlers.js new file mode 100644 index 0000000..bc889f3 --- /dev/null +++ b/node_modules/jest-circus/build/globalErrorHandlers.js @@ -0,0 +1,51 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.restoreGlobalErrorHandlers = exports.injectGlobalErrorHandlers = void 0; + +var _state = require('./state'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const uncaught = error => { + (0, _state.dispatchSync)({ + error, + name: 'error' + }); +}; + +const injectGlobalErrorHandlers = parentProcess => { + const uncaughtException = process.listeners('uncaughtException').slice(); + const unhandledRejection = process.listeners('unhandledRejection').slice(); + parentProcess.removeAllListeners('uncaughtException'); + parentProcess.removeAllListeners('unhandledRejection'); + parentProcess.on('uncaughtException', uncaught); + parentProcess.on('unhandledRejection', uncaught); + return { + uncaughtException, + unhandledRejection + }; +}; + +exports.injectGlobalErrorHandlers = injectGlobalErrorHandlers; + +const restoreGlobalErrorHandlers = (parentProcess, originalErrorHandlers) => { + parentProcess.removeListener('uncaughtException', uncaught); + parentProcess.removeListener('unhandledRejection', uncaught); + + for (const listener of originalErrorHandlers.uncaughtException) { + parentProcess.on('uncaughtException', listener); + } + + for (const listener of originalErrorHandlers.unhandledRejection) { + parentProcess.on('unhandledRejection', listener); + } +}; + +exports.restoreGlobalErrorHandlers = restoreGlobalErrorHandlers; diff --git a/node_modules/jest-circus/build/index.d.ts b/node_modules/jest-circus/build/index.d.ts new file mode 100644 index 0000000..adab032 --- /dev/null +++ b/node_modules/jest-circus/build/index.d.ts @@ -0,0 +1,121 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Circus} from '@jest/types'; +import type {Global} from '@jest/types'; + +declare const afterAll_2: THook; +export {afterAll_2 as afterAll}; + +declare const afterEach_2: THook; +export {afterEach_2 as afterEach}; + +declare const beforeAll_2: THook; +export {beforeAll_2 as beforeAll}; + +declare const beforeEach_2: THook; +export {beforeEach_2 as beforeEach}; + +declare const _default: { + afterAll: THook; + afterEach: THook; + beforeAll: THook; + beforeEach: THook; + describe: { + (blockName: Global.BlockNameLike, blockFn: Global.BlockFn): void; + each: ( + table: Global.EachTable, + ...taggedTemplateData: Global.TemplateData + ) => ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: { + (blockName: Global.BlockNameLike, blockFn: Global.BlockFn): void; + each: ( + table: Global.EachTable, + ...taggedTemplateData: Global.TemplateData + ) => ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + skip: { + (blockName: Global.BlockNameLike, blockFn: Global.BlockFn): void; + each: ( + table: Global.EachTable, + ...taggedTemplateData: Global.TemplateData + ) => ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + }; + it: Global.It; + test: Global.It; +}; +export default _default; + +declare const describe_2: { + (blockName: Circus.BlockNameLike, blockFn: Circus.BlockFn): void; + each: ( + table: Global.EachTable, + ...taggedTemplateData: Global.TemplateData + ) => ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: { + (blockName: Circus.BlockNameLike, blockFn: Circus.BlockFn): void; + each: ( + table: Global.EachTable, + ...taggedTemplateData: Global.TemplateData + ) => ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + skip: { + (blockName: Circus.BlockNameLike, blockFn: Circus.BlockFn): void; + each: ( + table: Global.EachTable, + ...taggedTemplateData: Global.TemplateData + ) => ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; +}; +export {describe_2 as describe}; + +declare type Event_2 = Circus.Event; +export {Event_2 as Event}; + +export declare const getState: () => Circus.State; + +declare const it_2: Global.It; +export {it_2 as it}; + +export declare const resetState: () => void; + +export declare const run: () => Promise; + +export declare const setState: (state: Circus.State) => Circus.State; + +export declare type State = Circus.State; + +declare const test_2: Global.It; +export {test_2 as test}; + +declare type THook = (fn: Circus.HookFn, timeout?: number) => void; + +export {}; diff --git a/node_modules/jest-circus/build/index.js b/node_modules/jest-circus/build/index.js new file mode 100644 index 0000000..c6f0097 --- /dev/null +++ b/node_modules/jest-circus/build/index.js @@ -0,0 +1,269 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.describe = + exports.default = + exports.beforeEach = + exports.beforeAll = + exports.afterEach = + exports.afterAll = + void 0; +Object.defineProperty(exports, 'getState', { + enumerable: true, + get: function () { + return _state.getState; + } +}); +exports.it = void 0; +Object.defineProperty(exports, 'resetState', { + enumerable: true, + get: function () { + return _state.resetState; + } +}); +Object.defineProperty(exports, 'run', { + enumerable: true, + get: function () { + return _run.default; + } +}); +Object.defineProperty(exports, 'setState', { + enumerable: true, + get: function () { + return _state.setState; + } +}); +exports.test = void 0; + +var _jestEach = require('jest-each'); + +var _jestUtil = require('jest-util'); + +var _state = require('./state'); + +var _run = _interopRequireDefault(require('./run')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const describe = (() => { + const describe = (blockName, blockFn) => + _dispatchDescribe(blockFn, blockName, describe); + + const only = (blockName, blockFn) => + _dispatchDescribe(blockFn, blockName, only, 'only'); + + const skip = (blockName, blockFn) => + _dispatchDescribe(blockFn, blockName, skip, 'skip'); + + describe.each = (0, _jestEach.bind)(describe, false); + only.each = (0, _jestEach.bind)(only, false); + skip.each = (0, _jestEach.bind)(skip, false); + describe.only = only; + describe.skip = skip; + return describe; +})(); + +exports.describe = describe; + +const _dispatchDescribe = (blockFn, blockName, describeFn, mode) => { + const asyncError = new _jestUtil.ErrorWithStack(undefined, describeFn); + + if (blockFn === undefined) { + asyncError.message = + 'Missing second argument. It must be a callback function.'; + throw asyncError; + } + + if (typeof blockFn !== 'function') { + asyncError.message = `Invalid second argument, ${blockFn}. It must be a callback function.`; + throw asyncError; + } + + try { + blockName = (0, _jestUtil.convertDescriptorToString)(blockName); + } catch (error) { + asyncError.message = error.message; + throw asyncError; + } + + (0, _state.dispatchSync)({ + asyncError, + blockName, + mode, + name: 'start_describe_definition' + }); + const describeReturn = blockFn(); + + if ((0, _jestUtil.isPromise)(describeReturn)) { + throw new _jestUtil.ErrorWithStack( + 'Returning a Promise from "describe" is not supported. Tests must be defined synchronously.', + describeFn + ); + } else if (describeReturn !== undefined) { + throw new _jestUtil.ErrorWithStack( + 'A "describe" callback must not return a value.', + describeFn + ); + } + + (0, _state.dispatchSync)({ + blockName, + mode, + name: 'finish_describe_definition' + }); +}; + +const _addHook = (fn, hookType, hookFn, timeout) => { + const asyncError = new _jestUtil.ErrorWithStack(undefined, hookFn); + + if (typeof fn !== 'function') { + asyncError.message = + 'Invalid first argument. It must be a callback function.'; + throw asyncError; + } + + (0, _state.dispatchSync)({ + asyncError, + fn, + hookType, + name: 'add_hook', + timeout + }); +}; // Hooks have to pass themselves to the HOF in order for us to trim stack traces. + +const beforeEach = (fn, timeout) => + _addHook(fn, 'beforeEach', beforeEach, timeout); + +exports.beforeEach = beforeEach; + +const beforeAll = (fn, timeout) => + _addHook(fn, 'beforeAll', beforeAll, timeout); + +exports.beforeAll = beforeAll; + +const afterEach = (fn, timeout) => + _addHook(fn, 'afterEach', afterEach, timeout); + +exports.afterEach = afterEach; + +const afterAll = (fn, timeout) => _addHook(fn, 'afterAll', afterAll, timeout); + +exports.afterAll = afterAll; + +const test = (() => { + const test = (testName, fn, timeout) => + _addTest(testName, undefined, false, fn, test, timeout); + + const skip = (testName, fn, timeout) => + _addTest(testName, 'skip', false, fn, skip, timeout); + + const only = (testName, fn, timeout) => + _addTest(testName, 'only', false, fn, test.only, timeout); + + const concurrentTest = (testName, fn, timeout) => + _addTest(testName, undefined, true, fn, concurrentTest, timeout); + + const concurrentOnly = (testName, fn, timeout) => + _addTest(testName, 'only', true, fn, concurrentOnly, timeout); + + const bindFailing = (concurrent, mode) => { + const failing = (testName, fn, timeout) => + _addTest(testName, mode, concurrent, fn, failing, timeout, true); + + failing.each = (0, _jestEach.bind)(failing, false); + return failing; + }; + + test.todo = (testName, ...rest) => { + if (rest.length > 0 || typeof testName !== 'string') { + throw new _jestUtil.ErrorWithStack( + 'Todo must be called with only a description.', + test.todo + ); + } // eslint-disable-next-line @typescript-eslint/no-empty-function + + return _addTest(testName, 'todo', false, () => {}, test.todo); + }; + + const _addTest = ( + testName, + mode, + concurrent, + fn, + testFn, + timeout, + failing + ) => { + const asyncError = new _jestUtil.ErrorWithStack(undefined, testFn); + + try { + testName = (0, _jestUtil.convertDescriptorToString)(testName); + } catch (error) { + asyncError.message = error.message; + throw asyncError; + } + + if (fn === undefined) { + asyncError.message = + 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.'; + throw asyncError; + } + + if (typeof fn !== 'function') { + asyncError.message = `Invalid second argument, ${fn}. It must be a callback function.`; + throw asyncError; + } + + return (0, _state.dispatchSync)({ + asyncError, + concurrent, + failing: failing === undefined ? false : failing, + fn, + mode, + name: 'add_test', + testName, + timeout + }); + }; + + test.each = (0, _jestEach.bind)(test); + only.each = (0, _jestEach.bind)(only); + skip.each = (0, _jestEach.bind)(skip); + concurrentTest.each = (0, _jestEach.bind)(concurrentTest, false); + concurrentOnly.each = (0, _jestEach.bind)(concurrentOnly, false); + only.failing = bindFailing(false, 'only'); + skip.failing = bindFailing(false, 'skip'); + test.failing = bindFailing(false); + test.only = only; + test.skip = skip; + test.concurrent = concurrentTest; + concurrentTest.only = concurrentOnly; + concurrentTest.skip = skip; + concurrentTest.failing = bindFailing(true); + concurrentOnly.failing = bindFailing(true, 'only'); + return test; +})(); + +exports.test = test; +const it = test; +exports.it = it; +var _default = { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + it, + test +}; +exports.default = _default; diff --git a/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js new file mode 100644 index 0000000..97c3972 --- /dev/null +++ b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js @@ -0,0 +1,134 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _jestUtil = require('jest-util'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit'); + +const jestAdapter = async ( + globalConfig, + config, + environment, + runtime, + testPath, + sendMessageToJest +) => { + const {initialize, runAndTransformResultsToJestFormat} = + runtime.requireInternalModule(FRAMEWORK_INITIALIZER); + const {globals, snapshotState} = await initialize({ + config, + environment, + globalConfig, + localRequire: runtime.requireModule.bind(runtime), + parentProcess: process, + sendMessageToJest, + setGlobalsForRuntime: runtime.setGlobalsForRuntime.bind(runtime), + testPath + }); + + if (config.fakeTimers.enableGlobally) { + if (config.fakeTimers.legacyFakeTimers) { + // during setup, this cannot be null (and it's fine to explode if it is) + environment.fakeTimers.useFakeTimers(); + } else { + environment.fakeTimersModern.useFakeTimers(); + } + } + + globals.beforeEach(() => { + if (config.resetModules) { + runtime.resetModules(); + } + + if (config.clearMocks) { + runtime.clearAllMocks(); + } + + if (config.resetMocks) { + runtime.resetAllMocks(); + + if ( + config.fakeTimers.enableGlobally && + config.fakeTimers.legacyFakeTimers + ) { + // during setup, this cannot be null (and it's fine to explode if it is) + environment.fakeTimers.useFakeTimers(); + } + } + + if (config.restoreMocks) { + runtime.restoreAllMocks(); + } + }); + + for (const path of config.setupFilesAfterEnv) { + const esm = runtime.unstable_shouldLoadAsEsm(path); + + if (esm) { + await runtime.unstable_importModule(path); + } else { + runtime.requireModule(path); + } + } + + const esm = runtime.unstable_shouldLoadAsEsm(testPath); + + if (esm) { + await runtime.unstable_importModule(testPath); + } else { + runtime.requireModule(testPath); + } + + const results = await runAndTransformResultsToJestFormat({ + config, + globalConfig, + testPath + }); + + _addSnapshotData(results, snapshotState); // We need to copy the results object to ensure we don't leaks the prototypes + // from the VM. Jasmine creates the result objects in the parent process, we + // should consider doing that for circus as well. + + return (0, _jestUtil.deepCyclicCopy)(results, { + keepPrototype: false + }); +}; + +const _addSnapshotData = (results, snapshotState) => { + results.testResults.forEach(({fullName, status}) => { + if (status === 'pending' || status === 'failed') { + // if test is skipped or failed, we don't want to mark + // its snapshots as obsolete. + snapshotState.markSnapshotsAsCheckedForTest(fullName); + } + }); + const uncheckedCount = snapshotState.getUncheckedCount(); + const uncheckedKeys = snapshotState.getUncheckedKeys(); + + if (uncheckedCount) { + snapshotState.removeUncheckedKeys(); + } + + const status = snapshotState.save(); + results.snapshot.fileDeleted = status.deleted; + results.snapshot.added = snapshotState.added; + results.snapshot.matched = snapshotState.matched; + results.snapshot.unmatched = snapshotState.unmatched; + results.snapshot.updated = snapshotState.updated; + results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0; // Copy the array to prevent memory leaks + + results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); +}; + +var _default = jestAdapter; +exports.default = _default; diff --git a/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js new file mode 100644 index 0000000..412eb88 --- /dev/null +++ b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js @@ -0,0 +1,266 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.runAndTransformResultsToJestFormat = exports.initialize = void 0; + +var _expect = require('@jest/expect'); + +var _testResult = require('@jest/test-result'); + +var _jestMessageUtil = require('jest-message-util'); + +var _jestSnapshot = require('jest-snapshot'); + +var _ = _interopRequireDefault(require('..')); + +var _run = _interopRequireDefault(require('../run')); + +var _state = require('../state'); + +var _testCaseReportHandler = _interopRequireDefault( + require('../testCaseReportHandler') +); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const initialize = async ({ + config, + environment, + globalConfig, + localRequire, + parentProcess, + sendMessageToJest, + setGlobalsForRuntime, + testPath +}) => { + if (globalConfig.testTimeout) { + (0, _state.getState)().testTimeout = globalConfig.testTimeout; + } + + (0, _state.getState)().maxConcurrency = globalConfig.maxConcurrency; // @ts-expect-error: missing `concurrent` which is added later + + const globalsObject = { + ..._.default, + fdescribe: _.default.describe.only, + fit: _.default.it.only, + xdescribe: _.default.describe.skip, + xit: _.default.it.skip, + xtest: _.default.it.skip + }; + (0, _state.addEventHandler)(eventHandler); + + if (environment.handleTestEvent) { + (0, _state.addEventHandler)(environment.handleTestEvent.bind(environment)); + } + + _expect.jestExpect.setState({ + expand: globalConfig.expand + }); + + const runtimeGlobals = {...globalsObject, expect: _expect.jestExpect}; + setGlobalsForRuntime(runtimeGlobals); + + if (config.injectGlobals) { + Object.assign(environment.global, runtimeGlobals); + } + + await (0, _state.dispatch)({ + name: 'setup', + parentProcess, + runtimeGlobals, + testNamePattern: globalConfig.testNamePattern + }); + + if (config.testLocationInResults) { + await (0, _state.dispatch)({ + name: 'include_test_location_in_result' + }); + } // Jest tests snapshotSerializers in order preceding built-in serializers. + // Therefore, add in reverse because the last added is the first tested. + + config.snapshotSerializers + .concat() + .reverse() + .forEach(path => (0, _jestSnapshot.addSerializer)(localRequire(path))); + const snapshotResolver = await (0, _jestSnapshot.buildSnapshotResolver)( + config, + localRequire + ); + const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath); + const snapshotState = new _jestSnapshot.SnapshotState(snapshotPath, { + expand: globalConfig.expand, + prettierPath: config.prettierPath, + rootDir: config.rootDir, + snapshotFormat: config.snapshotFormat, + updateSnapshot: globalConfig.updateSnapshot + }); + + _expect.jestExpect.setState({ + snapshotState, + testPath + }); + + (0, _state.addEventHandler)(handleSnapshotStateAfterRetry(snapshotState)); + + if (sendMessageToJest) { + (0, _state.addEventHandler)( + (0, _testCaseReportHandler.default)(testPath, sendMessageToJest) + ); + } // Return it back to the outer scope (test runner outside the VM). + + return { + globals: globalsObject, + snapshotState + }; +}; + +exports.initialize = initialize; + +const runAndTransformResultsToJestFormat = async ({ + config, + globalConfig, + testPath +}) => { + const runResult = await (0, _run.default)(); + let numFailingTests = 0; + let numPassingTests = 0; + let numPendingTests = 0; + let numTodoTests = 0; + const assertionResults = runResult.testResults.map(testResult => { + let status; + + if (testResult.status === 'skip') { + status = 'pending'; + numPendingTests += 1; + } else if (testResult.status === 'todo') { + status = 'todo'; + numTodoTests += 1; + } else if (testResult.errors.length) { + status = 'failed'; + numFailingTests += 1; + } else { + status = 'passed'; + numPassingTests += 1; + } + + const ancestorTitles = testResult.testPath.filter( + name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME + ); + const title = ancestorTitles.pop(); + return { + ancestorTitles, + duration: testResult.duration, + failureDetails: testResult.errorsDetailed, + failureMessages: testResult.errors, + fullName: title + ? ancestorTitles.concat(title).join(' ') + : ancestorTitles.join(' '), + invocations: testResult.invocations, + location: testResult.location, + numPassingAsserts: 0, + retryReasons: testResult.retryReasons, + status, + title: testResult.testPath[testResult.testPath.length - 1] + }; + }); + let failureMessage = (0, _jestMessageUtil.formatResultsErrors)( + assertionResults, + config, + globalConfig, + testPath + ); + let testExecError; + + if (runResult.unhandledErrors.length) { + testExecError = { + message: '', + stack: runResult.unhandledErrors.join('\n') + }; + failureMessage = `${failureMessage || ''}\n\n${runResult.unhandledErrors + .map(err => + (0, _jestMessageUtil.formatExecError)(err, config, globalConfig) + ) + .join('\n')}`; + } + + await (0, _state.dispatch)({ + name: 'teardown' + }); + return { + ...(0, _testResult.createEmptyTestResult)(), + console: undefined, + displayName: config.displayName, + failureMessage, + numFailingTests, + numPassingTests, + numPendingTests, + numTodoTests, + testExecError, + testFilePath: testPath, + testResults: assertionResults + }; +}; + +exports.runAndTransformResultsToJestFormat = runAndTransformResultsToJestFormat; + +const handleSnapshotStateAfterRetry = snapshotState => event => { + switch (event.name) { + case 'test_retry': { + // Clear any snapshot data that occurred in previous test run + snapshotState.clear(); + } + } +}; + +const eventHandler = async event => { + switch (event.name) { + case 'test_start': { + _expect.jestExpect.setState({ + currentTestName: (0, _utils.getTestID)(event.test) + }); + + break; + } + + case 'test_done': { + _addSuppressedErrors(event.test); + + _addExpectedAssertionErrors(event.test); + + break; + } + } +}; + +const _addExpectedAssertionErrors = test => { + const failures = _expect.jestExpect.extractExpectedAssertionsErrors(); + + const errors = failures.map(failure => failure.error); + test.errors = test.errors.concat(errors); +}; // Get suppressed errors from ``jest-matchers`` that weren't throw during +// test execution and add them to the test result, potentially failing +// a passing test. + +const _addSuppressedErrors = test => { + const {suppressedErrors} = _expect.jestExpect.getState(); + + _expect.jestExpect.setState({ + suppressedErrors: [] + }); + + if (suppressedErrors.length) { + test.errors = test.errors.concat(suppressedErrors); + } +}; diff --git a/node_modules/jest-circus/build/run.js b/node_modules/jest-circus/build/run.js new file mode 100644 index 0000000..3031e36 --- /dev/null +++ b/node_modules/jest-circus/build/run.js @@ -0,0 +1,313 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _pLimit = _interopRequireDefault(require('p-limit')); + +var _state = require('./state'); + +var _types = require('./types'); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const run = async () => { + const {rootDescribeBlock} = (0, _state.getState)(); + await (0, _state.dispatch)({ + name: 'run_start' + }); + await _runTestsForDescribeBlock(rootDescribeBlock, true); + await (0, _state.dispatch)({ + name: 'run_finish' + }); + return (0, _utils.makeRunResult)( + (0, _state.getState)().rootDescribeBlock, + (0, _state.getState)().unhandledErrors + ); +}; + +const _runTestsForDescribeBlock = async ( + describeBlock, + isRootBlock = false +) => { + await (0, _state.dispatch)({ + describeBlock, + name: 'run_describe_start' + }); + const {beforeAll, afterAll} = (0, _utils.getAllHooksForDescribe)( + describeBlock + ); + const isSkipped = describeBlock.mode === 'skip'; + + if (!isSkipped) { + for (const hook of beforeAll) { + await _callCircusHook({ + describeBlock, + hook + }); + } + } + + if (isRootBlock) { + const concurrentTests = collectConcurrentTests(describeBlock); + const mutex = (0, _pLimit.default)((0, _state.getState)().maxConcurrency); + + for (const test of concurrentTests) { + try { + const promise = mutex(test.fn); // Avoid triggering the uncaught promise rejection handler in case the + // test errors before being awaited on. + // eslint-disable-next-line @typescript-eslint/no-empty-function + + promise.catch(() => {}); + + test.fn = () => promise; + } catch (err) { + test.fn = () => { + throw err; + }; + } + } + } // Tests that fail and are retried we run after other tests + // eslint-disable-next-line no-restricted-globals + + const retryTimes = parseInt(global[_types.RETRY_TIMES], 10) || 0; + const deferredRetryTests = []; + + for (const child of describeBlock.children) { + switch (child.type) { + case 'describeBlock': { + await _runTestsForDescribeBlock(child); + break; + } + + case 'test': { + const hasErrorsBeforeTestRun = child.errors.length > 0; + await _runTest(child, isSkipped); + + if ( + hasErrorsBeforeTestRun === false && + retryTimes > 0 && + child.errors.length > 0 + ) { + deferredRetryTests.push(child); + } + + break; + } + } + } // Re-run failed tests n-times if configured + + for (const test of deferredRetryTests) { + let numRetriesAvailable = retryTimes; + + while (numRetriesAvailable > 0 && test.errors.length > 0) { + // Clear errors so retries occur + await (0, _state.dispatch)({ + name: 'test_retry', + test + }); + await _runTest(test, isSkipped); + numRetriesAvailable--; + } + } + + if (!isSkipped) { + for (const hook of afterAll) { + await _callCircusHook({ + describeBlock, + hook + }); + } + } + + await (0, _state.dispatch)({ + describeBlock, + name: 'run_describe_finish' + }); +}; + +function collectConcurrentTests(describeBlock) { + if (describeBlock.mode === 'skip') { + return []; + } + + const {hasFocusedTests, testNamePattern} = (0, _state.getState)(); + return describeBlock.children.flatMap(child => { + switch (child.type) { + case 'describeBlock': + return collectConcurrentTests(child); + + case 'test': + const skip = + !child.concurrent || + child.mode === 'skip' || + (hasFocusedTests && child.mode !== 'only') || + (testNamePattern && + !testNamePattern.test((0, _utils.getTestID)(child))); + return skip ? [] : [child]; + } + }); +} + +const _runTest = async (test, parentSkipped) => { + await (0, _state.dispatch)({ + name: 'test_start', + test + }); + const testContext = Object.create(null); + const {hasFocusedTests, testNamePattern} = (0, _state.getState)(); + const isSkipped = + parentSkipped || + test.mode === 'skip' || + (hasFocusedTests && test.mode !== 'only') || + (testNamePattern && !testNamePattern.test((0, _utils.getTestID)(test))); + + if (isSkipped) { + await (0, _state.dispatch)({ + name: 'test_skip', + test + }); + return; + } + + if (test.mode === 'todo') { + await (0, _state.dispatch)({ + name: 'test_todo', + test + }); + return; + } + + const {afterEach, beforeEach} = (0, _utils.getEachHooksForTest)(test); + + for (const hook of beforeEach) { + if (test.errors.length) { + // If any of the before hooks failed already, we don't run any + // hooks after that. + break; + } + + await _callCircusHook({ + hook, + test, + testContext + }); + } + + await _callCircusTest(test, testContext); + + for (const hook of afterEach) { + await _callCircusHook({ + hook, + test, + testContext + }); + } // `afterAll` hooks should not affect test status (pass or fail), because if + // we had a global `afterAll` hook it would block all existing tests until + // this hook is executed. So we dispatch `test_done` right away. + + await (0, _state.dispatch)({ + name: 'test_done', + test + }); +}; + +const _callCircusHook = async ({ + hook, + test, + describeBlock, + testContext = {} +}) => { + await (0, _state.dispatch)({ + hook, + name: 'hook_start' + }); + const timeout = hook.timeout || (0, _state.getState)().testTimeout; + + try { + await (0, _utils.callAsyncCircusFn)(hook, testContext, { + isHook: true, + timeout + }); + await (0, _state.dispatch)({ + describeBlock, + hook, + name: 'hook_success', + test + }); + } catch (error) { + await (0, _state.dispatch)({ + describeBlock, + error, + hook, + name: 'hook_failure', + test + }); + } +}; + +const _callCircusTest = async (test, testContext) => { + await (0, _state.dispatch)({ + name: 'test_fn_start', + test + }); + const timeout = test.timeout || (0, _state.getState)().testTimeout; + (0, _utils.invariant)( + test.fn, + "Tests with no 'fn' should have 'mode' set to 'skipped'" + ); + + if (test.errors.length) { + return; // We don't run the test if there's already an error in before hooks. + } + + try { + await (0, _utils.callAsyncCircusFn)(test, testContext, { + isHook: false, + timeout + }); + + if (test.failing) { + test.asyncError.message = + 'Failing test passed even though it was supposed to fail. Remove `.failing` to remove error.'; + await (0, _state.dispatch)({ + error: test.asyncError, + name: 'test_fn_failure', + test + }); + } else { + await (0, _state.dispatch)({ + name: 'test_fn_success', + test + }); + } + } catch (error) { + if (test.failing) { + await (0, _state.dispatch)({ + name: 'test_fn_success', + test + }); + } else { + await (0, _state.dispatch)({ + error, + name: 'test_fn_failure', + test + }); + } + } +}; + +var _default = run; +exports.default = _default; diff --git a/node_modules/jest-circus/build/state.js b/node_modules/jest-circus/build/state.js new file mode 100644 index 0000000..528b774 --- /dev/null +++ b/node_modules/jest-circus/build/state.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.setState = + exports.resetState = + exports.getState = + exports.dispatchSync = + exports.dispatch = + exports.addEventHandler = + exports.ROOT_DESCRIBE_BLOCK_NAME = + void 0; + +var _eventHandler = _interopRequireDefault(require('./eventHandler')); + +var _formatNodeAssertErrors = _interopRequireDefault( + require('./formatNodeAssertErrors') +); + +var _types = require('./types'); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const eventHandlers = [_eventHandler.default, _formatNodeAssertErrors.default]; +const ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK'; +exports.ROOT_DESCRIBE_BLOCK_NAME = ROOT_DESCRIBE_BLOCK_NAME; + +const createState = () => { + const ROOT_DESCRIBE_BLOCK = (0, _utils.makeDescribe)( + ROOT_DESCRIBE_BLOCK_NAME + ); + return { + currentDescribeBlock: ROOT_DESCRIBE_BLOCK, + currentlyRunningTest: null, + expand: undefined, + hasFocusedTests: false, + hasStarted: false, + includeTestLocationInResult: false, + maxConcurrency: 5, + parentProcess: null, + rootDescribeBlock: ROOT_DESCRIBE_BLOCK, + testNamePattern: null, + testTimeout: 5000, + unhandledErrors: [] + }; +}; +/* eslint-disable no-restricted-globals */ + +const resetState = () => { + global[_types.STATE_SYM] = createState(); +}; + +exports.resetState = resetState; +resetState(); + +const getState = () => global[_types.STATE_SYM]; + +exports.getState = getState; + +const setState = state => (global[_types.STATE_SYM] = state); +/* eslint-enable */ + +exports.setState = setState; + +const dispatch = async event => { + for (const handler of eventHandlers) { + await handler(event, getState()); + } +}; + +exports.dispatch = dispatch; + +const dispatchSync = event => { + for (const handler of eventHandlers) { + handler(event, getState()); + } +}; + +exports.dispatchSync = dispatchSync; + +const addEventHandler = handler => { + eventHandlers.push(handler); +}; + +exports.addEventHandler = addEventHandler; diff --git a/node_modules/jest-circus/build/testCaseReportHandler.js b/node_modules/jest-circus/build/testCaseReportHandler.js new file mode 100644 index 0000000..4c8beb1 --- /dev/null +++ b/node_modules/jest-circus/build/testCaseReportHandler.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _utils = require('./utils'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const testCaseReportHandler = (testPath, sendMessageToJest) => event => { + switch (event.name) { + case 'test_done': { + const testResult = (0, _utils.makeSingleTestResult)(event.test); + const testCaseResult = (0, _utils.parseSingleTestResult)(testResult); + sendMessageToJest('test-case-result', [testPath, testCaseResult]); + break; + } + } +}; + +var _default = testCaseReportHandler; +exports.default = _default; diff --git a/node_modules/jest-circus/build/types.js b/node_modules/jest-circus/build/types.js new file mode 100644 index 0000000..70116de --- /dev/null +++ b/node_modules/jest-circus/build/types.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.TEST_TIMEOUT_SYMBOL = + exports.STATE_SYM = + exports.RETRY_TIMES = + exports.LOG_ERRORS_BEFORE_RETRY = + void 0; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const STATE_SYM = Symbol('JEST_STATE_SYMBOL'); +exports.STATE_SYM = STATE_SYM; +const RETRY_TIMES = Symbol.for('RETRY_TIMES'); // To pass this value from Runtime object to state we need to use global[sym] + +exports.RETRY_TIMES = RETRY_TIMES; +const TEST_TIMEOUT_SYMBOL = Symbol.for('TEST_TIMEOUT_SYMBOL'); +exports.TEST_TIMEOUT_SYMBOL = TEST_TIMEOUT_SYMBOL; +const LOG_ERRORS_BEFORE_RETRY = Symbol.for('LOG_ERRORS_BEFORE_RETRY'); +exports.LOG_ERRORS_BEFORE_RETRY = LOG_ERRORS_BEFORE_RETRY; diff --git a/node_modules/jest-circus/build/utils.js b/node_modules/jest-circus/build/utils.js new file mode 100644 index 0000000..9a54c57 --- /dev/null +++ b/node_modules/jest-circus/build/utils.js @@ -0,0 +1,563 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getTestID = + exports.getTestDuration = + exports.getEachHooksForTest = + exports.getAllHooksForDescribe = + exports.describeBlockHasTests = + exports.callAsyncCircusFn = + exports.addErrorToEachTestUnderDescribe = + void 0; +exports.invariant = invariant; +exports.parseSingleTestResult = + exports.makeTest = + exports.makeSingleTestResult = + exports.makeRunResult = + exports.makeDescribe = + void 0; + +var path = _interopRequireWildcard(require('path')); + +var _co = _interopRequireDefault(require('co')); + +var _dedent = _interopRequireDefault(require('dedent')); + +var _isGeneratorFn = _interopRequireDefault(require('is-generator-fn')); + +var _slash = _interopRequireDefault(require('slash')); + +var _stackUtils = _interopRequireDefault(require('stack-utils')); + +var _jestUtil = require('jest-util'); + +var _prettyFormat = require('pretty-format'); + +var _state = require('./state'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestNow = globalThis[Symbol.for('jest-native-now')] || globalThis.Date.now; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Promise = + globalThis[Symbol.for('jest-native-promise')] || globalThis.Promise; +const stackUtils = new _stackUtils.default({ + cwd: 'A path that does not exist' +}); +const jestEachBuildDir = (0, _slash.default)( + path.dirname(require.resolve('jest-each')) +); + +function takesDoneCallback(fn) { + return fn.length > 0; +} + +function isGeneratorFunction(fn) { + return (0, _isGeneratorFn.default)(fn); +} + +const makeDescribe = (name, parent, mode) => { + let _mode = mode; + + if (parent && !mode) { + // If not set explicitly, inherit from the parent describe. + _mode = parent.mode; + } + + return { + type: 'describeBlock', + // eslint-disable-next-line sort-keys + children: [], + hooks: [], + mode: _mode, + name: (0, _jestUtil.convertDescriptorToString)(name), + parent, + tests: [] + }; +}; + +exports.makeDescribe = makeDescribe; + +const makeTest = ( + fn, + mode, + concurrent, + name, + parent, + timeout, + asyncError, + failing +) => ({ + type: 'test', + // eslint-disable-next-line sort-keys + asyncError, + concurrent, + duration: null, + errors: [], + failing, + fn, + invocations: 0, + mode, + name: (0, _jestUtil.convertDescriptorToString)(name), + parent, + retryReasons: [], + seenDone: false, + startedAt: null, + status: null, + timeout +}); // Traverse the tree of describe blocks and return true if at least one describe +// block has an enabled test. + +exports.makeTest = makeTest; + +const hasEnabledTest = describeBlock => { + const {hasFocusedTests, testNamePattern} = (0, _state.getState)(); + return describeBlock.children.some(child => + child.type === 'describeBlock' + ? hasEnabledTest(child) + : !( + child.mode === 'skip' || + (hasFocusedTests && child.mode !== 'only') || + (testNamePattern && !testNamePattern.test(getTestID(child))) + ) + ); +}; + +const getAllHooksForDescribe = describe => { + const result = { + afterAll: [], + beforeAll: [] + }; + + if (hasEnabledTest(describe)) { + for (const hook of describe.hooks) { + switch (hook.type) { + case 'beforeAll': + result.beforeAll.push(hook); + break; + + case 'afterAll': + result.afterAll.push(hook); + break; + } + } + } + + return result; +}; + +exports.getAllHooksForDescribe = getAllHooksForDescribe; + +const getEachHooksForTest = test => { + const result = { + afterEach: [], + beforeEach: [] + }; + + if (test.concurrent) { + // *Each hooks are not run for concurrent tests + return result; + } + + let block = test.parent; + + do { + const beforeEachForCurrentBlock = []; + + for (const hook of block.hooks) { + switch (hook.type) { + case 'beforeEach': + beforeEachForCurrentBlock.push(hook); + break; + + case 'afterEach': + result.afterEach.push(hook); + break; + } + } // 'beforeEach' hooks are executed from top to bottom, the opposite of the + // way we traversed it. + + result.beforeEach = [...beforeEachForCurrentBlock, ...result.beforeEach]; + } while ((block = block.parent)); + + return result; +}; + +exports.getEachHooksForTest = getEachHooksForTest; + +const describeBlockHasTests = describe => + describe.children.some( + child => child.type === 'test' || describeBlockHasTests(child) + ); + +exports.describeBlockHasTests = describeBlockHasTests; + +const _makeTimeoutMessage = (timeout, isHook) => + `Exceeded timeout of ${(0, _jestUtil.formatTime)(timeout)} for a ${ + isHook ? 'hook' : 'test' + }.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.`; // Global values can be overwritten by mocks or tests. We'll capture +// the original values in the variables before we require any files. + +const {setTimeout, clearTimeout} = globalThis; + +function checkIsError(error) { + return !!(error && error.message && error.stack); +} + +const callAsyncCircusFn = (testOrHook, testContext, {isHook, timeout}) => { + let timeoutID; + let completed = false; + const {fn, asyncError} = testOrHook; + return new Promise((resolve, reject) => { + timeoutID = setTimeout( + () => reject(_makeTimeoutMessage(timeout, isHook)), + timeout + ); // If this fn accepts `done` callback we return a promise that fulfills as + // soon as `done` called. + + if (takesDoneCallback(fn)) { + let returnedValue = undefined; + + const done = reason => { + // We need to keep a stack here before the promise tick + const errorAtDone = new _jestUtil.ErrorWithStack(undefined, done); + + if (!completed && testOrHook.seenDone) { + errorAtDone.message = + 'Expected done to be called once, but it was called multiple times.'; + + if (reason) { + errorAtDone.message += ` Reason: ${(0, _prettyFormat.format)( + reason, + { + maxDepth: 3 + } + )}`; + } + + reject(errorAtDone); + throw errorAtDone; + } else { + testOrHook.seenDone = true; + } // Use `Promise.resolve` to allow the event loop to go a single tick in case `done` is called synchronously + + Promise.resolve().then(() => { + if (returnedValue !== undefined) { + asyncError.message = (0, _dedent.default)` + Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise. + Returned value: ${(0, _prettyFormat.format)(returnedValue, { + maxDepth: 3 + })} + `; + return reject(asyncError); + } + + let errorAsErrorObject; + + if (checkIsError(reason)) { + errorAsErrorObject = reason; + } else { + errorAsErrorObject = errorAtDone; + errorAtDone.message = `Failed: ${(0, _prettyFormat.format)(reason, { + maxDepth: 3 + })}`; + } // Consider always throwing, regardless if `reason` is set or not + + if (completed && reason) { + errorAsErrorObject.message = `Caught error after test environment was torn down\n\n${errorAsErrorObject.message}`; + throw errorAsErrorObject; + } + + return reason ? reject(errorAsErrorObject) : resolve(); + }); + }; + + returnedValue = fn.call(testContext, done); + return; + } + + let returnedValue; + + if (isGeneratorFunction(fn)) { + returnedValue = _co.default.wrap(fn).call({}); + } else { + try { + returnedValue = fn.call(testContext); + } catch (error) { + reject(error); + return; + } + } // If it's a Promise, return it. Test for an object with a `then` function + // to support custom Promise implementations. + + if ( + typeof returnedValue === 'object' && + returnedValue !== null && + typeof returnedValue.then === 'function' + ) { + returnedValue.then(() => resolve(), reject); + return; + } + + if (!isHook && returnedValue !== undefined) { + reject( + new Error((0, _dedent.default)` + test functions can only return Promise or undefined. + Returned value: ${(0, _prettyFormat.format)(returnedValue, { + maxDepth: 3 + })} + `) + ); + return; + } // Otherwise this test is synchronous, and if it didn't throw it means + // it passed. + + resolve(); + }) + .then(() => { + completed = true; // If timeout is not cleared/unrefed the node process won't exit until + // it's resolved. + + timeoutID.unref?.(); + clearTimeout(timeoutID); + }) + .catch(error => { + completed = true; + timeoutID.unref?.(); + clearTimeout(timeoutID); + throw error; + }); +}; + +exports.callAsyncCircusFn = callAsyncCircusFn; + +const getTestDuration = test => { + const {startedAt} = test; + return typeof startedAt === 'number' ? jestNow() - startedAt : null; +}; + +exports.getTestDuration = getTestDuration; + +const makeRunResult = (describeBlock, unhandledErrors) => ({ + testResults: makeTestResults(describeBlock), + unhandledErrors: unhandledErrors.map(_getError).map(getErrorStack) +}); + +exports.makeRunResult = makeRunResult; + +const makeSingleTestResult = test => { + const {includeTestLocationInResult} = (0, _state.getState)(); + const testPath = []; + let parent = test; + const {status} = test; + invariant(status, 'Status should be present after tests are run.'); + + do { + testPath.unshift(parent.name); + } while ((parent = parent.parent)); + + let location = null; + + if (includeTestLocationInResult) { + const stackLines = test.asyncError.stack.split('\n'); + const stackLine = stackLines[1]; + let parsedLine = stackUtils.parseLine(stackLine); + + if (parsedLine?.file?.startsWith(jestEachBuildDir)) { + const stackLine = stackLines[4]; + parsedLine = stackUtils.parseLine(stackLine); + } + + if ( + parsedLine && + typeof parsedLine.column === 'number' && + typeof parsedLine.line === 'number' + ) { + location = { + column: parsedLine.column, + line: parsedLine.line + }; + } + } + + const errorsDetailed = test.errors.map(_getError); + return { + duration: test.duration, + errors: errorsDetailed.map(getErrorStack), + errorsDetailed, + invocations: test.invocations, + location, + retryReasons: test.retryReasons.map(_getError).map(getErrorStack), + status, + testPath: Array.from(testPath) + }; +}; + +exports.makeSingleTestResult = makeSingleTestResult; + +const makeTestResults = describeBlock => { + const testResults = []; + + for (const child of describeBlock.children) { + switch (child.type) { + case 'describeBlock': { + testResults.push(...makeTestResults(child)); + break; + } + + case 'test': { + testResults.push(makeSingleTestResult(child)); + break; + } + } + } + + return testResults; +}; // Return a string that identifies the test (concat of parent describe block +// names + test title) + +const getTestID = test => { + const titles = []; + let parent = test; + + do { + titles.unshift(parent.name); + } while ((parent = parent.parent)); + + titles.shift(); // remove TOP_DESCRIBE_BLOCK_NAME + + return titles.join(' '); +}; + +exports.getTestID = getTestID; + +const _getError = errors => { + let error; + let asyncError; + + if (Array.isArray(errors)) { + error = errors[0]; + asyncError = errors[1]; + } else { + error = errors; + asyncError = new Error(); + } + + if (error && (typeof error.stack === 'string' || error.message)) { + return error; + } + + asyncError.message = `thrown: ${(0, _prettyFormat.format)(error, { + maxDepth: 3 + })}`; + return asyncError; +}; + +const getErrorStack = error => + typeof error.stack === 'string' ? error.stack : error.message; + +const addErrorToEachTestUnderDescribe = (describeBlock, error, asyncError) => { + for (const child of describeBlock.children) { + switch (child.type) { + case 'describeBlock': + addErrorToEachTestUnderDescribe(child, error, asyncError); + break; + + case 'test': + child.errors.push([error, asyncError]); + break; + } + } +}; + +exports.addErrorToEachTestUnderDescribe = addErrorToEachTestUnderDescribe; + +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +const parseSingleTestResult = testResult => { + let status; + + if (testResult.status === 'skip') { + status = 'pending'; + } else if (testResult.status === 'todo') { + status = 'todo'; + } else if (testResult.errors.length > 0) { + status = 'failed'; + } else { + status = 'passed'; + } + + const ancestorTitles = testResult.testPath.filter( + name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME + ); + const title = ancestorTitles.pop(); + return { + ancestorTitles, + duration: testResult.duration, + failureDetails: testResult.errorsDetailed, + failureMessages: Array.from(testResult.errors), + fullName: title + ? ancestorTitles.concat(title).join(' ') + : ancestorTitles.join(' '), + invocations: testResult.invocations, + location: testResult.location, + numPassingAsserts: 0, + retryReasons: Array.from(testResult.retryReasons), + status, + title: testResult.testPath[testResult.testPath.length - 1] + }; +}; + +exports.parseSingleTestResult = parseSingleTestResult; diff --git a/node_modules/jest-circus/node_modules/p-limit/index.d.ts b/node_modules/jest-circus/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..f348d7f --- /dev/null +++ b/node_modules/jest-circus/node_modules/p-limit/index.d.ts @@ -0,0 +1,42 @@ +declare namespace pLimit { + interface Limit { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + } +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +declare function pLimit(concurrency: number): pLimit.Limit; + +export = pLimit; diff --git a/node_modules/jest-circus/node_modules/p-limit/index.js b/node_modules/jest-circus/node_modules/p-limit/index.js new file mode 100644 index 0000000..c2ae52d --- /dev/null +++ b/node_modules/jest-circus/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +'use strict'; +const Queue = require('yocto-queue'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +module.exports = pLimit; diff --git a/node_modules/jest-circus/node_modules/p-limit/license b/node_modules/jest-circus/node_modules/p-limit/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/jest-circus/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jest-circus/node_modules/p-limit/package.json b/node_modules/jest-circus/node_modules/p-limit/package.json new file mode 100644 index 0000000..a7c2d58 --- /dev/null +++ b/node_modules/jest-circus/node_modules/p-limit/package.json @@ -0,0 +1,84 @@ +{ + "_from": "p-limit@^3.1.0", + "_id": "p-limit@3.1.0", + "_inBundle": false, + "_integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "_location": "/jest-circus/p-limit", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "p-limit@^3.1.0", + "name": "p-limit", + "escapedName": "p-limit", + "rawSpec": "^3.1.0", + "saveSpec": null, + "fetchSpec": "^3.1.0" + }, + "_requiredBy": [ + "/jest-circus" + ], + "_resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "_shasum": "e1daccbe78d0d1388ca18c64fea38e3e57e3706b", + "_spec": "p-limit@^3.1.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-circus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/p-limit/issues" + }, + "bundleDependencies": false, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "deprecated": false, + "description": "Run multiple promise-returning & async functions with limited concurrency", + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.4.0", + "in-range": "^2.0.0", + "random-int": "^2.0.1", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/p-limit#readme", + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "license": "MIT", + "name": "p-limit", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/p-limit.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "3.1.0" +} diff --git a/node_modules/jest-circus/node_modules/p-limit/readme.md b/node_modules/jest-circus/node_modules/p-limit/readme.md new file mode 100644 index 0000000..b283c1e --- /dev/null +++ b/node_modules/jest-circus/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/jest-circus/package.json b/node_modules/jest-circus/package.json new file mode 100644 index 0000000..52cae18 --- /dev/null +++ b/node_modules/jest-circus/package.json @@ -0,0 +1,90 @@ +{ + "_from": "jest-circus@^29.0.1", + "_id": "jest-circus@29.0.1", + "_inBundle": false, + "_integrity": "sha512-I5J4LyK3qPo8EnqPmxsMAVR+2SFx7JOaZsbqW9xQmk4UDmTCD92EQgS162Ey3Jq6CfpKJKFDhzhG3QqiE0fRbw==", + "_location": "/jest-circus", + "_phantomChildren": { + "yocto-queue": "0.1.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-circus@^29.0.1", + "name": "jest-circus", + "escapedName": "jest-circus", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/jest-config" + ], + "_resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.0.1.tgz", + "_shasum": "7ecb4913e134fb4addc03655fb36c9398014fa07", + "_spec": "jest-circus@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-config", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/environment": "^29.0.1", + "@jest/expect": "^29.0.1", + "@jest/test-result": "^29.0.1", + "@jest/types": "^29.0.1", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^0.7.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.0.1", + "jest-matcher-utils": "^29.0.1", + "jest-message-util": "^29.0.1", + "jest-runtime": "^29.0.1", + "jest-snapshot": "^29.0.1", + "jest-util": "^29.0.1", + "p-limit": "^3.1.0", + "pretty-format": "^29.0.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "deprecated": false, + "description": "[type-definitions]: https://github.com/facebook/jest/blob/main/packages/jest-types/src/Circus.ts", + "devDependencies": { + "@babel/core": "^7.11.6", + "@babel/register": "^7.0.0", + "@types/co": "^4.6.2", + "@types/dedent": "^0.7.0", + "@types/graceful-fs": "^4.1.3", + "@types/stack-utils": "^2.0.0", + "execa": "^5.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json", + "./runner": "./runner.js" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-circus", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-circus" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-circus/runner.js b/node_modules/jest-circus/runner.js new file mode 100644 index 0000000..f61fd88 --- /dev/null +++ b/node_modules/jest-circus/runner.js @@ -0,0 +1,10 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Allow people to use `jest-circus/runner` as a runner. +const runner = require('./build/legacy-code-todo-rewrite/jestAdapter').default; +module.exports = runner; diff --git a/node_modules/jest-config/LICENSE b/node_modules/jest-config/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-config/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-config/build/Defaults.js b/node_modules/jest-config/build/Defaults.js new file mode 100644 index 0000000..252b5e8 --- /dev/null +++ b/node_modules/jest-config/build/Defaults.js @@ -0,0 +1,139 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _path() { + const data = require('path'); + + _path = function () { + return data; + }; + + return data; +} + +function _ciInfo() { + const data = require('ci-info'); + + _ciInfo = function () { + return data; + }; + + return data; +} + +function _jestRegexUtil() { + const data = require('jest-regex-util'); + + _jestRegexUtil = function () { + return data; + }; + + return data; +} + +var _constants = require('./constants'); + +var _getCacheDirectory = _interopRequireDefault(require('./getCacheDirectory')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const NODE_MODULES_REGEXP = (0, _jestRegexUtil().replacePathSepForRegex)( + _constants.NODE_MODULES +); +const defaultOptions = { + automock: false, + bail: 0, + cache: true, + cacheDirectory: (0, _getCacheDirectory.default)(), + changedFilesWithAncestor: false, + ci: _ciInfo().isCI, + clearMocks: false, + collectCoverage: false, + coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], + coverageProvider: 'babel', + coverageReporters: ['json', 'text', 'lcov', 'clover'], + detectLeaks: false, + detectOpenHandles: false, + errorOnDeprecated: false, + expand: false, + extensionsToTreatAsEsm: [], + fakeTimers: { + enableGlobally: false + }, + forceCoverageMatch: [], + globals: {}, + haste: { + computeSha1: false, + enableSymlinks: false, + forceNodeFilesystemAPI: true, + throwOnModuleCollision: false + }, + injectGlobals: true, + listTests: false, + maxConcurrency: 5, + maxWorkers: '50%', + moduleDirectories: ['node_modules'], + moduleFileExtensions: [ + 'js', + 'mjs', + 'cjs', + 'jsx', + 'ts', + 'tsx', + 'json', + 'node' + ], + moduleNameMapper: {}, + modulePathIgnorePatterns: [], + noStackTrace: false, + notify: false, + notifyMode: 'failure-change', + passWithNoTests: false, + prettierPath: 'prettier', + resetMocks: false, + resetModules: false, + restoreMocks: false, + roots: [''], + runTestsByPath: false, + runner: 'jest-runner', + setupFiles: [], + setupFilesAfterEnv: [], + skipFilter: false, + slowTestThreshold: 5, + snapshotFormat: { + escapeString: false, + printBasicPrototype: false + }, + snapshotSerializers: [], + testEnvironment: 'jest-environment-node', + testEnvironmentOptions: {}, + testFailureExitCode: 1, + testLocationInResults: false, + testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'], + testPathIgnorePatterns: [NODE_MODULES_REGEXP], + testRegex: [], + testRunner: 'jest-circus/runner', + testSequencer: '@jest/test-sequencer', + transformIgnorePatterns: [ + NODE_MODULES_REGEXP, + `\\.pnp\\.[^\\${_path().sep}]+$` + ], + useStderr: false, + watch: false, + watchPathIgnorePatterns: [], + watchman: true +}; +var _default = defaultOptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/Deprecated.js b/node_modules/jest-config/build/Deprecated.js new file mode 100644 index 0000000..713d23b --- /dev/null +++ b/node_modules/jest-config/build/Deprecated.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const deprecatedOptions = { + browser: () => + ` Option ${_chalk().default.bold( + '"browser"' + )} has been deprecated. Please install "browser-resolve" and use the "resolver" option in Jest configuration as shown in the documentation: https://jestjs.io/docs/configuration#resolver-string`, + collectCoverageOnlyFrom: _options => ` Option ${_chalk().default.bold( + '"collectCoverageOnlyFrom"' + )} was replaced by ${_chalk().default.bold('"collectCoverageFrom"')}. + + Please update your configuration.`, + extraGlobals: _options => ` Option ${_chalk().default.bold( + '"extraGlobals"' + )} was replaced by ${_chalk().default.bold('"sandboxInjectedGlobals"')}. + + Please update your configuration.`, + moduleLoader: _options => ` Option ${_chalk().default.bold( + '"moduleLoader"' + )} was replaced by ${_chalk().default.bold('"runtime"')}. + + Please update your configuration.`, + preprocessorIgnorePatterns: _options => ` Option ${_chalk().default.bold( + '"preprocessorIgnorePatterns"' + )} was replaced by ${_chalk().default.bold( + '"transformIgnorePatterns"' + )}, which support multiple preprocessors. + + Please update your configuration.`, + scriptPreprocessor: _options => ` Option ${_chalk().default.bold( + '"scriptPreprocessor"' + )} was replaced by ${_chalk().default.bold( + '"transform"' + )}, which support multiple preprocessors. + + Please update your configuration.`, + setupTestFrameworkScriptFile: _options => ` Option ${_chalk().default.bold( + '"setupTestFrameworkScriptFile"' + )} was replaced by configuration ${_chalk().default.bold( + '"setupFilesAfterEnv"' + )}, which supports multiple paths. + + Please update your configuration.`, + testPathDirs: _options => ` Option ${_chalk().default.bold( + '"testPathDirs"' + )} was replaced by ${_chalk().default.bold('"roots"')}. + + Please update your configuration. + `, + testURL: _options => ` Option ${_chalk().default.bold( + '"testURL"' + )} was replaced by passing the URL via ${_chalk().default.bold( + '"testEnvironmentOptions.url"' + )}. + + Please update your configuration.`, + timers: _options => ` Option ${_chalk().default.bold( + '"timers"' + )} was replaced by ${_chalk().default.bold('"fakeTimers"')}. + + Please update your configuration.` +}; +var _default = deprecatedOptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/Descriptions.js b/node_modules/jest-config/build/Descriptions.js new file mode 100644 index 0000000..3483ed5 --- /dev/null +++ b/node_modules/jest-config/build/Descriptions.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const descriptions = { + automock: 'All imported modules in your tests should be mocked automatically', + bail: 'Stop running tests after `n` failures', + cacheDirectory: + 'The directory where Jest should store its cached dependency information', + clearMocks: + 'Automatically clear mock calls, instances, contexts and results before every test', + collectCoverage: + 'Indicates whether the coverage information should be collected while executing the test', + collectCoverageFrom: + 'An array of glob patterns indicating a set of files for which coverage information should be collected', + coverageDirectory: + 'The directory where Jest should output its coverage files', + coveragePathIgnorePatterns: + 'An array of regexp pattern strings used to skip coverage collection', + coverageProvider: + 'Indicates which provider should be used to instrument code for coverage', + coverageReporters: + 'A list of reporter names that Jest uses when writing coverage reports', + coverageThreshold: + 'An object that configures minimum threshold enforcement for coverage results', + dependencyExtractor: 'A path to a custom dependency extractor', + errorOnDeprecated: + 'Make calling deprecated APIs throw helpful error messages', + fakeTimers: 'The default configuration for fake timers', + forceCoverageMatch: + 'Force coverage collection from ignored files using an array of glob patterns', + globalSetup: + 'A path to a module which exports an async function that is triggered once before all test suites', + globalTeardown: + 'A path to a module which exports an async function that is triggered once after all test suites', + globals: + 'A set of global variables that need to be available in all test environments', + maxWorkers: + 'The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.', + moduleDirectories: + "An array of directory names to be searched recursively up from the requiring module's location", + moduleFileExtensions: 'An array of file extensions your modules use', + moduleNameMapper: + 'A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module', + modulePathIgnorePatterns: + "An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader", + notify: 'Activates notifications for test results', + notifyMode: + 'An enum that specifies notification mode. Requires { notify: true }', + preset: "A preset that is used as a base for Jest's configuration", + projects: 'Run tests from one or more projects', + reporters: 'Use this configuration option to add custom reporters to Jest', + resetMocks: 'Automatically reset mock state before every test', + resetModules: 'Reset the module registry before running each individual test', + resolver: 'A path to a custom resolver', + restoreMocks: + 'Automatically restore mock state and implementation before every test', + rootDir: + 'The root directory that Jest should scan for tests and modules within', + roots: + 'A list of paths to directories that Jest should use to search for files in', + runner: + "Allows you to use a custom runner instead of Jest's default test runner", + setupFiles: + 'The paths to modules that run some code to configure or set up the testing environment before each test', + setupFilesAfterEnv: + 'A list of paths to modules that run some code to configure or set up the testing framework before each test', + slowTestThreshold: + 'The number of seconds after which a test is considered as slow and reported as such in the results.', + snapshotSerializers: + 'A list of paths to snapshot serializer modules Jest should use for snapshot testing', + testEnvironment: 'The test environment that will be used for testing', + testEnvironmentOptions: 'Options that will be passed to the testEnvironment', + testLocationInResults: 'Adds a location field to test results', + testMatch: 'The glob patterns Jest uses to detect test files', + testPathIgnorePatterns: + 'An array of regexp pattern strings that are matched against all test paths, matched tests are skipped', + testRegex: + 'The regexp pattern or array of patterns that Jest uses to detect test files', + testResultsProcessor: + 'This option allows the use of a custom results processor', + testRunner: 'This option allows use of a custom test runner', + transform: 'A map from regular expressions to paths to transformers', + transformIgnorePatterns: + 'An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation', + unmockedModulePathPatterns: + 'An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them', + verbose: + 'Indicates whether each individual test should be reported during the run', + watchPathIgnorePatterns: + 'An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode', + watchman: 'Whether to use watchman for file crawling' +}; +var _default = descriptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/ReporterValidationErrors.js b/node_modules/jest-config/build/ReporterValidationErrors.js new file mode 100644 index 0000000..9e576e6 --- /dev/null +++ b/node_modules/jest-config/build/ReporterValidationErrors.js @@ -0,0 +1,138 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.createArrayReporterError = createArrayReporterError; +exports.createReporterError = createReporterError; +exports.validateReporters = validateReporters; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _jestGetType() { + const data = require('jest-get-type'); + + _jestGetType = function () { + return data; + }; + + return data; +} + +function _jestValidate() { + const data = require('jest-validate'); + + _jestValidate = function () { + return data; + }; + + return data; +} + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const validReporterTypes = ['array', 'string']; +const ERROR = `${_utils.BULLET}Reporter Validation Error`; +/** + * Reporter Validation Error is thrown if the given arguments + * within the reporter are not valid. + * + * This is a highly specific reporter error and in the future will be + * merged with jest-validate. Till then, we can make use of it. It works + * and that's what counts most at this time. + */ + +function createReporterError(reporterIndex, reporterValue) { + const errorMessage = + ` Reporter at index ${reporterIndex} must be of type:\n` + + ` ${_chalk().default.bold.green(validReporterTypes.join(' or '))}\n` + + ' but instead received:\n' + + ` ${_chalk().default.bold.red( + (0, _jestGetType().getType)(reporterValue) + )}`; + return new (_jestValidate().ValidationError)( + ERROR, + errorMessage, + _utils.DOCUMENTATION_NOTE + ); +} + +function createArrayReporterError( + arrayReporter, + reporterIndex, + valueIndex, + value, + expectedType, + valueName +) { + const errorMessage = + ` Unexpected value for ${valueName} ` + + `at index ${valueIndex} of reporter at index ${reporterIndex}\n` + + ' Expected:\n' + + ` ${_chalk().default.bold.red(expectedType)}\n` + + ' Got:\n' + + ` ${_chalk().default.bold.green((0, _jestGetType().getType)(value))}\n` + + ' Reporter configuration:\n' + + ` ${_chalk().default.bold.green( + JSON.stringify(arrayReporter, null, 2).split('\n').join('\n ') + )}`; + return new (_jestValidate().ValidationError)( + ERROR, + errorMessage, + _utils.DOCUMENTATION_NOTE + ); +} + +function validateReporters(reporterConfig) { + return reporterConfig.every((reporter, index) => { + if (Array.isArray(reporter)) { + validateArrayReporter(reporter, index); + } else if (typeof reporter !== 'string') { + throw createReporterError(index, reporter); + } + + return true; + }); +} + +function validateArrayReporter(arrayReporter, reporterIndex) { + const [path, options] = arrayReporter; + + if (typeof path !== 'string') { + throw createArrayReporterError( + arrayReporter, + reporterIndex, + 0, + path, + 'string', + 'Path' + ); + } else if (typeof options !== 'object') { + throw createArrayReporterError( + arrayReporter, + reporterIndex, + 1, + options, + 'object', + 'Reporter Configuration' + ); + } +} diff --git a/node_modules/jest-config/build/ValidConfig.js b/node_modules/jest-config/build/ValidConfig.js new file mode 100644 index 0000000..9c98ef5 --- /dev/null +++ b/node_modules/jest-config/build/ValidConfig.js @@ -0,0 +1,230 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _jestRegexUtil() { + const data = require('jest-regex-util'); + + _jestRegexUtil = function () { + return data; + }; + + return data; +} + +function _jestValidate() { + const data = require('jest-validate'); + + _jestValidate = function () { + return data; + }; + + return data; +} + +function _prettyFormat() { + const data = require('pretty-format'); + + _prettyFormat = function () { + return data; + }; + + return data; +} + +var _constants = require('./constants'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const NODE_MODULES_REGEXP = (0, _jestRegexUtil().replacePathSepForRegex)( + _constants.NODE_MODULES +); +const initialOptions = { + automock: false, + bail: (0, _jestValidate().multipleValidOptions)(false, 0), + cache: true, + cacheDirectory: '/tmp/user/jest', + changedFilesWithAncestor: false, + changedSince: 'master', + ci: false, + clearMocks: false, + collectCoverage: true, + collectCoverageFrom: ['src', '!public'], + coverageDirectory: 'coverage', + coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], + coverageProvider: 'v8', + coverageReporters: ['json', 'text', 'lcov', 'clover'], + coverageThreshold: { + global: { + branches: 50, + functions: 100, + lines: 100, + statements: 100 + } + }, + dependencyExtractor: '/dependencyExtractor.js', + detectLeaks: false, + detectOpenHandles: false, + displayName: (0, _jestValidate().multipleValidOptions)('test-config', { + color: 'blue', + name: 'test-config' + }), + errorOnDeprecated: false, + expand: false, + extensionsToTreatAsEsm: [], + fakeTimers: { + advanceTimers: (0, _jestValidate().multipleValidOptions)(40, true), + doNotFake: [ + 'Date', + 'hrtime', + 'nextTick', + 'performance', + 'queueMicrotask', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'requestIdleCallback', + 'cancelIdleCallback', + 'setImmediate', + 'clearImmediate', + 'setInterval', + 'clearInterval', + 'setTimeout', + 'clearTimeout' + ], + enableGlobally: true, + legacyFakeTimers: false, + now: 1483228800000, + timerLimit: 1000 + }, + filter: '/filter.js', + forceCoverageMatch: ['**/*.t.js'], + forceExit: false, + globalSetup: 'setup.js', + globalTeardown: 'teardown.js', + globals: { + __DEV__: true + }, + haste: { + computeSha1: true, + defaultPlatform: 'ios', + enableSymlinks: false, + forceNodeFilesystemAPI: true, + hasteImplModulePath: '/haste_impl.js', + hasteMapModulePath: '', + platforms: ['ios', 'android'], + retainAllFiles: false, + throwOnModuleCollision: false + }, + id: 'string', + injectGlobals: true, + json: false, + lastCommit: false, + listTests: false, + logHeapUsage: true, + maxConcurrency: 5, + maxWorkers: '50%', + moduleDirectories: ['node_modules'], + moduleFileExtensions: [ + 'js', + 'mjs', + 'cjs', + 'json', + 'jsx', + 'ts', + 'tsx', + 'node' + ], + moduleNameMapper: { + '^React$': '/node_modules/react' + }, + modulePathIgnorePatterns: ['/build/'], + modulePaths: ['/shared/vendor/modules'], + noStackTrace: false, + notify: false, + notifyMode: 'failure-change', + onlyChanged: false, + onlyFailures: false, + passWithNoTests: false, + preset: 'react-native', + prettierPath: '/node_modules/prettier', + projects: ['project-a', 'project-b/'], + reporters: [ + 'default', + 'custom-reporter-1', + [ + 'custom-reporter-2', + { + configValue: true + } + ] + ], + resetMocks: false, + resetModules: false, + resolver: '/resolver.js', + restoreMocks: false, + rootDir: '/', + roots: [''], + runTestsByPath: false, + runner: 'jest-runner', + runtime: '', + sandboxInjectedGlobals: [], + setupFiles: ['/setup.js'], + setupFilesAfterEnv: ['/testSetupFile.js'], + silent: true, + skipFilter: false, + skipNodeResolution: false, + slowTestThreshold: 5, + snapshotFormat: _prettyFormat().DEFAULT_OPTIONS, + snapshotResolver: '/snapshotResolver.js', + snapshotSerializers: ['my-serializer-module'], + testEnvironment: 'jest-environment-node', + testEnvironmentOptions: { + url: 'http://localhost', + userAgent: 'Agent/007' + }, + testFailureExitCode: 1, + testLocationInResults: false, + testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'], + testNamePattern: 'test signature', + testPathIgnorePatterns: [NODE_MODULES_REGEXP], + testRegex: (0, _jestValidate().multipleValidOptions)( + '(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$', + ['/__tests__/\\.test\\.[jt]sx?$', '/__tests__/\\.spec\\.[jt]sx?$'] + ), + testResultsProcessor: 'processor-node-module', + testRunner: 'circus', + testSequencer: '@jest/test-sequencer', + testTimeout: 5000, + transform: { + '\\.js$': '/preprocessor.js' + }, + transformIgnorePatterns: [NODE_MODULES_REGEXP], + unmockedModulePathPatterns: ['mock'], + updateSnapshot: true, + useStderr: false, + verbose: false, + watch: false, + watchAll: false, + watchPathIgnorePatterns: ['/e2e/'], + watchPlugins: [ + 'path/to/yourWatchPlugin', + [ + 'jest-watch-typeahead/filename', + { + key: 'k', + prompt: 'do something with my custom prompt' + } + ] + ], + watchman: true, + workerIdleMemoryLimit: (0, _jestValidate().multipleValidOptions)(0.2, '50%') +}; +var _default = initialOptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/color.js b/node_modules/jest-config/build/color.js new file mode 100644 index 0000000..4955faf --- /dev/null +++ b/node_modules/jest-config/build/color.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getDisplayNameColor = void 0; + +function _crypto() { + const data = require('crypto'); + + _crypto = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']; + +const getDisplayNameColor = seed => { + if (seed === undefined) { + return 'white'; + } + + const hash = (0, _crypto().createHash)('sha256'); + hash.update(seed); + const num = hash.digest().readUInt32LE(0); + return colors[num % colors.length]; +}; + +exports.getDisplayNameColor = getDisplayNameColor; diff --git a/node_modules/jest-config/build/constants.js b/node_modules/jest-config/build/constants.js new file mode 100644 index 0000000..6dbc689 --- /dev/null +++ b/node_modules/jest-config/build/constants.js @@ -0,0 +1,101 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.PACKAGE_JSON = + exports.NODE_MODULES = + exports.JEST_CONFIG_EXT_TS = + exports.JEST_CONFIG_EXT_ORDER = + exports.JEST_CONFIG_EXT_MJS = + exports.JEST_CONFIG_EXT_JSON = + exports.JEST_CONFIG_EXT_JS = + exports.JEST_CONFIG_EXT_CJS = + exports.JEST_CONFIG_BASE_NAME = + exports.DEFAULT_JS_PATTERN = + void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const NODE_MODULES = `${path().sep}node_modules${path().sep}`; +exports.NODE_MODULES = NODE_MODULES; +const DEFAULT_JS_PATTERN = '\\.[jt]sx?$'; +exports.DEFAULT_JS_PATTERN = DEFAULT_JS_PATTERN; +const PACKAGE_JSON = 'package.json'; +exports.PACKAGE_JSON = PACKAGE_JSON; +const JEST_CONFIG_BASE_NAME = 'jest.config'; +exports.JEST_CONFIG_BASE_NAME = JEST_CONFIG_BASE_NAME; +const JEST_CONFIG_EXT_CJS = '.cjs'; +exports.JEST_CONFIG_EXT_CJS = JEST_CONFIG_EXT_CJS; +const JEST_CONFIG_EXT_MJS = '.mjs'; +exports.JEST_CONFIG_EXT_MJS = JEST_CONFIG_EXT_MJS; +const JEST_CONFIG_EXT_JS = '.js'; +exports.JEST_CONFIG_EXT_JS = JEST_CONFIG_EXT_JS; +const JEST_CONFIG_EXT_TS = '.ts'; +exports.JEST_CONFIG_EXT_TS = JEST_CONFIG_EXT_TS; +const JEST_CONFIG_EXT_JSON = '.json'; +exports.JEST_CONFIG_EXT_JSON = JEST_CONFIG_EXT_JSON; +const JEST_CONFIG_EXT_ORDER = Object.freeze([ + JEST_CONFIG_EXT_JS, + JEST_CONFIG_EXT_TS, + JEST_CONFIG_EXT_MJS, + JEST_CONFIG_EXT_CJS, + JEST_CONFIG_EXT_JSON +]); +exports.JEST_CONFIG_EXT_ORDER = JEST_CONFIG_EXT_ORDER; diff --git a/node_modules/jest-config/build/getCacheDirectory.js b/node_modules/jest-config/build/getCacheDirectory.js new file mode 100644 index 0000000..5373c1c --- /dev/null +++ b/node_modules/jest-config/build/getCacheDirectory.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const getCacheDirectory = () => { + const {getuid} = process; + const tmpdirPath = path().join( + (0, _jestUtil().tryRealpath)((0, _os().tmpdir)()), + 'jest' + ); + + if (getuid == null) { + return tmpdirPath; + } else { + // On some platforms tmpdir() is `/tmp`, causing conflicts between different + // users and permission issues. Adding an additional subdivision by UID can + // help. + return `${tmpdirPath}_${getuid.call(process).toString(36)}`; + } +}; + +var _default = getCacheDirectory; +exports.default = _default; diff --git a/node_modules/jest-config/build/getMaxWorkers.js b/node_modules/jest-config/build/getMaxWorkers.js new file mode 100644 index 0000000..ee95633 --- /dev/null +++ b/node_modules/jest-config/build/getMaxWorkers.js @@ -0,0 +1,58 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getMaxWorkers; + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function getMaxWorkers(argv, defaultOptions) { + if (argv.runInBand) { + return 1; + } else if (argv.maxWorkers) { + return parseWorkers(argv.maxWorkers); + } else if (defaultOptions && defaultOptions.maxWorkers) { + return parseWorkers(defaultOptions.maxWorkers); + } else { + // In watch mode, Jest should be unobtrusive and not use all available CPUs. + const cpusInfo = (0, _os().cpus)(); + const numCpus = cpusInfo?.length ?? 1; + const isWatchModeEnabled = argv.watch || argv.watchAll; + return Math.max( + isWatchModeEnabled ? Math.floor(numCpus / 2) : numCpus - 1, + 1 + ); + } +} + +const parseWorkers = maxWorkers => { + const parsed = parseInt(maxWorkers.toString(), 10); + + if ( + typeof maxWorkers === 'string' && + maxWorkers.trim().endsWith('%') && + parsed > 0 && + parsed <= 100 + ) { + const numCpus = (0, _os().cpus)().length; + const workers = Math.floor((parsed / 100) * numCpus); + return Math.max(workers, 1); + } + + return parsed > 0 ? parsed : 1; +}; diff --git a/node_modules/jest-config/build/index.d.ts b/node_modules/jest-config/build/index.d.ts new file mode 100644 index 0000000..9d56a7c --- /dev/null +++ b/node_modules/jest-config/build/index.d.ts @@ -0,0 +1,104 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {DeprecatedOptions} from 'jest-validate'; + +declare type AllOptions = Config.ProjectConfig & Config.GlobalConfig; + +declare namespace constants { + export { + NODE_MODULES, + DEFAULT_JS_PATTERN, + PACKAGE_JSON, + JEST_CONFIG_BASE_NAME, + JEST_CONFIG_EXT_CJS, + JEST_CONFIG_EXT_MJS, + JEST_CONFIG_EXT_JS, + JEST_CONFIG_EXT_TS, + JEST_CONFIG_EXT_JSON, + JEST_CONFIG_EXT_ORDER, + }; +} +export {constants}; + +declare const DEFAULT_JS_PATTERN = '\\.[jt]sx?$'; + +export declare const defaults: Config.DefaultOptions; + +export declare const deprecationEntries: DeprecatedOptions; + +export declare const descriptions: { + [key in keyof Config.InitialOptions]: string; +}; + +export declare const isJSONString: ( + text?: JSONString | string, +) => text is JSONString; + +declare const JEST_CONFIG_BASE_NAME = 'jest.config'; + +declare const JEST_CONFIG_EXT_CJS = '.cjs'; + +declare const JEST_CONFIG_EXT_JS = '.js'; + +declare const JEST_CONFIG_EXT_JSON = '.json'; + +declare const JEST_CONFIG_EXT_MJS = '.mjs'; + +declare const JEST_CONFIG_EXT_ORDER: readonly string[]; + +declare const JEST_CONFIG_EXT_TS = '.ts'; + +declare type JSONString = string & { + readonly $$type: never; +}; + +declare const NODE_MODULES: string; + +export declare function normalize( + initialOptions: Config.InitialOptions, + argv: Config.Argv, + configPath?: string | null, + projectIndex?: number, +): Promise<{ + hasDeprecationWarnings: boolean; + options: AllOptions; +}>; + +declare const PACKAGE_JSON = 'package.json'; + +declare type ReadConfig = { + configPath: string | null | undefined; + globalConfig: Config.GlobalConfig; + hasDeprecationWarnings: boolean; + projectConfig: Config.ProjectConfig; +}; + +export declare function readConfig( + argv: Config.Argv, + packageRootOrConfig: string | Config.InitialOptions, + skipArgvConfigOption?: boolean, + parentConfigDirname?: string | null, + projectIndex?: number, + skipMultipleConfigError?: boolean, +): Promise; + +export declare function readConfigs( + argv: Config.Argv, + projectPaths: Array, +): Promise<{ + globalConfig: Config.GlobalConfig; + configs: Array; + hasDeprecationWarnings: boolean; +}>; + +export declare const replaceRootDirInPath: ( + rootDir: string, + filePath: string, +) => string; + +export {}; diff --git a/node_modules/jest-config/build/index.js b/node_modules/jest-config/build/index.js new file mode 100644 index 0000000..0db6027 --- /dev/null +++ b/node_modules/jest-config/build/index.js @@ -0,0 +1,479 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.constants = void 0; +Object.defineProperty(exports, 'defaults', { + enumerable: true, + get: function () { + return _Defaults.default; + } +}); +Object.defineProperty(exports, 'deprecationEntries', { + enumerable: true, + get: function () { + return _Deprecated.default; + } +}); +Object.defineProperty(exports, 'descriptions', { + enumerable: true, + get: function () { + return _Descriptions.default; + } +}); +Object.defineProperty(exports, 'isJSONString', { + enumerable: true, + get: function () { + return _utils.isJSONString; + } +}); +Object.defineProperty(exports, 'normalize', { + enumerable: true, + get: function () { + return _normalize.default; + } +}); +exports.readConfig = readConfig; +exports.readConfigs = readConfigs; +Object.defineProperty(exports, 'replaceRootDirInPath', { + enumerable: true, + get: function () { + return _utils.replaceRootDirInPath; + } +}); + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var constants = _interopRequireWildcard(require('./constants')); + +exports.constants = constants; + +var _normalize = _interopRequireDefault(require('./normalize')); + +var _readConfigFileAndSetRootDir = _interopRequireDefault( + require('./readConfigFileAndSetRootDir') +); + +var _resolveConfigPath = _interopRequireDefault(require('./resolveConfigPath')); + +var _utils = require('./utils'); + +var _Deprecated = _interopRequireDefault(require('./Deprecated')); + +var _Defaults = _interopRequireDefault(require('./Defaults')); + +var _Descriptions = _interopRequireDefault(require('./Descriptions')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +async function readConfig( + argv, + packageRootOrConfig, // Whether it needs to look into `--config` arg passed to CLI. + // It only used to read initial config. If the initial config contains + // `project` property, we don't want to read `--config` value and rather + // read individual configs for every project. + skipArgvConfigOption, + parentConfigDirname, + projectIndex = Infinity, + skipMultipleConfigError = false +) { + let rawOptions; + let configPath = null; + + if (typeof packageRootOrConfig !== 'string') { + if (parentConfigDirname) { + rawOptions = packageRootOrConfig; + rawOptions.rootDir = rawOptions.rootDir + ? (0, _utils.replaceRootDirInPath)( + parentConfigDirname, + rawOptions.rootDir + ) + : parentConfigDirname; + } else { + throw new Error( + 'Jest: Cannot use configuration as an object without a file path.' + ); + } + } else if ((0, _utils.isJSONString)(argv.config)) { + // A JSON string was passed to `--config` argument and we can parse it + // and use as is. + let config; + + try { + config = JSON.parse(argv.config); + } catch { + throw new Error( + 'There was an error while parsing the `--config` argument as a JSON string.' + ); + } // NOTE: we might need to resolve this dir to an absolute path in the future + + config.rootDir = config.rootDir || packageRootOrConfig; + rawOptions = config; // A string passed to `--config`, which is either a direct path to the config + // or a path to directory containing `package.json`, `jest.config.js` or `jest.config.ts` + } else if (!skipArgvConfigOption && typeof argv.config == 'string') { + configPath = (0, _resolveConfigPath.default)( + argv.config, + process.cwd(), + skipMultipleConfigError + ); + rawOptions = await (0, _readConfigFileAndSetRootDir.default)(configPath); + } else { + // Otherwise just try to find config in the current rootDir. + configPath = (0, _resolveConfigPath.default)( + packageRootOrConfig, + process.cwd(), + skipMultipleConfigError + ); + rawOptions = await (0, _readConfigFileAndSetRootDir.default)(configPath); + } + + const {options, hasDeprecationWarnings} = await (0, _normalize.default)( + rawOptions, + argv, + configPath, + projectIndex + ); + const {globalConfig, projectConfig} = groupOptions(options); + return { + configPath, + globalConfig, + hasDeprecationWarnings, + projectConfig + }; +} + +const groupOptions = options => ({ + globalConfig: Object.freeze({ + bail: options.bail, + changedFilesWithAncestor: options.changedFilesWithAncestor, + changedSince: options.changedSince, + ci: options.ci, + collectCoverage: options.collectCoverage, + collectCoverageFrom: options.collectCoverageFrom, + coverageDirectory: options.coverageDirectory, + coverageProvider: options.coverageProvider, + coverageReporters: options.coverageReporters, + coverageThreshold: options.coverageThreshold, + detectLeaks: options.detectLeaks, + detectOpenHandles: options.detectOpenHandles, + errorOnDeprecated: options.errorOnDeprecated, + expand: options.expand, + filter: options.filter, + findRelatedTests: options.findRelatedTests, + forceExit: options.forceExit, + globalSetup: options.globalSetup, + globalTeardown: options.globalTeardown, + json: options.json, + lastCommit: options.lastCommit, + listTests: options.listTests, + logHeapUsage: options.logHeapUsage, + maxConcurrency: options.maxConcurrency, + maxWorkers: options.maxWorkers, + noSCM: undefined, + noStackTrace: options.noStackTrace, + nonFlagArgs: options.nonFlagArgs, + notify: options.notify, + notifyMode: options.notifyMode, + onlyChanged: options.onlyChanged, + onlyFailures: options.onlyFailures, + outputFile: options.outputFile, + passWithNoTests: options.passWithNoTests, + projects: options.projects, + replname: options.replname, + reporters: options.reporters, + rootDir: options.rootDir, + runTestsByPath: options.runTestsByPath, + shard: options.shard, + silent: options.silent, + skipFilter: options.skipFilter, + snapshotFormat: options.snapshotFormat, + testFailureExitCode: options.testFailureExitCode, + testNamePattern: options.testNamePattern, + testPathPattern: options.testPathPattern, + testResultsProcessor: options.testResultsProcessor, + testSequencer: options.testSequencer, + testTimeout: options.testTimeout, + updateSnapshot: options.updateSnapshot, + useStderr: options.useStderr, + verbose: options.verbose, + watch: options.watch, + watchAll: options.watchAll, + watchPlugins: options.watchPlugins, + watchman: options.watchman, + workerIdleMemoryLimit: options.workerIdleMemoryLimit + }), + projectConfig: Object.freeze({ + automock: options.automock, + cache: options.cache, + cacheDirectory: options.cacheDirectory, + clearMocks: options.clearMocks, + coveragePathIgnorePatterns: options.coveragePathIgnorePatterns, + cwd: options.cwd, + dependencyExtractor: options.dependencyExtractor, + detectLeaks: options.detectLeaks, + detectOpenHandles: options.detectOpenHandles, + displayName: options.displayName, + errorOnDeprecated: options.errorOnDeprecated, + extensionsToTreatAsEsm: options.extensionsToTreatAsEsm, + fakeTimers: options.fakeTimers, + filter: options.filter, + forceCoverageMatch: options.forceCoverageMatch, + globalSetup: options.globalSetup, + globalTeardown: options.globalTeardown, + globals: options.globals, + haste: options.haste, + id: options.id, + injectGlobals: options.injectGlobals, + moduleDirectories: options.moduleDirectories, + moduleFileExtensions: options.moduleFileExtensions, + moduleNameMapper: options.moduleNameMapper, + modulePathIgnorePatterns: options.modulePathIgnorePatterns, + modulePaths: options.modulePaths, + prettierPath: options.prettierPath, + resetMocks: options.resetMocks, + resetModules: options.resetModules, + resolver: options.resolver, + restoreMocks: options.restoreMocks, + rootDir: options.rootDir, + roots: options.roots, + runner: options.runner, + runtime: options.runtime, + sandboxInjectedGlobals: options.sandboxInjectedGlobals, + setupFiles: options.setupFiles, + setupFilesAfterEnv: options.setupFilesAfterEnv, + skipFilter: options.skipFilter, + skipNodeResolution: options.skipNodeResolution, + slowTestThreshold: options.slowTestThreshold, + snapshotFormat: options.snapshotFormat, + snapshotResolver: options.snapshotResolver, + snapshotSerializers: options.snapshotSerializers, + testEnvironment: options.testEnvironment, + testEnvironmentOptions: options.testEnvironmentOptions, + testLocationInResults: options.testLocationInResults, + testMatch: options.testMatch, + testPathIgnorePatterns: options.testPathIgnorePatterns, + testRegex: options.testRegex, + testRunner: options.testRunner, + transform: options.transform, + transformIgnorePatterns: options.transformIgnorePatterns, + unmockedModulePathPatterns: options.unmockedModulePathPatterns, + watchPathIgnorePatterns: options.watchPathIgnorePatterns + }) +}); + +const ensureNoDuplicateConfigs = (parsedConfigs, projects) => { + if (projects.length <= 1) { + return; + } + + const configPathMap = new Map(); + + for (const config of parsedConfigs) { + const {configPath} = config; + + if (configPathMap.has(configPath)) { + const message = `Whoops! Two projects resolved to the same config path: ${_chalk().default.bold( + String(configPath) + )}: + + Project 1: ${_chalk().default.bold( + projects[parsedConfigs.findIndex(x => x === config)] + )} + Project 2: ${_chalk().default.bold( + projects[parsedConfigs.findIndex(x => x === configPathMap.get(configPath))] + )} + +This usually means that your ${_chalk().default.bold( + '"projects"' + )} config includes a directory that doesn't have any configuration recognizable by Jest. Please fix it. +`; + throw new Error(message); + } + + if (configPath !== null) { + configPathMap.set(configPath, config); + } + } +}; // Possible scenarios: +// 1. jest --config config.json +// 2. jest --projects p1 p2 +// 3. jest --projects p1 p2 --config config.json +// 4. jest --projects p1 +// 5. jest +// +// If no projects are specified, process.cwd() will be used as the default +// (and only) project. + +async function readConfigs(argv, projectPaths) { + let globalConfig; + let hasDeprecationWarnings; + let configs = []; + let projects = projectPaths; + let configPath; + + if (projectPaths.length === 1) { + const parsedConfig = await readConfig(argv, projects[0]); + configPath = parsedConfig.configPath; + hasDeprecationWarnings = parsedConfig.hasDeprecationWarnings; + globalConfig = parsedConfig.globalConfig; + configs = [parsedConfig.projectConfig]; + + if (globalConfig.projects && globalConfig.projects.length) { + // Even though we had one project in CLI args, there might be more + // projects defined in the config. + // In other words, if this was a single project, + // and its config has `projects` settings, use that value instead. + projects = globalConfig.projects; + } + } + + if (projects.length > 0) { + const cwd = + process.platform === 'win32' + ? (0, _jestUtil().tryRealpath)(process.cwd()) + : process.cwd(); + const projectIsCwd = projects[0] === cwd; + const parsedConfigs = await Promise.all( + projects + .filter(root => { + // Ignore globbed files that cannot be `require`d. + if ( + typeof root === 'string' && + fs().existsSync(root) && + !fs().lstatSync(root).isDirectory() && + !constants.JEST_CONFIG_EXT_ORDER.some(ext => root.endsWith(ext)) + ) { + return false; + } + + return true; + }) + .map((root, projectIndex) => { + const projectIsTheOnlyProject = + projectIndex === 0 && projects.length === 1; + const skipArgvConfigOption = !( + projectIsTheOnlyProject && projectIsCwd + ); + return readConfig( + argv, + root, + skipArgvConfigOption, + configPath ? path().dirname(configPath) : cwd, + projectIndex, // we wanna skip the warning if this is the "main" project + projectIsCwd + ); + }) + ); + ensureNoDuplicateConfigs(parsedConfigs, projects); + configs = parsedConfigs.map(({projectConfig}) => projectConfig); + + if (!hasDeprecationWarnings) { + hasDeprecationWarnings = parsedConfigs.some( + ({hasDeprecationWarnings}) => !!hasDeprecationWarnings + ); + } // If no config was passed initially, use the one from the first project + + if (!globalConfig) { + globalConfig = parsedConfigs[0].globalConfig; + } + } + + if (!globalConfig || !configs.length) { + throw new Error('jest: No configuration found for any project.'); + } + + return { + configs, + globalConfig, + hasDeprecationWarnings: !!hasDeprecationWarnings + }; +} diff --git a/node_modules/jest-config/build/normalize.js b/node_modules/jest-config/build/normalize.js new file mode 100644 index 0000000..f08ea90 --- /dev/null +++ b/node_modules/jest-config/build/normalize.js @@ -0,0 +1,1322 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = normalize; + +function _crypto() { + const data = require('crypto'); + + _crypto = function () { + return data; + }; + + return data; +} + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _deepmerge() { + const data = _interopRequireDefault(require('deepmerge')); + + _deepmerge = function () { + return data; + }; + + return data; +} + +function _glob() { + const data = require('glob'); + + _glob = function () { + return data; + }; + + return data; +} + +function _gracefulFs() { + const data = require('graceful-fs'); + + _gracefulFs = function () { + return data; + }; + + return data; +} + +function _micromatch() { + const data = _interopRequireDefault(require('micromatch')); + + _micromatch = function () { + return data; + }; + + return data; +} + +function _jestRegexUtil() { + const data = require('jest-regex-util'); + + _jestRegexUtil = function () { + return data; + }; + + return data; +} + +function _jestResolve() { + const data = _interopRequireWildcard(require('jest-resolve')); + + _jestResolve = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _jestValidate() { + const data = require('jest-validate'); + + _jestValidate = function () { + return data; + }; + + return data; +} + +var _Defaults = _interopRequireDefault(require('./Defaults')); + +var _Deprecated = _interopRequireDefault(require('./Deprecated')); + +var _ReporterValidationErrors = require('./ReporterValidationErrors'); + +var _ValidConfig = _interopRequireDefault(require('./ValidConfig')); + +var _color = require('./color'); + +var _constants = require('./constants'); + +var _getMaxWorkers = _interopRequireDefault(require('./getMaxWorkers')); + +var _parseShardPair = require('./parseShardPair'); + +var _setFromArgv = _interopRequireDefault(require('./setFromArgv')); + +var _stringToBytes = _interopRequireDefault(require('./stringToBytes')); + +var _utils = require('./utils'); + +var _validatePattern = _interopRequireDefault(require('./validatePattern')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const ERROR = `${_utils.BULLET}Validation Error`; +const PRESET_EXTENSIONS = ['.json', '.js', '.cjs', '.mjs']; +const PRESET_NAME = 'jest-preset'; + +const createConfigError = message => + new (_jestValidate().ValidationError)( + ERROR, + message, + _utils.DOCUMENTATION_NOTE + ); + +function verifyDirectoryExists(path, key) { + try { + const rootStat = (0, _gracefulFs().statSync)(path); + + if (!rootStat.isDirectory()) { + throw createConfigError( + ` ${_chalk().default.bold(path)} in the ${_chalk().default.bold( + key + )} option is not a directory.` + ); + } + } catch (err) { + if (err instanceof _jestValidate().ValidationError) { + throw err; + } + + if (err.code === 'ENOENT') { + throw createConfigError( + ` Directory ${_chalk().default.bold( + path + )} in the ${_chalk().default.bold(key)} option was not found.` + ); + } // Not sure in which cases `statSync` can throw, so let's just show the underlying error to the user + + throw createConfigError( + ` Got an error trying to find ${_chalk().default.bold( + path + )} in the ${_chalk().default.bold(key)} option.\n\n Error was: ${ + err.message + }` + ); + } +} // TS 3.5 forces us to split these into 2 + +const mergeModuleNameMapperWithPreset = (options, preset) => { + if (options['moduleNameMapper'] && preset['moduleNameMapper']) { + options['moduleNameMapper'] = { + ...options['moduleNameMapper'], + ...preset['moduleNameMapper'], + ...options['moduleNameMapper'] + }; + } +}; + +const mergeTransformWithPreset = (options, preset) => { + if (options['transform'] && preset['transform']) { + options['transform'] = { + ...options['transform'], + ...preset['transform'], + ...options['transform'] + }; + } +}; + +const mergeGlobalsWithPreset = (options, preset) => { + if (options['globals'] && preset['globals']) { + options['globals'] = (0, _deepmerge().default)( + preset['globals'], + options['globals'] + ); + } +}; + +const setupPreset = async (options, optionsPreset) => { + let preset; + const presetPath = (0, _utils.replaceRootDirInPath)( + options.rootDir, + optionsPreset + ); + + const presetModule = _jestResolve().default.findNodeModule( + presetPath.startsWith('.') + ? presetPath + : path().join(presetPath, PRESET_NAME), + { + basedir: options.rootDir, + extensions: PRESET_EXTENSIONS + } + ); + + try { + if (!presetModule) { + throw new Error(`Cannot find module '${presetPath}'`); + } // Force re-evaluation to support multiple projects + + try { + delete require.cache[require.resolve(presetModule)]; + } catch {} + + preset = await (0, _jestUtil().requireOrImportModule)(presetModule); + } catch (error) { + if (error instanceof SyntaxError || error instanceof TypeError) { + throw createConfigError( + ` Preset ${_chalk().default.bold(presetPath)} is invalid:\n\n ${ + error.message + }\n ${error.stack}` + ); + } + + if (error.message.includes('Cannot find module')) { + if (error.message.includes(presetPath)) { + const preset = _jestResolve().default.findNodeModule(presetPath, { + basedir: options.rootDir + }); + + if (preset) { + throw createConfigError( + ` Module ${_chalk().default.bold( + presetPath + )} should have "jest-preset.js" or "jest-preset.json" file at the root.` + ); + } + + throw createConfigError( + ` Preset ${_chalk().default.bold(presetPath)} not found.` + ); + } + + throw createConfigError( + ` Missing dependency in ${_chalk().default.bold(presetPath)}:\n\n ${ + error.message + }\n ${error.stack}` + ); + } + + throw createConfigError( + ` An unknown error occurred in ${_chalk().default.bold( + presetPath + )}:\n\n ${error.message}\n ${error.stack}` + ); + } + + if (options.setupFiles) { + options.setupFiles = (preset.setupFiles || []).concat(options.setupFiles); + } + + if (options.setupFilesAfterEnv) { + options.setupFilesAfterEnv = (preset.setupFilesAfterEnv || []).concat( + options.setupFilesAfterEnv + ); + } + + if (options.modulePathIgnorePatterns && preset.modulePathIgnorePatterns) { + options.modulePathIgnorePatterns = preset.modulePathIgnorePatterns.concat( + options.modulePathIgnorePatterns + ); + } + + mergeModuleNameMapperWithPreset(options, preset); + mergeTransformWithPreset(options, preset); + mergeGlobalsWithPreset(options, preset); + return {...preset, ...options}; +}; + +const setupBabelJest = options => { + const transform = options.transform; + let babelJest; + + if (transform) { + const customJSPattern = Object.keys(transform).find(pattern => { + const regex = new RegExp(pattern); + return regex.test('a.js') || regex.test('a.jsx'); + }); + const customTSPattern = Object.keys(transform).find(pattern => { + const regex = new RegExp(pattern); + return regex.test('a.ts') || regex.test('a.tsx'); + }); + [customJSPattern, customTSPattern].forEach(pattern => { + if (pattern) { + const customTransformer = transform[pattern]; + + if (Array.isArray(customTransformer)) { + if (customTransformer[0] === 'babel-jest') { + babelJest = require.resolve('babel-jest'); + customTransformer[0] = babelJest; + } else if (customTransformer[0].includes('babel-jest')) { + babelJest = customTransformer[0]; + } + } else { + if (customTransformer === 'babel-jest') { + babelJest = require.resolve('babel-jest'); + transform[pattern] = babelJest; + } else if (customTransformer.includes('babel-jest')) { + babelJest = customTransformer; + } + } + } + }); + } else { + babelJest = require.resolve('babel-jest'); + options.transform = { + [_constants.DEFAULT_JS_PATTERN]: babelJest + }; + } +}; + +const normalizeCollectCoverageFrom = (options, key) => { + const initialCollectCoverageFrom = options[key]; + let value; + + if (!initialCollectCoverageFrom) { + value = []; + } + + if (!Array.isArray(initialCollectCoverageFrom)) { + try { + value = JSON.parse(initialCollectCoverageFrom); + } catch {} + + if (options[key] && !Array.isArray(value)) { + value = [initialCollectCoverageFrom]; + } + } else { + value = initialCollectCoverageFrom; + } + + if (value) { + value = value.map(filePath => + filePath.replace(/^(!?)(\/)(.*)/, '$1$3') + ); + } + + return value; +}; + +const normalizeUnmockedModulePathPatterns = ( + options, + key // _replaceRootDirTags is specifically well-suited for substituting +) => + // in paths (it deals with properly interpreting relative path + // separators, etc). + // + // For patterns, direct global substitution is far more ideal, so we + // special case substitutions for patterns here. + options[key].map(pattern => + (0, _jestRegexUtil().replacePathSepForRegex)( + pattern.replace(//g, options.rootDir) + ) + ); + +const normalizeMissingOptions = (options, configPath, projectIndex) => { + if (!options.id) { + options.id = (0, _crypto().createHash)('sha256') + .update(options.rootDir) // In case we load config from some path that has the same root dir + .update(configPath || '') + .update(String(projectIndex)) + .digest('hex') + .substring(0, 32); + } + + if (!options.setupFiles) { + options.setupFiles = []; + } + + return options; +}; + +const normalizeRootDir = options => { + // Assert that there *is* a rootDir + if (!options.rootDir) { + throw createConfigError( + ` Configuration option ${_chalk().default.bold( + 'rootDir' + )} must be specified.` + ); + } + + options.rootDir = path().normalize(options.rootDir); + + try { + // try to resolve windows short paths, ignoring errors (permission errors, mostly) + options.rootDir = (0, _jestUtil().tryRealpath)(options.rootDir); + } catch { + // ignored + } + + verifyDirectoryExists(options.rootDir, 'rootDir'); + return {...options, rootDir: options.rootDir}; +}; + +const normalizeReporters = ({reporters, rootDir}) => { + if (!reporters || !Array.isArray(reporters)) { + return undefined; + } + + (0, _ReporterValidationErrors.validateReporters)(reporters); + return reporters.map(reporterConfig => { + const normalizedReporterConfig = + typeof reporterConfig === 'string' // if reporter config is a string, we wrap it in an array + ? // and pass an empty object for options argument, to normalize + // the shape. + [reporterConfig, {}] + : reporterConfig; + const reporterPath = (0, _utils.replaceRootDirInPath)( + rootDir, + normalizedReporterConfig[0] + ); + + if (!['default', 'github-actions', 'summary'].includes(reporterPath)) { + const reporter = _jestResolve().default.findNodeModule(reporterPath, { + basedir: rootDir + }); + + if (!reporter) { + throw new (_jestResolve().default.ModuleNotFoundError)( + 'Could not resolve a module for a custom reporter.\n' + + ` Module name: ${reporterPath}` + ); + } + + normalizedReporterConfig[0] = reporter; + } + + return normalizedReporterConfig; + }); +}; + +const buildTestPathPattern = argv => { + const patterns = []; + + if (argv._) { + patterns.push(...argv._); + } + + if (argv.testPathPattern) { + patterns.push(...argv.testPathPattern); + } + + const replacePosixSep = pattern => { + // yargs coerces positional args into numbers + const patternAsString = pattern.toString(); + + if (path().sep === '/') { + return patternAsString; + } + + return patternAsString.replace(/\//g, '\\\\'); + }; + + const testPathPattern = patterns.map(replacePosixSep).join('|'); + + if ((0, _validatePattern.default)(testPathPattern)) { + return testPathPattern; + } else { + showTestPathPatternError(testPathPattern); + return ''; + } +}; + +const showTestPathPatternError = testPathPattern => { + (0, _jestUtil().clearLine)(process.stdout); // eslint-disable-next-line no-console + + console.log( + _chalk().default.red( + ` Invalid testPattern ${testPathPattern} supplied. ` + + 'Running all tests instead.' + ) + ); +}; + +function validateExtensionsToTreatAsEsm(extensionsToTreatAsEsm) { + if (!extensionsToTreatAsEsm || extensionsToTreatAsEsm.length === 0) { + return; + } + + function printConfig(opts) { + const string = opts.map(ext => `'${ext}'`).join(', '); + return _chalk().default.bold(`extensionsToTreatAsEsm: [${string}]`); + } + + const extensionWithoutDot = extensionsToTreatAsEsm.some( + ext => !ext.startsWith('.') + ); + + if (extensionWithoutDot) { + throw createConfigError(` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes a string that does not start with a period (${_chalk().default.bold( + '.' + )}). + Please change your configuration to ${printConfig( + extensionsToTreatAsEsm.map(ext => (ext.startsWith('.') ? ext : `.${ext}`)) + )}.`); + } + + if (extensionsToTreatAsEsm.includes('.js')) { + throw createConfigError( + ` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes ${_chalk().default.bold( + "'.js'" + )} which is always inferred based on ${_chalk().default.bold( + 'type' + )} in its nearest ${_chalk().default.bold('package.json')}.` + ); + } + + if (extensionsToTreatAsEsm.includes('.cjs')) { + throw createConfigError( + ` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes ${_chalk().default.bold( + "'.cjs'" + )} which is always treated as CommonJS.` + ); + } + + if (extensionsToTreatAsEsm.includes('.mjs')) { + throw createConfigError( + ` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes ${_chalk().default.bold( + "'.mjs'" + )} which is always treated as an ECMAScript Module.` + ); + } +} + +async function normalize( + initialOptions, + argv, + configPath, + projectIndex = Infinity +) { + const {hasDeprecationWarnings} = (0, _jestValidate().validate)( + initialOptions, + { + comment: _utils.DOCUMENTATION_NOTE, + deprecatedConfig: _Deprecated.default, + exampleConfig: _ValidConfig.default, + recursiveDenylist: [ + // 'coverageThreshold' allows to use 'global' and glob strings on the same + // level, there's currently no way we can deal with such config + 'coverageThreshold', + 'globals', + 'moduleNameMapper', + 'testEnvironmentOptions', + 'transform' + ] + } + ); + let options = normalizeMissingOptions( + normalizeRootDir((0, _setFromArgv.default)(initialOptions, argv)), + configPath, + projectIndex + ); + + if (options.preset) { + options = await setupPreset(options, options.preset); + } + + if (!options.setupFilesAfterEnv) { + options.setupFilesAfterEnv = []; + } + + options.testEnvironment = (0, _jestResolve().resolveTestEnvironment)({ + requireResolveFunction: require.resolve, + rootDir: options.rootDir, + testEnvironment: + options.testEnvironment || + require.resolve(_Defaults.default.testEnvironment) + }); + + if (!options.roots) { + options.roots = [options.rootDir]; + } + + if ( + !options.testRunner || + options.testRunner === 'circus' || + options.testRunner === 'jest-circus' || + options.testRunner === 'jest-circus/runner' + ) { + options.testRunner = require.resolve('jest-circus/runner'); + } else if (options.testRunner === 'jasmine2') { + try { + options.testRunner = require.resolve('jest-jasmine2'); + } catch (error) { + if (error.code === 'MODULE_NOT_FOUND') { + throw createConfigError( + 'jest-jasmine is no longer shipped by default with Jest, you need to install it explicitly or provide an absolute path to Jest' + ); + } + + throw error; + } + } + + if (!options.coverageDirectory) { + options.coverageDirectory = path().resolve(options.rootDir, 'coverage'); + } + + setupBabelJest(options); // TODO: Type this properly + + const newOptions = {..._Defaults.default}; + + if (options.resolver) { + newOptions.resolver = (0, _utils.resolve)(null, { + filePath: options.resolver, + key: 'resolver', + rootDir: options.rootDir + }); + } + + validateExtensionsToTreatAsEsm(options.extensionsToTreatAsEsm); + + if (options.watchman == null) { + options.watchman = _Defaults.default.watchman; + } + + const optionKeys = Object.keys(options); + optionKeys.reduce((newOptions, key) => { + // The resolver has been resolved separately; skip it + if (key === 'resolver') { + return newOptions; + } // This is cheating, because it claims that all keys of InitialOptions are Required. + // We only really know it's Required for oldOptions[key], not for oldOptions.someOtherKey, + // so oldOptions[key] is the only way it should be used. + + const oldOptions = options; + let value; + + switch (key) { + case 'setupFiles': + case 'setupFilesAfterEnv': + case 'snapshotSerializers': + { + const option = oldOptions[key]; + value = + option && + option.map(filePath => + (0, _utils.resolve)(newOptions.resolver, { + filePath, + key, + rootDir: options.rootDir + }) + ); + } + break; + + case 'modulePaths': + case 'roots': + { + const option = oldOptions[key]; + value = + option && + option.map(filePath => + path().resolve( + options.rootDir, + (0, _utils.replaceRootDirInPath)(options.rootDir, filePath) + ) + ); + } + break; + + case 'collectCoverageFrom': + value = normalizeCollectCoverageFrom(oldOptions, key); + break; + + case 'cacheDirectory': + case 'coverageDirectory': + { + const option = oldOptions[key]; + value = + option && + path().resolve( + options.rootDir, + (0, _utils.replaceRootDirInPath)(options.rootDir, option) + ); + } + break; + + case 'dependencyExtractor': + case 'globalSetup': + case 'globalTeardown': + case 'runtime': + case 'snapshotResolver': + case 'testResultsProcessor': + case 'testRunner': + case 'filter': + { + const option = oldOptions[key]; + value = + option && + (0, _utils.resolve)(newOptions.resolver, { + filePath: option, + key, + rootDir: options.rootDir + }); + } + break; + + case 'runner': + { + const option = oldOptions[key]; + value = + option && + (0, _jestResolve().resolveRunner)(newOptions.resolver, { + filePath: option, + requireResolveFunction: require.resolve, + rootDir: options.rootDir + }); + } + break; + + case 'prettierPath': + { + // We only want this to throw if "prettierPath" is explicitly passed + // from config or CLI, and the requested path isn't found. Otherwise we + // set it to null and throw an error lazily when it is used. + const option = oldOptions[key]; + value = + option && + (0, _utils.resolve)(newOptions.resolver, { + filePath: option, + key, + optional: option === _Defaults.default[key], + rootDir: options.rootDir + }); + } + break; + + case 'moduleNameMapper': + const moduleNameMapper = oldOptions[key]; + value = + moduleNameMapper && + Object.keys(moduleNameMapper).map(regex => { + const item = moduleNameMapper && moduleNameMapper[regex]; + return ( + item && [ + regex, + (0, _utils._replaceRootDirTags)(options.rootDir, item) + ] + ); + }); + break; + + case 'transform': + const transform = oldOptions[key]; + value = + transform && + Object.keys(transform).map(regex => { + const transformElement = transform[regex]; + return [ + regex, + (0, _utils.resolve)(newOptions.resolver, { + filePath: Array.isArray(transformElement) + ? transformElement[0] + : transformElement, + key, + rootDir: options.rootDir + }), + Array.isArray(transformElement) ? transformElement[1] : {} + ]; + }); + break; + + case 'reporters': + value = normalizeReporters(oldOptions); + break; + + case 'coveragePathIgnorePatterns': + case 'modulePathIgnorePatterns': + case 'testPathIgnorePatterns': + case 'transformIgnorePatterns': + case 'watchPathIgnorePatterns': + case 'unmockedModulePathPatterns': + value = normalizeUnmockedModulePathPatterns(oldOptions, key); + break; + + case 'haste': + value = {...oldOptions[key]}; + + if (value.hasteImplModulePath != null) { + const resolvedHasteImpl = (0, _utils.resolve)(newOptions.resolver, { + filePath: (0, _utils.replaceRootDirInPath)( + options.rootDir, + value.hasteImplModulePath + ), + key: 'haste.hasteImplModulePath', + rootDir: options.rootDir + }); + value.hasteImplModulePath = resolvedHasteImpl || undefined; + } + + break; + + case 'projects': + value = (oldOptions[key] || []) + .map(project => + typeof project === 'string' + ? (0, _utils._replaceRootDirTags)(options.rootDir, project) + : project + ) + .reduce((projects, project) => { + // Project can be specified as globs. If a glob matches any files, + // We expand it to these paths. If not, we keep the original path + // for the future resolution. + const globMatches = + typeof project === 'string' ? (0, _glob().sync)(project) : []; + return projects.concat(globMatches.length ? globMatches : project); + }, []); + break; + + case 'moduleDirectories': + case 'testMatch': + { + const replacedRootDirTags = (0, _utils._replaceRootDirTags)( + (0, _utils.escapeGlobCharacters)(options.rootDir), + oldOptions[key] + ); + + if (replacedRootDirTags) { + value = Array.isArray(replacedRootDirTags) + ? replacedRootDirTags.map(_jestUtil().replacePathSepForGlob) + : (0, _jestUtil().replacePathSepForGlob)(replacedRootDirTags); + } else { + value = replacedRootDirTags; + } + } + break; + + case 'testRegex': + { + const option = oldOptions[key]; + value = option + ? (Array.isArray(option) ? option : [option]).map( + _jestRegexUtil().replacePathSepForRegex + ) + : []; + } + break; + + case 'moduleFileExtensions': { + value = oldOptions[key]; + + if ( + Array.isArray(value) && // If it's the wrong type, it can throw at a later time + (options.runner === undefined || + options.runner === _Defaults.default.runner) && // Only require 'js' for the default jest-runner + !value.includes('js') + ) { + const errorMessage = + " moduleFileExtensions must include 'js':\n" + + ' but instead received:\n' + + ` ${_chalk().default.bold.red(JSON.stringify(value))}`; // If `js` is not included, any dependency Jest itself injects into + // the environment, like jasmine or sourcemap-support, will need to + // `require` its modules with a file extension. This is not plausible + // in the long run, so it's way easier to just fail hard early. + // We might consider throwing if `json` is missing as well, as it's a + // fair assumption from modules that they can do + // `require('some-package/package') without the trailing `.json` as it + // works in Node normally. + + throw createConfigError( + `${errorMessage}\n Please change your configuration to include 'js'.` + ); + } + + break; + } + + case 'bail': { + const bail = oldOptions[key]; + + if (typeof bail === 'boolean') { + value = bail ? 1 : 0; + } else if (typeof bail === 'string') { + value = 1; // If Jest is invoked as `jest --bail someTestPattern` then need to + // move the pattern from the `bail` configuration and into `argv._` + // to be processed as an extra parameter + + argv._.push(bail); + } else { + value = oldOptions[key]; + } + + break; + } + + case 'displayName': { + const displayName = oldOptions[key]; + /** + * Ensuring that displayName shape is correct here so that the + * reporters can trust the shape of the data + */ + + if (typeof displayName === 'object') { + const {name, color} = displayName; + + if ( + !name || + !color || + typeof name !== 'string' || + typeof color !== 'string' + ) { + const errorMessage = + ` Option "${_chalk().default.bold( + 'displayName' + )}" must be of type:\n\n` + + ' {\n' + + ' name: string;\n' + + ' color: string;\n' + + ' }\n'; + throw createConfigError(errorMessage); + } + + value = oldOptions[key]; + } else { + value = { + color: (0, _color.getDisplayNameColor)(options.runner), + name: displayName + }; + } + + break; + } + + case 'testTimeout': { + if (oldOptions[key] < 0) { + throw createConfigError( + ` Option "${_chalk().default.bold( + 'testTimeout' + )}" must be a natural number.` + ); + } + + value = oldOptions[key]; + break; + } + + case 'snapshotFormat': { + value = {..._Defaults.default.snapshotFormat, ...oldOptions[key]}; + break; + } + + case 'automock': + case 'cache': + case 'changedSince': + case 'changedFilesWithAncestor': + case 'clearMocks': + case 'collectCoverage': + case 'coverageProvider': + case 'coverageReporters': + case 'coverageThreshold': + case 'detectLeaks': + case 'detectOpenHandles': + case 'errorOnDeprecated': + case 'expand': + case 'extensionsToTreatAsEsm': + case 'globals': + case 'fakeTimers': + case 'findRelatedTests': + case 'forceCoverageMatch': + case 'forceExit': + case 'injectGlobals': + case 'lastCommit': + case 'listTests': + case 'logHeapUsage': + case 'maxConcurrency': + case 'id': + case 'noStackTrace': + case 'notify': + case 'notifyMode': + case 'onlyChanged': + case 'onlyFailures': + case 'outputFile': + case 'passWithNoTests': + case 'replname': + case 'resetMocks': + case 'resetModules': + case 'restoreMocks': + case 'rootDir': + case 'runTestsByPath': + case 'sandboxInjectedGlobals': + case 'silent': + case 'skipFilter': + case 'skipNodeResolution': + case 'slowTestThreshold': + case 'testEnvironment': + case 'testEnvironmentOptions': + case 'testFailureExitCode': + case 'testLocationInResults': + case 'testNamePattern': + case 'useStderr': + case 'verbose': + case 'watch': + case 'watchAll': + case 'watchman': + value = oldOptions[key]; + break; + + case 'workerIdleMemoryLimit': + value = (0, _stringToBytes.default)( + oldOptions[key], + (0, _os().totalmem)() + ); + break; + + case 'watchPlugins': + value = (oldOptions[key] || []).map(watchPlugin => { + if (typeof watchPlugin === 'string') { + return { + config: {}, + path: (0, _jestResolve().resolveWatchPlugin)( + newOptions.resolver, + { + filePath: watchPlugin, + requireResolveFunction: require.resolve, + rootDir: options.rootDir + } + ) + }; + } else { + return { + config: watchPlugin[1] || {}, + path: (0, _jestResolve().resolveWatchPlugin)( + newOptions.resolver, + { + filePath: watchPlugin[0], + requireResolveFunction: require.resolve, + rootDir: options.rootDir + } + ) + }; + } + }); + break; + } // @ts-expect-error: automock is missing in GlobalConfig, so what + + newOptions[key] = value; + return newOptions; + }, newOptions); + + if (options.watchman && options.haste?.enableSymlinks) { + throw new (_jestValidate().ValidationError)( + 'Validation Error', + 'haste.enableSymlinks is incompatible with watchman', + 'Either set haste.enableSymlinks to false or do not use watchman' + ); + } + + newOptions.roots.forEach((root, i) => { + verifyDirectoryExists(root, `roots[${i}]`); + }); + + try { + // try to resolve windows short paths, ignoring errors (permission errors, mostly) + newOptions.cwd = (0, _jestUtil().tryRealpath)(process.cwd()); + } catch { + // ignored + } + + newOptions.testSequencer = (0, _jestResolve().resolveSequencer)( + newOptions.resolver, + { + filePath: + options.testSequencer || + require.resolve(_Defaults.default.testSequencer), + requireResolveFunction: require.resolve, + rootDir: options.rootDir + } + ); + + if (newOptions.runner === _Defaults.default.runner) { + newOptions.runner = require.resolve(newOptions.runner); + } + + newOptions.nonFlagArgs = argv._?.map(arg => `${arg}`); + newOptions.testPathPattern = buildTestPathPattern(argv); + newOptions.json = !!argv.json; + newOptions.testFailureExitCode = parseInt(newOptions.testFailureExitCode, 10); + + if ( + newOptions.lastCommit || + newOptions.changedFilesWithAncestor || + newOptions.changedSince + ) { + newOptions.onlyChanged = true; + } + + if (argv.all) { + newOptions.onlyChanged = false; + newOptions.onlyFailures = false; + } else if (newOptions.testPathPattern) { + // When passing a test path pattern we don't want to only monitor changed + // files unless `--watch` is also passed. + newOptions.onlyChanged = newOptions.watch; + } + + if (!newOptions.onlyChanged) { + newOptions.onlyChanged = false; + } + + if (!newOptions.lastCommit) { + newOptions.lastCommit = false; + } + + if (!newOptions.onlyFailures) { + newOptions.onlyFailures = false; + } + + if (!newOptions.watchAll) { + newOptions.watchAll = false; + } // as unknown since it can happen. We really need to fix the types here + + if (newOptions.moduleNameMapper === _Defaults.default.moduleNameMapper) { + newOptions.moduleNameMapper = []; + } + + if (argv.ci != null) { + newOptions.ci = argv.ci; + } + + newOptions.updateSnapshot = + newOptions.ci && !argv.updateSnapshot + ? 'none' + : argv.updateSnapshot + ? 'all' + : 'new'; + newOptions.maxConcurrency = parseInt(newOptions.maxConcurrency, 10); + newOptions.maxWorkers = (0, _getMaxWorkers.default)(argv, options); + + if (newOptions.testRegex.length && options.testMatch) { + throw createConfigError( + ` Configuration options ${_chalk().default.bold('testMatch')} and` + + ` ${_chalk().default.bold('testRegex')} cannot be used together.` + ); + } + + if (newOptions.testRegex.length && !options.testMatch) { + // Prevent the default testMatch conflicting with any explicitly + // configured `testRegex` value + newOptions.testMatch = []; + } // If argv.json is set, coverageReporters shouldn't print a text report. + + if (argv.json) { + newOptions.coverageReporters = (newOptions.coverageReporters || []).filter( + reporter => reporter !== 'text' + ); + } // If collectCoverage is enabled while using --findRelatedTests we need to + // avoid having false negatives in the generated coverage report. + // The following: `--findRelatedTests '/rootDir/file1.js' --coverage` + // Is transformed to: `--findRelatedTests '/rootDir/file1.js' --coverage --collectCoverageFrom 'file1.js'` + // where arguments to `--collectCoverageFrom` should be globs (or relative + // paths to the rootDir) + + if (newOptions.collectCoverage && argv.findRelatedTests) { + let collectCoverageFrom = newOptions.nonFlagArgs.map(filename => { + filename = (0, _utils.replaceRootDirInPath)(options.rootDir, filename); + return path().isAbsolute(filename) + ? path().relative(options.rootDir, filename) + : filename; + }); // Don't override existing collectCoverageFrom options + + if (newOptions.collectCoverageFrom) { + collectCoverageFrom = collectCoverageFrom.reduce((patterns, filename) => { + if ( + (0, _micromatch().default)( + [ + (0, _jestUtil().replacePathSepForGlob)( + path().relative(options.rootDir, filename) + ) + ], + newOptions.collectCoverageFrom + ).length === 0 + ) { + return patterns; + } + + return [...patterns, filename]; + }, newOptions.collectCoverageFrom); + } + + newOptions.collectCoverageFrom = collectCoverageFrom; + } else if (!newOptions.collectCoverageFrom) { + newOptions.collectCoverageFrom = []; + } + + if (!newOptions.findRelatedTests) { + newOptions.findRelatedTests = false; + } + + if (!newOptions.projects) { + newOptions.projects = []; + } + + if (!newOptions.sandboxInjectedGlobals) { + newOptions.sandboxInjectedGlobals = []; + } + + if (!newOptions.forceExit) { + newOptions.forceExit = false; + } + + if (!newOptions.logHeapUsage) { + newOptions.logHeapUsage = false; + } + + if (argv.shard) { + newOptions.shard = (0, _parseShardPair.parseShardPair)(argv.shard); + } + + return { + hasDeprecationWarnings, + options: newOptions + }; +} diff --git a/node_modules/jest-config/build/parseShardPair.js b/node_modules/jest-config/build/parseShardPair.js new file mode 100644 index 0000000..a802698 --- /dev/null +++ b/node_modules/jest-config/build/parseShardPair.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.parseShardPair = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const parseShardPair = pair => { + const shardPair = pair + .split('/') + .filter(d => /^\d+$/.test(d)) + .map(d => parseInt(d, 10)) + .filter(shard => !Number.isNaN(shard)); + const [shardIndex, shardCount] = shardPair; + + if (shardPair.length !== 2) { + throw new Error( + 'The shard option requires a string in the format of /.' + ); + } + + if (shardIndex === 0 || shardCount === 0) { + throw new Error( + 'The shard option requires 1-based values, received 0 or lower in the pair.' + ); + } + + if (shardIndex > shardCount) { + throw new Error( + 'The shard option / requires to be lower or equal than .' + ); + } + + return { + shardCount, + shardIndex + }; +}; + +exports.parseShardPair = parseShardPair; diff --git a/node_modules/jest-config/build/readConfigFileAndSetRootDir.js b/node_modules/jest-config/build/readConfigFileAndSetRootDir.js new file mode 100644 index 0000000..a44734c --- /dev/null +++ b/node_modules/jest-config/build/readConfigFileAndSetRootDir.js @@ -0,0 +1,217 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = readConfigFileAndSetRootDir; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _parseJson() { + const data = _interopRequireDefault(require('parse-json')); + + _parseJson = function () { + return data; + }; + + return data; +} + +function _stripJsonComments() { + const data = _interopRequireDefault(require('strip-json-comments')); + + _stripJsonComments = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var _constants = require('./constants'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Read the configuration and set its `rootDir` +// 1. If it's a `package.json` file, we look into its "jest" property +// 2. If it's a `jest.config.ts` file, we use `ts-node` to transpile & require it +// 3. For any other file, we just require it. If we receive an 'ERR_REQUIRE_ESM' +// from node, perform a dynamic import instead. +async function readConfigFileAndSetRootDir(configPath) { + const isTS = configPath.endsWith(_constants.JEST_CONFIG_EXT_TS); + const isJSON = configPath.endsWith(_constants.JEST_CONFIG_EXT_JSON); + let configObject; + + try { + if (isTS) { + configObject = await loadTSConfigFile(configPath); + } else if (isJSON) { + const fileContent = fs().readFileSync(configPath, 'utf8'); + configObject = (0, _parseJson().default)( + (0, _stripJsonComments().default)(fileContent), + configPath + ); + } else { + configObject = await (0, _jestUtil().requireOrImportModule)(configPath); + } + } catch (error) { + if (isTS) { + throw new Error( + `Jest: Failed to parse the TypeScript config file ${configPath}\n` + + ` ${error}` + ); + } + + throw error; + } + + if (configPath.endsWith(_constants.PACKAGE_JSON)) { + // Event if there's no "jest" property in package.json we will still use + // an empty object. + configObject = configObject.jest || {}; + } + + if (typeof configObject === 'function') { + configObject = await configObject(); + } + + if (configObject.rootDir) { + // We don't touch it if it has an absolute path specified + if (!path().isAbsolute(configObject.rootDir)) { + // otherwise, we'll resolve it relative to the file's __dirname + configObject.rootDir = path().resolve( + path().dirname(configPath), + configObject.rootDir + ); + } + } else { + // If rootDir is not there, we'll set it to this file's __dirname + configObject.rootDir = path().dirname(configPath); + } + + return configObject; +} // Load the TypeScript configuration + +const loadTSConfigFile = async configPath => { + // Get registered TypeScript compiler instance + const registeredCompiler = await getRegisteredCompiler(); + registeredCompiler.enabled(true); + let configObject = (0, _jestUtil().interopRequireDefault)( + require(configPath) + ).default; // In case the config is a function which imports more Typescript code + + if (typeof configObject === 'function') { + configObject = await configObject(); + } + + registeredCompiler.enabled(false); + return configObject; +}; + +let registeredCompilerPromise; + +function getRegisteredCompiler() { + // Cache the promise to avoid multiple registrations + registeredCompilerPromise = registeredCompilerPromise ?? registerTsNode(); + return registeredCompilerPromise; +} + +async function registerTsNode() { + try { + // Register TypeScript compiler instance + const tsNode = await import('ts-node'); + return tsNode.register({ + compilerOptions: { + module: 'CommonJS' + }, + moduleTypes: { + '**': 'cjs' + } + }); + } catch (e) { + if (e.code === 'ERR_MODULE_NOT_FOUND') { + throw new Error( + `Jest: 'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${e.message}` + ); + } + + throw e; + } +} diff --git a/node_modules/jest-config/build/resolveConfigPath.js b/node_modules/jest-config/build/resolveConfigPath.js new file mode 100644 index 0000000..224eb6e --- /dev/null +++ b/node_modules/jest-config/build/resolveConfigPath.js @@ -0,0 +1,253 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = resolveConfigPath; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _slash() { + const data = _interopRequireDefault(require('slash')); + + _slash = function () { + return data; + }; + + return data; +} + +function _jestValidate() { + const data = require('jest-validate'); + + _jestValidate = function () { + return data; + }; + + return data; +} + +var _constants = require('./constants'); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const isFile = filePath => + fs().existsSync(filePath) && !fs().lstatSync(filePath).isDirectory(); + +const getConfigFilename = ext => _constants.JEST_CONFIG_BASE_NAME + ext; + +function resolveConfigPath( + pathToResolve, + cwd, + skipMultipleConfigError = false +) { + if (!path().isAbsolute(cwd)) { + throw new Error(`"cwd" must be an absolute path. cwd: ${cwd}`); + } + + const absolutePath = path().isAbsolute(pathToResolve) + ? pathToResolve + : path().resolve(cwd, pathToResolve); + + if (isFile(absolutePath)) { + return absolutePath; + } // This is a guard against passing non existing path as a project/config, + // that will otherwise result in a very confusing situation. + // e.g. + // With a directory structure like this: + // my_project/ + // package.json + // + // Passing a `my_project/some_directory_that_doesnt_exist` as a project + // name will resolve into a (possibly empty) `my_project/package.json` and + // try to run all tests it finds under `my_project` directory. + + if (!fs().existsSync(absolutePath)) { + throw new Error( + "Can't find a root directory while resolving a config file path.\n" + + `Provided path to resolve: ${pathToResolve}\n` + + `cwd: ${cwd}` + ); + } + + return resolveConfigPathByTraversing( + absolutePath, + pathToResolve, + cwd, + skipMultipleConfigError + ); +} + +const resolveConfigPathByTraversing = ( + pathToResolve, + initialPath, + cwd, + skipMultipleConfigError +) => { + const configFiles = _constants.JEST_CONFIG_EXT_ORDER.map(ext => + path().resolve(pathToResolve, getConfigFilename(ext)) + ).filter(isFile); + + const packageJson = findPackageJson(pathToResolve); + + if (packageJson && hasPackageJsonJestKey(packageJson)) { + configFiles.push(packageJson); + } + + if (!skipMultipleConfigError && configFiles.length > 1) { + throw new (_jestValidate().ValidationError)( + ...makeMultipleConfigsErrorMessage(configFiles) + ); + } + + if (configFiles.length > 0 || packageJson) { + return configFiles[0] ?? packageJson; + } // This is the system root. + // We tried everything, config is nowhere to be found ¯\_(ツ)_/¯ + + if (pathToResolve === path().dirname(pathToResolve)) { + throw new Error(makeResolutionErrorMessage(initialPath, cwd)); + } // go up a level and try it again + + return resolveConfigPathByTraversing( + path().dirname(pathToResolve), + initialPath, + cwd, + skipMultipleConfigError + ); +}; + +const findPackageJson = pathToResolve => { + const packagePath = path().resolve(pathToResolve, _constants.PACKAGE_JSON); + + if (isFile(packagePath)) { + return packagePath; + } + + return undefined; +}; + +const hasPackageJsonJestKey = packagePath => { + const content = fs().readFileSync(packagePath, 'utf8'); + + try { + return 'jest' in JSON.parse(content); + } catch { + // If package is not a valid JSON + return false; + } +}; + +const makeResolutionErrorMessage = (initialPath, cwd) => + 'Could not find a config file based on provided values:\n' + + `path: "${initialPath}"\n` + + `cwd: "${cwd}"\n` + + 'Config paths must be specified by either a direct path to a config\n' + + 'file, or a path to a directory. If directory is given, Jest will try to\n' + + `traverse directory tree up, until it finds one of those files in exact order: ${_constants.JEST_CONFIG_EXT_ORDER.map( + ext => `"${getConfigFilename(ext)}"` + ).join(' or ')}.`; + +function extraIfPackageJson(configPath) { + if (configPath.endsWith(_constants.PACKAGE_JSON)) { + return '`jest` key in '; + } + + return ''; +} + +const makeMultipleConfigsErrorMessage = configPaths => [ + `${_utils.BULLET}${_chalk().default.bold('Multiple configurations found')}`, + [ + ...configPaths.map( + configPath => + ` * ${extraIfPackageJson(configPath)}${(0, _slash().default)( + configPath + )}` + ), + '', + ' Implicit config resolution does not allow multiple configuration files.', + ' Either remove unused config files or select one explicitly with `--config`.' + ].join('\n'), + _utils.DOCUMENTATION_NOTE +]; diff --git a/node_modules/jest-config/build/setFromArgv.js b/node_modules/jest-config/build/setFromArgv.js new file mode 100644 index 0000000..1cc08bd --- /dev/null +++ b/node_modules/jest-config/build/setFromArgv.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = setFromArgv; + +var _utils = require('./utils'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const specialArgs = ['_', '$0', 'h', 'help', 'config']; + +function setFromArgv(options, argv) { + const argvToOptions = Object.keys(argv) + .filter(key => argv[key] !== undefined && specialArgs.indexOf(key) === -1) + .reduce((options, key) => { + switch (key) { + case 'coverage': + options.collectCoverage = argv[key]; + break; + + case 'json': + options.useStderr = argv[key]; + break; + + case 'watchAll': + options.watch = false; + options.watchAll = argv[key]; + break; + + case 'env': + options.testEnvironment = argv[key]; + break; + + case 'config': + break; + + case 'coverageThreshold': + case 'globals': + case 'haste': + case 'moduleNameMapper': + case 'testEnvironmentOptions': + case 'transform': + const str = argv[key]; + + if ((0, _utils.isJSONString)(str)) { + options[key] = JSON.parse(str); + } + + break; + + default: + options[key] = argv[key]; + } + + return options; + }, {}); + return { + ...options, + ...((0, _utils.isJSONString)(argv.config) ? JSON.parse(argv.config) : null), + ...argvToOptions + }; +} diff --git a/node_modules/jest-config/build/stringToBytes.js b/node_modules/jest-config/build/stringToBytes.js new file mode 100644 index 0000000..6deefa1 --- /dev/null +++ b/node_modules/jest-config/build/stringToBytes.js @@ -0,0 +1,88 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Converts a string representing an amount of memory to bytes. + * + * @param input The value to convert to bytes. + * @param percentageReference The reference value to use when a '%' value is supplied. + */ +function stringToBytes(input, percentageReference) { + if (input === null || input === undefined) { + return input; + } + + if (typeof input === 'string') { + if (isNaN(Number.parseFloat(input.slice(-1)))) { + // eslint-disable-next-line prefer-const + let [, numericString, trailingChars] = + input.match(/(.*?)([^0-9.-]+)$/i) || []; + + if (trailingChars && numericString) { + const numericValue = Number.parseFloat(numericString); + trailingChars = trailingChars.toLowerCase(); + + switch (trailingChars) { + case '%': + input = numericValue / 100; + break; + + case 'kb': + case 'k': + return numericValue * 1000; + + case 'kib': + return numericValue * 1024; + + case 'mb': + case 'm': + return numericValue * 1000 * 1000; + + case 'mib': + return numericValue * 1024 * 1024; + + case 'gb': + case 'g': + return numericValue * 1000 * 1000 * 1000; + + case 'gib': + return numericValue * 1024 * 1024 * 1024; + } + } // It ends in some kind of char so we need to do some parsing + } else { + input = Number.parseFloat(input); + } + } + + if (typeof input === 'number') { + if (input <= 1 && input > 0) { + if (percentageReference) { + return Math.floor(input * percentageReference); + } else { + throw new Error( + 'For a percentage based memory limit a percentageReference must be supplied' + ); + } + } else if (input > 1) { + return Math.floor(input); + } else { + throw new Error('Unexpected numerical input'); + } + } + + throw new Error('Unexpected input'); +} // https://github.com/import-js/eslint-plugin-import/issues/1590 + +var _default = stringToBytes; +exports.default = _default; diff --git a/node_modules/jest-config/build/utils.js b/node_modules/jest-config/build/utils.js new file mode 100644 index 0000000..28b05d3 --- /dev/null +++ b/node_modules/jest-config/build/utils.js @@ -0,0 +1,209 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.resolve = + exports.replaceRootDirInPath = + exports.isJSONString = + exports.escapeGlobCharacters = + exports._replaceRootDirTags = + exports.DOCUMENTATION_NOTE = + exports.BULLET = + void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _jestResolve() { + const data = _interopRequireDefault(require('jest-resolve')); + + _jestResolve = function () { + return data; + }; + + return data; +} + +function _jestValidate() { + const data = require('jest-validate'); + + _jestValidate = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const BULLET = _chalk().default.bold('\u25cf '); + +exports.BULLET = BULLET; +const DOCUMENTATION_NOTE = ` ${_chalk().default.bold( + 'Configuration Documentation:' +)} + https://jestjs.io/docs/configuration +`; +exports.DOCUMENTATION_NOTE = DOCUMENTATION_NOTE; + +const createValidationError = message => + new (_jestValidate().ValidationError)( + `${BULLET}Validation Error`, + message, + DOCUMENTATION_NOTE + ); + +const resolve = (resolver, {key, filePath, rootDir, optional}) => { + const module = _jestResolve().default.findNodeModule( + replaceRootDirInPath(rootDir, filePath), + { + basedir: rootDir, + resolver: resolver || undefined + } + ); + + if (!module && !optional) { + throw createValidationError(` Module ${_chalk().default.bold( + filePath + )} in the ${_chalk().default.bold(key)} option was not found. + ${_chalk().default.bold('')} is: ${rootDir}`); + } /// can cast as string since nulls will be thrown + + return module; +}; + +exports.resolve = resolve; + +const escapeGlobCharacters = path => path.replace(/([()*{}[\]!?\\])/g, '\\$1'); + +exports.escapeGlobCharacters = escapeGlobCharacters; + +const replaceRootDirInPath = (rootDir, filePath) => { + if (!/^/.test(filePath)) { + return filePath; + } + + return path().resolve( + rootDir, + path().normalize(`./${filePath.substring(''.length)}`) + ); +}; + +exports.replaceRootDirInPath = replaceRootDirInPath; + +const _replaceRootDirInObject = (rootDir, config) => { + const newConfig = {}; + + for (const configKey in config) { + newConfig[configKey] = + configKey === 'rootDir' + ? config[configKey] + : _replaceRootDirTags(rootDir, config[configKey]); + } + + return newConfig; +}; + +const _replaceRootDirTags = (rootDir, config) => { + if (config == null) { + return config; + } + + switch (typeof config) { + case 'object': + if (Array.isArray(config)) { + /// can be string[] or {}[] + return config.map(item => _replaceRootDirTags(rootDir, item)); + } + + if (config instanceof RegExp) { + return config; + } + + return _replaceRootDirInObject(rootDir, config); + + case 'string': + return replaceRootDirInPath(rootDir, config); + } + + return config; +}; + +exports._replaceRootDirTags = _replaceRootDirTags; + +// newtype +const isJSONString = text => + text != null && + typeof text === 'string' && + text.startsWith('{') && + text.endsWith('}'); + +exports.isJSONString = isJSONString; diff --git a/node_modules/jest-config/build/validatePattern.js b/node_modules/jest-config/build/validatePattern.js new file mode 100644 index 0000000..d18752e --- /dev/null +++ b/node_modules/jest-config/build/validatePattern.js @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = validatePattern; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function validatePattern(pattern) { + if (pattern) { + try { + // eslint-disable-next-line no-new + new RegExp(pattern, 'i'); + } catch { + return false; + } + } + + return true; +} diff --git a/node_modules/jest-config/package.json b/node_modules/jest-config/package.json new file mode 100644 index 0000000..6618db1 --- /dev/null +++ b/node_modules/jest-config/package.json @@ -0,0 +1,100 @@ +{ + "_from": "jest-config@^29.0.1", + "_id": "jest-config@29.0.1", + "_inBundle": false, + "_integrity": "sha512-3duIx5ucEPIsUOESDTuasMfqHonD0oZRjqHycIMHSC4JwbvHDjAWNKN/NiM0ZxHXjAYrMTLt2QxSQ+IqlbYE5A==", + "_location": "/jest-config", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-config@^29.0.1", + "name": "jest-config", + "escapedName": "jest-config", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/jest/jest-cli" + ], + "_resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.0.1.tgz", + "_shasum": "bccc2aedc3bafb6cb08bad23e5f0fcc3b1959268", + "_spec": "jest-config@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.0.1", + "@jest/types": "^29.0.1", + "babel-jest": "^29.0.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.0.1", + "jest-environment-node": "^29.0.1", + "jest-get-type": "^29.0.0", + "jest-regex-util": "^29.0.0", + "jest-resolve": "^29.0.1", + "jest-runner": "^29.0.1", + "jest-util": "^29.0.1", + "jest-validate": "^29.0.1", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.0.1", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "deprecated": false, + "devDependencies": { + "@types/glob": "^7.1.1", + "@types/graceful-fs": "^4.1.3", + "@types/micromatch": "^4.0.1", + "semver": "^7.3.5", + "ts-node": "^10.5.0", + "typescript": "^4.7.4" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-config", + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-config" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-diff/LICENSE b/node_modules/jest-diff/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-diff/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-diff/README.md b/node_modules/jest-diff/README.md new file mode 100644 index 0000000..d52f821 --- /dev/null +++ b/node_modules/jest-diff/README.md @@ -0,0 +1,671 @@ +# jest-diff + +Display differences clearly so people can review changes confidently. + +The `diff` named export serializes JavaScript **values**, compares them line-by-line, and returns a string which includes comparison lines. + +Two named exports compare **strings** character-by-character: + +- `diffStringsUnified` returns a string. +- `diffStringsRaw` returns an array of `Diff` objects. + +Three named exports compare **arrays of strings** line-by-line: + +- `diffLinesUnified` and `diffLinesUnified2` return a string. +- `diffLinesRaw` returns an array of `Diff` objects. + +## Installation + +To add this package as a dependency of a project, run either of the following commands: + +- `npm install jest-diff` +- `yarn add jest-diff` + +## Usage of `diff()` + +Given JavaScript **values**, `diff(a, b, options?)` does the following: + +1. **serialize** the values as strings using the `pretty-format` package +2. **compare** the strings line-by-line using the `diff-sequences` package +3. **format** the changed or common lines using the `chalk` package + +To use this function, write either of the following: + +- `const {diff} = require('jest-diff');` in CommonJS modules +- `import {diff} from 'jest-diff';` in ECMAScript modules + +### Example of `diff()` + +```js +const a = ['delete', 'common', 'changed from']; +const b = ['common', 'changed to', 'insert']; + +const difference = diff(a, b); +``` + +The returned **string** consists of: + +- annotation lines: describe the two change indicators with labels, and a blank line +- comparison lines: similar to “unified” view on GitHub, but `Expected` lines are green, `Received` lines are red, and common lines are dim (by default, see Options) + +```diff +- Expected ++ Received + + Array [ +- "delete", + "common", +- "changed from", ++ "changed to", ++ "insert", + ] +``` + +### Edge cases of `diff()` + +Here are edge cases for the return value: + +- `' Comparing two different types of values. …'` if the arguments have **different types** according to the `jest-get-type` package (instances of different classes have the same `'object'` type) +- `'Compared values have no visual difference.'` if the arguments have either **referential identity** according to `Object.is` method or **same serialization** according to the `pretty-format` package +- `null` if either argument is a so-called **asymmetric matcher** in Jasmine or Jest + +## Usage of diffStringsUnified + +Given **strings**, `diffStringsUnified(a, b, options?)` does the following: + +1. **compare** the strings character-by-character using the `diff-sequences` package +2. **clean up** small (often coincidental) common substrings, also known as chaff +3. **format** the changed or common lines using the `chalk` package + +Although the function is mainly for **multiline** strings, it compares any strings. + +Write either of the following: + +- `const {diffStringsUnified} = require('jest-diff');` in CommonJS modules +- `import {diffStringsUnified} from 'jest-diff';` in ECMAScript modules + +### Example of diffStringsUnified + +```js +const a = 'common\nchanged from'; +const b = 'common\nchanged to'; + +const difference = diffStringsUnified(a, b); +``` + +The returned **string** consists of: + +- annotation lines: describe the two change indicators with labels, and a blank line +- comparison lines: similar to “unified” view on GitHub, and **changed substrings** have **inverse** foreground and background colors (that is, `from` has white-on-green and `to` has white-on-red, which the following example does not show) + +```diff +- Expected ++ Received + + common +- changed from ++ changed to +``` + +### Performance of diffStringsUnified + +To get the benefit of **changed substrings** within the comparison lines, a character-by-character comparison has a higher computational cost (in time and space) than a line-by-line comparison. + +If the input strings can have **arbitrary length**, we recommend that the calling code set a limit, beyond which splits the strings, and then calls `diffLinesUnified` instead. For example, Jest falls back to line-by-line comparison if either string has length greater than 20K characters. + +## Usage of diffLinesUnified + +Given **arrays of strings**, `diffLinesUnified(aLines, bLines, options?)` does the following: + +1. **compare** the arrays line-by-line using the `diff-sequences` package +2. **format** the changed or common lines using the `chalk` package + +You might call this function when strings have been split into lines and you do not need to see changed substrings within lines. + +### Example of diffLinesUnified + +```js +const aLines = ['delete', 'common', 'changed from']; +const bLines = ['common', 'changed to', 'insert']; + +const difference = diffLinesUnified(aLines, bLines); +``` + +```diff +- Expected ++ Received + +- delete + common +- changed from ++ changed to ++ insert +``` + +### Edge cases of diffLinesUnified or diffStringsUnified + +Here are edge cases for arguments and return values: + +- both `a` and `b` are empty strings: no comparison lines +- only `a` is empty string: all comparison lines have `bColor` and `bIndicator` (see Options) +- only `b` is empty string: all comparison lines have `aColor` and `aIndicator` (see Options) +- `a` and `b` are equal non-empty strings: all comparison lines have `commonColor` and `commonIndicator` (see Options) + +## Usage of diffLinesUnified2 + +Given two **pairs** of arrays of strings, `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options?)` does the following: + +1. **compare** the pair of `Compare` arrays line-by-line using the `diff-sequences` package +2. **format** the corresponding lines in the pair of `Display` arrays using the `chalk` package + +Jest calls this function to consider lines as common instead of changed if the only difference is indentation. + +You might call this function for case insensitive or Unicode equivalence comparison of lines. + +### Example of diffLinesUnified2 + +```js +import {format} from 'pretty-format'; + +const a = { + text: 'Ignore indentation in serialized object', + time: '2019-09-19T12:34:56.000Z', + type: 'CREATE_ITEM', +}; +const b = { + payload: { + text: 'Ignore indentation in serialized object', + time: '2019-09-19T12:34:56.000Z', + }, + type: 'CREATE_ITEM', +}; + +const difference = diffLinesUnified2( + // serialize with indentation to display lines + format(a).split('\n'), + format(b).split('\n'), + // serialize without indentation to compare lines + format(a, {indent: 0}).split('\n'), + format(b, {indent: 0}).split('\n'), +); +``` + +The `text` and `time` properties are common, because their only difference is indentation: + +```diff +- Expected ++ Received + + Object { ++ payload: Object { + text: 'Ignore indentation in serialized object', + time: '2019-09-19T12:34:56.000Z', ++ }, + type: 'CREATE_ITEM', + } +``` + +The preceding example illustrates why (at least for indentation) it seems more intuitive that the function returns the common line from the `bLinesDisplay` array instead of from the `aLinesDisplay` array. + +## Usage of diffStringsRaw + +Given **strings** and a boolean option, `diffStringsRaw(a, b, cleanup)` does the following: + +1. **compare** the strings character-by-character using the `diff-sequences` package +2. optionally **clean up** small (often coincidental) common substrings, also known as chaff + +Because `diffStringsRaw` returns the difference as **data** instead of a string, you can format it as your application requires (for example, enclosed in HTML markup for browser instead of escape sequences for console). + +The returned **array** describes substrings as instances of the `Diff` class, which calling code can access like array tuples: + +The value at index `0` is one of the following: + +| value | named export | description | +| ----: | :------------ | :-------------------- | +| `0` | `DIFF_EQUAL` | in `a` and in `b` | +| `-1` | `DIFF_DELETE` | in `a` but not in `b` | +| `1` | `DIFF_INSERT` | in `b` but not in `a` | + +The value at index `1` is a substring of `a` or `b` or both. + +### Example of diffStringsRaw with cleanup + +```js +const diffs = diffStringsRaw('changed from', 'changed to', true); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------ | +| `0` | `0` | `'changed '` | +| `1` | `-1` | `'from'` | +| `2` | `1` | `'to'` | + +### Example of diffStringsRaw without cleanup + +```js +const diffs = diffStringsRaw('changed from', 'changed to', false); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------ | +| `0` | `0` | `'changed '` | +| `1` | `-1` | `'fr'` | +| `2` | `1` | `'t'` | +| `3` | `0` | `'o'` | +| `4` | `-1` | `'m'` | + +### Advanced import for diffStringsRaw + +Here are all the named imports that you might need for the `diffStringsRaw` function: + +- `const {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} = require('jest-diff');` in CommonJS modules +- `import {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} from 'jest-diff';` in ECMAScript modules + +To write a **formatting** function, you might need the named constants (and `Diff` in TypeScript annotations). + +If you write an application-specific **cleanup** algorithm, then you might need to call the `Diff` constructor: + +```js +const diffCommon = new Diff(DIFF_EQUAL, 'changed '); +const diffDelete = new Diff(DIFF_DELETE, 'from'); +const diffInsert = new Diff(DIFF_INSERT, 'to'); +``` + +## Usage of diffLinesRaw + +Given **arrays of strings**, `diffLinesRaw(aLines, bLines)` does the following: + +- **compare** the arrays line-by-line using the `diff-sequences` package + +Because `diffLinesRaw` returns the difference as **data** instead of a string, you can format it as your application requires. + +### Example of diffLinesRaw + +```js +const aLines = ['delete', 'common', 'changed from']; +const bLines = ['common', 'changed to', 'insert']; + +const diffs = diffLinesRaw(aLines, bLines); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :--------------- | +| `0` | `-1` | `'delete'` | +| `1` | `0` | `'common'` | +| `2` | `-1` | `'changed from'` | +| `3` | `1` | `'changed to'` | +| `4` | `1` | `'insert'` | + +### Edge case of diffLinesRaw + +If you call `string.split('\n')` for an empty string: + +- the result is `['']` an array which contains an empty string +- instead of `[]` an empty array + +Depending of your application, you might call `diffLinesRaw` with either array. + +### Example of split method + +```js +import {diffLinesRaw} from 'jest-diff'; + +const a = 'non-empty string'; +const b = ''; + +const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------------- | +| `0` | `-1` | `'non-empty string'` | +| `1` | `1` | `''` | + +Which you might format as follows: + +```diff +- Expected - 1 ++ Received + 1 + +- non-empty string ++ +``` + +### Example of splitLines0 function + +For edge case behavior like the `diffLinesUnified` function, you might define a `splitLines0` function, which given an empty string, returns `[]` an empty array: + +```js +export const splitLines0 = string => + string.length === 0 ? [] : string.split('\n'); +``` + +```js +import {diffLinesRaw} from 'jest-diff'; + +const a = ''; +const b = 'line 1\nline 2\nline 3'; + +const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------ | +| `0` | `1` | `'line 1'` | +| `1` | `1` | `'line 2'` | +| `2` | `1` | `'line 3'` | + +Which you might format as follows: + +```diff +- Expected - 0 ++ Received + 3 + ++ line 1 ++ line 2 ++ line 3 +``` + +In contrast to the `diffLinesRaw` function, the `diffLinesUnified` and `diffLinesUnified2` functions **automatically** convert array arguments computed by string `split` method, so callers do **not** need a `splitLine0` function. + +## Options + +The default options are for the report when an assertion fails from the `expect` package used by Jest. + +For other applications, you can provide an options object as a third argument: + +- `diff(a, b, options)` +- `diffStringsUnified(a, b, options)` +- `diffLinesUnified(aLines, bLines, options)` +- `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options)` + +### Properties of options object + +| name | default | +| :-------------------------------- | :----------------- | +| `aAnnotation` | `'Expected'` | +| `aColor` | `chalk.green` | +| `aIndicator` | `'-'` | +| `bAnnotation` | `'Received'` | +| `bColor` | `chalk.red` | +| `bIndicator` | `'+'` | +| `changeColor` | `chalk.inverse` | +| `changeLineTrailingSpaceColor` | `string => string` | +| `commonColor` | `chalk.dim` | +| `commonIndicator` | `' '` | +| `commonLineTrailingSpaceColor` | `string => string` | +| `compareKeys` | `undefined` | +| `contextLines` | `5` | +| `emptyFirstOrLastLinePlaceholder` | `''` | +| `expand` | `true` | +| `includeChangeCounts` | `false` | +| `omitAnnotationLines` | `false` | +| `patchColor` | `chalk.yellow` | + +For more information about the options, see the following examples. + +### Example of options for labels + +If the application is code modification, you might replace the labels: + +```js +const options = { + aAnnotation: 'Original', + bAnnotation: 'Modified', +}; +``` + +```diff +- Original ++ Modified + + common +- changed from ++ changed to +``` + +The `jest-diff` package does not assume that the 2 labels have equal length. + +### Example of options for colors of changed lines + +For consistency with most diff tools, you might exchange the colors: + +```ts +import chalk = require('chalk'); + +const options = { + aColor: chalk.red, + bColor: chalk.green, +}; +``` + +### Example of option for color of changed substrings + +Although the default inverse of foreground and background colors is hard to beat for changed substrings **within lines**, especially because it highlights spaces, if you want bold font weight on yellow background color: + +```ts +import chalk = require('chalk'); + +const options = { + changeColor: chalk.bold.bgYellowBright, +}; +``` + +### Example of option to format trailing spaces + +Because `diff()` does not display substring differences within lines, formatting can help you see when lines differ by the presence or absence of trailing spaces found by `/\s+$/` regular expression. + +- If change lines have a background color, then you can see trailing spaces. +- If common lines have default dim color, then you cannot see trailing spaces. You might want yellowish background color to see them. + +```js +const options = { + aColor: chalk.rgb(128, 0, 128).bgRgb(255, 215, 255), // magenta + bColor: chalk.rgb(0, 95, 0).bgRgb(215, 255, 215), // green + commonLineTrailingSpaceColor: chalk.bgYellow, +}; +``` + +The value of a Color option is a function, which given a string, returns a string. + +If you want to replace trailing spaces with middle dot characters: + +```js +const replaceSpacesWithMiddleDot = string => '·'.repeat(string.length); + +const options = { + changeLineTrailingSpaceColor: replaceSpacesWithMiddleDot, + commonLineTrailingSpaceColor: replaceSpacesWithMiddleDot, +}; +``` + +If you need the TypeScript type of a Color option: + +```ts +import {DiffOptionsColor} from 'jest-diff'; +``` + +### Example of options for no colors + +To store the difference in a file without escape codes for colors, provide an identity function: + +```js +const noColor = string => string; + +const options = { + aColor: noColor, + bColor: noColor, + changeColor: noColor, + commonColor: noColor, + patchColor: noColor, +}; +``` + +### Example of options for indicators + +For consistency with the `diff` command, you might replace the indicators: + +```js +const options = { + aIndicator: '<', + bIndicator: '>', +}; +``` + +The `jest-diff` package assumes (but does not enforce) that the 3 indicators have equal length. + +### Example of options to limit common lines + +By default, the output includes all common lines. + +To emphasize the changes, you might limit the number of common “context” lines: + +```js +const options = { + contextLines: 1, + expand: false, +}; +``` + +A patch mark like `@@ -12,7 +12,9 @@` accounts for omitted common lines. + +### Example of option for color of patch marks + +If you want patch marks to have the same dim color as common lines: + +```ts +import chalk = require('chalk'); + +const options = { + expand: false, + patchColor: chalk.dim, +}; +``` + +### Example of option to include change counts + +To display the number of changed lines at the right of annotation lines: + +```js +const a = ['common', 'changed from']; +const b = ['common', 'changed to', 'insert']; + +const options = { + includeChangeCounts: true, +}; + +const difference = diff(a, b, options); +``` + +```diff +- Expected - 1 ++ Received + 2 + + Array [ + "common", +- "changed from", ++ "changed to", ++ "insert", + ] +``` + +### Example of option to omit annotation lines + +To display only the comparison lines: + +```js +const a = 'common\nchanged from'; +const b = 'common\nchanged to'; + +const options = { + omitAnnotationLines: true, +}; + +const difference = diffStringsUnified(a, b, options); +``` + +```diff + common +- changed from ++ changed to +``` + +### Example of option for empty first or last lines + +If the **first** or **last** comparison line is **empty**, because the content is empty and the indicator is a space, you might not notice it. + +The replacement option is a string whose default value is `''` empty string. + +Because Jest trims the report when a matcher fails, it deletes an empty last line. + +Therefore, Jest uses as placeholder the downwards arrow with corner leftwards: + +```js +const options = { + emptyFirstOrLastLinePlaceholder: '↵', // U+21B5 +}; +``` + +If a content line is empty, then the corresponding comparison line is automatically trimmed to remove the margin space (represented as a middle dot below) for the default indicators: + +| Indicator | untrimmed | trimmed | +| ----------------: | :-------- | :------ | +| `aIndicator` | `'-·'` | `'-'` | +| `bIndicator` | `'+·'` | `'+'` | +| `commonIndicator` | `' ·'` | `''` | + +### Example of option for sorting object keys + +When two objects are compared their keys are printed in alphabetical order by default. If this was not the original order of the keys the diff becomes harder to read as the keys are not in their original position. + +Use `compareKeys` to pass a function which will be used when sorting the object keys. + +```js +const a = {c: 'c', b: 'b1', a: 'a'}; +const b = {c: 'c', b: 'b2', a: 'a'}; + +const options = { + // The keys will be in their original order + compareKeys: () => 0, +}; + +const difference = diff(a, b, options); +``` + +```diff +- Expected ++ Received + + Object { + "c": "c", +- "b": "b1", ++ "b": "b2", + "a": "a", + } +``` + +Depending on the implementation of `compareKeys` any sort order can be used. + +```js +const a = {c: 'c', b: 'b1', a: 'a'}; +const b = {c: 'c', b: 'b2', a: 'a'}; + +const options = { + // The keys will be in reverse order + compareKeys: (a, b) => (a > b ? -1 : 1), +}; + +const difference = diff(a, b, options); +``` + +```diff +- Expected ++ Received + + Object { + "a": "a", +- "b": "b1", ++ "b": "b2", + "c": "c", + } +``` diff --git a/node_modules/jest-diff/build/cleanupSemantic.js b/node_modules/jest-diff/build/cleanupSemantic.js new file mode 100644 index 0000000..6640de5 --- /dev/null +++ b/node_modules/jest-diff/build/cleanupSemantic.js @@ -0,0 +1,640 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.cleanupSemantic = + exports.Diff = + exports.DIFF_INSERT = + exports.DIFF_EQUAL = + exports.DIFF_DELETE = + void 0; + +/** + * Diff Match and Patch + * Copyright 2018 The diff-match-patch Authors. + * https://github.com/google/diff-match-patch + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @fileoverview Computes the difference between two texts to create a patch. + * Applies the patch onto another text, allowing for errors. + * @author fraser@google.com (Neil Fraser) + */ + +/** + * CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: + * + * 1. Delete anything not needed to use diff_cleanupSemantic method + * 2. Convert from prototype properties to var declarations + * 3. Convert Diff to class from constructor and prototype + * 4. Add type annotations for arguments and return values + * 5. Add exports + */ + +/** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ +var DIFF_DELETE = -1; +exports.DIFF_DELETE = DIFF_DELETE; +var DIFF_INSERT = 1; +exports.DIFF_INSERT = DIFF_INSERT; +var DIFF_EQUAL = 0; +/** + * Class representing one diff tuple. + * Attempts to look like a two-element array (which is what this used to be). + * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. + * @param {string} text Text to be deleted, inserted, or retained. + * @constructor + */ + +exports.DIFF_EQUAL = DIFF_EQUAL; + +class Diff { + 0; + 1; + + constructor(op, text) { + this[0] = op; + this[1] = text; + } +} +/** + * Determine the common prefix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the start of each + * string. + */ + +exports.Diff = Diff; + +var diff_commonPrefix = function (text1, text2) { + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { + return 0; + } // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerstart = 0; + + while (pointermin < pointermid) { + if ( + text1.substring(pointerstart, pointermid) == + text2.substring(pointerstart, pointermid) + ) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + + return pointermid; +}; +/** + * Determine the common suffix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of each string. + */ + +var diff_commonSuffix = function (text1, text2) { + // Quick check for common null cases. + if ( + !text1 || + !text2 || + text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1) + ) { + return 0; + } // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerend = 0; + + while (pointermin < pointermid) { + if ( + text1.substring(text1.length - pointermid, text1.length - pointerend) == + text2.substring(text2.length - pointermid, text2.length - pointerend) + ) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + + return pointermid; +}; +/** + * Determine if the suffix of one string is the prefix of another. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of the first + * string and the start of the second string. + * @private + */ + +var diff_commonOverlap_ = function (text1, text2) { + // Cache the text lengths to prevent multiple calls. + var text1_length = text1.length; + var text2_length = text2.length; // Eliminate the null case. + + if (text1_length == 0 || text2_length == 0) { + return 0; + } // Truncate the longer string. + + if (text1_length > text2_length) { + text1 = text1.substring(text1_length - text2_length); + } else if (text1_length < text2_length) { + text2 = text2.substring(0, text1_length); + } + + var text_length = Math.min(text1_length, text2_length); // Quick check for the worst case. + + if (text1 == text2) { + return text_length; + } // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: https://neil.fraser.name/news/2010/11/04/ + + var best = 0; + var length = 1; + + while (true) { + var pattern = text1.substring(text_length - length); + var found = text2.indexOf(pattern); + + if (found == -1) { + return best; + } + + length += found; + + if ( + found == 0 || + text1.substring(text_length - length) == text2.substring(0, length) + ) { + best = length; + length++; + } + } +}; +/** + * Reduce the number of edits by eliminating semantically trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ + +var diff_cleanupSemantic = function (diffs) { + var changes = false; + var equalities = []; // Stack of indices where equalities are found. + + var equalitiesLength = 0; // Keeping our own length var is faster in JS. + + /** @type {?string} */ + + var lastEquality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1] + + var pointer = 0; // Index of current position. + // Number of characters that changed prior to the equality. + + var length_insertions1 = 0; + var length_deletions1 = 0; // Number of characters that changed after the equality. + + var length_insertions2 = 0; + var length_deletions2 = 0; + + while (pointer < diffs.length) { + if (diffs[pointer][0] == DIFF_EQUAL) { + // Equality found. + equalities[equalitiesLength++] = pointer; + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs[pointer][1]; + } else { + // An insertion or deletion. + if (diffs[pointer][0] == DIFF_INSERT) { + length_insertions2 += diffs[pointer][1].length; + } else { + length_deletions2 += diffs[pointer][1].length; + } // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + + if ( + lastEquality && + lastEquality.length <= + Math.max(length_insertions1, length_deletions1) && + lastEquality.length <= Math.max(length_insertions2, length_deletions2) + ) { + // Duplicate record. + diffs.splice( + equalities[equalitiesLength - 1], + 0, + new Diff(DIFF_DELETE, lastEquality) + ); // Change second copy to insert. + + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; // Throw away the equality we just deleted. + + equalitiesLength--; // Throw away the previous equality (it needs to be reevaluated). + + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; // Reset the counters. + + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + + pointer++; + } // Normalize the diff. + + if (changes) { + diff_cleanupMerge(diffs); + } + + diff_cleanupSemanticLossless(diffs); // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + + pointer = 1; + + while (pointer < diffs.length) { + if ( + diffs[pointer - 1][0] == DIFF_DELETE && + diffs[pointer][0] == DIFF_INSERT + ) { + var deletion = diffs[pointer - 1][1]; + var insertion = diffs[pointer][1]; + var overlap_length1 = diff_commonOverlap_(deletion, insertion); + var overlap_length2 = diff_commonOverlap_(insertion, deletion); + + if (overlap_length1 >= overlap_length2) { + if ( + overlap_length1 >= deletion.length / 2 || + overlap_length1 >= insertion.length / 2 + ) { + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice( + pointer, + 0, + new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1)) + ); + diffs[pointer - 1][1] = deletion.substring( + 0, + deletion.length - overlap_length1 + ); + diffs[pointer + 1][1] = insertion.substring(overlap_length1); + pointer++; + } + } else { + if ( + overlap_length2 >= deletion.length / 2 || + overlap_length2 >= insertion.length / 2 + ) { + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice( + pointer, + 0, + new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2)) + ); + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = insertion.substring( + 0, + insertion.length - overlap_length2 + ); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = deletion.substring(overlap_length2); + pointer++; + } + } + + pointer++; + } + + pointer++; + } +}; +/** + * Look for single edits surrounded on both sides by equalities + * which can be shifted sideways to align the edit to a word boundary. + * e.g: The cat came. -> The cat came. + * @param {!Array.} diffs Array of diff tuples. + */ + +exports.cleanupSemantic = diff_cleanupSemantic; + +var diff_cleanupSemanticLossless = function (diffs) { + /** + * Given two strings, compute a score representing whether the internal + * boundary falls on logical boundaries. + * Scores range from 6 (best) to 0 (worst). + * Closure, but does not reference any external variables. + * @param {string} one First string. + * @param {string} two Second string. + * @return {number} The score. + * @private + */ + function diff_cleanupSemanticScore_(one, two) { + if (!one || !two) { + // Edges are the best. + return 6; + } // Each port of this function behaves slightly differently due to + // subtle differences in each language's definition of things like + // 'whitespace'. Since this function's purpose is largely cosmetic, + // the choice has been made to use each language's native features + // rather than force total conformity. + + var char1 = one.charAt(one.length - 1); + var char2 = two.charAt(0); + var nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); + var nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); + var whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); + var whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); + var lineBreak1 = whitespace1 && char1.match(linebreakRegex_); + var lineBreak2 = whitespace2 && char2.match(linebreakRegex_); + var blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); + var blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); + + if (blankLine1 || blankLine2) { + // Five points for blank lines. + return 5; + } else if (lineBreak1 || lineBreak2) { + // Four points for line breaks. + return 4; + } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + // Three points for end of sentences. + return 3; + } else if (whitespace1 || whitespace2) { + // Two points for whitespace. + return 2; + } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + // One point for non-alphanumeric. + return 1; + } + + return 0; + } + + var pointer = 1; // Intentionally ignore the first and last element (don't need checking). + + while (pointer < diffs.length - 1) { + if ( + diffs[pointer - 1][0] == DIFF_EQUAL && + diffs[pointer + 1][0] == DIFF_EQUAL + ) { + // This is a single edit surrounded by equalities. + var equality1 = diffs[pointer - 1][1]; + var edit = diffs[pointer][1]; + var equality2 = diffs[pointer + 1][1]; // First, shift the edit as far left as possible. + + var commonOffset = diff_commonSuffix(equality1, edit); + + if (commonOffset) { + var commonString = edit.substring(edit.length - commonOffset); + equality1 = equality1.substring(0, equality1.length - commonOffset); + edit = commonString + edit.substring(0, edit.length - commonOffset); + equality2 = commonString + equality2; + } // Second, step character by character right, looking for the best fit. + + var bestEquality1 = equality1; + var bestEdit = edit; + var bestEquality2 = equality2; + var bestScore = + diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); + + while (edit.charAt(0) === equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + var score = + diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); // The >= encourages trailing rather than leading whitespace on edits. + + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + + if (diffs[pointer - 1][1] != bestEquality1) { + // We have an improvement, save it back to the diff. + if (bestEquality1) { + diffs[pointer - 1][1] = bestEquality1; + } else { + diffs.splice(pointer - 1, 1); + pointer--; + } + + diffs[pointer][1] = bestEdit; + + if (bestEquality2) { + diffs[pointer + 1][1] = bestEquality2; + } else { + diffs.splice(pointer + 1, 1); + pointer--; + } + } + } + + pointer++; + } +}; // Define some regex patterns for matching boundaries. + +var nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; +var whitespaceRegex_ = /\s/; +var linebreakRegex_ = /[\r\n]/; +var blanklineEndRegex_ = /\n\r?\n$/; +var blanklineStartRegex_ = /^\r?\n\r?\n/; +/** + * Reorder and merge like edit sections. Merge equalities. + * Any edit section can move as long as it doesn't cross an equality. + * @param {!Array.} diffs Array of diff tuples. + */ + +var diff_cleanupMerge = function (diffs) { + // Add a dummy entry at the end. + diffs.push(new Diff(DIFF_EQUAL, '')); + var pointer = 0; + var count_delete = 0; + var count_insert = 0; + var text_delete = ''; + var text_insert = ''; + var commonlength; + + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer][1]; + pointer++; + break; + + case DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer][1]; + pointer++; + break; + + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (count_delete + count_insert > 1) { + if (count_delete !== 0 && count_insert !== 0) { + // Factor out any common prefixies. + commonlength = diff_commonPrefix(text_insert, text_delete); + + if (commonlength !== 0) { + if ( + pointer - count_delete - count_insert > 0 && + diffs[pointer - count_delete - count_insert - 1][0] == + DIFF_EQUAL + ) { + diffs[pointer - count_delete - count_insert - 1][1] += + text_insert.substring(0, commonlength); + } else { + diffs.splice( + 0, + 0, + new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength)) + ); + pointer++; + } + + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } // Factor out any common suffixies. + + commonlength = diff_commonSuffix(text_insert, text_delete); + + if (commonlength !== 0) { + diffs[pointer][1] = + text_insert.substring(text_insert.length - commonlength) + + diffs[pointer][1]; + text_insert = text_insert.substring( + 0, + text_insert.length - commonlength + ); + text_delete = text_delete.substring( + 0, + text_delete.length - commonlength + ); + } + } // Delete the offending records and add the merged ones. + + pointer -= count_delete + count_insert; + diffs.splice(pointer, count_delete + count_insert); + + if (text_delete.length) { + diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); + pointer++; + } + + if (text_insert.length) { + diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); + pointer++; + } + + pointer++; + } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { + // Merge this equality with the previous one. + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + + count_insert = 0; + count_delete = 0; + text_delete = ''; + text_insert = ''; + break; + } + } + + if (diffs[diffs.length - 1][1] === '') { + diffs.pop(); // Remove the dummy entry at the end. + } // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: ABAC -> ABAC + + var changes = false; + pointer = 1; // Intentionally ignore the first and last element (don't need checking). + + while (pointer < diffs.length - 1) { + if ( + diffs[pointer - 1][0] == DIFF_EQUAL && + diffs[pointer + 1][0] == DIFF_EQUAL + ) { + // This is a single edit surrounded by equalities. + if ( + diffs[pointer][1].substring( + diffs[pointer][1].length - diffs[pointer - 1][1].length + ) == diffs[pointer - 1][1] + ) { + // Shift the edit over the previous equality. + diffs[pointer][1] = + diffs[pointer - 1][1] + + diffs[pointer][1].substring( + 0, + diffs[pointer][1].length - diffs[pointer - 1][1].length + ); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if ( + diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == + diffs[pointer + 1][1] + ) { + // Shift the edit over the next equality. + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = + diffs[pointer][1].substring(diffs[pointer + 1][1].length) + + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + + pointer++; + } // If shifts were made, the diff needs reordering and another shift sweep. + + if (changes) { + diff_cleanupMerge(diffs); + } +}; diff --git a/node_modules/jest-diff/build/constants.js b/node_modules/jest-diff/build/constants.js new file mode 100644 index 0000000..ccf73e5 --- /dev/null +++ b/node_modules/jest-diff/build/constants.js @@ -0,0 +1,19 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.SIMILAR_MESSAGE = exports.NO_DIFF_MESSAGE = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const NO_DIFF_MESSAGE = 'Compared values have no visual difference.'; +exports.NO_DIFF_MESSAGE = NO_DIFF_MESSAGE; +const SIMILAR_MESSAGE = + 'Compared values serialize to the same structure.\n' + + 'Printing internal object structure without calling `toJSON` instead.'; +exports.SIMILAR_MESSAGE = SIMILAR_MESSAGE; diff --git a/node_modules/jest-diff/build/diffLines.js b/node_modules/jest-diff/build/diffLines.js new file mode 100644 index 0000000..65ea41b --- /dev/null +++ b/node_modules/jest-diff/build/diffLines.js @@ -0,0 +1,215 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printDiffLines = + exports.diffLinesUnified2 = + exports.diffLinesUnified = + exports.diffLinesRaw = + void 0; + +var _diffSequences = _interopRequireDefault(require('diff-sequences')); + +var _cleanupSemantic = require('./cleanupSemantic'); + +var _joinAlignedDiffs = require('./joinAlignedDiffs'); + +var _normalizeDiffOptions = require('./normalizeDiffOptions'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const isEmptyString = lines => lines.length === 1 && lines[0].length === 0; + +const countChanges = diffs => { + let a = 0; + let b = 0; + diffs.forEach(diff => { + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + a += 1; + break; + + case _cleanupSemantic.DIFF_INSERT: + b += 1; + break; + } + }); + return { + a, + b + }; +}; + +const printAnnotation = ( + { + aAnnotation, + aColor, + aIndicator, + bAnnotation, + bColor, + bIndicator, + includeChangeCounts, + omitAnnotationLines + }, + changeCounts +) => { + if (omitAnnotationLines) { + return ''; + } + + let aRest = ''; + let bRest = ''; + + if (includeChangeCounts) { + const aCount = String(changeCounts.a); + const bCount = String(changeCounts.b); // Padding right aligns the ends of the annotations. + + const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length; + const aAnnotationPadding = ' '.repeat(Math.max(0, baAnnotationLengthDiff)); + const bAnnotationPadding = ' '.repeat(Math.max(0, -baAnnotationLengthDiff)); // Padding left aligns the ends of the counts. + + const baCountLengthDiff = bCount.length - aCount.length; + const aCountPadding = ' '.repeat(Math.max(0, baCountLengthDiff)); + const bCountPadding = ' '.repeat(Math.max(0, -baCountLengthDiff)); + aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`; + bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`; + } + + const a = `${aIndicator} ${aAnnotation}${aRest}`; + const b = `${bIndicator} ${bAnnotation}${bRest}`; + return `${aColor(a)}\n${bColor(b)}\n\n`; +}; + +const printDiffLines = (diffs, options) => + printAnnotation(options, countChanges(diffs)) + + (options.expand + ? (0, _joinAlignedDiffs.joinAlignedDiffsExpand)(diffs, options) + : (0, _joinAlignedDiffs.joinAlignedDiffsNoExpand)(diffs, options)); // Compare two arrays of strings line-by-line. Format as comparison lines. + +exports.printDiffLines = printDiffLines; + +const diffLinesUnified = (aLines, bLines, options) => + printDiffLines( + diffLinesRaw( + isEmptyString(aLines) ? [] : aLines, + isEmptyString(bLines) ? [] : bLines + ), + (0, _normalizeDiffOptions.normalizeDiffOptions)(options) + ); // Given two pairs of arrays of strings: +// Compare the pair of comparison arrays line-by-line. +// Format the corresponding lines in the pair of displayable arrays. + +exports.diffLinesUnified = diffLinesUnified; + +const diffLinesUnified2 = ( + aLinesDisplay, + bLinesDisplay, + aLinesCompare, + bLinesCompare, + options +) => { + if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { + aLinesDisplay = []; + aLinesCompare = []; + } + + if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { + bLinesDisplay = []; + bLinesCompare = []; + } + + if ( + aLinesDisplay.length !== aLinesCompare.length || + bLinesDisplay.length !== bLinesCompare.length + ) { + // Fall back to diff of display lines. + return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); + } + + const diffs = diffLinesRaw(aLinesCompare, bLinesCompare); // Replace comparison lines with displayable lines. + + let aIndex = 0; + let bIndex = 0; + diffs.forEach(diff => { + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + diff[1] = aLinesDisplay[aIndex]; + aIndex += 1; + break; + + case _cleanupSemantic.DIFF_INSERT: + diff[1] = bLinesDisplay[bIndex]; + bIndex += 1; + break; + + default: + diff[1] = bLinesDisplay[bIndex]; + aIndex += 1; + bIndex += 1; + } + }); + return printDiffLines( + diffs, + (0, _normalizeDiffOptions.normalizeDiffOptions)(options) + ); +}; // Compare two arrays of strings line-by-line. + +exports.diffLinesUnified2 = diffLinesUnified2; + +const diffLinesRaw = (aLines, bLines) => { + const aLength = aLines.length; + const bLength = bLines.length; + + const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; + + const diffs = []; + let aIndex = 0; + let bIndex = 0; + + const foundSubsequence = (nCommon, aCommon, bCommon) => { + for (; aIndex !== aCommon; aIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, aLines[aIndex]) + ); + } + + for (; bIndex !== bCommon; bIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, bLines[bIndex]) + ); + } + + for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_EQUAL, bLines[bIndex]) + ); + } + }; + + (0, _diffSequences.default)(aLength, bLength, isCommon, foundSubsequence); // After the last common subsequence, push remaining change items. + + for (; aIndex !== aLength; aIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, aLines[aIndex]) + ); + } + + for (; bIndex !== bLength; bIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, bLines[bIndex]) + ); + } + + return diffs; +}; + +exports.diffLinesRaw = diffLinesRaw; diff --git a/node_modules/jest-diff/build/diffStrings.js b/node_modules/jest-diff/build/diffStrings.js new file mode 100644 index 0000000..3ad4f1a --- /dev/null +++ b/node_modules/jest-diff/build/diffStrings.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _diffSequences = _interopRequireDefault(require('diff-sequences')); + +var _cleanupSemantic = require('./cleanupSemantic'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const diffStrings = (a, b) => { + const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; + + let aIndex = 0; + let bIndex = 0; + const diffs = []; + + const foundSubsequence = (nCommon, aCommon, bCommon) => { + if (aIndex !== aCommon) { + diffs.push( + new _cleanupSemantic.Diff( + _cleanupSemantic.DIFF_DELETE, + a.slice(aIndex, aCommon) + ) + ); + } + + if (bIndex !== bCommon) { + diffs.push( + new _cleanupSemantic.Diff( + _cleanupSemantic.DIFF_INSERT, + b.slice(bIndex, bCommon) + ) + ); + } + + aIndex = aCommon + nCommon; // number of characters compared in a + + bIndex = bCommon + nCommon; // number of characters compared in b + + diffs.push( + new _cleanupSemantic.Diff( + _cleanupSemantic.DIFF_EQUAL, + b.slice(bCommon, bIndex) + ) + ); + }; + + (0, _diffSequences.default)(a.length, b.length, isCommon, foundSubsequence); // After the last common subsequence, push remaining change items. + + if (aIndex !== a.length) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, a.slice(aIndex)) + ); + } + + if (bIndex !== b.length) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, b.slice(bIndex)) + ); + } + + return diffs; +}; + +var _default = diffStrings; +exports.default = _default; diff --git a/node_modules/jest-diff/build/getAlignedDiffs.js b/node_modules/jest-diff/build/getAlignedDiffs.js new file mode 100644 index 0000000..60dc141 --- /dev/null +++ b/node_modules/jest-diff/build/getAlignedDiffs.js @@ -0,0 +1,231 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _cleanupSemantic = require('./cleanupSemantic'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Given change op and array of diffs, return concatenated string: +// * include common strings +// * include change strings which have argument op with changeColor +// * exclude change strings which have opposite op +const concatenateRelevantDiffs = (op, diffs, changeColor) => + diffs.reduce( + (reduced, diff) => + reduced + + (diff[0] === _cleanupSemantic.DIFF_EQUAL + ? diff[1] + : diff[0] === op && diff[1].length !== 0 // empty if change is newline + ? changeColor(diff[1]) + : ''), + '' + ); // Encapsulate change lines until either a common newline or the end. + +class ChangeBuffer { + op; + line; // incomplete line + + lines; // complete lines + + changeColor; + + constructor(op, changeColor) { + this.op = op; + this.line = []; + this.lines = []; + this.changeColor = changeColor; + } + + pushSubstring(substring) { + this.pushDiff(new _cleanupSemantic.Diff(this.op, substring)); + } + + pushLine() { + // Assume call only if line has at least one diff, + // therefore an empty line must have a diff which has an empty string. + // If line has multiple diffs, then assume it has a common diff, + // therefore change diffs have change color; + // otherwise then it has line color only. + this.lines.push( + this.line.length !== 1 + ? new _cleanupSemantic.Diff( + this.op, + concatenateRelevantDiffs(this.op, this.line, this.changeColor) + ) + : this.line[0][0] === this.op + ? this.line[0] // can use instance + : new _cleanupSemantic.Diff(this.op, this.line[0][1]) // was common diff + ); + this.line.length = 0; + } + + isLineEmpty() { + return this.line.length === 0; + } // Minor input to buffer. + + pushDiff(diff) { + this.line.push(diff); + } // Main input to buffer. + + align(diff) { + const string = diff[1]; + + if (string.includes('\n')) { + const substrings = string.split('\n'); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i < iLast) { + // The first substring completes the current change line. + // A middle substring is a change line. + this.pushSubstring(substring); + this.pushLine(); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushSubstring(substring); + } + }); + } else { + // Append non-multiline string to current change line. + this.pushDiff(diff); + } + } // Output from buffer. + + moveLinesTo(lines) { + if (!this.isLineEmpty()) { + this.pushLine(); + } + + lines.push(...this.lines); + this.lines.length = 0; + } +} // Encapsulate common and change lines. + +class CommonBuffer { + deleteBuffer; + insertBuffer; + lines; + + constructor(deleteBuffer, insertBuffer) { + this.deleteBuffer = deleteBuffer; + this.insertBuffer = insertBuffer; + this.lines = []; + } + + pushDiffCommonLine(diff) { + this.lines.push(diff); + } + + pushDiffChangeLines(diff) { + const isDiffEmpty = diff[1].length === 0; // An empty diff string is redundant, unless a change line is empty. + + if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { + this.deleteBuffer.pushDiff(diff); + } + + if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { + this.insertBuffer.pushDiff(diff); + } + } + + flushChangeLines() { + this.deleteBuffer.moveLinesTo(this.lines); + this.insertBuffer.moveLinesTo(this.lines); + } // Input to buffer. + + align(diff) { + const op = diff[0]; + const string = diff[1]; + + if (string.includes('\n')) { + const substrings = string.split('\n'); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i === 0) { + const subdiff = new _cleanupSemantic.Diff(op, substring); + + if ( + this.deleteBuffer.isLineEmpty() && + this.insertBuffer.isLineEmpty() + ) { + // If both current change lines are empty, + // then the first substring is a common line. + this.flushChangeLines(); + this.pushDiffCommonLine(subdiff); + } else { + // If either current change line is non-empty, + // then the first substring completes the change lines. + this.pushDiffChangeLines(subdiff); + this.flushChangeLines(); + } + } else if (i < iLast) { + // A middle substring is a common line. + this.pushDiffCommonLine(new _cleanupSemantic.Diff(op, substring)); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushDiffChangeLines(new _cleanupSemantic.Diff(op, substring)); + } + }); + } else { + // Append non-multiline string to current change lines. + // Important: It cannot be at the end following empty change lines, + // because newline appended to the end of expected and received strings. + this.pushDiffChangeLines(diff); + } + } // Output from buffer. + + getLines() { + this.flushChangeLines(); + return this.lines; + } +} // Given diffs from expected and received strings, +// return new array of diffs split or joined into lines. +// +// To correctly align a change line at the end, the algorithm: +// * assumes that a newline was appended to the strings +// * omits the last newline from the output array +// +// Assume the function is not called: +// * if either expected or received is empty string +// * if neither expected nor received is multiline string + +const getAlignedDiffs = (diffs, changeColor) => { + const deleteBuffer = new ChangeBuffer( + _cleanupSemantic.DIFF_DELETE, + changeColor + ); + const insertBuffer = new ChangeBuffer( + _cleanupSemantic.DIFF_INSERT, + changeColor + ); + const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); + diffs.forEach(diff => { + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + deleteBuffer.align(diff); + break; + + case _cleanupSemantic.DIFF_INSERT: + insertBuffer.align(diff); + break; + + default: + commonBuffer.align(diff); + } + }); + return commonBuffer.getLines(); +}; + +var _default = getAlignedDiffs; +exports.default = _default; diff --git a/node_modules/jest-diff/build/index.d.ts b/node_modules/jest-diff/build/index.d.ts new file mode 100644 index 0000000..79bcffc --- /dev/null +++ b/node_modules/jest-diff/build/index.d.ts @@ -0,0 +1,93 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {CompareKeys} from 'pretty-format'; + +/** + * Class representing one diff tuple. + * Attempts to look like a two-element array (which is what this used to be). + * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. + * @param {string} text Text to be deleted, inserted, or retained. + * @constructor + */ +export declare class Diff { + 0: number; + 1: string; + constructor(op: number, text: string); +} + +export declare function diff( + a: any, + b: any, + options?: DiffOptions, +): string | null; + +/** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ +export declare var DIFF_DELETE: number; + +export declare var DIFF_EQUAL: number; + +export declare var DIFF_INSERT: number; + +export declare const diffLinesRaw: ( + aLines: Array, + bLines: Array, +) => Array; + +export declare const diffLinesUnified: ( + aLines: Array, + bLines: Array, + options?: DiffOptions, +) => string; + +export declare const diffLinesUnified2: ( + aLinesDisplay: Array, + bLinesDisplay: Array, + aLinesCompare: Array, + bLinesCompare: Array, + options?: DiffOptions, +) => string; + +export declare type DiffOptions = { + aAnnotation?: string; + aColor?: DiffOptionsColor; + aIndicator?: string; + bAnnotation?: string; + bColor?: DiffOptionsColor; + bIndicator?: string; + changeColor?: DiffOptionsColor; + changeLineTrailingSpaceColor?: DiffOptionsColor; + commonColor?: DiffOptionsColor; + commonIndicator?: string; + commonLineTrailingSpaceColor?: DiffOptionsColor; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + patchColor?: DiffOptionsColor; + compareKeys?: CompareKeys; +}; + +export declare type DiffOptionsColor = (arg: string) => string; + +export declare const diffStringsRaw: ( + a: string, + b: string, + cleanup: boolean, +) => Array; + +export declare const diffStringsUnified: ( + a: string, + b: string, + options?: DiffOptions, +) => string; + +export {}; diff --git a/node_modules/jest-diff/build/index.js b/node_modules/jest-diff/build/index.js new file mode 100644 index 0000000..cd0b866 --- /dev/null +++ b/node_modules/jest-diff/build/index.js @@ -0,0 +1,253 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'DIFF_DELETE', { + enumerable: true, + get: function () { + return _cleanupSemantic.DIFF_DELETE; + } +}); +Object.defineProperty(exports, 'DIFF_EQUAL', { + enumerable: true, + get: function () { + return _cleanupSemantic.DIFF_EQUAL; + } +}); +Object.defineProperty(exports, 'DIFF_INSERT', { + enumerable: true, + get: function () { + return _cleanupSemantic.DIFF_INSERT; + } +}); +Object.defineProperty(exports, 'Diff', { + enumerable: true, + get: function () { + return _cleanupSemantic.Diff; + } +}); +exports.diff = diff; +Object.defineProperty(exports, 'diffLinesRaw', { + enumerable: true, + get: function () { + return _diffLines.diffLinesRaw; + } +}); +Object.defineProperty(exports, 'diffLinesUnified', { + enumerable: true, + get: function () { + return _diffLines.diffLinesUnified; + } +}); +Object.defineProperty(exports, 'diffLinesUnified2', { + enumerable: true, + get: function () { + return _diffLines.diffLinesUnified2; + } +}); +Object.defineProperty(exports, 'diffStringsRaw', { + enumerable: true, + get: function () { + return _printDiffs.diffStringsRaw; + } +}); +Object.defineProperty(exports, 'diffStringsUnified', { + enumerable: true, + get: function () { + return _printDiffs.diffStringsUnified; + } +}); + +var _chalk = _interopRequireDefault(require('chalk')); + +var _jestGetType = require('jest-get-type'); + +var _prettyFormat = require('pretty-format'); + +var _cleanupSemantic = require('./cleanupSemantic'); + +var _constants = require('./constants'); + +var _diffLines = require('./diffLines'); + +var _normalizeDiffOptions = require('./normalizeDiffOptions'); + +var _printDiffs = require('./printDiffs'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; + +const getCommonMessage = (message, options) => { + const {commonColor} = (0, _normalizeDiffOptions.normalizeDiffOptions)( + options + ); + return commonColor(message); +}; + +const { + AsymmetricMatcher, + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent +} = _prettyFormat.plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +const FORMAT_OPTIONS = { + plugins: PLUGINS +}; +const FALLBACK_FORMAT_OPTIONS = { + callToJSON: false, + maxDepth: 10, + plugins: PLUGINS +}; // Generate a string that will highlight the difference between two values +// with green and red. (similar to how github does code diffing) +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + +function diff(a, b, options) { + if (Object.is(a, b)) { + return getCommonMessage(_constants.NO_DIFF_MESSAGE, options); + } + + const aType = (0, _jestGetType.getType)(a); + let expectedType = aType; + let omitDifference = false; + + if (aType === 'object' && typeof a.asymmetricMatch === 'function') { + if (a.$$typeof !== Symbol.for('jest.asymmetricMatcher')) { + // Do not know expected type of user-defined asymmetric matcher. + return null; + } + + if (typeof a.getExpectedType !== 'function') { + // For example, expect.anything() matches either null or undefined + return null; + } + + expectedType = a.getExpectedType(); // Primitive types boolean and number omit difference below. + // For example, omit difference for expect.stringMatching(regexp) + + omitDifference = expectedType === 'string'; + } + + if (expectedType !== (0, _jestGetType.getType)(b)) { + return ( + ' Comparing two different types of values.' + + ` Expected ${_chalk.default.green(expectedType)} but ` + + `received ${_chalk.default.red((0, _jestGetType.getType)(b))}.` + ); + } + + if (omitDifference) { + return null; + } + + switch (aType) { + case 'string': + return (0, _diffLines.diffLinesUnified)( + a.split('\n'), + b.split('\n'), + options + ); + + case 'boolean': + case 'number': + return comparePrimitive(a, b, options); + + case 'map': + return compareObjects(sortMap(a), sortMap(b), options); + + case 'set': + return compareObjects(sortSet(a), sortSet(b), options); + + default: + return compareObjects(a, b, options); + } +} + +function comparePrimitive(a, b, options) { + const aFormat = (0, _prettyFormat.format)(a, FORMAT_OPTIONS); + const bFormat = (0, _prettyFormat.format)(b, FORMAT_OPTIONS); + return aFormat === bFormat + ? getCommonMessage(_constants.NO_DIFF_MESSAGE, options) + : (0, _diffLines.diffLinesUnified)( + aFormat.split('\n'), + bFormat.split('\n'), + options + ); +} + +function sortMap(map) { + return new Map(Array.from(map.entries()).sort()); +} + +function sortSet(set) { + return new Set(Array.from(set.values()).sort()); +} + +function compareObjects(a, b, options) { + let difference; + let hasThrown = false; + + try { + const formatOptions = getFormatOptions(FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + } catch { + hasThrown = true; + } + + const noDiffMessage = getCommonMessage(_constants.NO_DIFF_MESSAGE, options); // If the comparison yields no results, compare again but this time + // without calling `toJSON`. It's also possible that toJSON might throw. + + if (difference === undefined || difference === noDiffMessage) { + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + + if (difference !== noDiffMessage && !hasThrown) { + difference = `${getCommonMessage( + _constants.SIMILAR_MESSAGE, + options + )}\n\n${difference}`; + } + } + + return difference; +} + +function getFormatOptions(formatOptions, options) { + const {compareKeys} = (0, _normalizeDiffOptions.normalizeDiffOptions)( + options + ); + return {...formatOptions, compareKeys}; +} + +function getObjectsDifference(a, b, formatOptions, options) { + const formatOptionsZeroIndent = {...formatOptions, indent: 0}; + const aCompare = (0, _prettyFormat.format)(a, formatOptionsZeroIndent); + const bCompare = (0, _prettyFormat.format)(b, formatOptionsZeroIndent); + + if (aCompare === bCompare) { + return getCommonMessage(_constants.NO_DIFF_MESSAGE, options); + } else { + const aDisplay = (0, _prettyFormat.format)(a, formatOptions); + const bDisplay = (0, _prettyFormat.format)(b, formatOptions); + return (0, _diffLines.diffLinesUnified2)( + aDisplay.split('\n'), + bDisplay.split('\n'), + aCompare.split('\n'), + bCompare.split('\n'), + options + ); + } +} diff --git a/node_modules/jest-diff/build/joinAlignedDiffs.js b/node_modules/jest-diff/build/joinAlignedDiffs.js new file mode 100644 index 0000000..9eba70f --- /dev/null +++ b/node_modules/jest-diff/build/joinAlignedDiffs.js @@ -0,0 +1,303 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.joinAlignedDiffsNoExpand = exports.joinAlignedDiffsExpand = void 0; + +var _cleanupSemantic = require('./cleanupSemantic'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const formatTrailingSpaces = (line, trailingSpaceFormatter) => + line.replace(/\s+$/, match => trailingSpaceFormatter(match)); + +const printDiffLine = ( + line, + isFirstOrLast, + color, + indicator, + trailingSpaceFormatter, + emptyFirstOrLastLinePlaceholder +) => + line.length !== 0 + ? color( + `${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}` + ) + : indicator !== ' ' + ? color(indicator) + : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 + ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) + : ''; + +const printDeleteLine = ( + line, + isFirstOrLast, + { + aColor, + aIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + } +) => + printDiffLine( + line, + isFirstOrLast, + aColor, + aIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); + +const printInsertLine = ( + line, + isFirstOrLast, + { + bColor, + bIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + } +) => + printDiffLine( + line, + isFirstOrLast, + bColor, + bIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); + +const printCommonLine = ( + line, + isFirstOrLast, + { + commonColor, + commonIndicator, + commonLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + } +) => + printDiffLine( + line, + isFirstOrLast, + commonColor, + commonIndicator, + commonLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); // In GNU diff format, indexes are one-based instead of zero-based. + +const createPatchMark = (aStart, aEnd, bStart, bEnd, {patchColor}) => + patchColor( + `@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@` + ); // jest --no-expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting (and patch marks, if needed). + +const joinAlignedDiffsNoExpand = (diffs, options) => { + const iLength = diffs.length; + const nContextLines = options.contextLines; + const nContextLines2 = nContextLines + nContextLines; // First pass: count output lines and see if it has patches. + + let jLength = iLength; + let hasExcessAtStartOrEnd = false; + let nExcessesBetweenChanges = 0; + let i = 0; + + while (i !== iLength) { + const iStart = i; + + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_EQUAL) { + i += 1; + } + + if (iStart !== i) { + if (iStart === 0) { + // at start + if (i > nContextLines) { + jLength -= i - nContextLines; // subtract excess common lines + + hasExcessAtStartOrEnd = true; + } + } else if (i === iLength) { + // at end + const n = i - iStart; + + if (n > nContextLines) { + jLength -= n - nContextLines; // subtract excess common lines + + hasExcessAtStartOrEnd = true; + } + } else { + // between changes + const n = i - iStart; + + if (n > nContextLines2) { + jLength -= n - nContextLines2; // subtract excess common lines + + nExcessesBetweenChanges += 1; + } + } + } + + while (i !== iLength && diffs[i][0] !== _cleanupSemantic.DIFF_EQUAL) { + i += 1; + } + } + + const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd; + + if (nExcessesBetweenChanges !== 0) { + jLength += nExcessesBetweenChanges + 1; // add patch lines + } else if (hasExcessAtStartOrEnd) { + jLength += 1; // add patch line + } + + const jLast = jLength - 1; + const lines = []; + let jPatchMark = 0; // index of placeholder line for current patch mark + + if (hasPatch) { + lines.push(''); // placeholder line for first patch mark + } // Indexes of expected or received lines in current patch: + + let aStart = 0; + let bStart = 0; + let aEnd = 0; + let bEnd = 0; + + const pushCommonLine = line => { + const j = lines.length; + lines.push(printCommonLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + bEnd += 1; + }; + + const pushDeleteLine = line => { + const j = lines.length; + lines.push(printDeleteLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + }; + + const pushInsertLine = line => { + const j = lines.length; + lines.push(printInsertLine(line, j === 0 || j === jLast, options)); + bEnd += 1; + }; // Second pass: push lines with diff formatting (and patch marks, if needed). + + i = 0; + + while (i !== iLength) { + let iStart = i; + + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_EQUAL) { + i += 1; + } + + if (iStart !== i) { + if (iStart === 0) { + // at beginning + if (i > nContextLines) { + iStart = i - nContextLines; + aStart = iStart; + bStart = iStart; + aEnd = aStart; + bEnd = bStart; + } + + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else if (i === iLength) { + // at end + const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; + + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + // between changes + const nCommon = i - iStart; + + if (nCommon > nContextLines2) { + const iEnd = iStart + nContextLines; + + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + + lines[jPatchMark] = createPatchMark( + aStart, + aEnd, + bStart, + bEnd, + options + ); + jPatchMark = lines.length; + lines.push(''); // placeholder line for next patch mark + + const nOmit = nCommon - nContextLines2; + aStart = aEnd + nOmit; + bStart = bEnd + nOmit; + aEnd = aStart; + bEnd = bStart; + + for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } + } + } + + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_DELETE) { + pushDeleteLine(diffs[i][1]); + i += 1; + } + + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_INSERT) { + pushInsertLine(diffs[i][1]); + i += 1; + } + } + + if (hasPatch) { + lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); + } + + return lines.join('\n'); +}; // jest --expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting. + +exports.joinAlignedDiffsNoExpand = joinAlignedDiffsNoExpand; + +const joinAlignedDiffsExpand = (diffs, options) => + diffs + .map((diff, i, diffs) => { + const line = diff[1]; + const isFirstOrLast = i === 0 || i === diffs.length - 1; + + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + return printDeleteLine(line, isFirstOrLast, options); + + case _cleanupSemantic.DIFF_INSERT: + return printInsertLine(line, isFirstOrLast, options); + + default: + return printCommonLine(line, isFirstOrLast, options); + } + }) + .join('\n'); + +exports.joinAlignedDiffsExpand = joinAlignedDiffsExpand; diff --git a/node_modules/jest-diff/build/normalizeDiffOptions.js b/node_modules/jest-diff/build/normalizeDiffOptions.js new file mode 100644 index 0000000..b22a804 --- /dev/null +++ b/node_modules/jest-diff/build/normalizeDiffOptions.js @@ -0,0 +1,64 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.normalizeDiffOptions = exports.noColor = void 0; + +var _chalk = _interopRequireDefault(require('chalk')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const noColor = string => string; + +exports.noColor = noColor; +const DIFF_CONTEXT_DEFAULT = 5; +const OPTIONS_DEFAULT = { + aAnnotation: 'Expected', + aColor: _chalk.default.green, + aIndicator: '-', + bAnnotation: 'Received', + bColor: _chalk.default.red, + bIndicator: '+', + changeColor: _chalk.default.inverse, + changeLineTrailingSpaceColor: noColor, + commonColor: _chalk.default.dim, + commonIndicator: ' ', + commonLineTrailingSpaceColor: noColor, + compareKeys: undefined, + contextLines: DIFF_CONTEXT_DEFAULT, + emptyFirstOrLastLinePlaceholder: '', + expand: true, + includeChangeCounts: false, + omitAnnotationLines: false, + patchColor: _chalk.default.yellow +}; + +const getCompareKeys = compareKeys => + compareKeys && typeof compareKeys === 'function' + ? compareKeys + : OPTIONS_DEFAULT.compareKeys; + +const getContextLines = contextLines => + typeof contextLines === 'number' && + Number.isSafeInteger(contextLines) && + contextLines >= 0 + ? contextLines + : DIFF_CONTEXT_DEFAULT; // Pure function returns options with all properties. + +const normalizeDiffOptions = (options = {}) => ({ + ...OPTIONS_DEFAULT, + ...options, + compareKeys: getCompareKeys(options.compareKeys), + contextLines: getContextLines(options.contextLines) +}); + +exports.normalizeDiffOptions = normalizeDiffOptions; diff --git a/node_modules/jest-diff/build/printDiffs.js b/node_modules/jest-diff/build/printDiffs.js new file mode 100644 index 0000000..497ff07 --- /dev/null +++ b/node_modules/jest-diff/build/printDiffs.js @@ -0,0 +1,85 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.diffStringsUnified = exports.diffStringsRaw = void 0; + +var _cleanupSemantic = require('./cleanupSemantic'); + +var _diffLines = require('./diffLines'); + +var _diffStrings = _interopRequireDefault(require('./diffStrings')); + +var _getAlignedDiffs = _interopRequireDefault(require('./getAlignedDiffs')); + +var _normalizeDiffOptions = require('./normalizeDiffOptions'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const hasCommonDiff = (diffs, isMultiline) => { + if (isMultiline) { + // Important: Ignore common newline that was appended to multiline strings! + const iLast = diffs.length - 1; + return diffs.some( + (diff, i) => + diff[0] === _cleanupSemantic.DIFF_EQUAL && + (i !== iLast || diff[1] !== '\n') + ); + } + + return diffs.some(diff => diff[0] === _cleanupSemantic.DIFF_EQUAL); +}; // Compare two strings character-by-character. +// Format as comparison lines in which changed substrings have inverse colors. + +const diffStringsUnified = (a, b, options) => { + if (a !== b && a.length !== 0 && b.length !== 0) { + const isMultiline = a.includes('\n') || b.includes('\n'); // getAlignedDiffs assumes that a newline was appended to the strings. + + const diffs = diffStringsRaw( + isMultiline ? `${a}\n` : a, + isMultiline ? `${b}\n` : b, + true // cleanupSemantic + ); + + if (hasCommonDiff(diffs, isMultiline)) { + const optionsNormalized = (0, _normalizeDiffOptions.normalizeDiffOptions)( + options + ); + const lines = (0, _getAlignedDiffs.default)( + diffs, + optionsNormalized.changeColor + ); + return (0, _diffLines.printDiffLines)(lines, optionsNormalized); + } + } // Fall back to line-by-line diff. + + return (0, _diffLines.diffLinesUnified)( + a.split('\n'), + b.split('\n'), + options + ); +}; // Compare two strings character-by-character. +// Optionally clean up small common substrings, also known as chaff. + +exports.diffStringsUnified = diffStringsUnified; + +const diffStringsRaw = (a, b, cleanup) => { + const diffs = (0, _diffStrings.default)(a, b); + + if (cleanup) { + (0, _cleanupSemantic.cleanupSemantic)(diffs); // impure function + } + + return diffs; +}; + +exports.diffStringsRaw = diffStringsRaw; diff --git a/node_modules/jest-diff/build/types.js b/node_modules/jest-diff/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-diff/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-diff/package.json b/node_modules/jest-diff/package.json new file mode 100644 index 0000000..5486e03 --- /dev/null +++ b/node_modules/jest-diff/package.json @@ -0,0 +1,67 @@ +{ + "_from": "jest-diff@^29.0.1", + "_id": "jest-diff@29.0.1", + "_inBundle": false, + "_integrity": "sha512-l8PYeq2VhcdxG9tl5cU78ClAlg/N7RtVSp0v3MlXURR0Y99i6eFnegmasOandyTmO6uEdo20+FByAjBFEO9nuw==", + "_location": "/jest-diff", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-diff@^29.0.1", + "name": "jest-diff", + "escapedName": "jest-diff", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/jest-matcher-utils", + "/jest-snapshot" + ], + "_resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.0.1.tgz", + "_shasum": "d14e900a38ee4798d42feaaf0c61cb5b98e4c028", + "_spec": "jest-diff@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-matcher-utils", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.0.0", + "jest-get-type": "^29.0.0", + "pretty-format": "^29.0.1" + }, + "deprecated": false, + "description": "Display differences clearly so people can review changes confidently.", + "devDependencies": { + "@jest/test-utils": "^29.0.1", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-diff", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-diff" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-docblock/LICENSE b/node_modules/jest-docblock/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-docblock/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-docblock/README.md b/node_modules/jest-docblock/README.md new file mode 100644 index 0000000..ba3fc7b --- /dev/null +++ b/node_modules/jest-docblock/README.md @@ -0,0 +1,108 @@ +# jest-docblock + +`jest-docblock` is a package that can extract and parse a specially-formatted comment called a "docblock" at the top of a file. + +A docblock looks like this: + +```js +/** + * Stuff goes here! + */ +``` + +Docblocks can contain pragmas, which are words prefixed by `@`: + +```js +/** + * Pragma incoming! + * + * @flow + */ +``` + +Pragmas can also take arguments: + +```js +/** + * Check this out: + * + * @myPragma it is so cool + */ +``` + +`jest-docblock` can: + +- extract the docblock from some code as a string +- parse a docblock string's pragmas into an object +- print an object and some comments back to a string + +## Installation + +```sh +# with yarn +$ yarn add jest-docblock +# with npm +$ npm install jest-docblock +``` + +## Usage + +```js +const code = ` +/** + * Everything is awesome! + * + * @everything is:awesome + * @flow + */ + + export const everything = Object.create(null); + export default function isAwesome(something) { + return something === everything; + } +`; + +const { + extract, + strip, + parse, + parseWithComments, + print, +} = require('jest-docblock'); + +const docblock = extract(code); +console.log(docblock); // "/**\n * Everything is awesome!\n * \n * @everything is:awesome\n * @flow\n */" + +const stripped = strip(code); +console.log(stripped); // "export const everything = Object.create(null);\n export default function isAwesome(something) {\n return something === everything;\n }" + +const pragmas = parse(docblock); +console.log(pragmas); // { everything: "is:awesome", flow: "" } + +const parsed = parseWithComments(docblock); +console.log(parsed); // { comments: "Everything is awesome!", pragmas: { everything: "is:awesome", flow: "" } } + +console.log(print({pragmas, comments: 'hi!'})); // /**\n * hi!\n *\n * @everything is:awesome\n * @flow\n */; +``` + +## API Documentation + +### `extract(contents: string): string` + +Extracts a docblock from some file contents. Returns the docblock contained in `contents`. If `contents` did not contain a docblock, it will return the empty string (`""`). + +### `strip(contents: string): string` + +Strips the top docblock from a file and return the result. If a file does not have a docblock at the top, then return the file unchanged. + +### `parse(docblock: string): {[key: string]: string | string[] }` + +Parses the pragmas in a docblock string into an object whose keys are the pragma tags and whose values are the arguments to those pragmas. + +### `parseWithComments(docblock: string): { comments: string, pragmas: {[key: string]: string | string[]} }` + +Similar to `parse` except this method also returns the comments from the docblock. Useful when used with `print()`. + +### `print({ comments?: string, pragmas?: {[key: string]: string | string[]} }): string` + +Prints an object of key-value pairs back into a docblock. If `comments` are provided, they will be positioned on the top of the docblock. diff --git a/node_modules/jest-docblock/build/index.d.ts b/node_modules/jest-docblock/build/index.d.ts new file mode 100644 index 0000000..3c25df5 --- /dev/null +++ b/node_modules/jest-docblock/build/index.d.ts @@ -0,0 +1,29 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare function extract(contents: string): string; + +export declare function parse(docblock: string): Pragmas; + +export declare function parseWithComments(docblock: string): { + comments: string; + pragmas: Pragmas; +}; + +declare type Pragmas = Record>; + +declare function print_2({ + comments, + pragmas, +}: { + comments?: string; + pragmas?: Pragmas; +}): string; +export {print_2 as print}; + +export declare function strip(contents: string): string; + +export {}; diff --git a/node_modules/jest-docblock/build/index.js b/node_modules/jest-docblock/build/index.js new file mode 100644 index 0000000..94fd352 --- /dev/null +++ b/node_modules/jest-docblock/build/index.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.extract = extract; +exports.parse = parse; +exports.parseWithComments = parseWithComments; +exports.print = print; +exports.strip = strip; + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +function _detectNewline() { + const data = _interopRequireDefault(require('detect-newline')); + + _detectNewline = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const commentEndRe = /\*\/$/; +const commentStartRe = /^\/\*\*?/; +const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; +const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; +const ltrimNewlineRe = /^(\r?\n)+/; +const multilineRe = + /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; +const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; +const stringStartRe = /(\r?\n|^) *\* ?/g; +const STRING_ARRAY = []; + +function extract(contents) { + const match = contents.match(docblockRe); + return match ? match[0].trimLeft() : ''; +} + +function strip(contents) { + const match = contents.match(docblockRe); + return match && match[0] ? contents.substring(match[0].length) : contents; +} + +function parse(docblock) { + return parseWithComments(docblock).pragmas; +} + +function parseWithComments(docblock) { + const line = (0, _detectNewline().default)(docblock) || _os().EOL; + + docblock = docblock + .replace(commentStartRe, '') + .replace(commentEndRe, '') + .replace(stringStartRe, '$1'); // Normalize multi-line directives + + let prev = ''; + + while (prev !== docblock) { + prev = docblock; + docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`); + } + + docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); + const result = Object.create(null); + const comments = docblock + .replace(propertyRe, '') + .replace(ltrimNewlineRe, '') + .trimRight(); + let match; + + while ((match = propertyRe.exec(docblock))) { + // strip linecomments from pragmas + const nextPragma = match[2].replace(lineCommentRe, ''); + + if ( + typeof result[match[1]] === 'string' || + Array.isArray(result[match[1]]) + ) { + result[match[1]] = STRING_ARRAY.concat(result[match[1]], nextPragma); + } else { + result[match[1]] = nextPragma; + } + } + + return { + comments, + pragmas: result + }; +} + +function print({comments = '', pragmas = {}}) { + const line = (0, _detectNewline().default)(comments) || _os().EOL; + + const head = '/**'; + const start = ' *'; + const tail = ' */'; + const keys = Object.keys(pragmas); + const printedObject = keys + .map(key => printKeyValues(key, pragmas[key])) + .reduce((arr, next) => arr.concat(next), []) + .map(keyValue => `${start} ${keyValue}${line}`) + .join(''); + + if (!comments) { + if (keys.length === 0) { + return ''; + } + + if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { + const value = pragmas[keys[0]]; + return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`; + } + } + + const printedComments = + comments + .split(line) + .map(textLine => `${start} ${textLine}`) + .join(line) + line; + return ( + head + + line + + (comments ? printedComments : '') + + (comments && keys.length ? start + line : '') + + printedObject + + tail + ); +} + +function printKeyValues(key, valueOrArray) { + return STRING_ARRAY.concat(valueOrArray).map(value => + `@${key} ${value}`.trim() + ); +} diff --git a/node_modules/jest-docblock/package.json b/node_modules/jest-docblock/package.json new file mode 100644 index 0000000..5b5b722 --- /dev/null +++ b/node_modules/jest-docblock/package.json @@ -0,0 +1,62 @@ +{ + "_from": "jest-docblock@^29.0.0", + "_id": "jest-docblock@29.0.0", + "_inBundle": false, + "_integrity": "sha512-s5Kpra/kLzbqu9dEjov30kj1n4tfu3e7Pl8v+f8jOkeWNqM6Ds8jRaJfZow3ducoQUrf2Z4rs2N5S3zXnb83gw==", + "_location": "/jest-docblock", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-docblock@^29.0.0", + "name": "jest-docblock", + "escapedName": "jest-docblock", + "rawSpec": "^29.0.0", + "saveSpec": null, + "fetchSpec": "^29.0.0" + }, + "_requiredBy": [ + "/jest-runner" + ], + "_resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.0.0.tgz", + "_shasum": "3151bcc45ed7f5a8af4884dcc049aee699b4ceae", + "_spec": "jest-docblock@^29.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-runner", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "detect-newline": "^3.0.0" + }, + "deprecated": false, + "description": "`jest-docblock` is a package that can extract and parse a specially-formatted comment called a \"docblock\" at the top of a file.", + "devDependencies": { + "@types/node": "*" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "75006e46c76f6fda14bbc0548f86edb2ba087cd2", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-docblock", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-docblock" + }, + "types": "./build/index.d.ts", + "version": "29.0.0" +} diff --git a/node_modules/jest-each/LICENSE b/node_modules/jest-each/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-each/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-each/README.md b/node_modules/jest-each/README.md new file mode 100644 index 0000000..da3b2ad --- /dev/null +++ b/node_modules/jest-each/README.md @@ -0,0 +1,548 @@ +
+

jest-each

+ Jest Parameterised Testing +
+ +
+ +[![version](https://img.shields.io/npm/v/jest-each.svg?style=flat-square)](https://www.npmjs.com/package/jest-each) [![downloads](https://img.shields.io/npm/dm/jest-each.svg?style=flat-square)](http://npm-stat.com/charts.html?package=jest-each&from=2017-03-21) [![MIT License](https://img.shields.io/npm/l/jest-each.svg?style=flat-square)](https://github.com/facebook/jest/blob/main/LICENSE) + +A parameterised testing library for [Jest](https://jestjs.io/) inspired by [mocha-each](https://github.com/ryym/mocha-each). + +jest-each allows you to provide multiple arguments to your `test`/`describe` which results in the test/suite being run once per row of parameters. + +## Features + +- `.test` to runs multiple tests with parameterised data + - Also under the alias: `.it` +- `.test.only` to only run the parameterised tests + - Also under the aliases: `.it.only` or `.fit` +- `.test.skip` to skip the parameterised tests + - Also under the aliases: `.it.skip` or `.xit` or `.xtest` +- `.test.concurrent` + - Also under the alias: `.it.concurrent` +- `.test.concurrent.only` + - Also under the alias: `.it.concurrent.only` +- `.test.concurrent.skip` + - Also under the alias: `.it.concurrent.skip` +- `.describe` to runs test suites with parameterised data +- `.describe.only` to only run the parameterised suite of tests + - Also under the aliases: `.fdescribe` +- `.describe.skip` to skip the parameterised suite of tests + - Also under the aliases: `.xdescribe` +- Asynchronous tests with `done` +- Unique test titles with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. +- Unique test titles by injecting properties of test case object +- 🖖 Spock like data tables with [Tagged Template Literals](#tagged-template-literal-of-rows) + +--- + +- [Demo](#demo) +- [Installation](#installation) +- [Importing](#importing) +- APIs + - [Array of Rows](#array-of-rows) + - [Usage](#usage) + - [Tagged Template Literal of rows](#tagged-template-literal-of-rows) + - [Usage](#usage-1) + +## Demo + +#### Tests without jest-each + +![Current jest tests](assets/default-demo.gif) + +#### Tests can be re-written with jest-each to: + +**`.test`** + +![Current jest tests](assets/test-demo.gif) + +**`.test` with Tagged Template Literals** + +![Current jest tests](assets/tagged-template-literal.gif) + +**`.describe`** + +![Current jest tests](assets/describe-demo.gif) + +## Installation + +`npm i --save-dev jest-each` + +`yarn add -D jest-each` + +## Importing + +jest-each is a default export so it can be imported with whatever name you like. + +```js +// es6 +import each from 'jest-each'; +``` + +```js +// es5 +const each = require('jest-each').default; +``` + +## Array of rows + +### API + +#### `each([parameters]).test(name, testFn)` + +##### `each`: + +- parameters: `Array` of Arrays with the arguments that are passed into the `testFn` for each row + - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` + +##### `.test`: + +- name: `String` the title of the `test`. + - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. + - Or generate unique test titles by injecting properties of test case object with `$variable` + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` + - You can use `$#` to inject the index of the test case + - You cannot use `$variable` with the `printf` formatting except for `%%` +- testFn: `Function` the test logic, this is the function that will receive the parameters of each row as function arguments + +#### `each([parameters]).describe(name, suiteFn)` + +##### `each`: + +- parameters: `Array` of Arrays with the arguments that are passed into the `suiteFn` for each row + - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` + +##### `.describe`: + +- name: `String` the title of the `describe` + - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. + - Or generate unique test titles by injecting properties of test case object with `$variable` + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` + - You can use `$#` to inject the index of the test case + - You cannot use `$variable` with the `printf` formatting except for `%%` +- suiteFn: `Function` the suite of `test`/`it`s to be ran, this is the function that will receive the parameters in each row as function arguments + +### Usage + +#### `.test(name, fn)` + +Alias: `.it(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test('returns the result of adding %d to %d', (a, b, expected) => { + expect(a + b).toBe(expected); +}); +``` + +```js +each([ + {a: 1, b: 1, expected: 2}, + {a: 1, b: 2, expected: 3}, + {a: 2, b: 1, expected: 3}, +]).test('returns the result of adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.only(name, fn)` + +Aliases: `.it.only(name, fn)` or `.fit(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.only('returns the result of adding %d to %d', (a, b, expected) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.skip(name, fn)` + +Aliases: `.it.skip(name, fn)` or `.xit(name, fn)` or `.xtest(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.skip('returns the result of adding %d to %d', (a, b, expected) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.concurrent(name, fn)` + +Aliases: `.it.concurrent(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.concurrent( + 'returns the result of adding %d to %d', + (a, b, expected) => { + expect(a + b).toBe(expected); + }, +); +``` + +#### `.test.concurrent.only(name, fn)` + +Aliases: `.it.concurrent.only(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.concurrent.only( + 'returns the result of adding %d to %d', + (a, b, expected) => { + expect(a + b).toBe(expected); + }, +); +``` + +#### `.test.concurrent.skip(name, fn)` + +Aliases: `.it.concurrent.skip(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.concurrent.skip( + 'returns the result of adding %d to %d', + (a, b, expected) => { + expect(a + b).toBe(expected); + }, +); +``` + +#### Asynchronous `.test(name, fn(done))` + +Alias: `.it(name, fn(done))` + +```js +each([['hello'], ['mr'], ['spy']]).test( + 'gives 007 secret message: %s', + (str, done) => { + const asynchronousSpy = message => { + expect(message).toBe(str); + done(); + }; + callSomeAsynchronousFunction(asynchronousSpy)(str); + }, +); +``` + +#### `.describe(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).describe('.add(%d, %d)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +```js +each([ + {a: 1, b: 1, expected: 2}, + {a: 1, b: 2, expected: 3}, + {a: 2, b: 1, expected: 3}, +]).describe('.add($a, $b)', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +#### `.describe.only(name, fn)` + +Aliases: `.fdescribe(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).describe.only('.add(%d, %d)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +#### `.describe.skip(name, fn)` + +Aliases: `.xdescribe(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).describe.skip('.add(%d, %d)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +--- + +## Tagged Template Literal of rows + +### API + +#### `each[tagged template].test(name, suiteFn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +##### `each` takes a tagged template string with: + +- First row of variable name column headings separated with `|` +- One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. + +##### `.test`: + +- name: `String` the title of the `test`, use `$variable` in the name string to inject test values into the test title from the tagged template expressions + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` + - You can use `$#` to inject the index of the table row. +- testFn: `Function` the test logic, this is the function that will receive the parameters of each row as function arguments + +#### `each[tagged template].describe(name, suiteFn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +##### `each` takes a tagged template string with: + +- First row of variable name column headings separated with `|` +- One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. + +##### `.describe`: + +- name: `String` the title of the `test`, use `$variable` in the name string to inject test values into the test title from the tagged template expressions + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` +- suiteFn: `Function` the suite of `test`/`it`s to be ran, this is the function that will receive the parameters in each row as function arguments + +### Usage + +#### `.test(name, fn)` + +Alias: `.it(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.only(name, fn)` + +Aliases: `.it.only(name, fn)` or `.fit(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test.only('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.skip(name, fn)` + +Aliases: `.it.skip(name, fn)` or `.xit(name, fn)` or `.xtest(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test.skip('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### Asynchronous `.test(name, fn(done))` + +Alias: `.it(name, fn(done))` + +```js +each` + str + ${'hello'} + ${'mr'} + ${'spy'} +`.test('gives 007 secret message: $str', ({str}, done) => { + const asynchronousSpy = message => { + expect(message).toBe(str); + done(); + }; + callSomeAsynchronousFunction(asynchronousSpy)(str); +}); +``` + +#### `.describe(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +#### `.describe.only(name, fn)` + +Aliases: `.fdescribe(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe.only('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +#### `.describe.skip(name, fn)` + +Aliases: `.xdescribe(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe.skip('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +## License + +MIT diff --git a/node_modules/jest-each/build/bind.js b/node_modules/jest-each/build/bind.js new file mode 100644 index 0000000..ff82bc2 --- /dev/null +++ b/node_modules/jest-each/build/bind.js @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = bind; + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var _array = _interopRequireDefault(require('./table/array')); + +var _template = _interopRequireDefault(require('./table/template')); + +var _validation = require('./validation'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +function bind(cb, supportsDone = true) { + return (table, ...taggedTemplateData) => + function eachBind(title, test, timeout) { + title = (0, _jestUtil().convertDescriptorToString)(title); + + try { + const tests = isArrayTable(taggedTemplateData) + ? buildArrayTests(title, table) + : buildTemplateTests(title, table, taggedTemplateData); + return tests.forEach(row => + cb( + row.title, + applyArguments(supportsDone, row.arguments, test), + timeout + ) + ); + } catch (e) { + const error = new (_jestUtil().ErrorWithStack)(e.message, eachBind); + return cb(title, () => { + throw error; + }); + } + }; +} + +const isArrayTable = data => data.length === 0; + +const buildArrayTests = (title, table) => { + (0, _validation.validateArrayTable)(table); + return (0, _array.default)(title, table); +}; + +const buildTemplateTests = (title, table, taggedTemplateData) => { + const headings = getHeadingKeys(table[0]); + (0, _validation.validateTemplateTableArguments)(headings, taggedTemplateData); + return (0, _template.default)(title, headings, taggedTemplateData); +}; + +const getHeadingKeys = headings => + (0, _validation.extractValidTemplateHeadings)(headings) + .replace(/\s/g, '') + .split('|'); + +const applyArguments = (supportsDone, params, test) => + supportsDone && params.length < test.length + ? done => test(...params, done) + : () => test(...params); diff --git a/node_modules/jest-each/build/index.d.ts b/node_modules/jest-each/build/index.d.ts new file mode 100644 index 0000000..eb2ad30 --- /dev/null +++ b/node_modules/jest-each/build/index.d.ts @@ -0,0 +1,266 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Global} from '@jest/types'; + +export declare function bind( + cb: GlobalCallback, + supportsDone?: boolean, +): ( + table: Global.EachTable, + ...taggedTemplateData: Global.TemplateData +) => ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number, +) => void; + +declare const each: { + (table: Global.EachTable, ...data: Global.TemplateData): ReturnType< + typeof install + >; + withGlobal(g: Global): ( + table: Global.EachTable, + ...data: Global.TemplateData + ) => { + describe: { + ( + title: string, + suite: Global.EachTestFn, + timeout?: number, + ): void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + fdescribe: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + fit: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + it: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + }; + test: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + }; + xdescribe: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + xit: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + xtest: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; +}; +export default each; + +declare type GlobalCallback = ( + testName: string, + fn: Global.ConcurrentTestFn, + timeout?: number, +) => void; + +declare const install: ( + g: Global, + table: Global.EachTable, + ...data: Global.TemplateData +) => { + describe: { + ( + title: string, + suite: Global.EachTestFn, + timeout?: number, + ): void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + fdescribe: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + fit: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + it: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + }; + test: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): void; + only: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + skip: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + }; + }; + xdescribe: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + xit: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; + xtest: ( + title: Global.BlockNameLike, + test: Global.EachTestFn, + timeout?: number | undefined, + ) => void; +}; + +export {}; diff --git a/node_modules/jest-each/build/index.js b/node_modules/jest-each/build/index.js new file mode 100644 index 0000000..3f779b8 --- /dev/null +++ b/node_modules/jest-each/build/index.js @@ -0,0 +1,97 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'bind', { + enumerable: true, + get: function () { + return _bind.default; + } +}); +exports.default = void 0; + +var _bind = _interopRequireDefault(require('./bind')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const install = (g, table, ...data) => { + const bindingWithArray = data.length === 0; + const bindingWithTemplate = Array.isArray(table) && !!table.raw; + + if (!bindingWithArray && !bindingWithTemplate) { + throw new Error( + '`.each` must only be called with an Array or Tagged Template Literal.' + ); + } + + const test = (title, test, timeout) => + (0, _bind.default)(g.test)(table, ...data)(title, test, timeout); + + test.skip = (0, _bind.default)(g.test.skip)(table, ...data); + test.only = (0, _bind.default)(g.test.only)(table, ...data); + + const testConcurrent = (title, test, timeout) => + (0, _bind.default)(g.test.concurrent)(table, ...data)(title, test, timeout); + + test.concurrent = testConcurrent; + testConcurrent.only = (0, _bind.default)(g.test.concurrent.only)( + table, + ...data + ); + testConcurrent.skip = (0, _bind.default)(g.test.concurrent.skip)( + table, + ...data + ); + + const it = (title, test, timeout) => + (0, _bind.default)(g.it)(table, ...data)(title, test, timeout); + + it.skip = (0, _bind.default)(g.it.skip)(table, ...data); + it.only = (0, _bind.default)(g.it.only)(table, ...data); + it.concurrent = testConcurrent; + const xit = (0, _bind.default)(g.xit)(table, ...data); + const fit = (0, _bind.default)(g.fit)(table, ...data); + const xtest = (0, _bind.default)(g.xtest)(table, ...data); + + const describe = (title, suite, timeout) => + (0, _bind.default)(g.describe, false)(table, ...data)( + title, + suite, + timeout + ); + + describe.skip = (0, _bind.default)(g.describe.skip, false)(table, ...data); + describe.only = (0, _bind.default)(g.describe.only, false)(table, ...data); + const fdescribe = (0, _bind.default)(g.fdescribe, false)(table, ...data); + const xdescribe = (0, _bind.default)(g.xdescribe, false)(table, ...data); + return { + describe, + fdescribe, + fit, + it, + test, + xdescribe, + xit, + xtest + }; +}; + +const each = (table, ...data) => install(globalThis, table, ...data); + +each.withGlobal = + g => + (table, ...data) => + install(g, table, ...data); + +var _default = each; +exports.default = _default; diff --git a/node_modules/jest-each/build/table/array.js b/node_modules/jest-each/build/table/array.js new file mode 100644 index 0000000..996e830 --- /dev/null +++ b/node_modules/jest-each/build/table/array.js @@ -0,0 +1,151 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = array; + +function util() { + const data = _interopRequireWildcard(require('util')); + + util = function () { + return data; + }; + + return data; +} + +function _prettyFormat() { + const data = require('pretty-format'); + + _prettyFormat = function () { + return data; + }; + + return data; +} + +var _interpolation = require('./interpolation'); + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const SUPPORTED_PLACEHOLDERS = /%[sdifjoOp#]/g; +const PRETTY_PLACEHOLDER = '%p'; +const INDEX_PLACEHOLDER = '%#'; +const PLACEHOLDER_PREFIX = '%'; +const ESCAPED_PLACEHOLDER_PREFIX = /%%/g; +const JEST_EACH_PLACEHOLDER_ESCAPE = '@@__JEST_EACH_PLACEHOLDER_ESCAPE__@@'; + +function array(title, arrayTable) { + if (isTemplates(title, arrayTable)) { + return arrayTable.map((template, index) => ({ + arguments: [template], + title: (0, _interpolation.interpolateVariables)( + title, + template, + index + ).replace(ESCAPED_PLACEHOLDER_PREFIX, PLACEHOLDER_PREFIX) + })); + } + + return normaliseTable(arrayTable).map((row, index) => ({ + arguments: row, + title: formatTitle(title, row, index) + })); +} + +const isTemplates = (title, arrayTable) => + !SUPPORTED_PLACEHOLDERS.test(interpolateEscapedPlaceholders(title)) && + !isTable(arrayTable) && + arrayTable.every(col => col != null && typeof col === 'object'); + +const normaliseTable = table => (isTable(table) ? table : table.map(colToRow)); + +const isTable = table => table.every(Array.isArray); + +const colToRow = col => [col]; + +const formatTitle = (title, row, rowIndex) => + row + .reduce((formattedTitle, value) => { + const [placeholder] = getMatchingPlaceholders(formattedTitle); + const normalisedValue = normalisePlaceholderValue(value); + if (!placeholder) return formattedTitle; + if (placeholder === PRETTY_PLACEHOLDER) + return interpolatePrettyPlaceholder(formattedTitle, normalisedValue); + return util().format(formattedTitle, normalisedValue); + }, interpolateTitleIndex(interpolateEscapedPlaceholders(title), rowIndex)) + .replace(new RegExp(JEST_EACH_PLACEHOLDER_ESCAPE, 'g'), PLACEHOLDER_PREFIX); + +const normalisePlaceholderValue = value => + typeof value === 'string' + ? value.replace( + new RegExp(PLACEHOLDER_PREFIX, 'g'), + JEST_EACH_PLACEHOLDER_ESCAPE + ) + : value; + +const getMatchingPlaceholders = title => + title.match(SUPPORTED_PLACEHOLDERS) || []; + +const interpolateEscapedPlaceholders = title => + title.replace(ESCAPED_PLACEHOLDER_PREFIX, JEST_EACH_PLACEHOLDER_ESCAPE); + +const interpolateTitleIndex = (title, index) => + title.replace(INDEX_PLACEHOLDER, index.toString()); + +const interpolatePrettyPlaceholder = (title, value) => + title.replace( + PRETTY_PLACEHOLDER, + (0, _prettyFormat().format)(value, { + maxDepth: 1, + min: true + }) + ); diff --git a/node_modules/jest-each/build/table/interpolation.js b/node_modules/jest-each/build/table/interpolation.js new file mode 100644 index 0000000..7703edf --- /dev/null +++ b/node_modules/jest-each/build/table/interpolation.js @@ -0,0 +1,69 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getPath = getPath; +exports.interpolateVariables = void 0; + +function _jestGetType() { + const data = require('jest-get-type'); + + _jestGetType = function () { + return data; + }; + + return data; +} + +function _prettyFormat() { + const data = require('pretty-format'); + + _prettyFormat = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const interpolateVariables = (title, template, index) => + Object.keys(template) + .reduce(getMatchingKeyPaths(title), []) // aka flatMap + .reduce(replaceKeyPathWithValue(template), title) + .replace('$#', `${index}`); + +exports.interpolateVariables = interpolateVariables; + +const getMatchingKeyPaths = title => (matches, key) => + matches.concat(title.match(new RegExp(`\\$${key}[\\.\\w]*`, 'g')) || []); + +const replaceKeyPathWithValue = template => (title, match) => { + const keyPath = match.replace('$', '').split('.'); + const value = getPath(template, keyPath); + + if ((0, _jestGetType().isPrimitive)(value)) { + return title.replace(match, String(value)); + } + + return title.replace( + match, + (0, _prettyFormat().format)(value, { + maxDepth: 1, + min: true + }) + ); +}; +/* eslint import/export: 0*/ + +function getPath(template, [head, ...tail]) { + if (!head || !Object.prototype.hasOwnProperty.call(template, head)) + return template; + return getPath(template[head], tail); +} diff --git a/node_modules/jest-each/build/table/template.js b/node_modules/jest-each/build/table/template.js new file mode 100644 index 0000000..3edc0c1 --- /dev/null +++ b/node_modules/jest-each/build/table/template.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = template; + +var _interpolation = require('./interpolation'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +function template(title, headings, row) { + const table = convertRowToTable(row, headings); + const templates = convertTableToTemplates(table, headings); + return templates.map((template, index) => ({ + arguments: [template], + title: (0, _interpolation.interpolateVariables)(title, template, index) + })); +} + +const convertRowToTable = (row, headings) => + Array.from({ + length: row.length / headings.length + }).map((_, index) => + row.slice( + index * headings.length, + index * headings.length + headings.length + ) + ); + +const convertTableToTemplates = (table, headings) => + table.map(row => + row.reduce( + (acc, value, index) => + Object.assign(acc, { + [headings[index]]: value + }), + {} + ) + ); diff --git a/node_modules/jest-each/build/validation.js b/node_modules/jest-each/build/validation.js new file mode 100644 index 0000000..242ecb4 --- /dev/null +++ b/node_modules/jest-each/build/validation.js @@ -0,0 +1,132 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.validateTemplateTableArguments = + exports.validateArrayTable = + exports.extractValidTemplateHeadings = + void 0; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _prettyFormat() { + const data = require('pretty-format'); + + _prettyFormat = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const EXPECTED_COLOR = _chalk().default.green; + +const RECEIVED_COLOR = _chalk().default.red; + +const validateArrayTable = table => { + if (!Array.isArray(table)) { + throw new Error( + '`.each` must be called with an Array or Tagged Template Literal.\n\n' + + `Instead was called with: ${(0, _prettyFormat().format)(table, { + maxDepth: 1, + min: true + })}\n` + ); + } + + if (isTaggedTemplateLiteral(table)) { + if (isEmptyString(table[0])) { + throw new Error( + 'Error: `.each` called with an empty Tagged Template Literal of table data.\n' + ); + } + + throw new Error( + 'Error: `.each` called with a Tagged Template Literal with no data, remember to interpolate with ${expression} syntax.\n' + ); + } + + if (isEmptyTable(table)) { + throw new Error( + 'Error: `.each` called with an empty Array of table data.\n' + ); + } +}; + +exports.validateArrayTable = validateArrayTable; + +const isTaggedTemplateLiteral = array => array.raw !== undefined; + +const isEmptyTable = table => table.length === 0; + +const isEmptyString = str => typeof str === 'string' && str.trim() === ''; + +const validateTemplateTableArguments = (headings, data) => { + const incompleteData = data.length % headings.length; + const missingData = headings.length - incompleteData; + + if (incompleteData > 0) { + throw new Error( + `Not enough arguments supplied for given headings:\n${EXPECTED_COLOR( + headings.join(' | ') + )}\n\n` + + `Received:\n${RECEIVED_COLOR((0, _prettyFormat().format)(data))}\n\n` + + `Missing ${RECEIVED_COLOR(missingData.toString())} ${pluralize( + 'argument', + missingData + )}` + ); + } +}; + +exports.validateTemplateTableArguments = validateTemplateTableArguments; + +const pluralize = (word, count) => word + (count === 1 ? '' : 's'); + +const START_OF_LINE = '^'; +const NEWLINE = '\\n'; +const HEADING = '\\s*[^\\s]+\\s*'; +const PIPE = '\\|'; +const REPEATABLE_HEADING = `(${PIPE}${HEADING})*`; +const HEADINGS_FORMAT = new RegExp( + START_OF_LINE + NEWLINE + HEADING + REPEATABLE_HEADING + NEWLINE, + 'g' +); + +const extractValidTemplateHeadings = headings => { + const matches = headings.match(HEADINGS_FORMAT); + + if (matches === null) { + throw new Error( + `Table headings do not conform to expected format:\n\n${EXPECTED_COLOR( + 'heading1 | headingN' + )}\n\nReceived:\n\n${RECEIVED_COLOR( + (0, _prettyFormat().format)(headings) + )}` + ); + } + + return matches[0]; +}; + +exports.extractValidTemplateHeadings = extractValidTemplateHeadings; diff --git a/node_modules/jest-each/package.json b/node_modules/jest-each/package.json new file mode 100644 index 0000000..2ba338b --- /dev/null +++ b/node_modules/jest-each/package.json @@ -0,0 +1,73 @@ +{ + "_from": "jest-each@^29.0.1", + "_id": "jest-each@29.0.1", + "_inBundle": false, + "_integrity": "sha512-UmCZYU9LPvRfSDoCrKJqrCNmgTYGGb3Ga6IVsnnVjedBTRRR9GJMca7UmDKRrJ1s+U632xrVtiRD27BxaG1aaQ==", + "_location": "/jest-each", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-each@^29.0.1", + "name": "jest-each", + "escapedName": "jest-each", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/jest-circus" + ], + "_resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.0.1.tgz", + "_shasum": "c17da68a7073440122dbd47dca3941351ee0cbe5", + "_spec": "jest-each@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-circus", + "author": { + "name": "Matt Phillips", + "url": "mattphillips" + }, + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/types": "^29.0.1", + "chalk": "^4.0.0", + "jest-get-type": "^29.0.0", + "jest-util": "^29.0.1", + "pretty-format": "^29.0.1" + }, + "deprecated": false, + "description": "Parameterised tests for Jest", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "keywords": [ + "jest", + "parameterised", + "test", + "each" + ], + "license": "MIT", + "main": "./build/index.js", + "name": "jest-each", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-each" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-environment-node/LICENSE b/node_modules/jest-environment-node/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-environment-node/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-environment-node/build/index.d.ts b/node_modules/jest-environment-node/build/index.d.ts new file mode 100644 index 0000000..8dde21c --- /dev/null +++ b/node_modules/jest-environment-node/build/index.d.ts @@ -0,0 +1,41 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import {Context} from 'vm'; +import type {EnvironmentContext} from '@jest/environment'; +import type {Global} from '@jest/types'; +import type {JestEnvironment} from '@jest/environment'; +import type {JestEnvironmentConfig} from '@jest/environment'; +import {LegacyFakeTimers} from '@jest/fake-timers'; +import {ModernFakeTimers} from '@jest/fake-timers'; +import {ModuleMocker} from 'jest-mock'; + +declare class NodeEnvironment implements JestEnvironment { + context: Context | null; + fakeTimers: LegacyFakeTimers | null; + fakeTimersModern: ModernFakeTimers | null; + global: Global.Global; + moduleMocker: ModuleMocker | null; + customExportConditions: string[]; + constructor(config: JestEnvironmentConfig, _context: EnvironmentContext); + setup(): Promise; + teardown(): Promise; + exportConditions(): Array; + getVmContext(): Context | null; +} +export default NodeEnvironment; + +export declare const TestEnvironment: typeof NodeEnvironment; + +declare type Timer = { + id: number; + ref: () => Timer; + unref: () => Timer; +}; + +export {}; diff --git a/node_modules/jest-environment-node/build/index.js b/node_modules/jest-environment-node/build/index.js new file mode 100644 index 0000000..3c0fb4a --- /dev/null +++ b/node_modules/jest-environment-node/build/index.js @@ -0,0 +1,214 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = exports.TestEnvironment = void 0; + +function _vm() { + const data = require('vm'); + + _vm = function () { + return data; + }; + + return data; +} + +function _fakeTimers() { + const data = require('@jest/fake-timers'); + + _fakeTimers = function () { + return data; + }; + + return data; +} + +function _jestMock() { + const data = require('jest-mock'); + + _jestMock = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// some globals we do not want, either because deprecated or we set it ourselves +const denyList = new Set([ + 'GLOBAL', + 'root', + 'global', + 'Buffer', + 'ArrayBuffer', + 'Uint8Array', // if env is loaded within a jest test + 'jest-symbol-do-not-touch' +]); +const nodeGlobals = new Map( + Object.getOwnPropertyNames(globalThis) + .filter(global => !denyList.has(global)) + .map(nodeGlobalsKey => { + const descriptor = Object.getOwnPropertyDescriptor( + globalThis, + nodeGlobalsKey + ); + + if (!descriptor) { + throw new Error( + `No property descriptor for ${nodeGlobalsKey}, this is a bug in Jest.` + ); + } + + return [nodeGlobalsKey, descriptor]; + }) +); + +class NodeEnvironment { + context; + fakeTimers; + fakeTimersModern; + global; + moduleMocker; + customExportConditions = ['node', 'node-addons']; // while `context` is unused, it should always be passed + + constructor(config, _context) { + const {projectConfig} = config; + this.context = (0, _vm().createContext)(); + const global = (this.global = (0, _vm().runInContext)( + 'this', + Object.assign(this.context, projectConfig.testEnvironmentOptions) + )); + const contextGlobals = new Set(Object.getOwnPropertyNames(global)); + + for (const [nodeGlobalsKey, descriptor] of nodeGlobals) { + if (!contextGlobals.has(nodeGlobalsKey)) { + Object.defineProperty(global, nodeGlobalsKey, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + + get() { + // @ts-expect-error: no index signature + const val = globalThis[nodeGlobalsKey]; // override lazy getter + + Object.defineProperty(global, nodeGlobalsKey, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + value: val, + writable: descriptor.writable + }); + return val; + }, + + set(val) { + // override lazy getter + Object.defineProperty(global, nodeGlobalsKey, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + value: val, + writable: true + }); + } + }); + } + } + + global.global = global; + global.Buffer = Buffer; + global.ArrayBuffer = ArrayBuffer; // TextEncoder (global or via 'util') references a Uint8Array constructor + // different than the global one used by users in tests. This makes sure the + // same constructor is referenced by both. + + global.Uint8Array = Uint8Array; + (0, _jestUtil().installCommonGlobals)(global, projectConfig.globals); + + if ('customExportConditions' in projectConfig.testEnvironmentOptions) { + const {customExportConditions} = projectConfig.testEnvironmentOptions; + + if ( + Array.isArray(customExportConditions) && + customExportConditions.every(item => typeof item === 'string') + ) { + this.customExportConditions = customExportConditions; + } else { + throw new Error( + 'Custom export conditions specified but they are not an array of strings' + ); + } + } + + this.moduleMocker = new (_jestMock().ModuleMocker)(global); + + const timerIdToRef = id => ({ + id, + + ref() { + return this; + }, + + unref() { + return this; + } + }); + + const timerRefToId = timer => (timer && timer.id) || undefined; + + this.fakeTimers = new (_fakeTimers().LegacyFakeTimers)({ + config: projectConfig, + global, + moduleMocker: this.moduleMocker, + timerConfig: { + idToRef: timerIdToRef, + refToId: timerRefToId + } + }); + this.fakeTimersModern = new (_fakeTimers().ModernFakeTimers)({ + config: projectConfig, + global + }); + } // eslint-disable-next-line @typescript-eslint/no-empty-function + + async setup() {} + + async teardown() { + if (this.fakeTimers) { + this.fakeTimers.dispose(); + } + + if (this.fakeTimersModern) { + this.fakeTimersModern.dispose(); + } + + this.context = null; + this.fakeTimers = null; + this.fakeTimersModern = null; + } + + exportConditions() { + return this.customExportConditions; + } + + getVmContext() { + return this.context; + } +} + +exports.default = NodeEnvironment; +const TestEnvironment = NodeEnvironment; +exports.TestEnvironment = TestEnvironment; diff --git a/node_modules/jest-environment-node/package.json b/node_modules/jest-environment-node/package.json new file mode 100644 index 0000000..50ddd2a --- /dev/null +++ b/node_modules/jest-environment-node/package.json @@ -0,0 +1,67 @@ +{ + "_from": "jest-environment-node@^29.0.1", + "_id": "jest-environment-node@29.0.1", + "_inBundle": false, + "_integrity": "sha512-PcIRBrEBFAPBqkbL53ZpEvTptcAnOW6/lDfqBfACMm3vkVT0N7DcfkH/hqNSbDmSxzGr0FtJI6Ej3TPhveWCMA==", + "_location": "/jest-environment-node", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-environment-node@^29.0.1", + "name": "jest-environment-node", + "escapedName": "jest-environment-node", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/jest-config", + "/jest-runner" + ], + "_resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.0.1.tgz", + "_shasum": "b09db2a1b8439aace11a6805719d92498a64987e", + "_spec": "jest-environment-node@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-config", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/environment": "^29.0.1", + "@jest/fake-timers": "^29.0.1", + "@jest/types": "^29.0.1", + "@types/node": "*", + "jest-mock": "^29.0.1", + "jest-util": "^29.0.1" + }, + "deprecated": false, + "devDependencies": { + "@jest/test-utils": "^29.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-environment-node", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-environment-node" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-get-type/LICENSE b/node_modules/jest-get-type/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-get-type/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-get-type/build/index.d.ts b/node_modules/jest-get-type/build/index.d.ts new file mode 100644 index 0000000..096d2d1 --- /dev/null +++ b/node_modules/jest-get-type/build/index.d.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare function getType(value: unknown): ValueType; + +export declare const isPrimitive: (value: unknown) => boolean; + +declare type ValueType = + | 'array' + | 'bigint' + | 'boolean' + | 'function' + | 'null' + | 'number' + | 'object' + | 'regexp' + | 'map' + | 'set' + | 'date' + | 'string' + | 'symbol' + | 'undefined'; + +export {}; diff --git a/node_modules/jest-get-type/build/index.js b/node_modules/jest-get-type/build/index.js new file mode 100644 index 0000000..d2bc995 --- /dev/null +++ b/node_modules/jest-get-type/build/index.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getType = getType; +exports.isPrimitive = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// get the type of a value with handling the edge cases like `typeof []` +// and `typeof null` +function getType(value) { + if (value === undefined) { + return 'undefined'; + } else if (value === null) { + return 'null'; + } else if (Array.isArray(value)) { + return 'array'; + } else if (typeof value === 'boolean') { + return 'boolean'; + } else if (typeof value === 'function') { + return 'function'; + } else if (typeof value === 'number') { + return 'number'; + } else if (typeof value === 'string') { + return 'string'; + } else if (typeof value === 'bigint') { + return 'bigint'; + } else if (typeof value === 'object') { + if (value != null) { + if (value.constructor === RegExp) { + return 'regexp'; + } else if (value.constructor === Map) { + return 'map'; + } else if (value.constructor === Set) { + return 'set'; + } else if (value.constructor === Date) { + return 'date'; + } + } + + return 'object'; + } else if (typeof value === 'symbol') { + return 'symbol'; + } + + throw new Error(`value of unknown type: ${value}`); +} + +const isPrimitive = value => Object(value) !== value; + +exports.isPrimitive = isPrimitive; diff --git a/node_modules/jest-get-type/package.json b/node_modules/jest-get-type/package.json new file mode 100644 index 0000000..4e152e0 --- /dev/null +++ b/node_modules/jest-get-type/package.json @@ -0,0 +1,64 @@ +{ + "_from": "jest-get-type@^29.0.0", + "_id": "jest-get-type@29.0.0", + "_inBundle": false, + "_integrity": "sha512-83X19z/HuLKYXYHskZlBAShO7UfLFXu/vWajw9ZNJASN32li8yHMaVGAQqxFW1RCFOkB7cubaL6FaJVQqqJLSw==", + "_location": "/jest-get-type", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-get-type@^29.0.0", + "name": "jest-get-type", + "escapedName": "jest-get-type", + "rawSpec": "^29.0.0", + "saveSpec": null, + "fetchSpec": "^29.0.0" + }, + "_requiredBy": [ + "/@jest/expect-utils", + "/expect", + "/jest-config", + "/jest-diff", + "/jest-each", + "/jest-leak-detector", + "/jest-matcher-utils", + "/jest-snapshot", + "/jest-validate" + ], + "_resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.0.0.tgz", + "_shasum": "843f6c50a1b778f7325df1129a0fd7aa713aef80", + "_spec": "jest-get-type@^29.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-config", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A utility function to get the type of a value", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "75006e46c76f6fda14bbc0548f86edb2ba087cd2", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-get-type", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-get-type" + }, + "types": "./build/index.d.ts", + "version": "29.0.0" +} diff --git a/node_modules/jest-haste-map/LICENSE b/node_modules/jest-haste-map/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-haste-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-haste-map/build/HasteFS.js b/node_modules/jest-haste-map/build/HasteFS.js new file mode 100644 index 0000000..757f23c --- /dev/null +++ b/node_modules/jest-haste-map/build/HasteFS.js @@ -0,0 +1,170 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var _constants = _interopRequireDefault(require('./constants')); + +var fastPath = _interopRequireWildcard(require('./lib/fast_path')); + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class HasteFS { + _rootDir; + _files; + + constructor({rootDir, files}) { + this._rootDir = rootDir; + this._files = files; + } + + getModuleName(file) { + const fileMetadata = this._getFileData(file); + + return (fileMetadata && fileMetadata[_constants.default.ID]) || null; + } + + getSize(file) { + const fileMetadata = this._getFileData(file); + + return (fileMetadata && fileMetadata[_constants.default.SIZE]) || null; + } + + getDependencies(file) { + const fileMetadata = this._getFileData(file); + + if (fileMetadata) { + return fileMetadata[_constants.default.DEPENDENCIES] + ? fileMetadata[_constants.default.DEPENDENCIES].split( + _constants.default.DEPENDENCY_DELIM + ) + : []; + } else { + return null; + } + } + + getSha1(file) { + const fileMetadata = this._getFileData(file); + + return (fileMetadata && fileMetadata[_constants.default.SHA1]) || null; + } + + exists(file) { + return this._getFileData(file) != null; + } + + getAllFiles() { + return Array.from(this.getAbsoluteFileIterator()); + } + + getFileIterator() { + return this._files.keys(); + } + + *getAbsoluteFileIterator() { + for (const file of this.getFileIterator()) { + yield fastPath.resolve(this._rootDir, file); + } + } + + matchFiles(pattern) { + if (!(pattern instanceof RegExp)) { + pattern = new RegExp(pattern); + } + + const files = []; + + for (const file of this.getAbsoluteFileIterator()) { + if (pattern.test(file)) { + files.push(file); + } + } + + return files; + } + + matchFilesWithGlob(globs, root) { + const files = new Set(); + const matcher = (0, _jestUtil().globsToMatcher)(globs); + + for (const file of this.getAbsoluteFileIterator()) { + const filePath = root ? fastPath.relative(root, file) : file; + + if (matcher((0, _jestUtil().replacePathSepForGlob)(filePath))) { + files.add(file); + } + } + + return files; + } + + _getFileData(file) { + const relativePath = fastPath.relative(this._rootDir, file); + return this._files.get(relativePath); + } +} + +exports.default = HasteFS; diff --git a/node_modules/jest-haste-map/build/ModuleMap.js b/node_modules/jest-haste-map/build/ModuleMap.js new file mode 100644 index 0000000..6a19869 --- /dev/null +++ b/node_modules/jest-haste-map/build/ModuleMap.js @@ -0,0 +1,292 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _constants = _interopRequireDefault(require('./constants')); + +var fastPath = _interopRequireWildcard(require('./lib/fast_path')); + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const EMPTY_OBJ = {}; +const EMPTY_MAP = new Map(); + +class ModuleMap { + static DuplicateHasteCandidatesError; + _raw; + json; + + static mapToArrayRecursive(map) { + let arr = Array.from(map); + + if (arr[0] && arr[0][1] instanceof Map) { + arr = arr.map(el => [el[0], this.mapToArrayRecursive(el[1])]); + } + + return arr; + } + + static mapFromArrayRecursive(arr) { + if (arr[0] && Array.isArray(arr[1])) { + arr = arr.map(el => [el[0], this.mapFromArrayRecursive(el[1])]); + } + + return new Map(arr); + } + + constructor(raw) { + this._raw = raw; + } + + getModule(name, platform, supportsNativePlatform, type) { + if (type == null) { + type = _constants.default.MODULE; + } + + const module = this._getModuleMetadata( + name, + platform, + !!supportsNativePlatform + ); + + if (module && module[_constants.default.TYPE] === type) { + const modulePath = module[_constants.default.PATH]; + return modulePath && fastPath.resolve(this._raw.rootDir, modulePath); + } + + return null; + } + + getPackage(name, platform, _supportsNativePlatform) { + return this.getModule(name, platform, null, _constants.default.PACKAGE); + } + + getMockModule(name) { + const mockPath = + this._raw.mocks.get(name) || this._raw.mocks.get(`${name}/index`); + + return mockPath && fastPath.resolve(this._raw.rootDir, mockPath); + } + + getRawModuleMap() { + return { + duplicates: this._raw.duplicates, + map: this._raw.map, + mocks: this._raw.mocks, + rootDir: this._raw.rootDir + }; + } + + toJSON() { + if (!this.json) { + this.json = { + duplicates: ModuleMap.mapToArrayRecursive(this._raw.duplicates), + map: Array.from(this._raw.map), + mocks: Array.from(this._raw.mocks), + rootDir: this._raw.rootDir + }; + } + + return this.json; + } + + static fromJSON(serializableModuleMap) { + return new ModuleMap({ + duplicates: ModuleMap.mapFromArrayRecursive( + serializableModuleMap.duplicates + ), + map: new Map(serializableModuleMap.map), + mocks: new Map(serializableModuleMap.mocks), + rootDir: serializableModuleMap.rootDir + }); + } + /** + * When looking up a module's data, we walk through each eligible platform for + * the query. For each platform, we want to check if there are known + * duplicates for that name+platform pair. The duplication logic normally + * removes elements from the `map` object, but we want to check upfront to be + * extra sure. If metadata exists both in the `duplicates` object and the + * `map`, this would be a bug. + */ + + _getModuleMetadata(name, platform, supportsNativePlatform) { + const map = this._raw.map.get(name) || EMPTY_OBJ; + const dupMap = this._raw.duplicates.get(name) || EMPTY_MAP; + + if (platform != null) { + this._assertNoDuplicates( + name, + platform, + supportsNativePlatform, + dupMap.get(platform) + ); + + if (map[platform] != null) { + return map[platform]; + } + } + + if (supportsNativePlatform) { + this._assertNoDuplicates( + name, + _constants.default.NATIVE_PLATFORM, + supportsNativePlatform, + dupMap.get(_constants.default.NATIVE_PLATFORM) + ); + + if (map[_constants.default.NATIVE_PLATFORM]) { + return map[_constants.default.NATIVE_PLATFORM]; + } + } + + this._assertNoDuplicates( + name, + _constants.default.GENERIC_PLATFORM, + supportsNativePlatform, + dupMap.get(_constants.default.GENERIC_PLATFORM) + ); + + if (map[_constants.default.GENERIC_PLATFORM]) { + return map[_constants.default.GENERIC_PLATFORM]; + } + + return null; + } + + _assertNoDuplicates(name, platform, supportsNativePlatform, relativePathSet) { + if (relativePathSet == null) { + return; + } // Force flow refinement + + const previousSet = relativePathSet; + const duplicates = new Map(); + + for (const [relativePath, type] of previousSet) { + const duplicatePath = fastPath.resolve(this._raw.rootDir, relativePath); + duplicates.set(duplicatePath, type); + } + + throw new DuplicateHasteCandidatesError( + name, + platform, + supportsNativePlatform, + duplicates + ); + } + + static create(rootDir) { + return new ModuleMap({ + duplicates: new Map(), + map: new Map(), + mocks: new Map(), + rootDir + }); + } +} + +exports.default = ModuleMap; + +class DuplicateHasteCandidatesError extends Error { + hasteName; + platform; + supportsNativePlatform; + duplicatesSet; + + constructor(name, platform, supportsNativePlatform, duplicatesSet) { + const platformMessage = getPlatformMessage(platform); + super( + `The name \`${name}\` was looked up in the Haste module map. It ` + + 'cannot be resolved, because there exists several different ' + + 'files, or packages, that provide a module for ' + + `that particular name and platform. ${platformMessage} You must ` + + `delete or exclude files until there remains only one of these:\n\n${Array.from( + duplicatesSet + ) + .map( + ([dupFilePath, dupFileType]) => + ` * \`${dupFilePath}\` (${getTypeMessage(dupFileType)})\n` + ) + .sort() + .join('')}` + ); + this.hasteName = name; + this.platform = platform; + this.supportsNativePlatform = supportsNativePlatform; + this.duplicatesSet = duplicatesSet; + } +} + +function getPlatformMessage(platform) { + if (platform === _constants.default.GENERIC_PLATFORM) { + return 'The platform is generic (no extension).'; + } + + return `The platform extension is \`${platform}\`.`; +} + +function getTypeMessage(type) { + switch (type) { + case _constants.default.MODULE: + return 'module'; + + case _constants.default.PACKAGE: + return 'package'; + } + + return 'unknown'; +} + +ModuleMap.DuplicateHasteCandidatesError = DuplicateHasteCandidatesError; diff --git a/node_modules/jest-haste-map/build/blacklist.js b/node_modules/jest-haste-map/build/blacklist.js new file mode 100644 index 0000000..190a398 --- /dev/null +++ b/node_modules/jest-haste-map/build/blacklist.js @@ -0,0 +1,59 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// This list is compiled after the MDN list of the most common MIME types (see +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/ +// Complete_list_of_MIME_types). +// +// Only MIME types starting with "image/", "video/", "audio/" and "font/" are +// reflected in the list. Adding "application/" is too risky since some text +// file formats (like ".js" and ".json") have an "application/" MIME type. +// +// Feel free to add any extensions that cannot be a Haste module. +const extensions = new Set([ + // JSONs are never haste modules, except for "package.json", which is handled. + '.json', // Image extensions. + '.bmp', + '.gif', + '.ico', + '.jpeg', + '.jpg', + '.png', + '.svg', + '.tiff', + '.tif', + '.webp', // Video extensions. + '.avi', + '.mp4', + '.mpeg', + '.mpg', + '.ogv', + '.webm', + '.3gp', + '.3g2', // Audio extensions. + '.aac', + '.midi', + '.mid', + '.mp3', + '.oga', + '.wav', + '.3gp', + '.3g2', // Font extensions. + '.eot', + '.otf', + '.ttf', + '.woff', + '.woff2' +]); +var _default = extensions; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/constants.js b/node_modules/jest-haste-map/build/constants.js new file mode 100644 index 0000000..2269de4 --- /dev/null +++ b/node_modules/jest-haste-map/build/constants.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* + * This file exports a set of constants that are used for Jest's haste map + * serialization. On very large repositories, the haste map cache becomes very + * large to the point where it is the largest overhead in starting up Jest. + * + * This constant key map allows to keep the map smaller without having to build + * a custom serialization library. + */ + +/* eslint-disable sort-keys */ +const constants = { + /* dependency serialization */ + DEPENDENCY_DELIM: '\0', + + /* file map attributes */ + ID: 0, + MTIME: 1, + SIZE: 2, + VISITED: 3, + DEPENDENCIES: 4, + SHA1: 5, + + /* module map attributes */ + PATH: 0, + TYPE: 1, + + /* module types */ + MODULE: 0, + PACKAGE: 1, + + /* platforms */ + GENERIC_PLATFORM: 'g', + NATIVE_PLATFORM: 'native' +}; +/* eslint-enable */ + +var _default = constants; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/crawlers/node.js b/node_modules/jest-haste-map/build/crawlers/node.js new file mode 100644 index 0000000..419a151 --- /dev/null +++ b/node_modules/jest-haste-map/build/crawlers/node.js @@ -0,0 +1,311 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.nodeCrawl = nodeCrawl; + +function _child_process() { + const data = require('child_process'); + + _child_process = function () { + return data; + }; + + return data; +} + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +var _constants = _interopRequireDefault(require('../constants')); + +var fastPath = _interopRequireWildcard(require('../lib/fast_path')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +async function hasNativeFindSupport(forceNodeFilesystemAPI) { + if (forceNodeFilesystemAPI) { + return false; + } + + try { + return await new Promise(resolve => { + // Check the find binary supports the non-POSIX -iname parameter wrapped in parens. + const args = [ + '.', + '-type', + 'f', + '(', + '-iname', + '*.ts', + '-o', + '-iname', + '*.js', + ')' + ]; + const child = (0, _child_process().spawn)('find', args, { + cwd: __dirname + }); + child.on('error', () => { + resolve(false); + }); + child.on('exit', code => { + resolve(code === 0); + }); + }); + } catch { + return false; + } +} + +function find(roots, extensions, ignore, enableSymlinks, callback) { + const result = []; + let activeCalls = 0; + + function search(directory) { + activeCalls++; + fs().readdir( + directory, + { + withFileTypes: true + }, + (err, entries) => { + activeCalls--; + + if (err) { + if (activeCalls === 0) { + callback(result); + } + + return; + } + + entries.forEach(entry => { + const file = path().join(directory, entry.name); + + if (ignore(file)) { + return; + } + + if (entry.isSymbolicLink()) { + return; + } + + if (entry.isDirectory()) { + search(file); + return; + } + + activeCalls++; + const stat = enableSymlinks ? fs().stat : fs().lstat; + stat(file, (err, stat) => { + activeCalls--; // This logic is unnecessary for node > v10.10, but leaving it in + // since we need it for backwards-compatibility still. + + if (!err && stat && !stat.isSymbolicLink()) { + if (stat.isDirectory()) { + search(file); + } else { + const ext = path().extname(file).substr(1); + + if (extensions.indexOf(ext) !== -1) { + result.push([file, stat.mtime.getTime(), stat.size]); + } + } + } + + if (activeCalls === 0) { + callback(result); + } + }); + }); + + if (activeCalls === 0) { + callback(result); + } + } + ); + } + + if (roots.length > 0) { + roots.forEach(search); + } else { + callback(result); + } +} + +function findNative(roots, extensions, ignore, enableSymlinks, callback) { + const args = Array.from(roots); + + if (enableSymlinks) { + args.push('(', '-type', 'f', '-o', '-type', 'l', ')'); + } else { + args.push('-type', 'f'); + } + + if (extensions.length) { + args.push('('); + } + + extensions.forEach((ext, index) => { + if (index) { + args.push('-o'); + } + + args.push('-iname'); + args.push(`*.${ext}`); + }); + + if (extensions.length) { + args.push(')'); + } + + const child = (0, _child_process().spawn)('find', args); + let stdout = ''; + + if (child.stdout === null) { + throw new Error( + 'stdout is null - this should never happen. Please open up an issue at https://github.com/facebook/jest' + ); + } + + child.stdout.setEncoding('utf-8'); + child.stdout.on('data', data => (stdout += data)); + child.stdout.on('close', () => { + const lines = stdout + .trim() + .split('\n') + .filter(x => !ignore(x)); + const result = []; + let count = lines.length; + + if (!count) { + callback([]); + } else { + lines.forEach(path => { + fs().stat(path, (err, stat) => { + // Filter out symlinks that describe directories + if (!err && stat && !stat.isDirectory()) { + result.push([path, stat.mtime.getTime(), stat.size]); + } + + if (--count === 0) { + callback(result); + } + }); + }); + } + }); +} + +async function nodeCrawl(options) { + const { + data, + extensions, + forceNodeFilesystemAPI, + ignore, + rootDir, + enableSymlinks, + roots + } = options; + const useNativeFind = await hasNativeFindSupport(forceNodeFilesystemAPI); + return new Promise(resolve => { + const callback = list => { + const files = new Map(); + const removedFiles = new Map(data.files); + list.forEach(fileData => { + const [filePath, mtime, size] = fileData; + const relativeFilePath = fastPath.relative(rootDir, filePath); + const existingFile = data.files.get(relativeFilePath); + + if (existingFile && existingFile[_constants.default.MTIME] === mtime) { + files.set(relativeFilePath, existingFile); + } else { + // See ../constants.js; SHA-1 will always be null and fulfilled later. + files.set(relativeFilePath, ['', mtime, size, 0, '', null]); + } + + removedFiles.delete(relativeFilePath); + }); + data.files = files; + resolve({ + hasteMap: data, + removedFiles + }); + }; + + if (useNativeFind) { + findNative(roots, extensions, ignore, enableSymlinks, callback); + } else { + find(roots, extensions, ignore, enableSymlinks, callback); + } + }); +} diff --git a/node_modules/jest-haste-map/build/crawlers/watchman.js b/node_modules/jest-haste-map/build/crawlers/watchman.js new file mode 100644 index 0000000..418b759 --- /dev/null +++ b/node_modules/jest-haste-map/build/crawlers/watchman.js @@ -0,0 +1,369 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.watchmanCrawl = watchmanCrawl; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _fbWatchman() { + const data = _interopRequireDefault(require('fb-watchman')); + + _fbWatchman = function () { + return data; + }; + + return data; +} + +var _constants = _interopRequireDefault(require('../constants')); + +var fastPath = _interopRequireWildcard(require('../lib/fast_path')); + +var _normalizePathSep = _interopRequireDefault( + require('../lib/normalizePathSep') +); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const watchmanURL = 'https://facebook.github.io/watchman/docs/troubleshooting'; + +function WatchmanError(error) { + error.message = + `Watchman error: ${error.message.trim()}. Make sure watchman ` + + `is running for this project. See ${watchmanURL}.`; + return error; +} +/** + * Wrap watchman capabilityCheck method as a promise. + * + * @param client watchman client + * @param caps capabilities to verify + * @returns a promise resolving to a list of verified capabilities + */ + +async function capabilityCheck(client, caps) { + return new Promise((resolve, reject) => { + client.capabilityCheck( + // @ts-expect-error: incorrectly typed + caps, + (error, response) => { + if (error) { + reject(error); + } else { + resolve(response); + } + } + ); + }); +} + +async function watchmanCrawl(options) { + const fields = ['name', 'exists', 'mtime_ms', 'size']; + const {data, extensions, ignore, rootDir, roots} = options; + const defaultWatchExpression = ['allof', ['type', 'f']]; + const clocks = data.clocks; + const client = new (_fbWatchman().default.Client)(); // https://facebook.github.io/watchman/docs/capabilities.html + // Check adds about ~28ms + + const capabilities = await capabilityCheck(client, { + // If a required capability is missing then an error will be thrown, + // we don't need this assertion, so using optional instead. + optional: ['suffix-set'] + }); + + if (capabilities?.capabilities['suffix-set']) { + // If available, use the optimized `suffix-set` operation: + // https://facebook.github.io/watchman/docs/expr/suffix.html#suffix-set + defaultWatchExpression.push(['suffix', extensions]); + } else { + // Otherwise use the older and less optimal suffix tuple array + defaultWatchExpression.push([ + 'anyof', + ...extensions.map(extension => ['suffix', extension]) + ]); + } + + let clientError; + client.on('error', error => (clientError = WatchmanError(error))); + + const cmd = (...args) => + new Promise((resolve, reject) => + client.command(args, (error, result) => + error ? reject(WatchmanError(error)) : resolve(result) + ) + ); + + if (options.computeSha1) { + const {capabilities} = await cmd('list-capabilities'); + + if (capabilities.indexOf('field-content.sha1hex') !== -1) { + fields.push('content.sha1hex'); + } + } + + async function getWatchmanRoots(roots) { + const watchmanRoots = new Map(); + await Promise.all( + roots.map(async root => { + const response = await cmd('watch-project', root); + const existing = watchmanRoots.get(response.watch); // A root can only be filtered if it was never seen with a + // relative_path before. + + const canBeFiltered = !existing || existing.length > 0; + + if (canBeFiltered) { + if (response.relative_path) { + watchmanRoots.set( + response.watch, + (existing || []).concat(response.relative_path) + ); + } else { + // Make the filter directories an empty array to signal that this + // root was already seen and needs to be watched for all files or + // directories. + watchmanRoots.set(response.watch, []); + } + } + }) + ); + return watchmanRoots; + } + + async function queryWatchmanForDirs(rootProjectDirMappings) { + const results = new Map(); + let isFresh = false; + await Promise.all( + Array.from(rootProjectDirMappings).map( + async ([root, directoryFilters]) => { + const expression = Array.from(defaultWatchExpression); + const glob = []; + + if (directoryFilters.length > 0) { + expression.push([ + 'anyof', + ...directoryFilters.map(dir => ['dirname', dir]) + ]); + + for (const directory of directoryFilters) { + for (const extension of extensions) { + glob.push(`${directory}/**/*.${extension}`); + } + } + } else { + for (const extension of extensions) { + glob.push(`**/*.${extension}`); + } + } // Jest is only going to store one type of clock; a string that + // represents a local clock. However, the Watchman crawler supports + // a second type of clock that can be written by automation outside of + // Jest, called an "scm query", which fetches changed files based on + // source control mergebases. The reason this is necessary is because + // local clocks are not portable across systems, but scm queries are. + // By using scm queries, we can create the haste map on a different + // system and import it, transforming the clock into a local clock. + + const since = clocks.get(fastPath.relative(rootDir, root)); + const query = + since !== undefined // Use the `since` generator if we have a clock available + ? { + expression, + fields, + since + } // Otherwise use the `glob` filter + : { + expression, + fields, + glob, + glob_includedotfiles: true + }; + const response = await cmd('query', root, query); + + if ('warning' in response) { + console.warn('watchman warning: ', response.warning); + } // When a source-control query is used, we ignore the "is fresh" + // response from Watchman because it will be true despite the query + // being incremental. + + const isSourceControlQuery = + typeof since !== 'string' && + since?.scm?.['mergebase-with'] !== undefined; + + if (!isSourceControlQuery) { + isFresh = isFresh || response.is_fresh_instance; + } + + results.set(root, response); + } + ) + ); + return { + isFresh, + results + }; + } + + let files = data.files; + let removedFiles = new Map(); + const changedFiles = new Map(); + let results; + let isFresh = false; + + try { + const watchmanRoots = await getWatchmanRoots(roots); + const watchmanFileResults = await queryWatchmanForDirs(watchmanRoots); // Reset the file map if watchman was restarted and sends us a list of + // files. + + if (watchmanFileResults.isFresh) { + files = new Map(); + removedFiles = new Map(data.files); + isFresh = true; + } + + results = watchmanFileResults.results; + } finally { + client.end(); + } + + if (clientError) { + throw clientError; + } + + for (const [watchRoot, response] of results) { + const fsRoot = (0, _normalizePathSep.default)(watchRoot); + const relativeFsRoot = fastPath.relative(rootDir, fsRoot); + clocks.set( + relativeFsRoot, // Ensure we persist only the local clock. + typeof response.clock === 'string' ? response.clock : response.clock.clock + ); + + for (const fileData of response.files) { + const filePath = + fsRoot + path().sep + (0, _normalizePathSep.default)(fileData.name); + const relativeFilePath = fastPath.relative(rootDir, filePath); + const existingFileData = data.files.get(relativeFilePath); // If watchman is fresh, the removed files map starts with all files + // and we remove them as we verify they still exist. + + if (isFresh && existingFileData && fileData.exists) { + removedFiles.delete(relativeFilePath); + } + + if (!fileData.exists) { + // No need to act on files that do not exist and were not tracked. + if (existingFileData) { + files.delete(relativeFilePath); // If watchman is not fresh, we will know what specific files were + // deleted since we last ran and can track only those files. + + if (!isFresh) { + removedFiles.set(relativeFilePath, existingFileData); + } + } + } else if (!ignore(filePath)) { + const mtime = + typeof fileData.mtime_ms === 'number' + ? fileData.mtime_ms + : fileData.mtime_ms.toNumber(); + const size = fileData.size; + let sha1hex = fileData['content.sha1hex']; + + if (typeof sha1hex !== 'string' || sha1hex.length !== 40) { + sha1hex = undefined; + } + + let nextData; + + if ( + existingFileData && + existingFileData[_constants.default.MTIME] === mtime + ) { + nextData = existingFileData; + } else if ( + existingFileData && + sha1hex && + existingFileData[_constants.default.SHA1] === sha1hex + ) { + nextData = [ + existingFileData[0], + mtime, + existingFileData[2], + existingFileData[3], + existingFileData[4], + existingFileData[5] + ]; + } else { + // See ../constants.ts + nextData = ['', mtime, size, 0, '', sha1hex ?? null]; + } + + files.set(relativeFilePath, nextData); + changedFiles.set(relativeFilePath, nextData); + } + } + } + + data.files = files; + return { + changedFiles: isFresh ? undefined : changedFiles, + hasteMap: data, + removedFiles + }; +} diff --git a/node_modules/jest-haste-map/build/getMockName.js b/node_modules/jest-haste-map/build/getMockName.js new file mode 100644 index 0000000..19d8237 --- /dev/null +++ b/node_modules/jest-haste-map/build/getMockName.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const MOCKS_PATTERN = `${path().sep}__mocks__${path().sep}`; + +const getMockName = filePath => { + const mockPath = filePath.split(MOCKS_PATTERN)[1]; + return mockPath + .substring(0, mockPath.lastIndexOf(path().extname(mockPath))) + .replace(/\\/g, '/'); +}; + +var _default = getMockName; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/index.d.ts b/node_modules/jest-haste-map/build/index.d.ts new file mode 100644 index 0000000..d5b37fe --- /dev/null +++ b/node_modules/jest-haste-map/build/index.d.ts @@ -0,0 +1,380 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {Config} from '@jest/types'; +import {EventEmitter} from 'events'; +import type {Stats} from 'graceful-fs'; + +export declare type ChangeEvent = { + eventsQueue: EventsQueue; + hasteFS: FS; + moduleMap: ModuleMap; +}; + +export declare class DuplicateError extends Error { + mockPath1: string; + mockPath2: string; + constructor(mockPath1: string, mockPath2: string); +} + +declare class DuplicateHasteCandidatesError extends Error { + hasteName: string; + platform: string | null; + supportsNativePlatform: boolean; + duplicatesSet: DuplicatesSet; + constructor( + name: string, + platform: string, + supportsNativePlatform: boolean, + duplicatesSet: DuplicatesSet, + ); +} + +declare type DuplicatesIndex = Map>; + +declare type DuplicatesSet = Map; + +declare type EventsQueue = Array<{ + filePath: string; + stat: Stats | undefined; + type: string; +}>; + +declare type FileData = Map; + +declare type FileMetaData = [ + id: string, + mtime: number, + size: number, + visited: 0 | 1, + dependencies: string, + sha1: string | null | undefined, +]; + +export declare class FS { + private readonly _rootDir; + private readonly _files; + constructor({rootDir, files}: {rootDir: string; files: FileData}); + getModuleName(file: string): string | null; + getSize(file: string): number | null; + getDependencies(file: string): Array | null; + getSha1(file: string): string | null; + exists(file: string): boolean; + getAllFiles(): Array; + getFileIterator(): Iterable; + getAbsoluteFileIterator(): Iterable; + matchFiles(pattern: RegExp | string): Array; + matchFilesWithGlob(globs: Array, root: string | null): Set; + private _getFileData; +} + +/** + * HasteMap is a JavaScript implementation of Facebook's haste module system. + * + * This implementation is inspired by https://github.com/facebook/node-haste + * and was built with for high-performance in large code repositories with + * hundreds of thousands of files. This implementation is scalable and provides + * predictable performance. + * + * Because the haste map creation and synchronization is critical to startup + * performance and most tasks are blocked by I/O this class makes heavy use of + * synchronous operations. It uses worker processes for parallelizing file + * access and metadata extraction. + * + * The data structures created by `jest-haste-map` can be used directly from the + * cache without further processing. The metadata objects in the `files` and + * `map` objects contain cross-references: a metadata object from one can look + * up the corresponding metadata object in the other map. Note that in most + * projects, the number of files will be greater than the number of haste + * modules one module can refer to many files based on platform extensions. + * + * type HasteMap = { + * clocks: WatchmanClocks, + * files: {[filepath: string]: FileMetaData}, + * map: {[id: string]: ModuleMapItem}, + * mocks: {[id: string]: string}, + * } + * + * // Watchman clocks are used for query synchronization and file system deltas. + * type WatchmanClocks = {[filepath: string]: string}; + * + * type FileMetaData = { + * id: ?string, // used to look up module metadata objects in `map`. + * mtime: number, // check for outdated files. + * size: number, // size of the file in bytes. + * visited: boolean, // whether the file has been parsed or not. + * dependencies: Array, // all relative dependencies of this file. + * sha1: ?string, // SHA-1 of the file, if requested via options. + * }; + * + * // Modules can be targeted to a specific platform based on the file name. + * // Example: platform.ios.js and Platform.android.js will both map to the same + * // `Platform` module. The platform should be specified during resolution. + * type ModuleMapItem = {[platform: string]: ModuleMetaData}; + * + * // + * type ModuleMetaData = { + * path: string, // the path to look up the file object in `files`. + * type: string, // the module type (either `package` or `module`). + * }; + * + * Note that the data structures described above are conceptual only. The actual + * implementation uses arrays and constant keys for metadata storage. Instead of + * `{id: 'flatMap', mtime: 3421, size: 42, visited: true, dependencies: []}` the real + * representation is similar to `['flatMap', 3421, 42, 1, []]` to save storage space + * and reduce parse and write time of a big JSON blob. + * + * The HasteMap is created as follows: + * 1. read data from the cache or create an empty structure. + * + * 2. crawl the file system. + * * empty cache: crawl the entire file system. + * * cache available: + * * if watchman is available: get file system delta changes. + * * if watchman is unavailable: crawl the entire file system. + * * build metadata objects for every file. This builds the `files` part of + * the `HasteMap`. + * + * 3. parse and extract metadata from changed files. + * * this is done in parallel over worker processes to improve performance. + * * the worst case is to parse all files. + * * the best case is no file system access and retrieving all data from + * the cache. + * * the average case is a small number of changed files. + * + * 4. serialize the new `HasteMap` in a cache file. + * Worker processes can directly access the cache through `HasteMap.read()`. + * + */ +declare class HasteMap extends EventEmitter { + private _buildPromise; + private _cachePath; + private _changeInterval?; + private _console; + private _isWatchmanInstalledPromise; + private _options; + private _watchers; + private _worker; + static getStatic(config: Config.ProjectConfig): HasteMapStatic; + static create(options: Options): Promise; + private constructor(); + private setupCachePath; + static getCacheFilePath( + tmpdir: string, + id: string, + ...extra: Array + ): string; + static getModuleMapFromJSON(json: SerializableModuleMap): ModuleMap; + getCacheFilePath(): string; + build(): Promise; + /** + * 1. read data from the cache or create an empty structure. + */ + read(): InternalHasteMap; + readModuleMap(): ModuleMap; + /** + * 2. crawl the file system. + */ + private _buildFileMap; + /** + * 3. parse and extract metadata from changed files. + */ + private _processFile; + private _buildHasteMap; + private _cleanup; + /** + * 4. serialize the new `HasteMap` in a cache file. + */ + private _persist; + /** + * Creates workers or parses files and extracts metadata in-process. + */ + private _getWorker; + private _crawl; + /** + * Watch mode + */ + private _watch; + /** + * This function should be called when the file under `filePath` is removed + * or changed. When that happens, we want to figure out if that file was + * part of a group of files that had the same ID. If it was, we want to + * remove it from the group. Furthermore, if there is only one file + * remaining in the group, then we want to restore that single file as the + * correct resolution for its ID, and cleanup the duplicates index. + */ + private _recoverDuplicates; + end(): Promise; + /** + * Helpers + */ + private _ignore; + private _shouldUseWatchman; + private _createEmptyMap; + static H: HType; +} +export default HasteMap; + +export declare type HasteMapObject = { + hasteFS: FS; + moduleMap: ModuleMap; + __hasteMapForTest?: InternalHasteMap | null; +}; + +declare type HasteMapStatic = { + getCacheFilePath( + tmpdir: string, + name: string, + ...extra: Array + ): string; + getModuleMapFromJSON(json: S): IModuleMap; +}; + +declare type HasteRegExp = RegExp | ((str: string) => boolean); + +declare type HType = { + ID: 0; + MTIME: 1; + SIZE: 2; + VISITED: 3; + DEPENDENCIES: 4; + SHA1: 5; + PATH: 0; + TYPE: 1; + MODULE: 0; + PACKAGE: 1; + GENERIC_PLATFORM: 'g'; + NATIVE_PLATFORM: 'native'; + DEPENDENCY_DELIM: '\0'; +}; + +declare type HTypeValue = HType[keyof HType]; + +export declare interface IModuleMap { + getModule( + name: string, + platform?: string | null, + supportsNativePlatform?: boolean | null, + type?: HTypeValue | null, + ): string | null; + getPackage( + name: string, + platform: string | null | undefined, + _supportsNativePlatform: boolean | null, + ): string | null; + getMockModule(name: string): string | undefined; + getRawModuleMap(): RawModuleMap; + toJSON(): S; +} + +declare type InternalHasteMap = { + clocks: WatchmanClocks; + duplicates: DuplicatesIndex; + files: FileData; + map: ModuleMapData; + mocks: MockData; +}; + +declare type MockData = Map; + +export declare class ModuleMap implements IModuleMap { + static DuplicateHasteCandidatesError: typeof DuplicateHasteCandidatesError; + private readonly _raw; + private json; + private static mapToArrayRecursive; + private static mapFromArrayRecursive; + constructor(raw: RawModuleMap); + getModule( + name: string, + platform?: string | null, + supportsNativePlatform?: boolean | null, + type?: HTypeValue | null, + ): string | null; + getPackage( + name: string, + platform: string | null | undefined, + _supportsNativePlatform: boolean | null, + ): string | null; + getMockModule(name: string): string | undefined; + getRawModuleMap(): RawModuleMap; + toJSON(): SerializableModuleMap; + static fromJSON(serializableModuleMap: SerializableModuleMap): ModuleMap; + /** + * When looking up a module's data, we walk through each eligible platform for + * the query. For each platform, we want to check if there are known + * duplicates for that name+platform pair. The duplication logic normally + * removes elements from the `map` object, but we want to check upfront to be + * extra sure. If metadata exists both in the `duplicates` object and the + * `map`, this would be a bug. + */ + private _getModuleMetadata; + private _assertNoDuplicates; + static create(rootDir: string): ModuleMap; +} + +declare type ModuleMapData = Map; + +declare type ModuleMapItem = { + [platform: string]: ModuleMetaData; +}; + +declare type ModuleMetaData = [path: string, type: number]; + +declare type Options = { + cacheDirectory?: string; + computeDependencies?: boolean; + computeSha1?: boolean; + console?: Console; + dependencyExtractor?: string | null; + enableSymlinks?: boolean; + extensions: Array; + forceNodeFilesystemAPI?: boolean; + hasteImplModulePath?: string; + hasteMapModulePath?: string; + id: string; + ignorePattern?: HasteRegExp; + maxWorkers: number; + mocksPattern?: string; + platforms: Array; + resetCache?: boolean; + retainAllFiles: boolean; + rootDir: string; + roots: Array; + skipPackageJson?: boolean; + throwOnModuleCollision?: boolean; + useWatchman?: boolean; + watch?: boolean; +}; + +declare type RawModuleMap = { + rootDir: string; + duplicates: DuplicatesIndex; + map: ModuleMapData; + mocks: MockData; +}; + +export declare type SerializableModuleMap = { + duplicates: ReadonlyArray<[string, [string, [string, [string, number]]]]>; + map: ReadonlyArray<[string, ValueType]>; + mocks: ReadonlyArray<[string, ValueType]>; + rootDir: string; +}; + +declare type ValueType = T extends Map ? V : never; + +declare type WatchmanClocks = Map; + +declare type WatchmanClockSpec = + | string + | { + scm: { + 'mergebase-with': string; + }; + }; + +export {}; diff --git a/node_modules/jest-haste-map/build/index.js b/node_modules/jest-haste-map/build/index.js new file mode 100644 index 0000000..447bb71 --- /dev/null +++ b/node_modules/jest-haste-map/build/index.js @@ -0,0 +1,1274 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.DuplicateError = void 0; +Object.defineProperty(exports, 'ModuleMap', { + enumerable: true, + get: function () { + return _ModuleMap.default; + } +}); +exports.default = void 0; + +function _crypto() { + const data = require('crypto'); + + _crypto = function () { + return data; + }; + + return data; +} + +function _events() { + const data = require('events'); + + _events = function () { + return data; + }; + + return data; +} + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _v() { + const data = require('v8'); + + _v = function () { + return data; + }; + + return data; +} + +function _gracefulFs() { + const data = require('graceful-fs'); + + _gracefulFs = function () { + return data; + }; + + return data; +} + +function _jestRegexUtil() { + const data = require('jest-regex-util'); + + _jestRegexUtil = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _jestWorker() { + const data = require('jest-worker'); + + _jestWorker = function () { + return data; + }; + + return data; +} + +var _HasteFS = _interopRequireDefault(require('./HasteFS')); + +var _ModuleMap = _interopRequireDefault(require('./ModuleMap')); + +var _constants = _interopRequireDefault(require('./constants')); + +var _node = require('./crawlers/node'); + +var _watchman = require('./crawlers/watchman'); + +var _getMockName = _interopRequireDefault(require('./getMockName')); + +var fastPath = _interopRequireWildcard(require('./lib/fast_path')); + +var _getPlatformExtension = _interopRequireDefault( + require('./lib/getPlatformExtension') +); + +var _isWatchmanInstalled = _interopRequireDefault( + require('./lib/isWatchmanInstalled') +); + +var _normalizePathSep = _interopRequireDefault( + require('./lib/normalizePathSep') +); + +var _FSEventsWatcher = require('./watchers/FSEventsWatcher'); + +var _NodeWatcher = _interopRequireDefault(require('./watchers/NodeWatcher')); + +var _WatchmanWatcher = _interopRequireDefault( + require('./watchers/WatchmanWatcher') +); + +var _worker = require('./worker'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/facebook/jest/pull/10919 +// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/facebook/jest/pull/5387 +// TypeScript doesn't like us importing from outside `rootDir`, but it doesn't +// understand `require`. +const {version: VERSION} = require('../package.json'); + +const CHANGE_INTERVAL = 30; +const MAX_WAIT_TIME = 240000; +const NODE_MODULES = `${path().sep}node_modules${path().sep}`; +const PACKAGE_JSON = `${path().sep}package.json`; +const VCS_DIRECTORIES = ['.git', '.hg'] + .map(vcs => + (0, _jestRegexUtil().escapePathForRegex)(path().sep + vcs + path().sep) + ) + .join('|'); + +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} +/** + * HasteMap is a JavaScript implementation of Facebook's haste module system. + * + * This implementation is inspired by https://github.com/facebook/node-haste + * and was built with for high-performance in large code repositories with + * hundreds of thousands of files. This implementation is scalable and provides + * predictable performance. + * + * Because the haste map creation and synchronization is critical to startup + * performance and most tasks are blocked by I/O this class makes heavy use of + * synchronous operations. It uses worker processes for parallelizing file + * access and metadata extraction. + * + * The data structures created by `jest-haste-map` can be used directly from the + * cache without further processing. The metadata objects in the `files` and + * `map` objects contain cross-references: a metadata object from one can look + * up the corresponding metadata object in the other map. Note that in most + * projects, the number of files will be greater than the number of haste + * modules one module can refer to many files based on platform extensions. + * + * type HasteMap = { + * clocks: WatchmanClocks, + * files: {[filepath: string]: FileMetaData}, + * map: {[id: string]: ModuleMapItem}, + * mocks: {[id: string]: string}, + * } + * + * // Watchman clocks are used for query synchronization and file system deltas. + * type WatchmanClocks = {[filepath: string]: string}; + * + * type FileMetaData = { + * id: ?string, // used to look up module metadata objects in `map`. + * mtime: number, // check for outdated files. + * size: number, // size of the file in bytes. + * visited: boolean, // whether the file has been parsed or not. + * dependencies: Array, // all relative dependencies of this file. + * sha1: ?string, // SHA-1 of the file, if requested via options. + * }; + * + * // Modules can be targeted to a specific platform based on the file name. + * // Example: platform.ios.js and Platform.android.js will both map to the same + * // `Platform` module. The platform should be specified during resolution. + * type ModuleMapItem = {[platform: string]: ModuleMetaData}; + * + * // + * type ModuleMetaData = { + * path: string, // the path to look up the file object in `files`. + * type: string, // the module type (either `package` or `module`). + * }; + * + * Note that the data structures described above are conceptual only. The actual + * implementation uses arrays and constant keys for metadata storage. Instead of + * `{id: 'flatMap', mtime: 3421, size: 42, visited: true, dependencies: []}` the real + * representation is similar to `['flatMap', 3421, 42, 1, []]` to save storage space + * and reduce parse and write time of a big JSON blob. + * + * The HasteMap is created as follows: + * 1. read data from the cache or create an empty structure. + * + * 2. crawl the file system. + * * empty cache: crawl the entire file system. + * * cache available: + * * if watchman is available: get file system delta changes. + * * if watchman is unavailable: crawl the entire file system. + * * build metadata objects for every file. This builds the `files` part of + * the `HasteMap`. + * + * 3. parse and extract metadata from changed files. + * * this is done in parallel over worker processes to improve performance. + * * the worst case is to parse all files. + * * the best case is no file system access and retrieving all data from + * the cache. + * * the average case is a small number of changed files. + * + * 4. serialize the new `HasteMap` in a cache file. + * Worker processes can directly access the cache through `HasteMap.read()`. + * + */ + +class HasteMap extends _events().EventEmitter { + _buildPromise = null; + _cachePath = ''; + _changeInterval; + _console; + _isWatchmanInstalledPromise = null; + _options; + _watchers = []; + _worker = null; + + static getStatic(config) { + if (config.haste.hasteMapModulePath) { + return require(config.haste.hasteMapModulePath); + } + + return HasteMap; + } + + static async create(options) { + if (options.hasteMapModulePath) { + const CustomHasteMap = require(options.hasteMapModulePath); + + return new CustomHasteMap(options); + } + + const hasteMap = new HasteMap(options); + await hasteMap.setupCachePath(options); + return hasteMap; + } + + constructor(options) { + super(); + this._options = { + cacheDirectory: options.cacheDirectory || (0, _os().tmpdir)(), + computeDependencies: options.computeDependencies ?? true, + computeSha1: options.computeSha1 || false, + dependencyExtractor: options.dependencyExtractor || null, + enableSymlinks: options.enableSymlinks || false, + extensions: options.extensions, + forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, + hasteImplModulePath: options.hasteImplModulePath, + id: options.id, + maxWorkers: options.maxWorkers, + mocksPattern: options.mocksPattern + ? new RegExp(options.mocksPattern) + : null, + platforms: options.platforms, + resetCache: options.resetCache, + retainAllFiles: options.retainAllFiles, + rootDir: options.rootDir, + roots: Array.from(new Set(options.roots)), + skipPackageJson: !!options.skipPackageJson, + throwOnModuleCollision: !!options.throwOnModuleCollision, + useWatchman: options.useWatchman ?? true, + watch: !!options.watch + }; + this._console = options.console || globalThis.console; + + if (options.ignorePattern) { + if (options.ignorePattern instanceof RegExp) { + this._options.ignorePattern = new RegExp( + options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), + options.ignorePattern.flags + ); + } else { + throw new Error( + 'jest-haste-map: the `ignorePattern` option must be a RegExp' + ); + } + } else { + this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); + } + + if (this._options.enableSymlinks && this._options.useWatchman) { + throw new Error( + 'jest-haste-map: enableSymlinks config option was set, but ' + + 'is incompatible with watchman.\n' + + 'Set either `enableSymlinks` to false or `useWatchman` to false.' + ); + } + } + + async setupCachePath(options) { + const rootDirHash = (0, _crypto().createHash)('sha256') + .update(options.rootDir) + .digest('hex') + .substring(0, 32); + let hasteImplHash = ''; + let dependencyExtractorHash = ''; + + if (options.hasteImplModulePath) { + const hasteImpl = require(options.hasteImplModulePath); + + if (hasteImpl.getCacheKey) { + hasteImplHash = String(hasteImpl.getCacheKey()); + } + } + + if (options.dependencyExtractor) { + const dependencyExtractor = await (0, _jestUtil().requireOrImportModule)( + options.dependencyExtractor, + false + ); + + if (dependencyExtractor.getCacheKey) { + dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); + } + } + + this._cachePath = HasteMap.getCacheFilePath( + this._options.cacheDirectory, + `haste-map-${this._options.id}-${rootDirHash}`, + VERSION, + this._options.id, + this._options.roots + .map(root => fastPath.relative(options.rootDir, root)) + .join(':'), + this._options.extensions.join(':'), + this._options.platforms.join(':'), + this._options.computeSha1.toString(), + options.mocksPattern || '', + (options.ignorePattern || '').toString(), + hasteImplHash, + dependencyExtractorHash, + this._options.computeDependencies.toString() + ); + } + + static getCacheFilePath(tmpdir, id, ...extra) { + const hash = (0, _crypto().createHash)('sha256').update(extra.join('')); + return path().join( + tmpdir, + `${id.replace(/\W/g, '-')}-${hash.digest('hex').substring(0, 32)}` + ); + } + + static getModuleMapFromJSON(json) { + return _ModuleMap.default.fromJSON(json); + } + + getCacheFilePath() { + return this._cachePath; + } + + build() { + if (!this._buildPromise) { + this._buildPromise = (async () => { + const data = await this._buildFileMap(); // Persist when we don't know if files changed (changedFiles undefined) + // or when we know a file was changed or deleted. + + let hasteMap; + + if ( + data.changedFiles === undefined || + data.changedFiles.size > 0 || + data.removedFiles.size > 0 + ) { + hasteMap = await this._buildHasteMap(data); + + this._persist(hasteMap); + } else { + hasteMap = data.hasteMap; + } + + const rootDir = this._options.rootDir; + const hasteFS = new _HasteFS.default({ + files: hasteMap.files, + rootDir + }); + const moduleMap = new _ModuleMap.default({ + duplicates: hasteMap.duplicates, + map: hasteMap.map, + mocks: hasteMap.mocks, + rootDir + }); + + const __hasteMapForTest = + (process.env.NODE_ENV === 'test' && hasteMap) || null; + + await this._watch(hasteMap); + return { + __hasteMapForTest, + hasteFS, + moduleMap + }; + })(); + } + + return this._buildPromise; + } + /** + * 1. read data from the cache or create an empty structure. + */ + + read() { + let hasteMap; + + try { + hasteMap = (0, _v().deserialize)( + (0, _gracefulFs().readFileSync)(this._cachePath) + ); + } catch { + hasteMap = this._createEmptyMap(); + } + + return hasteMap; + } + + readModuleMap() { + const data = this.read(); + return new _ModuleMap.default({ + duplicates: data.duplicates, + map: data.map, + mocks: data.mocks, + rootDir: this._options.rootDir + }); + } + /** + * 2. crawl the file system. + */ + + async _buildFileMap() { + let hasteMap; + + try { + const read = this._options.resetCache ? this._createEmptyMap : this.read; + hasteMap = read.call(this); + } catch { + hasteMap = this._createEmptyMap(); + } + + return this._crawl(hasteMap); + } + /** + * 3. parse and extract metadata from changed files. + */ + + _processFile(hasteMap, map, mocks, filePath, workerOptions) { + const rootDir = this._options.rootDir; + + const setModule = (id, module) => { + let moduleMap = map.get(id); + + if (!moduleMap) { + moduleMap = Object.create(null); + map.set(id, moduleMap); + } + + const platform = + (0, _getPlatformExtension.default)( + module[_constants.default.PATH], + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + + const existingModule = moduleMap[platform]; + + if ( + existingModule && + existingModule[_constants.default.PATH] !== + module[_constants.default.PATH] + ) { + const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; + + this._console[method]( + [ + `jest-haste-map: Haste module naming collision: ${id}`, + ' The following files share their name; please adjust your hasteImpl:', + ` * ${path().sep}${ + existingModule[_constants.default.PATH] + }`, + ` * ${path().sep}${module[_constants.default.PATH]}`, + '' + ].join('\n') + ); + + if (this._options.throwOnModuleCollision) { + throw new DuplicateError( + existingModule[_constants.default.PATH], + module[_constants.default.PATH] + ); + } // We do NOT want consumers to use a module that is ambiguous. + + delete moduleMap[platform]; + + if (Object.keys(moduleMap).length === 1) { + map.delete(id); + } + + let dupsByPlatform = hasteMap.duplicates.get(id); + + if (dupsByPlatform == null) { + dupsByPlatform = new Map(); + hasteMap.duplicates.set(id, dupsByPlatform); + } + + const dups = new Map([ + [module[_constants.default.PATH], module[_constants.default.TYPE]], + [ + existingModule[_constants.default.PATH], + existingModule[_constants.default.TYPE] + ] + ]); + dupsByPlatform.set(platform, dups); + return; + } + + const dupsByPlatform = hasteMap.duplicates.get(id); + + if (dupsByPlatform != null) { + const dups = dupsByPlatform.get(platform); + + if (dups != null) { + dups.set( + module[_constants.default.PATH], + module[_constants.default.TYPE] + ); + } + + return; + } + + moduleMap[platform] = module; + }; + + const relativeFilePath = fastPath.relative(rootDir, filePath); + const fileMetadata = hasteMap.files.get(relativeFilePath); + + if (!fileMetadata) { + throw new Error( + 'jest-haste-map: File to process was not found in the haste map.' + ); + } + + const moduleMetadata = hasteMap.map.get( + fileMetadata[_constants.default.ID] + ); + const computeSha1 = + this._options.computeSha1 && !fileMetadata[_constants.default.SHA1]; // Callback called when the response from the worker is successful. + + const workerReply = metadata => { + // `1` for truthy values instead of `true` to save cache space. + fileMetadata[_constants.default.VISITED] = 1; + const metadataId = metadata.id; + const metadataModule = metadata.module; + + if (metadataId && metadataModule) { + fileMetadata[_constants.default.ID] = metadataId; + setModule(metadataId, metadataModule); + } + + fileMetadata[_constants.default.DEPENDENCIES] = metadata.dependencies + ? metadata.dependencies.join(_constants.default.DEPENDENCY_DELIM) + : ''; + + if (computeSha1) { + fileMetadata[_constants.default.SHA1] = metadata.sha1; + } + }; // Callback called when the response from the worker is an error. + + const workerError = error => { + if (typeof error !== 'object' || !error.message || !error.stack) { + error = new Error(error); + error.stack = ''; // Remove stack for stack-less errors. + } + + if (!['ENOENT', 'EACCES'].includes(error.code)) { + throw error; + } // If a file cannot be read we remove it from the file list and + // ignore the failure silently. + + hasteMap.files.delete(relativeFilePath); + }; // If we retain all files in the virtual HasteFS representation, we avoid + // reading them if they aren't important (node_modules). + + if (this._options.retainAllFiles && filePath.includes(NODE_MODULES)) { + if (computeSha1) { + return this._getWorker(workerOptions) + .getSha1({ + computeDependencies: this._options.computeDependencies, + computeSha1, + dependencyExtractor: this._options.dependencyExtractor, + filePath, + hasteImplModulePath: this._options.hasteImplModulePath, + rootDir + }) + .then(workerReply, workerError); + } + + return null; + } + + if ( + this._options.mocksPattern && + this._options.mocksPattern.test(filePath) + ) { + const mockPath = (0, _getMockName.default)(filePath); + const existingMockPath = mocks.get(mockPath); + + if (existingMockPath) { + const secondMockPath = fastPath.relative(rootDir, filePath); + + if (existingMockPath !== secondMockPath) { + const method = this._options.throwOnModuleCollision + ? 'error' + : 'warn'; + + this._console[method]( + [ + `jest-haste-map: duplicate manual mock found: ${mockPath}`, + ' The following files share their name; please delete one of them:', + ` * ${path().sep}${existingMockPath}`, + ` * ${path().sep}${secondMockPath}`, + '' + ].join('\n') + ); + + if (this._options.throwOnModuleCollision) { + throw new DuplicateError(existingMockPath, secondMockPath); + } + } + } + + mocks.set(mockPath, relativeFilePath); + } + + if (fileMetadata[_constants.default.VISITED]) { + if (!fileMetadata[_constants.default.ID]) { + return null; + } + + if (moduleMetadata != null) { + const platform = + (0, _getPlatformExtension.default)( + filePath, + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + + const module = moduleMetadata[platform]; + + if (module == null) { + return null; + } + + const moduleId = fileMetadata[_constants.default.ID]; + let modulesByPlatform = map.get(moduleId); + + if (!modulesByPlatform) { + modulesByPlatform = Object.create(null); + map.set(moduleId, modulesByPlatform); + } + + modulesByPlatform[platform] = module; + return null; + } + } + + return this._getWorker(workerOptions) + .worker({ + computeDependencies: this._options.computeDependencies, + computeSha1, + dependencyExtractor: this._options.dependencyExtractor, + filePath, + hasteImplModulePath: this._options.hasteImplModulePath, + rootDir + }) + .then(workerReply, workerError); + } + + _buildHasteMap(data) { + const {removedFiles, changedFiles, hasteMap} = data; // If any files were removed or we did not track what files changed, process + // every file looking for changes. Otherwise, process only changed files. + + let map; + let mocks; + let filesToProcess; + + if (changedFiles === undefined || removedFiles.size) { + map = new Map(); + mocks = new Map(); + filesToProcess = hasteMap.files; + } else { + map = hasteMap.map; + mocks = hasteMap.mocks; + filesToProcess = changedFiles; + } + + for (const [relativeFilePath, fileMetadata] of removedFiles) { + this._recoverDuplicates( + hasteMap, + relativeFilePath, + fileMetadata[_constants.default.ID] + ); + } + + const promises = []; + + for (const relativeFilePath of filesToProcess.keys()) { + if ( + this._options.skipPackageJson && + relativeFilePath.endsWith(PACKAGE_JSON) + ) { + continue; + } // SHA-1, if requested, should already be present thanks to the crawler. + + const filePath = fastPath.resolve( + this._options.rootDir, + relativeFilePath + ); + + const promise = this._processFile(hasteMap, map, mocks, filePath); + + if (promise) { + promises.push(promise); + } + } + + return Promise.all(promises).then( + () => { + this._cleanup(); + + hasteMap.map = map; + hasteMap.mocks = mocks; + return hasteMap; + }, + error => { + this._cleanup(); + + throw error; + } + ); + } + + _cleanup() { + const worker = this._worker; + + if (worker && 'end' in worker) { + worker.end(); + } + + this._worker = null; + } + /** + * 4. serialize the new `HasteMap` in a cache file. + */ + + _persist(hasteMap) { + (0, _gracefulFs().writeFileSync)( + this._cachePath, + (0, _v().serialize)(hasteMap) + ); + } + /** + * Creates workers or parses files and extracts metadata in-process. + */ + + _getWorker( + options = { + forceInBand: false + } + ) { + if (!this._worker) { + if (options.forceInBand || this._options.maxWorkers <= 1) { + this._worker = { + getSha1: _worker.getSha1, + worker: _worker.worker + }; + } else { + this._worker = new (_jestWorker().Worker)(require.resolve('./worker'), { + exposedMethods: ['getSha1', 'worker'], + forkOptions: { + serialization: 'json' + }, + maxRetries: 3, + numWorkers: this._options.maxWorkers + }); + } + } + + return this._worker; + } + + async _crawl(hasteMap) { + const options = this._options; + + const ignore = this._ignore.bind(this); + + const crawl = (await this._shouldUseWatchman()) + ? _watchman.watchmanCrawl + : _node.nodeCrawl; + const crawlerOptions = { + computeSha1: options.computeSha1, + data: hasteMap, + enableSymlinks: options.enableSymlinks, + extensions: options.extensions, + forceNodeFilesystemAPI: options.forceNodeFilesystemAPI, + ignore, + rootDir: options.rootDir, + roots: options.roots + }; + + const retry = error => { + if (crawl === _watchman.watchmanCrawl) { + this._console.warn( + 'jest-haste-map: Watchman crawl failed. Retrying once with node ' + + 'crawler.\n' + + " Usually this happens when watchman isn't running. Create an " + + "empty `.watchmanconfig` file in your project's root folder or " + + 'initialize a git or hg repository in your project.\n' + + ` ${error}` + ); + + return (0, _node.nodeCrawl)(crawlerOptions).catch(e => { + throw new Error( + 'Crawler retry failed:\n' + + ` Original error: ${error.message}\n` + + ` Retry error: ${e.message}\n` + ); + }); + } + + throw error; + }; + + try { + return crawl(crawlerOptions).catch(retry); + } catch (error) { + return retry(error); + } + } + /** + * Watch mode + */ + + async _watch(hasteMap) { + if (!this._options.watch) { + return Promise.resolve(); + } // In watch mode, we'll only warn about module collisions and we'll retain + // all files, even changes to node_modules. + + this._options.throwOnModuleCollision = false; + this._options.retainAllFiles = true; // WatchmanWatcher > FSEventsWatcher > sane.NodeWatcher + + const Watcher = (await this._shouldUseWatchman()) + ? _WatchmanWatcher.default + : _FSEventsWatcher.FSEventsWatcher.isSupported() + ? _FSEventsWatcher.FSEventsWatcher + : _NodeWatcher.default; + const extensions = this._options.extensions; + const ignorePattern = this._options.ignorePattern; + const rootDir = this._options.rootDir; + let changeQueue = Promise.resolve(); + let eventsQueue = []; // We only need to copy the entire haste map once on every "frame". + + let mustCopy = true; + + const createWatcher = root => { + const watcher = new Watcher(root, { + dot: true, + glob: extensions.map(extension => `**/*.${extension}`), + ignored: ignorePattern + }); + return new Promise((resolve, reject) => { + const rejectTimeout = setTimeout( + () => reject(new Error('Failed to start watch mode.')), + MAX_WAIT_TIME + ); + watcher.once('ready', () => { + clearTimeout(rejectTimeout); + watcher.on('all', onChange); + resolve(watcher); + }); + }); + }; + + const emitChange = () => { + if (eventsQueue.length) { + mustCopy = true; + const changeEvent = { + eventsQueue, + hasteFS: new _HasteFS.default({ + files: hasteMap.files, + rootDir + }), + moduleMap: new _ModuleMap.default({ + duplicates: hasteMap.duplicates, + map: hasteMap.map, + mocks: hasteMap.mocks, + rootDir + }) + }; + this.emit('change', changeEvent); + eventsQueue = []; + } + }; + + const onChange = (type, filePath, root, stat) => { + filePath = path().join(root, (0, _normalizePathSep.default)(filePath)); + + if ( + (stat && stat.isDirectory()) || + this._ignore(filePath) || + !extensions.some(extension => filePath.endsWith(extension)) + ) { + return; + } + + const relativeFilePath = fastPath.relative(rootDir, filePath); + const fileMetadata = hasteMap.files.get(relativeFilePath); // The file has been accessed, not modified + + if ( + type === 'change' && + fileMetadata && + stat && + fileMetadata[_constants.default.MTIME] === stat.mtime.getTime() + ) { + return; + } + + changeQueue = changeQueue + .then(() => { + // If we get duplicate events for the same file, ignore them. + if ( + eventsQueue.find( + event => + event.type === type && + event.filePath === filePath && + ((!event.stat && !stat) || + (!!event.stat && + !!stat && + event.stat.mtime.getTime() === stat.mtime.getTime())) + ) + ) { + return null; + } + + if (mustCopy) { + mustCopy = false; + hasteMap = { + clocks: new Map(hasteMap.clocks), + duplicates: new Map(hasteMap.duplicates), + files: new Map(hasteMap.files), + map: new Map(hasteMap.map), + mocks: new Map(hasteMap.mocks) + }; + } + + const add = () => { + eventsQueue.push({ + filePath, + stat, + type + }); + return null; + }; + + const fileMetadata = hasteMap.files.get(relativeFilePath); // If it's not an addition, delete the file and all its metadata + + if (fileMetadata != null) { + const moduleName = fileMetadata[_constants.default.ID]; + + const platform = + (0, _getPlatformExtension.default)( + filePath, + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + + hasteMap.files.delete(relativeFilePath); + let moduleMap = hasteMap.map.get(moduleName); + + if (moduleMap != null) { + // We are forced to copy the object because jest-haste-map exposes + // the map as an immutable entity. + moduleMap = copy(moduleMap); + delete moduleMap[platform]; + + if (Object.keys(moduleMap).length === 0) { + hasteMap.map.delete(moduleName); + } else { + hasteMap.map.set(moduleName, moduleMap); + } + } + + if ( + this._options.mocksPattern && + this._options.mocksPattern.test(filePath) + ) { + const mockName = (0, _getMockName.default)(filePath); + hasteMap.mocks.delete(mockName); + } + + this._recoverDuplicates(hasteMap, relativeFilePath, moduleName); + } // If the file was added or changed, + // parse it and update the haste map. + + if (type === 'add' || type === 'change') { + invariant( + stat, + 'since the file exists or changed, it should have stats' + ); + const fileMetadata = [ + '', + stat.mtime.getTime(), + stat.size, + 0, + '', + null + ]; + hasteMap.files.set(relativeFilePath, fileMetadata); + + const promise = this._processFile( + hasteMap, + hasteMap.map, + hasteMap.mocks, + filePath, + { + forceInBand: true + } + ); // Cleanup + + this._cleanup(); + + if (promise) { + return promise.then(add); + } else { + // If a file in node_modules has changed, + // emit an event regardless. + add(); + } + } else { + add(); + } + + return null; + }) + .catch(error => { + this._console.error( + `jest-haste-map: watch error:\n ${error.stack}\n` + ); + }); + }; + + this._changeInterval = setInterval(emitChange, CHANGE_INTERVAL); + return Promise.all(this._options.roots.map(createWatcher)).then( + watchers => { + this._watchers = watchers; + } + ); + } + /** + * This function should be called when the file under `filePath` is removed + * or changed. When that happens, we want to figure out if that file was + * part of a group of files that had the same ID. If it was, we want to + * remove it from the group. Furthermore, if there is only one file + * remaining in the group, then we want to restore that single file as the + * correct resolution for its ID, and cleanup the duplicates index. + */ + + _recoverDuplicates(hasteMap, relativeFilePath, moduleName) { + let dupsByPlatform = hasteMap.duplicates.get(moduleName); + + if (dupsByPlatform == null) { + return; + } + + const platform = + (0, _getPlatformExtension.default)( + relativeFilePath, + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + + let dups = dupsByPlatform.get(platform); + + if (dups == null) { + return; + } + + dupsByPlatform = copyMap(dupsByPlatform); + hasteMap.duplicates.set(moduleName, dupsByPlatform); + dups = copyMap(dups); + dupsByPlatform.set(platform, dups); + dups.delete(relativeFilePath); + + if (dups.size !== 1) { + return; + } + + const uniqueModule = dups.entries().next().value; + + if (!uniqueModule) { + return; + } + + let dedupMap = hasteMap.map.get(moduleName); + + if (!dedupMap) { + dedupMap = Object.create(null); + hasteMap.map.set(moduleName, dedupMap); + } + + dedupMap[platform] = uniqueModule; + dupsByPlatform.delete(platform); + + if (dupsByPlatform.size === 0) { + hasteMap.duplicates.delete(moduleName); + } + } + + async end() { + if (this._changeInterval) { + clearInterval(this._changeInterval); + } + + if (!this._watchers.length) { + return; + } + + await Promise.all(this._watchers.map(watcher => watcher.close())); + this._watchers = []; + } + /** + * Helpers + */ + + _ignore(filePath) { + const ignorePattern = this._options.ignorePattern; + const ignoreMatched = + ignorePattern instanceof RegExp + ? ignorePattern.test(filePath) + : ignorePattern && ignorePattern(filePath); + return ( + ignoreMatched || + (!this._options.retainAllFiles && filePath.includes(NODE_MODULES)) + ); + } + + async _shouldUseWatchman() { + if (!this._options.useWatchman) { + return false; + } + + if (!this._isWatchmanInstalledPromise) { + this._isWatchmanInstalledPromise = (0, _isWatchmanInstalled.default)(); + } + + return this._isWatchmanInstalledPromise; + } + + _createEmptyMap() { + return { + clocks: new Map(), + duplicates: new Map(), + files: new Map(), + map: new Map(), + mocks: new Map() + }; + } + + static H = _constants.default; +} + +exports.default = HasteMap; + +class DuplicateError extends Error { + mockPath1; + mockPath2; + + constructor(mockPath1, mockPath2) { + super('Duplicated files or mocks. Please check the console for more info'); + this.mockPath1 = mockPath1; + this.mockPath2 = mockPath2; + } +} + +exports.DuplicateError = DuplicateError; + +function copy(object) { + return Object.assign(Object.create(null), object); +} + +function copyMap(input) { + return new Map(input); +} diff --git a/node_modules/jest-haste-map/build/lib/dependencyExtractor.js b/node_modules/jest-haste-map/build/lib/dependencyExtractor.js new file mode 100644 index 0000000..4766553 --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/dependencyExtractor.js @@ -0,0 +1,92 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.extractor = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const NOT_A_DOT = '(? `([\`'"])([^'"\`]*?)(?:\\${pos})`; + +const WORD_SEPARATOR = '\\b'; +const LEFT_PARENTHESIS = '\\('; +const RIGHT_PARENTHESIS = '\\)'; +const WHITESPACE = '\\s*'; +const OPTIONAL_COMMA = '(:?,\\s*)?'; + +function createRegExp(parts, flags) { + return new RegExp(parts.join(''), flags); +} + +function alternatives(...parts) { + return `(?:${parts.join('|')})`; +} + +function functionCallStart(...names) { + return [ + NOT_A_DOT, + WORD_SEPARATOR, + alternatives(...names), + WHITESPACE, + LEFT_PARENTHESIS, + WHITESPACE + ]; +} + +const BLOCK_COMMENT_RE = /\/\*[^]*?\*\//g; +const LINE_COMMENT_RE = /\/\/.*/g; +const REQUIRE_OR_DYNAMIC_IMPORT_RE = createRegExp( + [ + ...functionCallStart('require', 'import'), + CAPTURE_STRING_LITERAL(1), + WHITESPACE, + OPTIONAL_COMMA, + RIGHT_PARENTHESIS + ], + 'g' +); +const IMPORT_OR_EXPORT_RE = createRegExp( + [ + '\\b(?:import|export)\\s+(?!type(?:of)?\\s+)(?:[^\'"]+\\s+from\\s+)?', + CAPTURE_STRING_LITERAL(1) + ], + 'g' +); +const JEST_EXTENSIONS_RE = createRegExp( + [ + ...functionCallStart( + 'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)' + ), + CAPTURE_STRING_LITERAL(1), + WHITESPACE, + OPTIONAL_COMMA, + RIGHT_PARENTHESIS + ], + 'g' +); +const extractor = { + extract(code) { + const dependencies = new Set(); + + const addDependency = (match, _, dep) => { + dependencies.add(dep); + return match; + }; + + code + .replace(BLOCK_COMMENT_RE, '') + .replace(LINE_COMMENT_RE, '') + .replace(IMPORT_OR_EXPORT_RE, addDependency) + .replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency) + .replace(JEST_EXTENSIONS_RE, addDependency); + return dependencies; + } +}; +exports.extractor = extractor; diff --git a/node_modules/jest-haste-map/build/lib/fast_path.js b/node_modules/jest-haste-map/build/lib/fast_path.js new file mode 100644 index 0000000..2a330af --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/fast_path.js @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.relative = relative; +exports.resolve = resolve; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// rootDir and filename must be absolute paths (resolved) +function relative(rootDir, filename) { + return filename.indexOf(rootDir + path().sep) === 0 + ? filename.substring(rootDir.length + 1) + : path().relative(rootDir, filename); +} + +const INDIRECTION_FRAGMENT = `..${path().sep}`; // rootDir must be an absolute path and relativeFilename must be simple +// (e.g.: foo/bar or ../foo/bar, but never ./foo or foo/../bar) + +function resolve(rootDir, relativeFilename) { + return relativeFilename.indexOf(INDIRECTION_FRAGMENT) === 0 + ? path().resolve(rootDir, relativeFilename) + : rootDir + path().sep + relativeFilename; +} diff --git a/node_modules/jest-haste-map/build/lib/getPlatformExtension.js b/node_modules/jest-haste-map/build/lib/getPlatformExtension.js new file mode 100644 index 0000000..6b9e564 --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/getPlatformExtension.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getPlatformExtension; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const SUPPORTED_PLATFORM_EXTS = new Set(['android', 'ios', 'native', 'web']); // Extract platform extension: index.ios.js -> ios + +function getPlatformExtension(file, platforms) { + const last = file.lastIndexOf('.'); + const secondToLast = file.lastIndexOf('.', last - 1); + + if (secondToLast === -1) { + return null; + } + + const platform = file.substring(secondToLast + 1, last); // If an overriding platform array is passed, check that first + + if (platforms && platforms.indexOf(platform) !== -1) { + return platform; + } + + return SUPPORTED_PLATFORM_EXTS.has(platform) ? platform : null; +} diff --git a/node_modules/jest-haste-map/build/lib/isWatchmanInstalled.js b/node_modules/jest-haste-map/build/lib/isWatchmanInstalled.js new file mode 100644 index 0000000..28a61b4 --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/isWatchmanInstalled.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = isWatchmanInstalled; + +function _child_process() { + const data = require('child_process'); + + _child_process = function () { + return data; + }; + + return data; +} + +function _util() { + const data = require('util'); + + _util = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +async function isWatchmanInstalled() { + try { + await (0, _util().promisify)(_child_process().execFile)('watchman', [ + '--version' + ]); + return true; + } catch { + return false; + } +} diff --git a/node_modules/jest-haste-map/build/lib/normalizePathSep.js b/node_modules/jest-haste-map/build/lib/normalizePathSep.js new file mode 100644 index 0000000..1f85cfb --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/normalizePathSep.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +let normalizePathSep; + +if (path().sep === '/') { + normalizePathSep = filePath => filePath; +} else { + normalizePathSep = filePath => filePath.replace(/\//g, path().sep); +} + +var _default = normalizePathSep; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/types.js b/node_modules/jest-haste-map/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-haste-map/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-haste-map/build/watchers/FSEventsWatcher.js b/node_modules/jest-haste-map/build/watchers/FSEventsWatcher.js new file mode 100644 index 0000000..221b8d7 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/FSEventsWatcher.js @@ -0,0 +1,285 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.FSEventsWatcher = void 0; + +function _events() { + const data = require('events'); + + _events = function () { + return data; + }; + + return data; +} + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _anymatch() { + const data = _interopRequireDefault(require('anymatch')); + + _anymatch = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _micromatch() { + const data = _interopRequireDefault(require('micromatch')); + + _micromatch = function () { + return data; + }; + + return data; +} + +function _walker() { + const data = _interopRequireDefault(require('walker')); + + _walker = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +// @ts-expect-error no types +// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/ban-ts-comment +// @ts-ignore: this is for CI which runs linux and might not have this +let fsevents = null; + +try { + fsevents = require('fsevents'); +} catch { + // Optional dependency, only supported on Darwin. +} + +const CHANGE_EVENT = 'change'; +const DELETE_EVENT = 'delete'; +const ADD_EVENT = 'add'; +const ALL_EVENT = 'all'; + +/** + * Export `FSEventsWatcher` class. + * Watches `dir`. + */ +class FSEventsWatcher extends _events().EventEmitter { + root; + ignored; + glob; + dot; + hasIgnore; + doIgnore; + fsEventsWatchStopper; + _tracked; + + static isSupported() { + return fsevents !== null; + } + + static normalizeProxy(callback) { + return (filepath, stats) => callback(path().normalize(filepath), stats); + } + + static recReaddir( + dir, + dirCallback, + fileCallback, + endCallback, + errorCallback, + ignored + ) { + (0, _walker().default)(dir) + .filterDir( + currentDir => !ignored || !(0, _anymatch().default)(ignored, currentDir) + ) + .on('dir', FSEventsWatcher.normalizeProxy(dirCallback)) + .on('file', FSEventsWatcher.normalizeProxy(fileCallback)) + .on('error', errorCallback) + .on('end', () => { + endCallback(); + }); + } + + constructor(dir, opts) { + if (!fsevents) { + throw new Error( + '`fsevents` unavailable (this watcher can only be used on Darwin)' + ); + } + + super(); + this.dot = opts.dot || false; + this.ignored = opts.ignored; + this.glob = Array.isArray(opts.glob) ? opts.glob : [opts.glob]; + this.hasIgnore = + Boolean(opts.ignored) && !(Array.isArray(opts) && opts.length > 0); + this.doIgnore = opts.ignored + ? (0, _anymatch().default)(opts.ignored) + : () => false; + this.root = path().resolve(dir); + this.fsEventsWatchStopper = fsevents.watch( + this.root, + this.handleEvent.bind(this) + ); + this._tracked = new Set(); + FSEventsWatcher.recReaddir( + this.root, + filepath => { + this._tracked.add(filepath); + }, + filepath => { + this._tracked.add(filepath); + }, + this.emit.bind(this, 'ready'), + this.emit.bind(this, 'error'), + this.ignored + ); + } + /** + * End watching. + */ + + async close(callback) { + await this.fsEventsWatchStopper(); + this.removeAllListeners(); + + if (typeof callback === 'function') { + process.nextTick(callback.bind(null, null, true)); + } + } + + isFileIncluded(relativePath) { + if (this.doIgnore(relativePath)) { + return false; + } + + return this.glob.length + ? (0, _micromatch().default)([relativePath], this.glob, { + dot: this.dot + }).length > 0 + : this.dot || + (0, _micromatch().default)([relativePath], '**/*').length > 0; + } + + handleEvent(filepath) { + const relativePath = path().relative(this.root, filepath); + + if (!this.isFileIncluded(relativePath)) { + return; + } + + fs().lstat(filepath, (error, stat) => { + if (error && error.code !== 'ENOENT') { + this.emit('error', error); + return; + } + + if (error) { + // Ignore files that aren't tracked and don't exist. + if (!this._tracked.has(filepath)) { + return; + } + + this._emit(DELETE_EVENT, relativePath); + + this._tracked.delete(filepath); + + return; + } + + if (this._tracked.has(filepath)) { + this._emit(CHANGE_EVENT, relativePath, stat); + } else { + this._tracked.add(filepath); + + this._emit(ADD_EVENT, relativePath, stat); + } + }); + } + /** + * Emit events. + */ + + _emit(type, file, stat) { + this.emit(type, file, this.root, stat); + this.emit(ALL_EVENT, type, file, this.root, stat); + } +} + +exports.FSEventsWatcher = FSEventsWatcher; diff --git a/node_modules/jest-haste-map/build/watchers/NodeWatcher.js b/node_modules/jest-haste-map/build/watchers/NodeWatcher.js new file mode 100644 index 0000000..878a2b9 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/NodeWatcher.js @@ -0,0 +1,375 @@ +// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/node_watcher.js +'use strict'; + +const EventEmitter = require('events').EventEmitter; + +const fs = require('fs'); + +const platform = require('os').platform(); + +const path = require('path'); + +const common = require('./common'); +/** + * Constants + */ + +const DEFAULT_DELAY = common.DEFAULT_DELAY; +const CHANGE_EVENT = common.CHANGE_EVENT; +const DELETE_EVENT = common.DELETE_EVENT; +const ADD_EVENT = common.ADD_EVENT; +const ALL_EVENT = common.ALL_EVENT; +/** + * Export `NodeWatcher` class. + * Watches `dir`. + * + * @class NodeWatcher + * @param {String} dir + * @param {Object} opts + * @public + */ + +module.exports = class NodeWatcher extends EventEmitter { + constructor(dir, opts) { + super(); + common.assignOptions(this, opts); + this.watched = Object.create(null); + this.changeTimers = Object.create(null); + this.dirRegistery = Object.create(null); + this.root = path.resolve(dir); + this.watchdir = this.watchdir.bind(this); + this.register = this.register.bind(this); + this.checkedEmitError = this.checkedEmitError.bind(this); + this.watchdir(this.root); + common.recReaddir( + this.root, + this.watchdir, + this.register, + this.emit.bind(this, 'ready'), + this.checkedEmitError, + this.ignored + ); + } + /** + * Register files that matches our globs to know what to type of event to + * emit in the future. + * + * Registery looks like the following: + * + * dirRegister => Map { + * dirpath => Map { + * filename => true + * } + * } + * + * @param {string} filepath + * @return {boolean} whether or not we have registered the file. + * @private + */ + + register(filepath) { + const relativePath = path.relative(this.root, filepath); + + if ( + !common.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath) + ) { + return false; + } + + const dir = path.dirname(filepath); + + if (!this.dirRegistery[dir]) { + this.dirRegistery[dir] = Object.create(null); + } + + const filename = path.basename(filepath); + this.dirRegistery[dir][filename] = true; + return true; + } + /** + * Removes a file from the registery. + * + * @param {string} filepath + * @private + */ + + unregister(filepath) { + const dir = path.dirname(filepath); + + if (this.dirRegistery[dir]) { + const filename = path.basename(filepath); + delete this.dirRegistery[dir][filename]; + } + } + /** + * Removes a dir from the registery. + * + * @param {string} dirpath + * @private + */ + + unregisterDir(dirpath) { + if (this.dirRegistery[dirpath]) { + delete this.dirRegistery[dirpath]; + } + } + /** + * Checks if a file or directory exists in the registery. + * + * @param {string} fullpath + * @return {boolean} + * @private + */ + + registered(fullpath) { + const dir = path.dirname(fullpath); + return ( + this.dirRegistery[fullpath] || + (this.dirRegistery[dir] && + this.dirRegistery[dir][path.basename(fullpath)]) + ); + } + /** + * Emit "error" event if it's not an ignorable event + * + * @param error + * @private + */ + + checkedEmitError(error) { + if (!isIgnorableFileError(error)) { + this.emit('error', error); + } + } + /** + * Watch a directory. + * + * @param {string} dir + * @private + */ + + watchdir(dir) { + if (this.watched[dir]) { + return; + } + + const watcher = fs.watch( + dir, + { + persistent: true + }, + this.normalizeChange.bind(this, dir) + ); + this.watched[dir] = watcher; + watcher.on('error', this.checkedEmitError); + + if (this.root !== dir) { + this.register(dir); + } + } + /** + * Stop watching a directory. + * + * @param {string} dir + * @private + */ + + stopWatching(dir) { + if (this.watched[dir]) { + this.watched[dir].close(); + delete this.watched[dir]; + } + } + /** + * End watching. + * + * @public + */ + + close() { + Object.keys(this.watched).forEach(this.stopWatching, this); + this.removeAllListeners(); + return Promise.resolve(); + } + /** + * On some platforms, as pointed out on the fs docs (most likely just win32) + * the file argument might be missing from the fs event. Try to detect what + * change by detecting if something was deleted or the most recent file change. + * + * @param {string} dir + * @param {string} event + * @param {string} file + * @public + */ + + detectChangedFile(dir, event, callback) { + if (!this.dirRegistery[dir]) { + return; + } + + let found = false; + let closest = { + mtime: 0 + }; + let c = 0; + Object.keys(this.dirRegistery[dir]).forEach(function (file, i, arr) { + fs.lstat(path.join(dir, file), (error, stat) => { + if (found) { + return; + } + + if (error) { + if (isIgnorableFileError(error)) { + found = true; + callback(file); + } else { + this.emit('error', error); + } + } else { + if (stat.mtime > closest.mtime) { + stat.file = file; + closest = stat; + } + + if (arr.length === ++c) { + callback(closest.file); + } + } + }); + }, this); + } + /** + * Normalize fs events and pass it on to be processed. + * + * @param {string} dir + * @param {string} event + * @param {string} file + * @public + */ + + normalizeChange(dir, event, file) { + if (!file) { + this.detectChangedFile(dir, event, actualFile => { + if (actualFile) { + this.processChange(dir, event, actualFile); + } + }); + } else { + this.processChange(dir, event, path.normalize(file)); + } + } + /** + * Process changes. + * + * @param {string} dir + * @param {string} event + * @param {string} file + * @public + */ + + processChange(dir, event, file) { + const fullPath = path.join(dir, file); + const relativePath = path.join(path.relative(this.root, dir), file); + fs.lstat(fullPath, (error, stat) => { + if (error && error.code !== 'ENOENT') { + this.emit('error', error); + } else if (!error && stat.isDirectory()) { + // win32 emits usless change events on dirs. + if (event !== 'change') { + this.watchdir(fullPath); + + if ( + common.isFileIncluded( + this.globs, + this.dot, + this.doIgnore, + relativePath + ) + ) { + this.emitEvent(ADD_EVENT, relativePath, stat); + } + } + } else { + const registered = this.registered(fullPath); + + if (error && error.code === 'ENOENT') { + this.unregister(fullPath); + this.stopWatching(fullPath); + this.unregisterDir(fullPath); + + if (registered) { + this.emitEvent(DELETE_EVENT, relativePath); + } + } else if (registered) { + this.emitEvent(CHANGE_EVENT, relativePath, stat); + } else { + if (this.register(fullPath)) { + this.emitEvent(ADD_EVENT, relativePath, stat); + } + } + } + }); + } + /** + * Triggers a 'change' event after debounding it to take care of duplicate + * events on os x. + * + * @private + */ + + emitEvent(type, file, stat) { + const key = `${type}-${file}`; + const addKey = `${ADD_EVENT}-${file}`; + + if (type === CHANGE_EVENT && this.changeTimers[addKey]) { + // Ignore the change event that is immediately fired after an add event. + // (This happens on Linux). + return; + } + + clearTimeout(this.changeTimers[key]); + this.changeTimers[key] = setTimeout(() => { + delete this.changeTimers[key]; + + if (type === ADD_EVENT && stat.isDirectory()) { + // Recursively emit add events and watch for sub-files/folders + common.recReaddir( + path.resolve(this.root, file), + function emitAddDir(dir, stats) { + this.watchdir(dir); + this.rawEmitEvent(ADD_EVENT, path.relative(this.root, dir), stats); + }.bind(this), + function emitAddFile(file, stats) { + this.register(file); + this.rawEmitEvent(ADD_EVENT, path.relative(this.root, file), stats); + }.bind(this), + function endCallback() {}, + this.checkedEmitError, + this.ignored + ); + } else { + this.rawEmitEvent(type, file, stat); + } + }, DEFAULT_DELAY); + } + /** + * Actually emit the events + */ + + rawEmitEvent(type, file, stat) { + this.emit(type, file, this.root, stat); + this.emit(ALL_EVENT, type, file, this.root, stat); + } +}; +/** + * Determine if a given FS error can be ignored + * + * @private + */ + +function isIgnorableFileError(error) { + return ( + error.code === 'ENOENT' || // Workaround Windows node issue #4337. + (error.code === 'EPERM' && platform === 'win32') + ); +} diff --git a/node_modules/jest-haste-map/build/watchers/RecrawlWarning.js b/node_modules/jest-haste-map/build/watchers/RecrawlWarning.js new file mode 100644 index 0000000..a89af20 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/RecrawlWarning.js @@ -0,0 +1,57 @@ +// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/utils/recrawl-warning-dedupe.js +'use strict'; + +class RecrawlWarning { + constructor(root, count) { + this.root = root; + this.count = count; + } + + static findByRoot(root) { + for (let i = 0; i < this.RECRAWL_WARNINGS.length; i++) { + const warning = this.RECRAWL_WARNINGS[i]; + + if (warning.root === root) { + return warning; + } + } + + return undefined; + } + + static isRecrawlWarningDupe(warningMessage) { + if (typeof warningMessage !== 'string') { + return false; + } + + const match = warningMessage.match(this.REGEXP); + + if (!match) { + return false; + } + + const count = Number(match[1]); + const root = match[2]; + const warning = this.findByRoot(root); + + if (warning) { + // only keep the highest count, assume count to either stay the same or + // increase. + if (warning.count >= count) { + return true; + } else { + // update the existing warning to the latest (highest) count + warning.count = count; + return false; + } + } else { + this.RECRAWL_WARNINGS.push(new RecrawlWarning(root, count)); + return false; + } + } +} + +RecrawlWarning.RECRAWL_WARNINGS = []; +RecrawlWarning.REGEXP = + /Recrawled this watch (\d+) times, most recently because:\n([^:]+)/; +module.exports = RecrawlWarning; diff --git a/node_modules/jest-haste-map/build/watchers/WatchmanWatcher.js b/node_modules/jest-haste-map/build/watchers/WatchmanWatcher.js new file mode 100644 index 0000000..86db538 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/WatchmanWatcher.js @@ -0,0 +1,418 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = WatchmanWatcher; + +function _assert() { + const data = _interopRequireDefault(require('assert')); + + _assert = function () { + return data; + }; + + return data; +} + +function _events() { + const data = require('events'); + + _events = function () { + return data; + }; + + return data; +} + +function _path() { + const data = _interopRequireDefault(require('path')); + + _path = function () { + return data; + }; + + return data; +} + +function _fbWatchman() { + const data = _interopRequireDefault(require('fb-watchman')); + + _fbWatchman = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +var _RecrawlWarning = _interopRequireDefault(require('./RecrawlWarning')); + +var _common = _interopRequireDefault(require('./common')); + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const CHANGE_EVENT = _common.default.CHANGE_EVENT; +const DELETE_EVENT = _common.default.DELETE_EVENT; +const ADD_EVENT = _common.default.ADD_EVENT; +const ALL_EVENT = _common.default.ALL_EVENT; +const SUB_NAME = 'sane-sub'; +/** + * Watches `dir`. + * + * @class PollWatcher + * @param String dir + * @param {Object} opts + * @public + */ + +function WatchmanWatcher(dir, opts) { + _common.default.assignOptions(this, opts); + + this.root = _path().default.resolve(dir); + this.init(); +} // eslint-disable-next-line no-proto + +WatchmanWatcher.prototype.__proto__ = _events().EventEmitter.prototype; +/** + * Run the watchman `watch` command on the root and subscribe to changes. + * + * @private + */ + +WatchmanWatcher.prototype.init = function () { + if (this.client) { + this.client.removeAllListeners(); + } + + const self = this; + this.client = new (_fbWatchman().default.Client)(); + this.client.on('error', error => { + self.emit('error', error); + }); + this.client.on('subscription', this.handleChangeEvent.bind(this)); + this.client.on('end', () => { + console.warn('[sane] Warning: Lost connection to watchman, reconnecting..'); + self.init(); + }); + this.watchProjectInfo = null; + + function getWatchRoot() { + return self.watchProjectInfo ? self.watchProjectInfo.root : self.root; + } + + function onCapability(error, resp) { + if (handleError(self, error)) { + // The Watchman watcher is unusable on this system, we cannot continue + return; + } + + handleWarning(resp); + self.capabilities = resp.capabilities; + + if (self.capabilities.relative_root) { + self.client.command(['watch-project', getWatchRoot()], onWatchProject); + } else { + self.client.command(['watch', getWatchRoot()], onWatch); + } + } + + function onWatchProject(error, resp) { + if (handleError(self, error)) { + return; + } + + handleWarning(resp); + self.watchProjectInfo = { + relativePath: resp.relative_path ? resp.relative_path : '', + root: resp.watch + }; + self.client.command(['clock', getWatchRoot()], onClock); + } + + function onWatch(error, resp) { + if (handleError(self, error)) { + return; + } + + handleWarning(resp); + self.client.command(['clock', getWatchRoot()], onClock); + } + + function onClock(error, resp) { + if (handleError(self, error)) { + return; + } + + handleWarning(resp); + const options = { + fields: ['name', 'exists', 'new'], + since: resp.clock + }; // If the server has the wildmatch capability available it supports + // the recursive **/*.foo style match and we can offload our globs + // to the watchman server. This saves both on data size to be + // communicated back to us and compute for evaluating the globs + // in our node process. + + if (self.capabilities.wildmatch) { + if (self.globs.length === 0) { + if (!self.dot) { + // Make sure we honor the dot option if even we're not using globs. + options.expression = [ + 'match', + '**', + 'wholename', + { + includedotfiles: false + } + ]; + } + } else { + options.expression = ['anyof']; + + for (const i in self.globs) { + options.expression.push([ + 'match', + self.globs[i], + 'wholename', + { + includedotfiles: self.dot + } + ]); + } + } + } + + if (self.capabilities.relative_root) { + options.relative_root = self.watchProjectInfo.relativePath; + } + + self.client.command( + ['subscribe', getWatchRoot(), SUB_NAME, options], + onSubscribe + ); + } + + function onSubscribe(error, resp) { + if (handleError(self, error)) { + return; + } + + handleWarning(resp); + self.emit('ready'); + } + + self.client.capabilityCheck( + { + optional: ['wildmatch', 'relative_root'] + }, + onCapability + ); +}; +/** + * Handles a change event coming from the subscription. + * + * @param {Object} resp + * @private + */ + +WatchmanWatcher.prototype.handleChangeEvent = function (resp) { + _assert().default.equal( + resp.subscription, + SUB_NAME, + 'Invalid subscription event.' + ); + + if (resp.is_fresh_instance) { + this.emit('fresh_instance'); + } + + if (resp.is_fresh_instance) { + this.emit('fresh_instance'); + } + + if (Array.isArray(resp.files)) { + resp.files.forEach(this.handleFileChange, this); + } +}; +/** + * Handles a single change event record. + * + * @param {Object} changeDescriptor + * @private + */ + +WatchmanWatcher.prototype.handleFileChange = function (changeDescriptor) { + const self = this; + let absPath; + let relativePath; + + if (this.capabilities.relative_root) { + relativePath = changeDescriptor.name; + absPath = _path().default.join( + this.watchProjectInfo.root, + this.watchProjectInfo.relativePath, + relativePath + ); + } else { + absPath = _path().default.join(this.root, changeDescriptor.name); + relativePath = changeDescriptor.name; + } + + if ( + !(self.capabilities.wildmatch && !this.hasIgnore) && + !_common.default.isFileIncluded( + this.globs, + this.dot, + this.doIgnore, + relativePath + ) + ) { + return; + } + + if (!changeDescriptor.exists) { + self.emitEvent(DELETE_EVENT, relativePath, self.root); + } else { + fs().lstat(absPath, (error, stat) => { + // Files can be deleted between the event and the lstat call + // the most reliable thing to do here is to ignore the event. + if (error && error.code === 'ENOENT') { + return; + } + + if (handleError(self, error)) { + return; + } + + const eventType = changeDescriptor.new ? ADD_EVENT : CHANGE_EVENT; // Change event on dirs are mostly useless. + + if (!(eventType === CHANGE_EVENT && stat.isDirectory())) { + self.emitEvent(eventType, relativePath, self.root, stat); + } + }); + } +}; +/** + * Dispatches the event. + * + * @param {string} eventType + * @param {string} filepath + * @param {string} root + * @param {fs.Stat} stat + * @private + */ + +WatchmanWatcher.prototype.emitEvent = function ( + eventType, + filepath, + root, + stat +) { + this.emit(eventType, filepath, root, stat); + this.emit(ALL_EVENT, eventType, filepath, root, stat); +}; +/** + * Closes the watcher. + * + */ + +WatchmanWatcher.prototype.close = function () { + this.client.removeAllListeners(); + this.client.end(); + return Promise.resolve(); +}; +/** + * Handles an error and returns true if exists. + * + * @param {WatchmanWatcher} self + * @param {Error} error + * @private + */ + +function handleError(self, error) { + if (error != null) { + self.emit('error', error); + return true; + } else { + return false; + } +} +/** + * Handles a warning in the watchman resp object. + * + * @param {object} resp + * @private + */ + +function handleWarning(resp) { + if ('warning' in resp) { + if (_RecrawlWarning.default.isRecrawlWarningDupe(resp.warning)) { + return true; + } + + console.warn(resp.warning); + return true; + } else { + return false; + } +} diff --git a/node_modules/jest-haste-map/build/watchers/common.js b/node_modules/jest-haste-map/build/watchers/common.js new file mode 100644 index 0000000..6372744 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/common.js @@ -0,0 +1,114 @@ +// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/common.js +'use strict'; + +const platform = require('os').platform(); + +const path = require('path'); + +const anymatch = require('anymatch'); + +const micromatch = require('micromatch'); + +const walker = require('walker'); +/** + * Constants + */ + +exports.DEFAULT_DELAY = 100; +exports.CHANGE_EVENT = 'change'; +exports.DELETE_EVENT = 'delete'; +exports.ADD_EVENT = 'add'; +exports.ALL_EVENT = 'all'; +/** + * Assigns options to the watcher. + * + * @param {NodeWatcher|PollWatcher|WatchmanWatcher} watcher + * @param {?object} opts + * @return {boolean} + * @public + */ + +exports.assignOptions = function (watcher, opts) { + opts = opts || {}; + watcher.globs = opts.glob || []; + watcher.dot = opts.dot || false; + watcher.ignored = opts.ignored || false; + + if (!Array.isArray(watcher.globs)) { + watcher.globs = [watcher.globs]; + } + + watcher.hasIgnore = + Boolean(opts.ignored) && !(Array.isArray(opts) && opts.length > 0); + watcher.doIgnore = opts.ignored ? anymatch(opts.ignored) : () => false; + + if (opts.watchman && opts.watchmanPath) { + watcher.watchmanPath = opts.watchmanPath; + } + + return opts; +}; +/** + * Checks a file relative path against the globs array. + * + * @param {array} globs + * @param {string} relativePath + * @return {boolean} + * @public + */ + +exports.isFileIncluded = function (globs, dot, doIgnore, relativePath) { + if (doIgnore(relativePath)) { + return false; + } + + return globs.length + ? micromatch.some(relativePath, globs, { + dot + }) + : dot || micromatch.some(relativePath, '**/*'); +}; +/** + * Traverse a directory recursively calling `callback` on every directory. + * + * @param {string} dir + * @param {function} dirCallback + * @param {function} fileCallback + * @param {function} endCallback + * @param {*} ignored + * @public + */ + +exports.recReaddir = function ( + dir, + dirCallback, + fileCallback, + endCallback, + errorCallback, + ignored +) { + walker(dir) + .filterDir(currentDir => !anymatch(ignored, currentDir)) + .on('dir', normalizeProxy(dirCallback)) + .on('file', normalizeProxy(fileCallback)) + .on('error', errorCallback) + .on('end', () => { + if (platform === 'win32') { + setTimeout(endCallback, 1000); + } else { + endCallback(); + } + }); +}; +/** + * Returns a callback that when called will normalize a path and call the + * original callback + * + * @param {function} callback + * @return {function} + * @private + */ + +function normalizeProxy(callback) { + return (filepath, stats) => callback(path.normalize(filepath), stats); +} diff --git a/node_modules/jest-haste-map/build/worker.js b/node_modules/jest-haste-map/build/worker.js new file mode 100644 index 0000000..44e54e4 --- /dev/null +++ b/node_modules/jest-haste-map/build/worker.js @@ -0,0 +1,209 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getSha1 = getSha1; +exports.worker = worker; + +function _crypto() { + const data = require('crypto'); + + _crypto = function () { + return data; + }; + + return data; +} + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var _blacklist = _interopRequireDefault(require('./blacklist')); + +var _constants = _interopRequireDefault(require('./constants')); + +var _dependencyExtractor = require('./lib/dependencyExtractor'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const PACKAGE_JSON = `${path().sep}package.json`; +let hasteImpl = null; +let hasteImplModulePath = null; + +function sha1hex(content) { + return (0, _crypto().createHash)('sha1').update(content).digest('hex'); +} + +async function worker(data) { + if ( + data.hasteImplModulePath && + data.hasteImplModulePath !== hasteImplModulePath + ) { + if (hasteImpl) { + throw new Error('jest-haste-map: hasteImplModulePath changed'); + } + + hasteImplModulePath = data.hasteImplModulePath; + hasteImpl = require(hasteImplModulePath); + } + + let content; + let dependencies; + let id; + let module; + let sha1; + const {computeDependencies, computeSha1, rootDir, filePath} = data; + + const getContent = () => { + if (content === undefined) { + content = fs().readFileSync(filePath, 'utf8'); + } + + return content; + }; + + if (filePath.endsWith(PACKAGE_JSON)) { + // Process a package.json that is returned as a PACKAGE type with its name. + try { + const fileData = JSON.parse(getContent()); + + if (fileData.name) { + const relativeFilePath = path().relative(rootDir, filePath); + id = fileData.name; + module = [relativeFilePath, _constants.default.PACKAGE]; + } + } catch (err) { + throw new Error(`Cannot parse ${filePath} as JSON: ${err.message}`); + } + } else if ( + !_blacklist.default.has(filePath.substring(filePath.lastIndexOf('.'))) + ) { + // Process a random file that is returned as a MODULE. + if (hasteImpl) { + id = hasteImpl.getHasteName(filePath); + } + + if (computeDependencies) { + const content = getContent(); + const extractor = data.dependencyExtractor + ? await (0, _jestUtil().requireOrImportModule)( + data.dependencyExtractor, + false + ) + : _dependencyExtractor.extractor; + dependencies = Array.from( + extractor.extract( + content, + filePath, + _dependencyExtractor.extractor.extract + ) + ); + } + + if (id) { + const relativeFilePath = path().relative(rootDir, filePath); + module = [relativeFilePath, _constants.default.MODULE]; + } + } // If a SHA-1 is requested on update, compute it. + + if (computeSha1) { + sha1 = sha1hex(content || fs().readFileSync(filePath)); + } + + return { + dependencies, + id, + module, + sha1 + }; +} + +async function getSha1(data) { + const sha1 = data.computeSha1 + ? sha1hex(fs().readFileSync(data.filePath)) + : null; + return { + dependencies: undefined, + id: undefined, + module: undefined, + sha1 + }; +} diff --git a/node_modules/jest-haste-map/package.json b/node_modules/jest-haste-map/package.json new file mode 100644 index 0000000..504fbfb --- /dev/null +++ b/node_modules/jest-haste-map/package.json @@ -0,0 +1,84 @@ +{ + "_from": "jest-haste-map@^29.0.1", + "_id": "jest-haste-map@29.0.1", + "_inBundle": false, + "_integrity": "sha512-gcKOAydafpGoSBvcj/mGCfhOKO8fRLkAeee1KXGdcJ1Pb9O2nnOl4I8bQSIID2MaZeMHtLLgNboukh/pUGkBtg==", + "_location": "/jest-haste-map", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-haste-map@^29.0.1", + "name": "jest-haste-map", + "escapedName": "jest-haste-map", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/@jest/test-sequencer", + "/@jest/transform", + "/jest-resolve", + "/jest-runner", + "/jest-runtime", + "/jest-snapshot" + ], + "_resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.0.1.tgz", + "_shasum": "472212f93ef44309bf97d191f93ddd2e41169615", + "_spec": "jest-haste-map@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/types": "^29.0.1", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "fsevents": "^2.3.2", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.0.0", + "jest-util": "^29.0.1", + "jest-worker": "^29.0.1", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "deprecated": false, + "devDependencies": { + "@jest/test-utils": "^29.0.1", + "@types/fb-watchman": "^2.0.0", + "@types/micromatch": "^4.0.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-haste-map", + "optionalDependencies": { + "fsevents": "^2.3.2" + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-haste-map" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-leak-detector/LICENSE b/node_modules/jest-leak-detector/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-leak-detector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-leak-detector/README.md b/node_modules/jest-leak-detector/README.md new file mode 100644 index 0000000..5e650b7 --- /dev/null +++ b/node_modules/jest-leak-detector/README.md @@ -0,0 +1,27 @@ +# jest-leak-detector + +Module for verifying whether an object has been garbage collected or not. + +Internally creates a weak reference to the object, and forces garbage collection to happen. If the reference is gone, it meant no one else was pointing to the object. + +## Example + +```javascript +(async function () { + let reference = {}; + let isLeaking; + + const detector = new LeakDetector(reference); + + // Reference is held in memory. + isLeaking = await detector.isLeaking(); + console.log(isLeaking); // true + + // We destroy the only reference to the object. + reference = null; + + // Reference is gone. + isLeaking = await detector.isLeaking(); + console.log(isLeaking); // false +})(); +``` diff --git a/node_modules/jest-leak-detector/build/index.d.ts b/node_modules/jest-leak-detector/build/index.d.ts new file mode 100644 index 0000000..28c762b --- /dev/null +++ b/node_modules/jest-leak-detector/build/index.d.ts @@ -0,0 +1,19 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +/// +declare class LeakDetector { + private _isReferenceBeingHeld; + private _finalizationRegistry?; + constructor(value: unknown); + isLeaking(): Promise; + private _runGarbageCollector; +} +export default LeakDetector; + +export {}; diff --git a/node_modules/jest-leak-detector/build/index.js b/node_modules/jest-leak-detector/build/index.js new file mode 100644 index 0000000..07926d6 --- /dev/null +++ b/node_modules/jest-leak-detector/build/index.js @@ -0,0 +1,117 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _util() { + const data = require('util'); + + _util = function () { + return data; + }; + + return data; +} + +function _v() { + const data = require('v8'); + + _v = function () { + return data; + }; + + return data; +} + +function _vm() { + const data = require('vm'); + + _vm = function () { + return data; + }; + + return data; +} + +function _jestGetType() { + const data = require('jest-get-type'); + + _jestGetType = function () { + return data; + }; + + return data; +} + +function _prettyFormat() { + const data = require('pretty-format'); + + _prettyFormat = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// +const tick = (0, _util().promisify)(setImmediate); + +class LeakDetector { + _isReferenceBeingHeld; + _finalizationRegistry; + + constructor(value) { + if ((0, _jestGetType().isPrimitive)(value)) { + throw new TypeError( + [ + 'Primitives cannot leak memory.', + `You passed a ${typeof value}: <${(0, _prettyFormat().format)( + value + )}>` + ].join(' ') + ); + } // When `_finalizationRegistry` is GCed the callback we set will no longer be called, + + this._finalizationRegistry = new FinalizationRegistry(() => { + this._isReferenceBeingHeld = false; + }); + + this._finalizationRegistry.register(value, undefined); + + this._isReferenceBeingHeld = true; // Ensure value is not leaked by the closure created by the "weak" callback. + + value = null; + } + + async isLeaking() { + this._runGarbageCollector(); // wait some ticks to allow GC to run properly, see https://github.com/nodejs/node/issues/34636#issuecomment-669366235 + + for (let i = 0; i < 10; i++) { + await tick(); + } + + return this._isReferenceBeingHeld; + } + + _runGarbageCollector() { + // @ts-expect-error: not a function on `globalThis` + const isGarbageCollectorHidden = globalThis.gc == null; // GC is usually hidden, so we have to expose it before running. + + (0, _v().setFlagsFromString)('--expose-gc'); + (0, _vm().runInNewContext)('gc')(); // The GC was not initially exposed, so let's hide it again. + + if (isGarbageCollectorHidden) { + (0, _v().setFlagsFromString)('--no-expose-gc'); + } + } +} + +exports.default = LeakDetector; diff --git a/node_modules/jest-leak-detector/package.json b/node_modules/jest-leak-detector/package.json new file mode 100644 index 0000000..949b763 --- /dev/null +++ b/node_modules/jest-leak-detector/package.json @@ -0,0 +1,60 @@ +{ + "_from": "jest-leak-detector@^29.0.1", + "_id": "jest-leak-detector@29.0.1", + "_inBundle": false, + "_integrity": "sha512-5tISHJphB+sCmKXtVHJGQGltj7ksrLLb9vkuNWwFR86Of1tfzjskvrrrZU1gSzEfWC+qXIn4tuh8noKHYGMIPA==", + "_location": "/jest-leak-detector", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-leak-detector@^29.0.1", + "name": "jest-leak-detector", + "escapedName": "jest-leak-detector", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/jest-runner" + ], + "_resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.0.1.tgz", + "_shasum": "1a7cf8475d85e7b2bd53efa5adc5195828a12c33", + "_spec": "jest-leak-detector@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-runner", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "jest-get-type": "^29.0.0", + "pretty-format": "^29.0.1" + }, + "deprecated": false, + "description": "Module for verifying whether an object has been garbage collected or not.", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-leak-detector", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-leak-detector" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-matcher-utils/LICENSE b/node_modules/jest-matcher-utils/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-matcher-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-matcher-utils/README.md b/node_modules/jest-matcher-utils/README.md new file mode 100644 index 0000000..d3e9d13 --- /dev/null +++ b/node_modules/jest-matcher-utils/README.md @@ -0,0 +1,24 @@ +# jest-matcher-utils + +This package's exports are most notably used by `expect`'s [`this.utils`](https://jestjs.io/docs/expect#thisutils). + +## Installation + +To add this package as a dependency of a project, run either of the following commands: + +- `npm install jest-matcher-utils` +- `yarn add jest-matcher-utils` + +## Exports ([src/index.ts](https://github.com/facebook/jest/blob/HEAD/packages/jest-matcher-utils/src/index.ts)) + +### Functions + +`stringify` `highlightTrailingWhitespace` `printReceived` `printExpected` `printWithType` `ensureNoExpected` `ensureActualIsNumber` `ensureExpectedIsNumber` `ensureNumbers` `ensureExpectedIsNonNegativeInteger` `printDiffOrStringify` `diff` `pluralize` `getLabelPrinter` `matcherErrorMessage` `matcherHint` + +### Types + +`MatcherHintOptions` `DiffOptions` + +### Constants + +`EXPECTED_COLOR` `RECEIVED_COLOR` `INVERTED_COLOR` `BOLD_WEIGHT` `DIM_COLOR` `SUGGEST_TO_CONTAIN_EQUAL` diff --git a/node_modules/jest-matcher-utils/build/Replaceable.js b/node_modules/jest-matcher-utils/build/Replaceable.js new file mode 100644 index 0000000..83330c7 --- /dev/null +++ b/node_modules/jest-matcher-utils/build/Replaceable.js @@ -0,0 +1,73 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _jestGetType = require('jest-get-type'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const supportTypes = ['map', 'array', 'object']; + +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +class Replaceable { + object; + type; + + constructor(object) { + this.object = object; + this.type = (0, _jestGetType.getType)(object); + + if (!supportTypes.includes(this.type)) { + throw new Error(`Type ${this.type} is not support in Replaceable!`); + } + } + + static isReplaceable(obj1, obj2) { + const obj1Type = (0, _jestGetType.getType)(obj1); + const obj2Type = (0, _jestGetType.getType)(obj2); + return obj1Type === obj2Type && supportTypes.includes(obj1Type); + } + + forEach(cb) { + if (this.type === 'object') { + const descriptors = Object.getOwnPropertyDescriptors(this.object); + [ + ...Object.keys(descriptors), + ...Object.getOwnPropertySymbols(descriptors) + ] //@ts-expect-error because typescript do not support symbol key in object + //https://github.com/microsoft/TypeScript/issues/1863 + .filter(key => descriptors[key].enumerable) + .forEach(key => { + cb(this.object[key], key, this.object); + }); + } else { + this.object.forEach(cb); + } + } + + get(key) { + if (this.type === 'map') { + return this.object.get(key); + } + + return this.object[key]; + } + + set(key, value) { + if (this.type === 'map') { + this.object.set(key, value); + } else { + this.object[key] = value; + } + } +} +/* eslint-enable */ + +exports.default = Replaceable; diff --git a/node_modules/jest-matcher-utils/build/deepCyclicCopyReplaceable.js b/node_modules/jest-matcher-utils/build/deepCyclicCopyReplaceable.js new file mode 100644 index 0000000..15a13e5 --- /dev/null +++ b/node_modules/jest-matcher-utils/build/deepCyclicCopyReplaceable.js @@ -0,0 +1,110 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = deepCyclicCopyReplaceable; + +var _prettyFormat = require('pretty-format'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const builtInObject = [ + Array, + Date, + Float32Array, + Float64Array, + Int16Array, + Int32Array, + Int8Array, + Map, + Set, + RegExp, + Uint16Array, + Uint32Array, + Uint8Array, + Uint8ClampedArray +]; + +if (typeof Buffer !== 'undefined') { + builtInObject.push(Buffer); +} + +const isBuiltInObject = object => builtInObject.includes(object.constructor); + +const isMap = value => value.constructor === Map; + +function deepCyclicCopyReplaceable(value, cycles = new WeakMap()) { + if (typeof value !== 'object' || value === null) { + return value; + } else if (cycles.has(value)) { + return cycles.get(value); + } else if (Array.isArray(value)) { + return deepCyclicCopyArray(value, cycles); + } else if (isMap(value)) { + return deepCyclicCopyMap(value, cycles); + } else if (isBuiltInObject(value)) { + return value; + } else if (_prettyFormat.plugins.DOMElement.test(value)) { + return value.cloneNode(true); + } else { + return deepCyclicCopyObject(value, cycles); + } +} + +function deepCyclicCopyObject(object, cycles) { + const newObject = Object.create(Object.getPrototypeOf(object)); + const descriptors = Object.getOwnPropertyDescriptors(object); + cycles.set(object, newObject); + const newDescriptors = [ + ...Object.keys(descriptors), + ...Object.getOwnPropertySymbols(descriptors) + ].reduce( + //@ts-expect-error because typescript do not support symbol key in object + //https://github.com/microsoft/TypeScript/issues/1863 + (newDescriptors, key) => { + const enumerable = descriptors[key].enumerable; + newDescriptors[key] = { + configurable: true, + enumerable, + value: deepCyclicCopyReplaceable( + // this accesses the value or getter, depending. We just care about the value anyways, and this allows us to not mess with accessors + // it has the side effect of invoking the getter here though, rather than copying it over + object[key], + cycles + ), + writable: true + }; + return newDescriptors; + }, + {} + ); //@ts-expect-error because typescript do not support symbol key in object + //https://github.com/microsoft/TypeScript/issues/1863 + + return Object.defineProperties(newObject, newDescriptors); +} + +function deepCyclicCopyArray(array, cycles) { + const newArray = new (Object.getPrototypeOf(array).constructor)(array.length); + const length = array.length; + cycles.set(array, newArray); + + for (let i = 0; i < length; i++) { + newArray[i] = deepCyclicCopyReplaceable(array[i], cycles); + } + + return newArray; +} + +function deepCyclicCopyMap(map, cycles) { + const newMap = new Map(); + cycles.set(map, newMap); + map.forEach((value, key) => { + newMap.set(key, deepCyclicCopyReplaceable(value, cycles)); + }); + return newMap; +} diff --git a/node_modules/jest-matcher-utils/build/index.d.ts b/node_modules/jest-matcher-utils/build/index.d.ts new file mode 100644 index 0000000..cd7fa45 --- /dev/null +++ b/node_modules/jest-matcher-utils/build/index.d.ts @@ -0,0 +1,128 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import chalk = require('chalk'); +import {DiffOptions as DiffOptions_2} from 'jest-diff'; + +export declare const BOLD_WEIGHT: chalk.Chalk; + +export declare const diff: ( + a: unknown, + b: unknown, + options?: DiffOptions, +) => string | null; + +export declare type DiffOptions = DiffOptions_2; + +export declare const DIM_COLOR: chalk.Chalk; + +/** + * Ensures that `actual` is of type `number | bigint` + */ +export declare const ensureActualIsNumber: ( + actual: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +export declare const ensureExpectedIsNonNegativeInteger: ( + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +/** + * Ensures that `expected` is of type `number | bigint` + */ +export declare const ensureExpectedIsNumber: ( + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +export declare const ensureNoExpected: ( + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +/** + * Ensures that `actual` & `expected` are of type `number | bigint` + */ +export declare const ensureNumbers: ( + actual: unknown, + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +export declare const EXPECTED_COLOR: chalk.Chalk; + +export declare const getLabelPrinter: (...strings: Array) => PrintLabel; + +export declare const highlightTrailingWhitespace: (text: string) => string; + +export declare const INVERTED_COLOR: chalk.Chalk; + +export declare const matcherErrorMessage: ( + hint: string, + generic: string, + specific?: string, +) => string; + +export declare const matcherHint: ( + matcherName: string, + received?: string, + expected?: string, + options?: MatcherHintOptions, +) => string; + +declare type MatcherHintColor = (arg: string) => string; + +export declare type MatcherHintOptions = { + comment?: string; + expectedColor?: MatcherHintColor; + isDirectExpectCall?: boolean; + isNot?: boolean; + promise?: string; + receivedColor?: MatcherHintColor; + secondArgument?: string; + secondArgumentColor?: MatcherHintColor; +}; + +export declare const pluralize: (word: string, count: number) => string; + +export declare const printDiffOrStringify: ( + expected: unknown, + received: unknown, + expectedLabel: string, + receivedLabel: string, + expand: boolean, +) => string; + +export declare const printExpected: (value: unknown) => string; + +declare type PrintLabel = (string: string) => string; + +export declare const printReceived: (object: unknown) => string; + +export declare function printWithType( + name: string, + value: T, + print: (value: T) => string, +): string; + +export declare const RECEIVED_COLOR: chalk.Chalk; + +export declare const stringify: ( + object: unknown, + maxDepth?: number, + maxWidth?: number, +) => string; + +export declare const SUGGEST_TO_CONTAIN_EQUAL: string; + +export {}; diff --git a/node_modules/jest-matcher-utils/build/index.js b/node_modules/jest-matcher-utils/build/index.js new file mode 100644 index 0000000..fca426e --- /dev/null +++ b/node_modules/jest-matcher-utils/build/index.js @@ -0,0 +1,590 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printReceived = + exports.printExpected = + exports.printDiffOrStringify = + exports.pluralize = + exports.matcherHint = + exports.matcherErrorMessage = + exports.highlightTrailingWhitespace = + exports.getLabelPrinter = + exports.ensureNumbers = + exports.ensureNoExpected = + exports.ensureExpectedIsNumber = + exports.ensureExpectedIsNonNegativeInteger = + exports.ensureActualIsNumber = + exports.diff = + exports.SUGGEST_TO_CONTAIN_EQUAL = + exports.RECEIVED_COLOR = + exports.INVERTED_COLOR = + exports.EXPECTED_COLOR = + exports.DIM_COLOR = + exports.BOLD_WEIGHT = + void 0; +exports.printWithType = printWithType; +exports.stringify = void 0; + +var _chalk = _interopRequireDefault(require('chalk')); + +var _jestDiff = require('jest-diff'); + +var _jestGetType = require('jest-get-type'); + +var _prettyFormat = require('pretty-format'); + +var _Replaceable = _interopRequireDefault(require('./Replaceable')); + +var _deepCyclicCopyReplaceable = _interopRequireDefault( + require('./deepCyclicCopyReplaceable') +); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ +const { + AsymmetricMatcher, + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent +} = _prettyFormat.plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +const EXPECTED_COLOR = _chalk.default.green; +exports.EXPECTED_COLOR = EXPECTED_COLOR; +const RECEIVED_COLOR = _chalk.default.red; +exports.RECEIVED_COLOR = RECEIVED_COLOR; +const INVERTED_COLOR = _chalk.default.inverse; +exports.INVERTED_COLOR = INVERTED_COLOR; +const BOLD_WEIGHT = _chalk.default.bold; +exports.BOLD_WEIGHT = BOLD_WEIGHT; +const DIM_COLOR = _chalk.default.dim; +exports.DIM_COLOR = DIM_COLOR; +const MULTILINE_REGEXP = /\n/; +const SPACE_SYMBOL = '\u{00B7}'; // middle dot + +const NUMBERS = [ + 'zero', + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'ten', + 'eleven', + 'twelve', + 'thirteen' +]; + +const SUGGEST_TO_CONTAIN_EQUAL = _chalk.default.dim( + 'Looks like you wanted to test for object/array equality with the stricter `toContain` matcher. You probably need to use `toContainEqual` instead.' +); + +exports.SUGGEST_TO_CONTAIN_EQUAL = SUGGEST_TO_CONTAIN_EQUAL; + +const stringify = (object, maxDepth = 10, maxWidth = 10) => { + const MAX_LENGTH = 10000; + let result; + + try { + result = (0, _prettyFormat.format)(object, { + maxDepth, + maxWidth, + min: true, + plugins: PLUGINS + }); + } catch { + result = (0, _prettyFormat.format)(object, { + callToJSON: false, + maxDepth, + maxWidth, + min: true, + plugins: PLUGINS + }); + } + + if (result.length >= MAX_LENGTH && maxDepth > 1) { + return stringify(object, Math.floor(maxDepth / 2), maxWidth); + } else if (result.length >= MAX_LENGTH && maxWidth > 1) { + return stringify(object, maxDepth, Math.floor(maxWidth / 2)); + } else { + return result; + } +}; + +exports.stringify = stringify; + +const highlightTrailingWhitespace = text => + text.replace(/\s+$/gm, _chalk.default.inverse('$&')); // Instead of inverse highlight which now implies a change, +// replace common spaces with middle dot at the end of any line. + +exports.highlightTrailingWhitespace = highlightTrailingWhitespace; + +const replaceTrailingSpaces = text => + text.replace(/\s+$/gm, spaces => SPACE_SYMBOL.repeat(spaces.length)); + +const printReceived = object => + RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); + +exports.printReceived = printReceived; + +const printExpected = value => + EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); + +exports.printExpected = printExpected; + +function printWithType(name, value, print) { + const type = (0, _jestGetType.getType)(value); + const hasType = + type !== 'null' && type !== 'undefined' + ? `${name} has type: ${type}\n` + : ''; + const hasValue = `${name} has value: ${print(value)}`; + return hasType + hasValue; +} + +const ensureNoExpected = (expected, matcherName, options) => { + if (typeof expected !== 'undefined') { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, '', options), // Because expected is omitted in hint above, + // expected is black instead of green in message below. + 'this matcher must not have an expected argument', + printWithType('Expected', expected, printExpected) + ) + ); + } +}; +/** + * Ensures that `actual` is of type `number | bigint` + */ + +exports.ensureNoExpected = ensureNoExpected; + +const ensureActualIsNumber = (actual, matcherName, options) => { + if (typeof actual !== 'number' && typeof actual !== 'bigint') { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, undefined, options), + `${RECEIVED_COLOR('received')} value must be a number or bigint`, + printWithType('Received', actual, printReceived) + ) + ); + } +}; +/** + * Ensures that `expected` is of type `number | bigint` + */ + +exports.ensureActualIsNumber = ensureActualIsNumber; + +const ensureExpectedIsNumber = (expected, matcherName, options) => { + if (typeof expected !== 'number' && typeof expected !== 'bigint') { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, undefined, options), + `${EXPECTED_COLOR('expected')} value must be a number or bigint`, + printWithType('Expected', expected, printExpected) + ) + ); + } +}; +/** + * Ensures that `actual` & `expected` are of type `number | bigint` + */ + +exports.ensureExpectedIsNumber = ensureExpectedIsNumber; + +const ensureNumbers = (actual, expected, matcherName, options) => { + ensureActualIsNumber(actual, matcherName, options); + ensureExpectedIsNumber(expected, matcherName, options); +}; + +exports.ensureNumbers = ensureNumbers; + +const ensureExpectedIsNonNegativeInteger = (expected, matcherName, options) => { + if ( + typeof expected !== 'number' || + !Number.isSafeInteger(expected) || + expected < 0 + ) { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, undefined, options), + `${EXPECTED_COLOR('expected')} value must be a non-negative integer`, + printWithType('Expected', expected, printExpected) + ) + ); + } +}; // Given array of diffs, return concatenated string: +// * include common substrings +// * exclude change substrings which have opposite op +// * include change substrings which have argument op +// with inverse highlight only if there is a common substring + +exports.ensureExpectedIsNonNegativeInteger = ensureExpectedIsNonNegativeInteger; + +const getCommonAndChangedSubstrings = (diffs, op, hasCommonDiff) => + diffs.reduce( + (reduced, diff) => + reduced + + (diff[0] === _jestDiff.DIFF_EQUAL + ? diff[1] + : diff[0] !== op + ? '' + : hasCommonDiff + ? INVERTED_COLOR(diff[1]) + : diff[1]), + '' + ); + +const isLineDiffable = (expected, received) => { + const expectedType = (0, _jestGetType.getType)(expected); + const receivedType = (0, _jestGetType.getType)(received); + + if (expectedType !== receivedType) { + return false; + } + + if ((0, _jestGetType.isPrimitive)(expected)) { + // Print generic line diff for strings only: + // * if neither string is empty + // * if either string has more than one line + return ( + typeof expected === 'string' && + typeof received === 'string' && + expected.length !== 0 && + received.length !== 0 && + (MULTILINE_REGEXP.test(expected) || MULTILINE_REGEXP.test(received)) + ); + } + + if ( + expectedType === 'date' || + expectedType === 'function' || + expectedType === 'regexp' + ) { + return false; + } + + if (expected instanceof Error && received instanceof Error) { + return false; + } + + if ( + receivedType === 'object' && + typeof received.asymmetricMatch === 'function' + ) { + return false; + } + + return true; +}; + +const MAX_DIFF_STRING_LENGTH = 20000; + +const printDiffOrStringify = ( + expected, + received, + expectedLabel, + receivedLabel, + expand // CLI options: true if `--expand` or false if `--no-expand` +) => { + if ( + typeof expected === 'string' && + typeof received === 'string' && + expected.length !== 0 && + received.length !== 0 && + expected.length <= MAX_DIFF_STRING_LENGTH && + received.length <= MAX_DIFF_STRING_LENGTH && + expected !== received + ) { + if (expected.includes('\n') || received.includes('\n')) { + return (0, _jestDiff.diffStringsUnified)(expected, received, { + aAnnotation: expectedLabel, + bAnnotation: receivedLabel, + changeLineTrailingSpaceColor: _chalk.default.bgYellow, + commonLineTrailingSpaceColor: _chalk.default.bgYellow, + emptyFirstOrLastLinePlaceholder: '↵', + // U+21B5 + expand, + includeChangeCounts: true + }); + } + + const diffs = (0, _jestDiff.diffStringsRaw)(expected, received, true); + const hasCommonDiff = diffs.some(diff => diff[0] === _jestDiff.DIFF_EQUAL); + const printLabel = getLabelPrinter(expectedLabel, receivedLabel); + const expectedLine = + printLabel(expectedLabel) + + printExpected( + getCommonAndChangedSubstrings( + diffs, + _jestDiff.DIFF_DELETE, + hasCommonDiff + ) + ); + const receivedLine = + printLabel(receivedLabel) + + printReceived( + getCommonAndChangedSubstrings( + diffs, + _jestDiff.DIFF_INSERT, + hasCommonDiff + ) + ); + return `${expectedLine}\n${receivedLine}`; + } + + if (isLineDiffable(expected, received)) { + const {replacedExpected, replacedReceived} = + replaceMatchedToAsymmetricMatcher( + (0, _deepCyclicCopyReplaceable.default)(expected), + (0, _deepCyclicCopyReplaceable.default)(received), + [], + [] + ); + const difference = (0, _jestDiff.diff)(replacedExpected, replacedReceived, { + aAnnotation: expectedLabel, + bAnnotation: receivedLabel, + expand, + includeChangeCounts: true + }); + + if ( + typeof difference === 'string' && + difference.includes(`- ${expectedLabel}`) && + difference.includes(`+ ${receivedLabel}`) + ) { + return difference; + } + } + + const printLabel = getLabelPrinter(expectedLabel, receivedLabel); + const expectedLine = printLabel(expectedLabel) + printExpected(expected); + const receivedLine = + printLabel(receivedLabel) + + (stringify(expected) === stringify(received) + ? 'serializes to the same string' + : printReceived(received)); + return `${expectedLine}\n${receivedLine}`; +}; // Sometimes, e.g. when comparing two numbers, the output from jest-diff +// does not contain more information than the `Expected:` / `Received:` already gives. +// In those cases, we do not print a diff to make the output shorter and not redundant. + +exports.printDiffOrStringify = printDiffOrStringify; + +const shouldPrintDiff = (actual, expected) => { + if (typeof actual === 'number' && typeof expected === 'number') { + return false; + } + + if (typeof actual === 'bigint' && typeof expected === 'bigint') { + return false; + } + + if (typeof actual === 'boolean' && typeof expected === 'boolean') { + return false; + } + + return true; +}; + +function replaceMatchedToAsymmetricMatcher( + replacedExpected, + replacedReceived, + expectedCycles, + receivedCycles +) { + if (!_Replaceable.default.isReplaceable(replacedExpected, replacedReceived)) { + return { + replacedExpected, + replacedReceived + }; + } + + if ( + expectedCycles.includes(replacedExpected) || + receivedCycles.includes(replacedReceived) + ) { + return { + replacedExpected, + replacedReceived + }; + } + + expectedCycles.push(replacedExpected); + receivedCycles.push(replacedReceived); + const expectedReplaceable = new _Replaceable.default(replacedExpected); + const receivedReplaceable = new _Replaceable.default(replacedReceived); + expectedReplaceable.forEach((expectedValue, key) => { + const receivedValue = receivedReplaceable.get(key); + + if (isAsymmetricMatcher(expectedValue)) { + if (expectedValue.asymmetricMatch(receivedValue)) { + receivedReplaceable.set(key, expectedValue); + } + } else if (isAsymmetricMatcher(receivedValue)) { + if (receivedValue.asymmetricMatch(expectedValue)) { + expectedReplaceable.set(key, receivedValue); + } + } else if ( + _Replaceable.default.isReplaceable(expectedValue, receivedValue) + ) { + const replaced = replaceMatchedToAsymmetricMatcher( + expectedValue, + receivedValue, + expectedCycles, + receivedCycles + ); + expectedReplaceable.set(key, replaced.replacedExpected); + receivedReplaceable.set(key, replaced.replacedReceived); + } + }); + return { + replacedExpected: expectedReplaceable.object, + replacedReceived: receivedReplaceable.object + }; +} + +function isAsymmetricMatcher(data) { + const type = (0, _jestGetType.getType)(data); + return type === 'object' && typeof data.asymmetricMatch === 'function'; +} + +const diff = (a, b, options) => + shouldPrintDiff(a, b) ? (0, _jestDiff.diff)(a, b, options) : null; + +exports.diff = diff; + +const pluralize = (word, count) => + `${NUMBERS[count] || count} ${word}${count === 1 ? '' : 's'}`; // To display lines of labeled values as two columns with monospace alignment: +// given the strings which will describe the values, +// return function which given each string, returns the label: +// string, colon, space, and enough padding spaces to align the value. + +exports.pluralize = pluralize; + +const getLabelPrinter = (...strings) => { + const maxLength = strings.reduce( + (max, string) => (string.length > max ? string.length : max), + 0 + ); + return string => `${string}: ${' '.repeat(maxLength - string.length)}`; +}; + +exports.getLabelPrinter = getLabelPrinter; + +const matcherErrorMessage = ( + hint, + generic, + specific // incorrect value returned from call to printWithType +) => + `${hint}\n\n${_chalk.default.bold('Matcher error')}: ${generic}${ + typeof specific === 'string' ? `\n\n${specific}` : '' + }`; // Display assertion for the report when a test fails. +// New format: rejects/resolves, not, and matcher name have black color +// Old format: matcher name has dim color + +exports.matcherErrorMessage = matcherErrorMessage; + +const matcherHint = ( + matcherName, + received = 'received', + expected = 'expected', + options = {} +) => { + const { + comment = '', + expectedColor = EXPECTED_COLOR, + isDirectExpectCall = false, + // seems redundant with received === '' + isNot = false, + promise = '', + receivedColor = RECEIVED_COLOR, + secondArgument = '', + secondArgumentColor = EXPECTED_COLOR + } = options; + let hint = ''; + let dimString = 'expect'; // concatenate adjacent dim substrings + + if (!isDirectExpectCall && received !== '') { + hint += DIM_COLOR(`${dimString}(`) + receivedColor(received); + dimString = ')'; + } + + if (promise !== '') { + hint += DIM_COLOR(`${dimString}.`) + promise; + dimString = ''; + } + + if (isNot) { + hint += `${DIM_COLOR(`${dimString}.`)}not`; + dimString = ''; + } + + if (matcherName.includes('.')) { + // Old format: for backward compatibility, + // especially without promise or isNot options + dimString += matcherName; + } else { + // New format: omit period from matcherName arg + hint += DIM_COLOR(`${dimString}.`) + matcherName; + dimString = ''; + } + + if (expected === '') { + dimString += '()'; + } else { + hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected); + + if (secondArgument) { + hint += DIM_COLOR(', ') + secondArgumentColor(secondArgument); + } + + dimString = ')'; + } + + if (comment !== '') { + dimString += ` // ${comment}`; + } + + if (dimString !== '') { + hint += DIM_COLOR(dimString); + } + + return hint; +}; + +exports.matcherHint = matcherHint; diff --git a/node_modules/jest-matcher-utils/package.json b/node_modules/jest-matcher-utils/package.json new file mode 100644 index 0000000..c4cc1f5 --- /dev/null +++ b/node_modules/jest-matcher-utils/package.json @@ -0,0 +1,68 @@ +{ + "_from": "jest-matcher-utils@^29.0.1", + "_id": "jest-matcher-utils@29.0.1", + "_inBundle": false, + "_integrity": "sha512-/e6UbCDmprRQFnl7+uBKqn4G22c/OmwriE5KCMVqxhElKCQUDcFnq5XM9iJeKtzy4DUjxT27y9VHmKPD8BQPaw==", + "_location": "/jest-matcher-utils", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-matcher-utils@^29.0.1", + "name": "jest-matcher-utils", + "escapedName": "jest-matcher-utils", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/expect", + "/jest-circus", + "/jest-snapshot" + ], + "_resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.0.1.tgz", + "_shasum": "eaa92dd5405c2df9d31d45ec4486361d219de3e9", + "_spec": "jest-matcher-utils@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-circus", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.0.1", + "jest-get-type": "^29.0.0", + "pretty-format": "^29.0.1" + }, + "deprecated": false, + "description": "A set of utility functions for expect and related packages", + "devDependencies": { + "@jest/test-utils": "^29.0.1", + "@types/node": "*" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-matcher-utils", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-matcher-utils" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-message-util/LICENSE b/node_modules/jest-message-util/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-message-util/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-message-util/build/index.d.ts b/node_modules/jest-message-util/build/index.d.ts new file mode 100644 index 0000000..b069c55 --- /dev/null +++ b/node_modules/jest-message-util/build/index.d.ts @@ -0,0 +1,67 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {StackData} from 'stack-utils'; +import type {TestResult} from '@jest/types'; + +export declare const formatExecError: ( + error: Error | TestResult.SerializableError | string | undefined, + config: StackTraceConfig, + options: StackTraceOptions, + testPath?: string, + reuseMessage?: boolean, +) => string; + +export declare const formatPath: ( + line: string, + config: StackTraceConfig, + relativeTestPath?: string | null, +) => string; + +export declare const formatResultsErrors: ( + testResults: Array, + config: StackTraceConfig, + options: StackTraceOptions, + testPath?: string, +) => string | null; + +export declare const formatStackTrace: ( + stack: string, + config: StackTraceConfig, + options: StackTraceOptions, + testPath?: string, +) => string; + +export declare interface Frame extends StackData { + file: string; +} + +export declare const getStackTraceLines: ( + stack: string, + options?: StackTraceOptions, +) => Array; + +export declare const getTopFrame: (lines: Array) => Frame | null; + +export declare const indentAllLines: (lines: string) => string; + +export declare const separateMessageFromStack: (content: string) => { + message: string; + stack: string; +}; + +export declare type StackTraceConfig = Pick< + Config.ProjectConfig, + 'rootDir' | 'testMatch' +>; + +export declare type StackTraceOptions = { + noStackTrace: boolean; + noCodeFrame?: boolean; +}; + +export {}; diff --git a/node_modules/jest-message-util/build/index.js b/node_modules/jest-message-util/build/index.js new file mode 100644 index 0000000..3a98246 --- /dev/null +++ b/node_modules/jest-message-util/build/index.js @@ -0,0 +1,462 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.separateMessageFromStack = + exports.indentAllLines = + exports.getTopFrame = + exports.getStackTraceLines = + exports.formatStackTrace = + exports.formatResultsErrors = + exports.formatPath = + exports.formatExecError = + void 0; + +var path = _interopRequireWildcard(require('path')); + +var _url = require('url'); + +var _codeFrame = require('@babel/code-frame'); + +var _chalk = _interopRequireDefault(require('chalk')); + +var fs = _interopRequireWildcard(require('graceful-fs')); + +var _micromatch = _interopRequireDefault(require('micromatch')); + +var _slash = _interopRequireDefault(require('slash')); + +var _stackUtils = _interopRequireDefault(require('stack-utils')); + +var _prettyFormat = require('pretty-format'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestReadFile = + globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync; +// stack utils tries to create pretty stack by making paths relative. +const stackUtils = new _stackUtils.default({ + cwd: 'something which does not exist' +}); +let nodeInternals = []; + +try { + nodeInternals = _stackUtils.default.nodeInternals(); +} catch { + // `StackUtils.nodeInternals()` fails in browsers. We don't need to remove + // node internals in the browser though, so no issue. +} + +const PATH_NODE_MODULES = `${path.sep}node_modules${path.sep}`; +const PATH_JEST_PACKAGES = `${path.sep}jest${path.sep}packages${path.sep}`; // filter for noisy stack trace lines + +const JASMINE_IGNORE = + /^\s+at(?:(?:.jasmine-)|\s+jasmine\.buildExpectationResult)/; +const JEST_INTERNALS_IGNORE = + /^\s+at.*?jest(-.*?)?(\/|\\)(build|node_modules|packages)(\/|\\)/; +const ANONYMOUS_FN_IGNORE = /^\s+at .*$/; +const ANONYMOUS_PROMISE_IGNORE = /^\s+at (new )?Promise \(\).*$/; +const ANONYMOUS_GENERATOR_IGNORE = /^\s+at Generator.next \(\).*$/; +const NATIVE_NEXT_IGNORE = /^\s+at next \(native\).*$/; +const TITLE_INDENT = ' '; +const MESSAGE_INDENT = ' '; +const STACK_INDENT = ' '; +const ANCESTRY_SEPARATOR = ' \u203A '; + +const TITLE_BULLET = _chalk.default.bold('\u25cf '); + +const STACK_TRACE_COLOR = _chalk.default.dim; +const STACK_PATH_REGEXP = /\s*at.*\(?(:\d*:\d*|native)\)?/; +const EXEC_ERROR_MESSAGE = 'Test suite failed to run'; +const NOT_EMPTY_LINE_REGEXP = /^(?!$)/gm; + +const indentAllLines = lines => + lines.replace(NOT_EMPTY_LINE_REGEXP, MESSAGE_INDENT); + +exports.indentAllLines = indentAllLines; + +const trim = string => (string || '').trim(); // Some errors contain not only line numbers in stack traces +// e.g. SyntaxErrors can contain snippets of code, and we don't +// want to trim those, because they may have pointers to the column/character +// which will get misaligned. + +const trimPaths = string => + string.match(STACK_PATH_REGEXP) ? trim(string) : string; + +const getRenderedCallsite = (fileContent, line, column) => { + let renderedCallsite = (0, _codeFrame.codeFrameColumns)( + fileContent, + { + start: { + column, + line + } + }, + { + highlightCode: true + } + ); + renderedCallsite = indentAllLines(renderedCallsite); + renderedCallsite = `\n${renderedCallsite}\n`; + return renderedCallsite; +}; + +const blankStringRegexp = /^\s*$/; + +function checkForCommonEnvironmentErrors(error) { + if ( + error.includes('ReferenceError: document is not defined') || + error.includes('ReferenceError: window is not defined') || + error.includes('ReferenceError: navigator is not defined') + ) { + return warnAboutWrongTestEnvironment(error, 'jsdom'); + } else if (error.includes('.unref is not a function')) { + return warnAboutWrongTestEnvironment(error, 'node'); + } + + return error; +} + +function warnAboutWrongTestEnvironment(error, env) { + return ( + _chalk.default.bold.red( + `The error below may be caused by using the wrong test environment, see ${_chalk.default.dim.underline( + 'https://jestjs.io/docs/configuration#testenvironment-string' + )}.\nConsider using the "${env}" test environment.\n\n` + ) + error + ); +} // ExecError is an error thrown outside of the test suite (not inside an `it` or +// `before/after each` hooks). If it's thrown, none of the tests in the file +// are executed. + +const formatExecError = (error, config, options, testPath, reuseMessage) => { + if (!error || typeof error === 'number') { + error = new Error(`Expected an Error, but "${String(error)}" was thrown`); + error.stack = ''; + } + + let message, stack; + + if (typeof error === 'string' || !error) { + error || (error = 'EMPTY ERROR'); + message = ''; + stack = error; + } else { + message = error.message; + stack = + typeof error.stack === 'string' + ? error.stack + : `thrown: ${(0, _prettyFormat.format)(error, { + maxDepth: 3 + })}`; + } + + const separated = separateMessageFromStack(stack || ''); + stack = separated.stack; + + if (separated.message.includes(trim(message))) { + // Often stack trace already contains the duplicate of the message + message = separated.message; + } + + message = checkForCommonEnvironmentErrors(message); + message = indentAllLines(message); + stack = + stack && !options.noStackTrace + ? `\n${formatStackTrace(stack, config, options, testPath)}` + : ''; + + if ( + typeof stack !== 'string' || + (blankStringRegexp.test(message) && blankStringRegexp.test(stack)) + ) { + // this can happen if an empty object is thrown. + message = `thrown: ${(0, _prettyFormat.format)(error, { + maxDepth: 3 + })}`; + } + + let messageToUse; + + if (reuseMessage) { + messageToUse = ` ${message.trim()}`; + } else { + messageToUse = `${EXEC_ERROR_MESSAGE}\n\n${message}`; + } + + return `${TITLE_INDENT + TITLE_BULLET + messageToUse + stack}\n`; +}; + +exports.formatExecError = formatExecError; + +const removeInternalStackEntries = (lines, options) => { + let pathCounter = 0; + return lines.filter(line => { + if (ANONYMOUS_FN_IGNORE.test(line)) { + return false; + } + + if (ANONYMOUS_PROMISE_IGNORE.test(line)) { + return false; + } + + if (ANONYMOUS_GENERATOR_IGNORE.test(line)) { + return false; + } + + if (NATIVE_NEXT_IGNORE.test(line)) { + return false; + } + + if (nodeInternals.some(internal => internal.test(line))) { + return false; + } + + if (!STACK_PATH_REGEXP.test(line)) { + return true; + } + + if (JASMINE_IGNORE.test(line)) { + return false; + } + + if (++pathCounter === 1) { + return true; // always keep the first line even if it's from Jest + } + + if (options.noStackTrace) { + return false; + } + + if (JEST_INTERNALS_IGNORE.test(line)) { + return false; + } + + return true; + }); +}; + +const formatPath = (line, config, relativeTestPath = null) => { + // Extract the file path from the trace line. + const match = line.match(/(^\s*at .*?\(?)([^()]+)(:[0-9]+:[0-9]+\)?.*$)/); + + if (!match) { + return line; + } + + let filePath = (0, _slash.default)(path.relative(config.rootDir, match[2])); // highlight paths from the current test file + + if ( + (config.testMatch && + config.testMatch.length && + (0, _micromatch.default)([filePath], config.testMatch).length > 0) || + filePath === relativeTestPath + ) { + filePath = _chalk.default.reset.cyan(filePath); + } + + return STACK_TRACE_COLOR(match[1]) + filePath + STACK_TRACE_COLOR(match[3]); +}; + +exports.formatPath = formatPath; + +const getStackTraceLines = ( + stack, + options = { + noCodeFrame: false, + noStackTrace: false + } +) => removeInternalStackEntries(stack.split(/\n/), options); + +exports.getStackTraceLines = getStackTraceLines; + +const getTopFrame = lines => { + for (const line of lines) { + if (line.includes(PATH_NODE_MODULES) || line.includes(PATH_JEST_PACKAGES)) { + continue; + } + + const parsedFrame = stackUtils.parseLine(line.trim()); + + if (parsedFrame && parsedFrame.file) { + if (parsedFrame.file.startsWith('file://')) { + parsedFrame.file = (0, _slash.default)( + (0, _url.fileURLToPath)(parsedFrame.file) + ); + } + + return parsedFrame; + } + } + + return null; +}; + +exports.getTopFrame = getTopFrame; + +const formatStackTrace = (stack, config, options, testPath) => { + const lines = getStackTraceLines(stack, options); + let renderedCallsite = ''; + const relativeTestPath = testPath + ? (0, _slash.default)(path.relative(config.rootDir, testPath)) + : null; + + if (!options.noStackTrace && !options.noCodeFrame) { + const topFrame = getTopFrame(lines); + + if (topFrame) { + const {column, file: filename, line} = topFrame; + + if (line && filename && path.isAbsolute(filename)) { + let fileContent; + + try { + // TODO: check & read HasteFS instead of reading the filesystem: + // see: https://github.com/facebook/jest/pull/5405#discussion_r164281696 + fileContent = jestReadFile(filename, 'utf8'); + renderedCallsite = getRenderedCallsite(fileContent, line, column); + } catch { + // the file does not exist or is inaccessible, we ignore + } + } + } + } + + const stacktrace = lines + .filter(Boolean) + .map( + line => + STACK_INDENT + formatPath(trimPaths(line), config, relativeTestPath) + ) + .join('\n'); + return renderedCallsite + ? `${renderedCallsite}\n${stacktrace}` + : `\n${stacktrace}`; +}; + +exports.formatStackTrace = formatStackTrace; + +const formatResultsErrors = (testResults, config, options, testPath) => { + const failedResults = testResults.reduce((errors, result) => { + result.failureMessages.forEach(item => { + errors.push({ + content: checkForCommonEnvironmentErrors(item), + result + }); + }); + return errors; + }, []); + + if (!failedResults.length) { + return null; + } + + return failedResults + .map(({result, content}) => { + let {message, stack} = separateMessageFromStack(content); + stack = options.noStackTrace + ? '' + : `${STACK_TRACE_COLOR( + formatStackTrace(stack, config, options, testPath) + )}\n`; + message = indentAllLines(message); + const title = `${_chalk.default.bold.red( + TITLE_INDENT + + TITLE_BULLET + + result.ancestorTitles.join(ANCESTRY_SEPARATOR) + + (result.ancestorTitles.length ? ANCESTRY_SEPARATOR : '') + + result.title + )}\n`; + return `${title}\n${message}\n${stack}`; + }) + .join('\n'); +}; + +exports.formatResultsErrors = formatResultsErrors; +const errorRegexp = /^Error:?\s*$/; + +const removeBlankErrorLine = str => + str + .split('\n') // Lines saying just `Error:` are useless + .filter(line => !errorRegexp.test(line)) + .join('\n') + .trimRight(); // jasmine and worker farm sometimes don't give us access to the actual +// Error object, so we have to regexp out the message from the stack string +// to format it. + +const separateMessageFromStack = content => { + if (!content) { + return { + message: '', + stack: '' + }; + } // All lines up to what looks like a stack -- or if nothing looks like a stack + // (maybe it's a code frame instead), just the first non-empty line. + // If the error is a plain "Error:" instead of a SyntaxError or TypeError we + // remove the prefix from the message because it is generally not useful. + + const messageMatch = content.match( + /^(?:Error: )?([\s\S]*?(?=\n\s*at\s.*:\d*:\d*)|\s*.*)([\s\S]*)$/ + ); + + if (!messageMatch) { + // For typescript + throw new Error('If you hit this error, the regex above is buggy.'); + } + + const message = removeBlankErrorLine(messageMatch[1]); + const stack = removeBlankErrorLine(messageMatch[2]); + return { + message, + stack + }; +}; + +exports.separateMessageFromStack = separateMessageFromStack; diff --git a/node_modules/jest-message-util/build/types.js b/node_modules/jest-message-util/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-message-util/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-message-util/package.json b/node_modules/jest-message-util/package.json new file mode 100644 index 0000000..187094f --- /dev/null +++ b/node_modules/jest-message-util/package.json @@ -0,0 +1,79 @@ +{ + "_from": "jest-message-util@^29.0.1", + "_id": "jest-message-util@29.0.1", + "_inBundle": false, + "_integrity": "sha512-wRMAQt3HrLpxSubdnzOo68QoTfQ+NLXFzU0Heb18ZUzO2S9GgaXNEdQ4rpd0fI9dq2NXkpCk1IUWSqzYKji64A==", + "_location": "/jest-message-util", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-message-util@^29.0.1", + "name": "jest-message-util", + "escapedName": "jest-message-util", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/console", + "/@jest/core", + "/@jest/fake-timers", + "/@jest/reporters", + "/expect", + "/jest-circus", + "/jest-runner", + "/jest-runtime", + "/jest-snapshot" + ], + "_resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.0.1.tgz", + "_shasum": "85c4b5b90296c228da158e168eaa5b079f2ab879", + "_spec": "jest-message-util@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.0.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.0.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "deprecated": false, + "devDependencies": { + "@types/babel__code-frame": "^7.0.0", + "@types/graceful-fs": "^4.1.3", + "@types/micromatch": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-message-util", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-message-util" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-mock/LICENSE b/node_modules/jest-mock/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-mock/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-mock/README.md b/node_modules/jest-mock/README.md new file mode 100644 index 0000000..5bc7509 --- /dev/null +++ b/node_modules/jest-mock/README.md @@ -0,0 +1,100 @@ +# jest-mock + +**Note:** More details on user side API can be found in [Jest documentation](https://jestjs.io/docs/mock-function-api). + +## API + +```js +import {ModuleMocker} from 'jest-mock'; +``` + +### `constructor(global)` + +Creates a new module mocker that generates mocks as if they were created in an environment with the given global object. + +### `generateFromMetadata(metadata)` + +Generates a mock based on the given metadata (Metadata for the mock in the schema returned by the `getMetadata()` method of this module). Mocks treat functions specially, and all mock functions have additional members, described in the documentation for `fn()` in this module. + +One important note: function prototypes are handled specially by this mocking framework. For functions with prototypes, when called as a constructor, the mock will install mocked function members on the instance. This allows different instances of the same constructor to have different values for its mocks member and its return values. + +### `getMetadata(component)` + +Inspects the argument and returns its schema in the following recursive format: + +``` +{ + type: ... + members: {} +} +``` + +Where type is one of `array`, `object`, `function`, or `ref`, and members is an optional dictionary where the keys are member names and the values are metadata objects. Function prototypes are defined by defining metadata for the `member.prototype` of the function. The type of a function prototype should always be `object`. For instance, a class might be defined like this: + +```js +const classDef = { + type: 'function', + members: { + staticMethod: {type: 'function'}, + prototype: { + type: 'object', + members: { + instanceMethod: {type: 'function'}, + }, + }, + }, +}; +``` + +Metadata may also contain references to other objects defined within the same metadata object. The metadata for the referent must be marked with `refID` key and an arbitrary value. The referrer must be marked with a `ref` key that has the same value as object with refID that it refers to. For instance, this metadata blob: + +```js +const refID = { + type: 'object', + refID: 1, + members: { + self: {ref: 1}, + }, +}; +``` + +Defines an object with a slot named `self` that refers back to the object. + +### `fn(implementation?)` + +Generates a stand-alone function with members that help drive unit tests or confirm expectations. Specifically, functions returned by this method have the following members: + +##### `.mock` + +An object with three members, `calls`, `instances` and `invocationCallOrder`, which are all lists. The items in the `calls` list are the arguments with which the function was called. The "instances" list stores the value of 'this' for each call to the function. This is useful for retrieving instances from a constructor. The `invocationCallOrder` lists the order in which the mock was called in relation to all mock calls, starting at 1. + +##### `.mockReturnValueOnce(value)` + +Pushes the given value onto a FIFO queue of return values for the function. + +##### `.mockReturnValue(value)` + +Sets the default return value for the function. + +##### `.mockImplementationOnce(function)` + +Pushes the given mock implementation onto a FIFO queue of mock implementations for the function. + +##### `.mockImplementation(function)` + +Sets the default mock implementation for the function. + +##### `.mockReturnThis()` + +Syntactic sugar for: + +```js +mockFn.mockImplementation(function () { + return this; +}); +``` + +In case both `.mockImplementationOnce()` / `.mockImplementation()` and `.mockReturnValueOnce()` / `.mockReturnValue()` are called. The priority of which to use is based on what is the last call: + +- if the last call is `.mockReturnValueOnce()` or `.mockReturnValue()`, use the specific return value or default return value. If specific return values are used up or no default return value is set, fall back to try `.mockImplementation()`; +- if the last call is `.mockImplementationOnce()` or `.mockImplementation()`, run the specific implementation and return the result or run default implementation and return the result. diff --git a/node_modules/jest-mock/build/index.d.ts b/node_modules/jest-mock/build/index.d.ts new file mode 100644 index 0000000..2c45562 --- /dev/null +++ b/node_modules/jest-mock/build/index.d.ts @@ -0,0 +1,374 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare type ClassLike = { + new (...args: any): any; +}; + +export declare type ConstructorLikeKeys = keyof { + [K in keyof T as T[K] extends ClassLike ? K : never]: T[K]; +}; + +export declare const fn: ( + implementation?: T | undefined, +) => Mock; + +export declare type FunctionLike = (...args: any) => any; + +export declare type MethodLikeKeys = keyof { + [K in keyof T as T[K] extends FunctionLike ? K : never]: T[K]; +}; + +/** + * All what the internal typings need is to be sure that we have any-function. + * `FunctionLike` type ensures that and helps to constrain the type as well. + * The default of `UnknownFunction` makes sure that `any`s do not leak to the + * user side. For instance, calling `fn()` without implementation will return + * a mock of `(...args: Array) => unknown` type. If implementation + * is provided, its typings are inferred correctly. + */ +export declare interface Mock + extends Function, + MockInstance { + new (...args: Parameters): ReturnType; + (...args: Parameters): ReturnType; +} + +export declare type Mocked = T extends ClassLike + ? MockedClass + : T extends FunctionLike + ? MockedFunction + : T extends object + ? MockedObject + : T; + +export declare const mocked: { + ( + source: T, + options?: { + shallow: false; + }, + ): Mocked; + ( + source: T_1, + options: { + shallow: true; + }, + ): MockedShallow; +}; + +export declare type MockedClass = MockInstance< + (...args: ConstructorParameters) => Mocked> +> & + MockedObject; + +export declare type MockedFunction = MockInstance & + MockedObject; + +declare type MockedFunctionShallow = MockInstance & + T; + +export declare type MockedObject = { + [K in keyof T]: T[K] extends ClassLike + ? MockedClass + : T[K] extends FunctionLike + ? MockedFunction + : T[K] extends object + ? MockedObject + : T[K]; +} & T; + +declare type MockedObjectShallow = { + [K in keyof T]: T[K] extends ClassLike + ? MockedClass + : T[K] extends FunctionLike + ? MockedFunctionShallow + : T[K]; +} & T; + +export declare type MockedShallow = T extends ClassLike + ? MockedClass + : T extends FunctionLike + ? MockedFunctionShallow + : T extends object + ? MockedObjectShallow + : T; + +export declare type MockFunctionMetadata< + T extends UnknownFunction = UnknownFunction, + MetadataType = MockFunctionMetadataType, +> = { + ref?: number; + members?: Record>; + mockImpl?: T; + name?: string; + refID?: number; + type?: MetadataType; + value?: ReturnType; + length?: number; +}; + +export declare type MockFunctionMetadataType = + | 'object' + | 'array' + | 'regexp' + | 'function' + | 'constant' + | 'collection' + | 'null' + | 'undefined'; + +declare type MockFunctionResult = + | MockFunctionResultIncomplete + | MockFunctionResultReturn + | MockFunctionResultThrow; + +declare type MockFunctionResultIncomplete = { + type: 'incomplete'; + /** + * Result of a single call to a mock function that has not yet completed. + * This occurs if you test the result from within the mock function itself, + * or from within a function that was called by the mock. + */ + value: undefined; +}; + +declare type MockFunctionResultReturn< + T extends FunctionLike = UnknownFunction, +> = { + type: 'return'; + /** + * Result of a single call to a mock function that returned. + */ + value: ReturnType; +}; + +declare type MockFunctionResultThrow = { + type: 'throw'; + /** + * Result of a single call to a mock function that threw. + */ + value: unknown; +}; + +declare type MockFunctionState = { + /** + * List of the call arguments of all calls that have been made to the mock. + */ + calls: Array>; + /** + * List of all the object instances that have been instantiated from the mock. + */ + instances: Array>; + /** + * List of all the function contexts that have been applied to calls to the mock. + */ + contexts: Array>; + /** + * List of the call order indexes of the mock. Jest is indexing the order of + * invocations of all mocks in a test file. The index is starting with `1`. + */ + invocationCallOrder: Array; + /** + * List of the call arguments of the last call that was made to the mock. + * If the function was not called, it will return `undefined`. + */ + lastCall?: Parameters; + /** + * List of the results of all calls that have been made to the mock. + */ + results: Array>; +}; + +export declare interface MockInstance< + T extends FunctionLike = UnknownFunction, +> { + _isMockFunction: true; + _protoImpl: Function; + getMockImplementation(): T | undefined; + getMockName(): string; + mock: MockFunctionState; + mockClear(): this; + mockReset(): this; + mockRestore(): void; + mockImplementation(fn: T): this; + mockImplementationOnce(fn: T): this; + mockName(name: string): this; + mockReturnThis(): this; + mockReturnValue(value: ReturnType): this; + mockReturnValueOnce(value: ReturnType): this; + mockResolvedValue(value: ResolveType): this; + mockResolvedValueOnce(value: ResolveType): this; + mockRejectedValue(value: RejectType): this; + mockRejectedValueOnce(value: RejectType): this; +} + +export declare class ModuleMocker { + private _environmentGlobal; + private _mockState; + private _mockConfigRegistry; + private _spyState; + private _invocationCallCounter; + /** + * @see README.md + * @param global Global object of the test environment, used to create + * mocks + */ + constructor(global: typeof globalThis); + private _getSlots; + private _ensureMockConfig; + private _ensureMockState; + private _defaultMockConfig; + private _defaultMockState; + private _makeComponent; + private _createMockFunction; + private _generateMock; + /** + * @see README.md + * @param metadata Metadata for the mock in the schema returned by the + * getMetadata method of this module. + */ + generateFromMetadata( + metadata: MockFunctionMetadata, + ): Mock; + /** + * @see README.md + * @param component The component for which to retrieve metadata. + */ + getMetadata( + component: ReturnType, + _refs?: Map, number>, + ): MockFunctionMetadata | null; + isMockFunction( + fn: SpyInstance, + ): fn is SpyInstance; + isMockFunction

, R extends unknown>( + fn: (...args: P) => R, + ): fn is Mock<(...args: P) => R>; + isMockFunction(fn: unknown): fn is Mock; + fn(implementation?: T): Mock; + spyOn>( + object: T, + methodName: M, + accessType: 'get', + ): SpyInstance<() => T[M]>; + spyOn>( + object: T, + methodName: M, + accessType: 'set', + ): SpyInstance<(arg: T[M]) => void>; + spyOn>( + object: T, + methodName: M, + ): T[M] extends ClassLike + ? SpyInstance<(...args: ConstructorParameters) => InstanceType> + : never; + spyOn>( + object: T, + methodName: M, + ): T[M] extends FunctionLike + ? SpyInstance<(...args: Parameters) => ReturnType> + : never; + private _spyOnProperty; + clearAllMocks(): void; + resetAllMocks(): void; + restoreAllMocks(): void; + private _typeOf; + mocked( + source: T, + options?: { + shallow: false; + }, + ): Mocked; + mocked( + source: T, + options: { + shallow: true; + }, + ): MockedShallow; +} + +export declare type PropertyLikeKeys = Exclude< + keyof T, + ConstructorLikeKeys | MethodLikeKeys +>; + +declare type RejectType = + ReturnType extends PromiseLike ? unknown : never; + +declare type ResolveType = + ReturnType extends PromiseLike ? U : never; + +export declare interface SpyInstance + extends MockInstance {} + +declare const spyOn_2: { + < + T extends object, + M extends Exclude< + keyof T, + | keyof {[K in keyof T as T[K] extends ClassLike ? K : never]: T[K]} + | keyof { + [K_1 in keyof T as T[K_1] extends FunctionLike ? K_1 : never]: T[K_1]; + } + >, + >( + object: T, + methodName: M, + accessType: 'get', + ): SpyInstance<() => T[M]>; + < + T_1 extends object, + M_1 extends Exclude< + keyof T_1, + | keyof { + [K_2 in keyof T_1 as T_1[K_2] extends ClassLike + ? K_2 + : never]: T_1[K_2]; + } + | keyof { + [K_3 in keyof T_1 as T_1[K_3] extends FunctionLike + ? K_3 + : never]: T_1[K_3]; + } + >, + >( + object: T_1, + methodName: M_1, + accessType: 'set', + ): SpyInstance<(arg: T_1[M_1]) => void>; + < + T_2 extends object, + M_2 extends keyof { + [K_4 in keyof T_2 as T_2[K_4] extends ClassLike ? K_4 : never]: T_2[K_4]; + }, + >( + object: T_2, + methodName: M_2, + ): T_2[M_2] extends ClassLike + ? SpyInstance< + (...args: ConstructorParameters) => InstanceType + > + : never; + < + T_3 extends object, + M_3 extends keyof { + [K_5 in keyof T_3 as T_3[K_5] extends FunctionLike + ? K_5 + : never]: T_3[K_5]; + }, + >( + object: T_3, + methodName: M_3, + ): T_3[M_3] extends FunctionLike + ? SpyInstance<(...args: Parameters) => ReturnType> + : never; +}; +export {spyOn_2 as spyOn}; + +export declare type UnknownFunction = (...args: Array) => unknown; + +export {}; diff --git a/node_modules/jest-mock/build/index.js b/node_modules/jest-mock/build/index.js new file mode 100644 index 0000000..500224a --- /dev/null +++ b/node_modules/jest-mock/build/index.js @@ -0,0 +1,949 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.spyOn = exports.mocked = exports.fn = exports.ModuleMocker = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */ + +/** + * All what the internal typings need is to be sure that we have any-function. + * `FunctionLike` type ensures that and helps to constrain the type as well. + * The default of `UnknownFunction` makes sure that `any`s do not leak to the + * user side. For instance, calling `fn()` without implementation will return + * a mock of `(...args: Array) => unknown` type. If implementation + * is provided, its typings are inferred correctly. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-interface +const MOCK_CONSTRUCTOR_NAME = 'mockConstructor'; +const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-/:-@[-`{-~]/; +const FUNCTION_NAME_RESERVED_REPLACE = new RegExp( + FUNCTION_NAME_RESERVED_PATTERN.source, + 'g' +); +const RESERVED_KEYWORDS = new Set([ + 'arguments', + 'await', + 'break', + 'case', + 'catch', + 'class', + 'const', + 'continue', + 'debugger', + 'default', + 'delete', + 'do', + 'else', + 'enum', + 'eval', + 'export', + 'extends', + 'false', + 'finally', + 'for', + 'function', + 'if', + 'implements', + 'import', + 'in', + 'instanceof', + 'interface', + 'let', + 'new', + 'null', + 'package', + 'private', + 'protected', + 'public', + 'return', + 'static', + 'super', + 'switch', + 'this', + 'throw', + 'true', + 'try', + 'typeof', + 'var', + 'void', + 'while', + 'with', + 'yield' +]); + +function matchArity(fn, length) { + let mockConstructor; + + switch (length) { + case 1: + mockConstructor = function (_a) { + return fn.apply(this, arguments); + }; + + break; + + case 2: + mockConstructor = function (_a, _b) { + return fn.apply(this, arguments); + }; + + break; + + case 3: + mockConstructor = function (_a, _b, _c) { + return fn.apply(this, arguments); + }; + + break; + + case 4: + mockConstructor = function (_a, _b, _c, _d) { + return fn.apply(this, arguments); + }; + + break; + + case 5: + mockConstructor = function (_a, _b, _c, _d, _e) { + return fn.apply(this, arguments); + }; + + break; + + case 6: + mockConstructor = function (_a, _b, _c, _d, _e, _f) { + return fn.apply(this, arguments); + }; + + break; + + case 7: + mockConstructor = function (_a, _b, _c, _d, _e, _f, _g) { + return fn.apply(this, arguments); + }; + + break; + + case 8: + mockConstructor = function (_a, _b, _c, _d, _e, _f, _g, _h) { + return fn.apply(this, arguments); + }; + + break; + + case 9: + mockConstructor = function (_a, _b, _c, _d, _e, _f, _g, _h, _i) { + return fn.apply(this, arguments); + }; + + break; + + default: + mockConstructor = function () { + return fn.apply(this, arguments); + }; + + break; + } + + return mockConstructor; +} + +function getObjectType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} + +function getType(ref) { + const typeName = getObjectType(ref); + + if ( + typeName === 'Function' || + typeName === 'AsyncFunction' || + typeName === 'GeneratorFunction' || + typeName === 'AsyncGeneratorFunction' + ) { + return 'function'; + } else if (Array.isArray(ref)) { + return 'array'; + } else if (typeName === 'Object') { + return 'object'; + } else if ( + typeName === 'Number' || + typeName === 'String' || + typeName === 'Boolean' || + typeName === 'Symbol' + ) { + return 'constant'; + } else if ( + typeName === 'Map' || + typeName === 'WeakMap' || + typeName === 'Set' + ) { + return 'collection'; + } else if (typeName === 'RegExp') { + return 'regexp'; + } else if (ref === undefined) { + return 'undefined'; + } else if (ref === null) { + return 'null'; + } else { + return null; + } +} + +function isReadonlyProp(object, prop) { + if ( + prop === 'arguments' || + prop === 'caller' || + prop === 'callee' || + prop === 'name' || + prop === 'length' + ) { + const typeName = getObjectType(object); + return ( + typeName === 'Function' || + typeName === 'AsyncFunction' || + typeName === 'GeneratorFunction' || + typeName === 'AsyncGeneratorFunction' + ); + } + + if ( + prop === 'source' || + prop === 'global' || + prop === 'ignoreCase' || + prop === 'multiline' + ) { + return getObjectType(object) === 'RegExp'; + } + + return false; +} + +class ModuleMocker { + _environmentGlobal; + _mockState; + _mockConfigRegistry; + _spyState; + _invocationCallCounter; + /** + * @see README.md + * @param global Global object of the test environment, used to create + * mocks + */ + + constructor(global) { + this._environmentGlobal = global; + this._mockState = new WeakMap(); + this._mockConfigRegistry = new WeakMap(); + this._spyState = new Set(); + this._invocationCallCounter = 1; + } + + _getSlots(object) { + if (!object) { + return []; + } + + const slots = new Set(); + const EnvObjectProto = this._environmentGlobal.Object.prototype; + const EnvFunctionProto = this._environmentGlobal.Function.prototype; + const EnvRegExpProto = this._environmentGlobal.RegExp.prototype; // Also check the builtins in the current context as they leak through + // core node modules. + + const ObjectProto = Object.prototype; + const FunctionProto = Function.prototype; + const RegExpProto = RegExp.prototype; // Properties of Object.prototype, Function.prototype and RegExp.prototype + // are never reported as slots + + while ( + object != null && + object !== EnvObjectProto && + object !== EnvFunctionProto && + object !== EnvRegExpProto && + object !== ObjectProto && + object !== FunctionProto && + object !== RegExpProto + ) { + const ownNames = Object.getOwnPropertyNames(object); + + for (let i = 0; i < ownNames.length; i++) { + const prop = ownNames[i]; + + if (!isReadonlyProp(object, prop)) { + const propDesc = Object.getOwnPropertyDescriptor(object, prop); + + if ((propDesc !== undefined && !propDesc.get) || object.__esModule) { + slots.add(prop); + } + } + } + + object = Object.getPrototypeOf(object); + } + + return Array.from(slots); + } + + _ensureMockConfig(f) { + let config = this._mockConfigRegistry.get(f); + + if (!config) { + config = this._defaultMockConfig(); + + this._mockConfigRegistry.set(f, config); + } + + return config; + } + + _ensureMockState(f) { + let state = this._mockState.get(f); + + if (!state) { + state = this._defaultMockState(); + + this._mockState.set(f, state); + } + + if (state.calls.length > 0) { + state.lastCall = state.calls[state.calls.length - 1]; + } + + return state; + } + + _defaultMockConfig() { + return { + mockImpl: undefined, + mockName: 'jest.fn()', + specificMockImpls: [], + specificReturnValues: [] + }; + } + + _defaultMockState() { + return { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + results: [] + }; + } + + _makeComponent(metadata, restore) { + if (metadata.type === 'object') { + return new this._environmentGlobal.Object(); + } else if (metadata.type === 'array') { + return new this._environmentGlobal.Array(); + } else if (metadata.type === 'regexp') { + return new this._environmentGlobal.RegExp(''); + } else if ( + metadata.type === 'constant' || + metadata.type === 'collection' || + metadata.type === 'null' || + metadata.type === 'undefined' + ) { + return metadata.value; + } else if (metadata.type === 'function') { + const prototype = + (metadata.members && + metadata.members.prototype && + metadata.members.prototype.members) || + {}; + + const prototypeSlots = this._getSlots(prototype); // eslint-disable-next-line @typescript-eslint/no-this-alias + + const mocker = this; + const mockConstructor = matchArity(function (...args) { + const mockState = mocker._ensureMockState(f); + + const mockConfig = mocker._ensureMockConfig(f); + + mockState.instances.push(this); + mockState.contexts.push(this); + mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon + // calling rather than waiting for the mock to return. This avoids + // issues caused by recursion where results can be recorded in the + // wrong order. + + const mockResult = { + type: 'incomplete', + value: undefined + }; + mockState.results.push(mockResult); + mockState.invocationCallOrder.push(mocker._invocationCallCounter++); // Will be set to the return value of the mock if an error is not thrown + + let finalReturnValue; // Will be set to the error that is thrown by the mock (if it throws) + + let thrownError; // Will be set to true if the mock throws an error. The presence of a + // value in `thrownError` is not a 100% reliable indicator because a + // function could throw a value of undefined. + + let callDidThrowError = false; + + try { + // The bulk of the implementation is wrapped in an immediately + // executed arrow function so the return value of the mock function + // can be easily captured and recorded, despite the many separate + // return points within the logic. + finalReturnValue = (() => { + if (this instanceof f) { + // This is probably being called as a constructor + prototypeSlots.forEach(slot => { + // Copy prototype methods to the instance to make + // it easier to interact with mock instance call and + // return values + if (prototype[slot].type === 'function') { + // @ts-expect-error no index signature + const protoImpl = this[slot]; // @ts-expect-error no index signature + + this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-expect-error no index signature + + this[slot]._protoImpl = protoImpl; + } + }); // Run the mock constructor implementation + + const mockImpl = mockConfig.specificMockImpls.length + ? mockConfig.specificMockImpls.shift() + : mockConfig.mockImpl; + return mockImpl && mockImpl.apply(this, arguments); + } // If mockImplementationOnce()/mockImplementation() is last set, + // implementation use the mock + + let specificMockImpl = mockConfig.specificMockImpls.shift(); + + if (specificMockImpl === undefined) { + specificMockImpl = mockConfig.mockImpl; + } + + if (specificMockImpl) { + return specificMockImpl.apply(this, arguments); + } // Otherwise use prototype implementation + + if (f._protoImpl) { + return f._protoImpl.apply(this, arguments); + } + + return undefined; + })(); + } catch (error) { + // Store the thrown error so we can record it, then re-throw it. + thrownError = error; + callDidThrowError = true; + throw error; + } finally { + // Record the result of the function. + // NOTE: Intentionally NOT pushing/indexing into the array of mock + // results here to avoid corrupting results data if mockClear() + // is called during the execution of the mock. + // @ts-expect-error reassigning 'incomplete' + mockResult.type = callDidThrowError ? 'throw' : 'return'; + mockResult.value = callDidThrowError ? thrownError : finalReturnValue; + } + + return finalReturnValue; + }, metadata.length || 0); + + const f = this._createMockFunction(metadata, mockConstructor); + + f._isMockFunction = true; + + f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl; + + if (typeof restore === 'function') { + this._spyState.add(restore); + } + + this._mockState.set(f, this._defaultMockState()); + + this._mockConfigRegistry.set(f, this._defaultMockConfig()); + + Object.defineProperty(f, 'mock', { + configurable: false, + enumerable: true, + get: () => this._ensureMockState(f), + set: val => this._mockState.set(f, val) + }); + + f.mockClear = () => { + this._mockState.delete(f); + + return f; + }; + + f.mockReset = () => { + f.mockClear(); + + this._mockConfigRegistry.delete(f); + + return f; + }; + + f.mockRestore = () => { + f.mockReset(); + return restore ? restore() : undefined; + }; + + f.mockReturnValueOnce = ( + value // next function call will return this value or default return value + ) => f.mockImplementationOnce(() => value); + + f.mockResolvedValueOnce = value => + f.mockImplementationOnce(() => Promise.resolve(value)); + + f.mockRejectedValueOnce = value => + f.mockImplementationOnce(() => Promise.reject(value)); + + f.mockReturnValue = ( + value // next function call will return specified return value or this one + ) => f.mockImplementation(() => value); + + f.mockResolvedValue = value => + f.mockImplementation(() => Promise.resolve(value)); + + f.mockRejectedValue = value => + f.mockImplementation(() => Promise.reject(value)); + + f.mockImplementationOnce = fn => { + // next function call will use this mock implementation return value + // or default mock implementation return value + const mockConfig = this._ensureMockConfig(f); + + mockConfig.specificMockImpls.push(fn); + return f; + }; + + f.mockImplementation = fn => { + // next function call will use mock implementation return value + const mockConfig = this._ensureMockConfig(f); + + mockConfig.mockImpl = fn; + return f; + }; + + f.mockReturnThis = () => + f.mockImplementation(function () { + return this; + }); + + f.mockName = name => { + if (name) { + const mockConfig = this._ensureMockConfig(f); + + mockConfig.mockName = name; + } + + return f; + }; + + f.getMockName = () => { + const mockConfig = this._ensureMockConfig(f); + + return mockConfig.mockName || 'jest.fn()'; + }; + + if (metadata.mockImpl) { + f.mockImplementation(metadata.mockImpl); + } + + return f; + } else { + const unknownType = metadata.type || 'undefined type'; + throw new Error(`Unrecognized type ${unknownType}`); + } + } + + _createMockFunction(metadata, mockConstructor) { + let name = metadata.name; + + if (!name) { + return mockConstructor; + } // Preserve `name` property of mocked function. + + const boundFunctionPrefix = 'bound '; + let bindCall = ''; // if-do-while for perf reasons. The common case is for the if to fail. + + if (name && name.startsWith(boundFunctionPrefix)) { + do { + name = name.substring(boundFunctionPrefix.length); // Call bind() just to alter the function name. + + bindCall = '.bind(null)'; + } while (name && name.startsWith(boundFunctionPrefix)); + } // Special case functions named `mockConstructor` to guard for infinite + // loops. + + if (name === MOCK_CONSTRUCTOR_NAME) { + return mockConstructor; + } + + if ( + // It's a syntax error to define functions with a reserved keyword + // as name. + RESERVED_KEYWORDS.has(name) || // It's also a syntax error to define functions with a name that starts with a number + /^\d/.test(name) + ) { + name = `$${name}`; + } // It's also a syntax error to define a function with a reserved character + // as part of it's name. + + if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { + name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$'); + } + + const body = + `return function ${name}() {` + + ` return ${MOCK_CONSTRUCTOR_NAME}.apply(this,arguments);` + + `}${bindCall}`; + const createConstructor = new this._environmentGlobal.Function( + MOCK_CONSTRUCTOR_NAME, + body + ); + return createConstructor(mockConstructor); + } + + _generateMock(metadata, callbacks, refs) { + // metadata not compatible but it's the same type, maybe problem with + // overloading of _makeComponent and not _generateMock? + // @ts-expect-error - unsure why TSC complains here? + const mock = this._makeComponent(metadata); + + if (metadata.refID != null) { + refs[metadata.refID] = mock; + } + + this._getSlots(metadata.members).forEach(slot => { + const slotMetadata = (metadata.members && metadata.members[slot]) || {}; + + if (slotMetadata.ref != null) { + callbacks.push( + (function (ref) { + return () => (mock[slot] = refs[ref]); + })(slotMetadata.ref) + ); + } else { + mock[slot] = this._generateMock(slotMetadata, callbacks, refs); + } + }); + + if ( + metadata.type !== 'undefined' && + metadata.type !== 'null' && + mock.prototype && + typeof mock.prototype === 'object' + ) { + mock.prototype.constructor = mock; + } + + return mock; + } + /** + * @see README.md + * @param metadata Metadata for the mock in the schema returned by the + * getMetadata method of this module. + */ + + generateFromMetadata(metadata) { + const callbacks = []; + const refs = {}; + + const mock = this._generateMock(metadata, callbacks, refs); + + callbacks.forEach(setter => setter()); + return mock; + } + /** + * @see README.md + * @param component The component for which to retrieve metadata. + */ + + getMetadata(component, _refs) { + const refs = _refs || new Map(); + const ref = refs.get(component); + + if (ref != null) { + return { + ref + }; + } + + const type = getType(component); + + if (!type) { + return null; + } + + const metadata = { + type + }; + + if ( + type === 'constant' || + type === 'collection' || + type === 'undefined' || + type === 'null' + ) { + metadata.value = component; + return metadata; + } else if (type === 'function') { + // @ts-expect-error component is a function so it has a name, but not + // necessarily a string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#function_names_in_classes + const componentName = component.name; + + if (typeof componentName === 'string') { + metadata.name = componentName; + } + + if (this.isMockFunction(component)) { + metadata.mockImpl = component.getMockImplementation(); + } + } + + metadata.refID = refs.size; + refs.set(component, metadata.refID); + let members = null; // Leave arrays alone + + if (type !== 'array') { + // @ts-expect-error component is object + this._getSlots(component).forEach(slot => { + if ( + type === 'function' && + this.isMockFunction(component) && + slot.match(/^mock/) + ) { + return; + } // @ts-expect-error no index signature + + const slotMetadata = this.getMetadata(component[slot], refs); + + if (slotMetadata) { + if (!members) { + members = {}; + } + + members[slot] = slotMetadata; + } + }); + } + + if (members) { + metadata.members = members; + } + + return metadata; + } + + isMockFunction(fn) { + return fn != null && fn._isMockFunction === true; + } + + fn(implementation) { + const length = implementation ? implementation.length : 0; + + const fn = this._makeComponent({ + length, + type: 'function' + }); + + if (implementation) { + fn.mockImplementation(implementation); + } + + return fn; + } + + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + spyOn(object, methodName, accessType) { + if (accessType) { + return this._spyOnProperty(object, methodName, accessType); + } + + if (typeof object !== 'object' && typeof object !== 'function') { + throw new Error( + `Cannot spyOn on a primitive value; ${this._typeOf(object)} given` + ); + } + + const original = object[methodName]; + + if (!this.isMockFunction(original)) { + if (typeof original !== 'function') { + throw new Error( + `Cannot spy the ${String( + methodName + )} property because it is not a function; ${this._typeOf( + original + )} given instead` + ); + } + + const isMethodOwner = Object.prototype.hasOwnProperty.call( + object, + methodName + ); + let descriptor = Object.getOwnPropertyDescriptor(object, methodName); + let proto = Object.getPrototypeOf(object); + + while (!descriptor && proto !== null) { + descriptor = Object.getOwnPropertyDescriptor(proto, methodName); + proto = Object.getPrototypeOf(proto); + } + + let mock; + + if (descriptor && descriptor.get) { + const originalGet = descriptor.get; + mock = this._makeComponent( + { + type: 'function' + }, + () => { + descriptor.get = originalGet; + Object.defineProperty(object, methodName, descriptor); + } + ); + + descriptor.get = () => mock; + + Object.defineProperty(object, methodName, descriptor); + } else { + mock = this._makeComponent( + { + type: 'function' + }, + () => { + if (isMethodOwner) { + object[methodName] = original; + } else { + delete object[methodName]; + } + } + ); // @ts-expect-error overriding original method with a Mock + + object[methodName] = mock; + } + + mock.mockImplementation(function () { + return original.apply(this, arguments); + }); + } + + return object[methodName]; + } + + _spyOnProperty(obj, propertyName, accessType = 'get') { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new Error( + `Cannot spyOn on a primitive value; ${this._typeOf(obj)} given` + ); + } + + if (!obj) { + throw new Error( + `spyOn could not find an object to spy upon for ${String(propertyName)}` + ); + } + + if (!propertyName) { + throw new Error('No property name supplied'); + } + + let descriptor = Object.getOwnPropertyDescriptor(obj, propertyName); + let proto = Object.getPrototypeOf(obj); + + while (!descriptor && proto !== null) { + descriptor = Object.getOwnPropertyDescriptor(proto, propertyName); + proto = Object.getPrototypeOf(proto); + } + + if (!descriptor) { + throw new Error(`${String(propertyName)} property does not exist`); + } + + if (!descriptor.configurable) { + throw new Error(`${String(propertyName)} is not declared configurable`); + } + + if (!descriptor[accessType]) { + throw new Error( + `Property ${String( + propertyName + )} does not have access type ${accessType}` + ); + } + + const original = descriptor[accessType]; + + if (!this.isMockFunction(original)) { + if (typeof original !== 'function') { + throw new Error( + `Cannot spy the ${String( + propertyName + )} property because it is not a function; ${this._typeOf( + original + )} given instead` + ); + } + + descriptor[accessType] = this._makeComponent( + { + type: 'function' + }, + () => { + // @ts-expect-error: mock is assignable + descriptor[accessType] = original; + Object.defineProperty(obj, propertyName, descriptor); + } + ); + descriptor[accessType].mockImplementation(function () { + // @ts-expect-error - wrong context + return original.apply(this, arguments); + }); + } + + Object.defineProperty(obj, propertyName, descriptor); + return descriptor[accessType]; + } + + clearAllMocks() { + this._mockState = new WeakMap(); + } + + resetAllMocks() { + this._mockConfigRegistry = new WeakMap(); + this._mockState = new WeakMap(); + } + + restoreAllMocks() { + this._spyState.forEach(restore => restore()); + + this._spyState = new Set(); + } + + _typeOf(value) { + return value == null ? `${value}` : typeof value; + } + + mocked(source, _options) { + return source; + } +} + +exports.ModuleMocker = ModuleMocker; +const JestMock = new ModuleMocker(globalThis); +const fn = JestMock.fn.bind(JestMock); +exports.fn = fn; +const spyOn = JestMock.spyOn.bind(JestMock); +exports.spyOn = spyOn; +const mocked = JestMock.mocked.bind(JestMock); +exports.mocked = mocked; diff --git a/node_modules/jest-mock/package.json b/node_modules/jest-mock/package.json new file mode 100644 index 0000000..2ab84f7 --- /dev/null +++ b/node_modules/jest-mock/package.json @@ -0,0 +1,68 @@ +{ + "_from": "jest-mock@^29.0.1", + "_id": "jest-mock@29.0.1", + "_inBundle": false, + "_integrity": "sha512-i1yTceg2GKJwUNZFjIzrH7Y74fN1SKJWxQX/Vu3LT4TiJerFARH5l+4URNyapZ+DNpchHYrGOP2deVbn3ma8JA==", + "_location": "/jest-mock", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-mock@^29.0.1", + "name": "jest-mock", + "escapedName": "jest-mock", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/environment", + "/@jest/fake-timers", + "/@jest/globals", + "/jest-environment-node", + "/jest-runtime" + ], + "_resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.0.1.tgz", + "_shasum": "12e1b137035365b022ccdb8fd67d476cd4d4bfad", + "_spec": "jest-mock@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/environment", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/types": "^29.0.1", + "@types/node": "*" + }, + "deprecated": false, + "description": "**Note:** More details on user side API can be found in [Jest documentation](https://jestjs.io/docs/mock-function-api).", + "devDependencies": { + "@tsd/typescript": "~4.7.4", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-mock", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-mock" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-pnp-resolver/README.md b/node_modules/jest-pnp-resolver/README.md new file mode 100644 index 0000000..20bf42a --- /dev/null +++ b/node_modules/jest-pnp-resolver/README.md @@ -0,0 +1,34 @@ +# [Plug'n'Play](https://github.com/yarnpkg/rfcs/pull/101) resolver for Jest + +[![npm version](https://img.shields.io/npm/v/jest-pnp-resolver.svg)](https://www.npmjs.com/package/jest-pnp-resolver) +[![node version](https://img.shields.io/node/v/jest-pnp-resolver.svg)](https://www.npmjs.com/package/jest-pnp-resolver) + +*This plugin is also available for Rollup ([rollup-plugin-pnp-resolve](https://github.com/arcanis/rollup-plugin-pnp-resolve)), TypeScript ([ts-pnp](https://github.com/arcanis/ts-pnp)), and Webpack ([pnp-webpack-plugin](https://github.com/arcanis/pnp-webpack-plugin))* + +## Installation + +``` +yarn add -D jest-pnp-resolver +``` + +## Usage + +As of `jest@^24.4.0` you don't need to manually add this package anymore. The default resolver will already use PnP. + +Simply add the resolver to your configuration. For example, a minimal `jest.config.js` would be as such: + +```js +module.exports = { + resolver: require.resolve(`jest-pnp-resolver`) +}; +``` + +## License (MIT) + +> **Copyright © 2016 Maël Nison** +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jest-pnp-resolver/createRequire.js b/node_modules/jest-pnp-resolver/createRequire.js new file mode 100644 index 0000000..7da60d6 --- /dev/null +++ b/node_modules/jest-pnp-resolver/createRequire.js @@ -0,0 +1,25 @@ +const nativeModule = require(`module`); + +module.exports = (filename) => { + // Added in Node v12.2.0 + if (nativeModule.createRequire) { + return nativeModule.createRequire(filename); + } + + // Added in Node v10.12.0 and deprecated since Node v12.2.0 + if (nativeModule.createRequireFromPath) { + return nativeModule.createRequireFromPath(filename); + } + + // Polyfill + return _createRequire(filename); +}; + +// Polyfill +function _createRequire (filename) { + const mod = new nativeModule.Module(filename, null) + mod.filename = filename + mod.paths = nativeModule.Module._nodeModulePaths(path.dirname(filename)) + mod._compile(`module.exports = require;`, filename) + return mod.exports +} diff --git a/node_modules/jest-pnp-resolver/getDefaultResolver.js b/node_modules/jest-pnp-resolver/getDefaultResolver.js new file mode 100644 index 0000000..ab90dbc --- /dev/null +++ b/node_modules/jest-pnp-resolver/getDefaultResolver.js @@ -0,0 +1,13 @@ +let defaultResolver; + +module.exports = () => { + if (!defaultResolver) { + try { + defaultResolver = require(`jest-resolve/build/defaultResolver`).default; + } catch (error) { + defaultResolver = require(`jest-resolve/build/default_resolver`).default; + } + } + + return defaultResolver; +}; diff --git a/node_modules/jest-pnp-resolver/index.d.ts b/node_modules/jest-pnp-resolver/index.d.ts new file mode 100644 index 0000000..1acbbac --- /dev/null +++ b/node_modules/jest-pnp-resolver/index.d.ts @@ -0,0 +1,10 @@ +type JestResolverOptions = { + basedir: string; + defaultResolver: (request: string, opts: any) => string, + extensions?: Array, +}; + +export default function resolve( + request: string, + options: JestResolverOptions, +): string; diff --git a/node_modules/jest-pnp-resolver/index.js b/node_modules/jest-pnp-resolver/index.js new file mode 100644 index 0000000..a61a577 --- /dev/null +++ b/node_modules/jest-pnp-resolver/index.js @@ -0,0 +1,49 @@ +let globalPnpApi; +try { + globalPnpApi = require(`pnpapi`); +} catch { + // Just ignore if we don't have a global PnP instance - perhaps + // we'll eventually find one at runtime due to multi-tree +} + +const createRequire = require(`./createRequire`); +const getDefaultResolver = require(`./getDefaultResolver`); + +module.exports = (request, options) => { + const {basedir, defaultResolver, extensions} = options; + + if (process.versions.pnp) { + let pnpApi = globalPnpApi; + + // While technically it would be more correct to run this code + // everytime (since they file being run *may* belong to a + // different dependency tree than the one owning Jest), in + // practice this doesn't happen anywhere else than on the Jest + // repository itself (in the test env). So in order to preserve + // the performances, we can afford a slight incoherence here. + if (!pnpApi) { + try { + const baseReq = createRequire(`${basedir}/internal.js`); + pnpApi = baseReq(`pnpapi`); + } catch { + // The file isn't part of a PnP dependency tree, so we can + // just use the default Jest resolver. + } + } + + if (pnpApi) { + const resolution = pnpApi.resolveRequest(request, `${basedir}/`, {extensions}); + + // When the request is a native module, Jest expects to get the string back unmodified, but pnp returns null instead. + if (resolution === null) + return request; + + return resolution; + } + } + + if (!defaultResolver) + defaultResolver = getDefaultResolver(); + + return defaultResolver(request, {...options, allowPnp: false}); +}; diff --git a/node_modules/jest-pnp-resolver/package.json b/node_modules/jest-pnp-resolver/package.json new file mode 100644 index 0000000..e90a1e0 --- /dev/null +++ b/node_modules/jest-pnp-resolver/package.json @@ -0,0 +1,56 @@ +{ + "_from": "jest-pnp-resolver@^1.2.2", + "_id": "jest-pnp-resolver@1.2.2", + "_inBundle": false, + "_integrity": "sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==", + "_location": "/jest-pnp-resolver", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-pnp-resolver@^1.2.2", + "name": "jest-pnp-resolver", + "escapedName": "jest-pnp-resolver", + "rawSpec": "^1.2.2", + "saveSpec": null, + "fetchSpec": "^1.2.2" + }, + "_requiredBy": [ + "/jest-resolve" + ], + "_resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz", + "_shasum": "b704ac0ae028a89108a4d040b3f919dfddc8e33c", + "_spec": "jest-pnp-resolver@^1.2.2", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-resolve", + "bugs": { + "url": "https://github.com/arcanis/jest-pnp-resolver/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "plug'n'play resolver for Webpack", + "engines": { + "node": ">=6" + }, + "homepage": "https://github.com/arcanis/jest-pnp-resolver", + "keywords": [ + "jest", + "yarn", + "plugnplay", + "pnp" + ], + "license": "MIT", + "name": "jest-pnp-resolver", + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/arcanis/jest-pnp-resolver.git" + }, + "version": "1.2.2" +} diff --git a/node_modules/jest-regex-util/LICENSE b/node_modules/jest-regex-util/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-regex-util/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-regex-util/build/index.d.ts b/node_modules/jest-regex-util/build/index.d.ts new file mode 100644 index 0000000..018afa6 --- /dev/null +++ b/node_modules/jest-regex-util/build/index.d.ts @@ -0,0 +1,20 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +export declare const escapePathForRegex: (dir: string) => string; + +export declare const escapeStrForRegex: (string: string) => string; + +export declare const replacePathSepForRegex: (string: string) => string; + +export {}; diff --git a/node_modules/jest-regex-util/build/index.js b/node_modules/jest-regex-util/build/index.js new file mode 100644 index 0000000..114b73b --- /dev/null +++ b/node_modules/jest-regex-util/build/index.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.replacePathSepForRegex = + exports.escapeStrForRegex = + exports.escapePathForRegex = + void 0; + +var _path = require('path'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +const escapePathForRegex = dir => { + if (_path.sep === '\\') { + // Replace "\" with "/" so it's not escaped by escapeStrForRegex. + // replacePathSepForRegex will convert it back. + dir = dir.replace(/\\/g, '/'); + } + + return replacePathSepForRegex(escapeStrForRegex(dir)); +}; + +exports.escapePathForRegex = escapePathForRegex; + +const escapeStrForRegex = string => + string.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&'); + +exports.escapeStrForRegex = escapeStrForRegex; + +const replacePathSepForRegex = string => { + if (_path.sep === '\\') { + return string.replace( + /(\/|(.)?\\(?![[\]{}()*+?.^$|\\]))/g, + (_match, _, p2) => (p2 && p2 !== '\\' ? `${p2}\\\\` : '\\\\') + ); + } + + return string; +}; + +exports.replacePathSepForRegex = replacePathSepForRegex; diff --git a/node_modules/jest-regex-util/package.json b/node_modules/jest-regex-util/package.json new file mode 100644 index 0000000..9e1f5a1 --- /dev/null +++ b/node_modules/jest-regex-util/package.json @@ -0,0 +1,63 @@ +{ + "_from": "jest-regex-util@^29.0.0", + "_id": "jest-regex-util@29.0.0", + "_inBundle": false, + "_integrity": "sha512-BV7VW7Sy0fInHWN93MMPtlClweYv2qrSCwfeFWmpribGZtQPWNvRSq9XOVgOEjU1iBGRKXUZil0o2AH7Iy9Lug==", + "_location": "/jest-regex-util", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-regex-util@^29.0.0", + "name": "jest-regex-util", + "escapedName": "jest-regex-util", + "rawSpec": "^29.0.0", + "saveSpec": null, + "fetchSpec": "^29.0.0" + }, + "_requiredBy": [ + "/@jest/core", + "/@jest/transform", + "/jest-config", + "/jest-haste-map", + "/jest-resolve-dependencies", + "/jest-runtime" + ], + "_resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.0.0.tgz", + "_shasum": "b442987f688289df8eb6c16fa8df488b4cd007de", + "_spec": "jest-regex-util@^29.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "devDependencies": { + "@types/node": "*" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "75006e46c76f6fda14bbc0548f86edb2ba087cd2", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-regex-util", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-regex-util" + }, + "types": "./build/index.d.ts", + "version": "29.0.0" +} diff --git a/node_modules/jest-resolve-dependencies/LICENSE b/node_modules/jest-resolve-dependencies/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-resolve-dependencies/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-resolve-dependencies/build/index.d.ts b/node_modules/jest-resolve-dependencies/build/index.d.ts new file mode 100644 index 0000000..df6ee5c --- /dev/null +++ b/node_modules/jest-resolve-dependencies/build/index.d.ts @@ -0,0 +1,43 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {default as default_2} from 'jest-resolve'; +import type {FS} from 'jest-haste-map'; +import type {ResolveModuleConfig} from 'jest-resolve'; +import {SnapshotResolver} from 'jest-snapshot'; + +/** + * DependencyResolver is used to resolve the direct dependencies of a module or + * to retrieve a list of all transitive inverse dependencies. + */ +export declare class DependencyResolver { + private _hasteFS; + private _resolver; + private _snapshotResolver; + constructor( + resolver: default_2, + hasteFS: FS, + snapshotResolver: SnapshotResolver, + ); + resolve(file: string, options?: ResolveModuleConfig): Array; + resolveInverseModuleMap( + paths: Set, + filter: (file: string) => boolean, + options?: ResolveModuleConfig, + ): Array; + resolveInverse( + paths: Set, + filter: (file: string) => boolean, + options?: ResolveModuleConfig, + ): Array; +} + +export declare type ResolvedModule = { + file: string; + dependencies: Array; +}; + +export {}; diff --git a/node_modules/jest-resolve-dependencies/build/index.js b/node_modules/jest-resolve-dependencies/build/index.js new file mode 100644 index 0000000..df9fcd2 --- /dev/null +++ b/node_modules/jest-resolve-dependencies/build/index.js @@ -0,0 +1,229 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.DependencyResolver = void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _jestSnapshot() { + const data = require('jest-snapshot'); + + _jestSnapshot = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * DependencyResolver is used to resolve the direct dependencies of a module or + * to retrieve a list of all transitive inverse dependencies. + */ +class DependencyResolver { + _hasteFS; + _resolver; + _snapshotResolver; + + constructor(resolver, hasteFS, snapshotResolver) { + this._resolver = resolver; + this._hasteFS = hasteFS; + this._snapshotResolver = snapshotResolver; + } + + resolve(file, options) { + const dependencies = this._hasteFS.getDependencies(file); + + if (!dependencies) { + return []; + } + + return dependencies.reduce((acc, dependency) => { + if (this._resolver.isCoreModule(dependency)) { + return acc; + } + + let resolvedDependency; + let resolvedMockDependency; + + try { + resolvedDependency = this._resolver.resolveModule( + file, + dependency, + options + ); + } catch { + try { + resolvedDependency = this._resolver.getMockModule(file, dependency); + } catch { + // leave resolvedDependency as undefined if nothing can be found + } + } + + if (!resolvedDependency) { + return acc; + } + + acc.push(resolvedDependency); // If we resolve a dependency, then look for a mock dependency + // of the same name in that dependency's directory. + + try { + resolvedMockDependency = this._resolver.getMockModule( + resolvedDependency, + path().basename(dependency) + ); + } catch { + // leave resolvedMockDependency as undefined if nothing can be found + } + + if (resolvedMockDependency) { + const dependencyMockDir = path().resolve( + path().dirname(resolvedDependency), + '__mocks__' + ); + resolvedMockDependency = path().resolve(resolvedMockDependency); // make sure mock is in the correct directory + + if (dependencyMockDir === path().dirname(resolvedMockDependency)) { + acc.push(resolvedMockDependency); + } + } + + return acc; + }, []); + } + + resolveInverseModuleMap(paths, filter, options) { + if (!paths.size) { + return []; + } + + const collectModules = (related, moduleMap, changed) => { + const visitedModules = new Set(); + const result = []; + + while (changed.size) { + changed = new Set( + moduleMap.reduce((acc, module) => { + if ( + visitedModules.has(module.file) || + !module.dependencies.some(dep => changed.has(dep)) + ) { + return acc; + } + + const file = module.file; + + if (filter(file)) { + result.push(module); + related.delete(file); + } + + visitedModules.add(file); + acc.push(file); + return acc; + }, []) + ); + } + + return result.concat( + Array.from(related).map(file => ({ + dependencies: [], + file + })) + ); + }; + + const relatedPaths = new Set(); + const changed = new Set(); + + for (const path of paths) { + if (this._hasteFS.exists(path)) { + const modulePath = (0, _jestSnapshot().isSnapshotPath)(path) + ? this._snapshotResolver.resolveTestPath(path) + : path; + changed.add(modulePath); + + if (filter(modulePath)) { + relatedPaths.add(modulePath); + } + } + } + + const modules = []; + + for (const file of this._hasteFS.getAbsoluteFileIterator()) { + modules.push({ + dependencies: this.resolve(file, options), + file + }); + } + + return collectModules(relatedPaths, modules, changed); + } + + resolveInverse(paths, filter, options) { + return this.resolveInverseModuleMap(paths, filter, options).map( + module => module.file + ); + } +} + +exports.DependencyResolver = DependencyResolver; diff --git a/node_modules/jest-resolve-dependencies/package.json b/node_modules/jest-resolve-dependencies/package.json new file mode 100644 index 0000000..631d062 --- /dev/null +++ b/node_modules/jest-resolve-dependencies/package.json @@ -0,0 +1,66 @@ +{ + "_from": "jest-resolve-dependencies@^29.0.1", + "_id": "jest-resolve-dependencies@29.0.1", + "_inBundle": false, + "_integrity": "sha512-fUGcYlSc1NzNz+tsHDjjG0rclw6blJcFZsLEsezxm/n54bAm9HFvJxgBuCV1CJQoPtIx6AfR+tXkR9lpWJs2LQ==", + "_location": "/jest-resolve-dependencies", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-resolve-dependencies@^29.0.1", + "name": "jest-resolve-dependencies", + "escapedName": "jest-resolve-dependencies", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core" + ], + "_resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.0.1.tgz", + "_shasum": "c41b88380c8ea178ce72a750029b5f3d5f65cb94", + "_spec": "jest-resolve-dependencies@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "jest-regex-util": "^29.0.0", + "jest-snapshot": "^29.0.1" + }, + "deprecated": false, + "devDependencies": { + "@jest/test-utils": "^29.0.1", + "@jest/types": "^29.0.1", + "jest-haste-map": "^29.0.1", + "jest-resolve": "^29.0.1", + "jest-runtime": "^29.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-resolve-dependencies", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-resolve-dependencies" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-resolve/LICENSE b/node_modules/jest-resolve/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-resolve/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-resolve/build/ModuleNotFoundError.js b/node_modules/jest-resolve/build/ModuleNotFoundError.js new file mode 100644 index 0000000..0b8482f --- /dev/null +++ b/node_modules/jest-resolve/build/ModuleNotFoundError.js @@ -0,0 +1,125 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _slash() { + const data = _interopRequireDefault(require('slash')); + + _slash = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class ModuleNotFoundError extends Error { + code = 'MODULE_NOT_FOUND'; + hint; + requireStack; + siblingWithSimilarExtensionFound; + moduleName; + _originalMessage; + + constructor(message, moduleName) { + super(message); + this._originalMessage = message; + this.moduleName = moduleName; + } + + buildMessage(rootDir) { + if (!this._originalMessage) { + this._originalMessage = this.message || ''; + } + + let message = this._originalMessage; + + if (this.requireStack?.length && this.requireStack.length > 1) { + message += ` + +Require stack: + ${this.requireStack + .map(p => p.replace(`${rootDir}${path().sep}`, '')) + .map(_slash().default) + .join('\n ')} +`; + } + + if (this.hint) { + message += this.hint; + } + + this.message = message; + } + + static duckType(error) { + error.buildMessage = ModuleNotFoundError.prototype.buildMessage; + return error; + } +} + +exports.default = ModuleNotFoundError; diff --git a/node_modules/jest-resolve/build/defaultResolver.js b/node_modules/jest-resolve/build/defaultResolver.js new file mode 100644 index 0000000..a19986b --- /dev/null +++ b/node_modules/jest-resolve/build/defaultResolver.js @@ -0,0 +1,182 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _path() { + const data = require('path'); + + _path = function () { + return data; + }; + + return data; +} + +function _jestPnpResolver() { + const data = _interopRequireDefault(require('jest-pnp-resolver')); + + _jestPnpResolver = function () { + return data; + }; + + return data; +} + +function _resolve() { + const data = require('resolve'); + + _resolve = function () { + return data; + }; + + return data; +} + +var _resolve2 = require('resolve.exports'); + +var _fileWalkers = require('./fileWalkers'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const defaultResolver = (path, options) => { + // Yarn 2 adds support to `resolve` automatically so the pnpResolver is only + // needed for Yarn 1 which implements version 1 of the pnp spec + if (process.versions.pnp === '1') { + return (0, _jestPnpResolver().default)(path, options); + } + + const resolveOptions = { + ...options, + isDirectory: _fileWalkers.isDirectory, + isFile: _fileWalkers.isFile, + preserveSymlinks: false, + readPackageSync, + realpathSync: _fileWalkers.realpathSync + }; + const pathToResolve = getPathInModule(path, resolveOptions); + const result = // if `getPathInModule` doesn't change the path, attempt to resolve it + pathToResolve === path + ? (0, _resolve().sync)(pathToResolve, resolveOptions) + : pathToResolve; // Dereference symlinks to ensure we don't create a separate + // module instance depending on how it was referenced. + + return (0, _fileWalkers.realpathSync)(result); +}; + +var _default = defaultResolver; +/* + * helper functions + */ + +exports.default = _default; + +function readPackageSync(_, file) { + return (0, _fileWalkers.readPackageCached)(file); +} + +function getPathInModule(path, options) { + if (shouldIgnoreRequestForExports(path)) { + return path; + } + + const segments = path.split('/'); + let moduleName = segments.shift(); + + if (moduleName) { + // TODO: handle `#` here: https://github.com/facebook/jest/issues/12270 + if (moduleName.startsWith('@')) { + moduleName = `${moduleName}/${segments.shift()}`; + } // self-reference + + const closestPackageJson = (0, _fileWalkers.findClosestPackageJson)( + options.basedir + ); + + if (closestPackageJson) { + const pkg = (0, _fileWalkers.readPackageCached)(closestPackageJson); + + if (pkg.name === moduleName && pkg.exports) { + const subpath = segments.join('/') || '.'; + const resolved = (0, _resolve2.resolve)( + pkg, + subpath, + createResolveOptions(options.conditions) + ); + + if (!resolved) { + throw new Error( + '`exports` exists, but no results - this is a bug in Jest. Please report an issue' + ); + } + + return (0, _path().resolve)( + (0, _path().dirname)(closestPackageJson), + resolved + ); + } + } + + let packageJsonPath = ''; + + try { + packageJsonPath = (0, _resolve().sync)( + `${moduleName}/package.json`, + options + ); + } catch { + // ignore if package.json cannot be found + } + + if (packageJsonPath && (0, _fileWalkers.isFile)(packageJsonPath)) { + const pkg = (0, _fileWalkers.readPackageCached)(packageJsonPath); + + if (pkg.exports) { + const subpath = segments.join('/') || '.'; + const resolved = (0, _resolve2.resolve)( + pkg, + subpath, + createResolveOptions(options.conditions) + ); + + if (!resolved) { + throw new Error( + '`exports` exists, but no results - this is a bug in Jest. Please report an issue' + ); + } + + return (0, _path().resolve)( + (0, _path().dirname)(packageJsonPath), + resolved + ); + } + } + } + + return path; +} + +function createResolveOptions(conditions) { + return conditions + ? { + conditions, + unsafe: true + } // no conditions were passed - let's assume this is Jest internal and it should be `require` + : { + browser: false, + require: true + }; +} // if it's a relative import or an absolute path, exports are ignored + +const shouldIgnoreRequestForExports = path => + path.startsWith('.') || (0, _path().isAbsolute)(path); diff --git a/node_modules/jest-resolve/build/fileWalkers.js b/node_modules/jest-resolve/build/fileWalkers.js new file mode 100644 index 0000000..d621fcf --- /dev/null +++ b/node_modules/jest-resolve/build/fileWalkers.js @@ -0,0 +1,214 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.clearFsCache = clearFsCache; +exports.findClosestPackageJson = findClosestPackageJson; +exports.isDirectory = isDirectory; +exports.isFile = isFile; +exports.readPackageCached = readPackageCached; +exports.realpathSync = realpathSync; + +function _path() { + const data = require('path'); + + _path = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function clearFsCache() { + checkedPaths.clear(); + checkedRealpathPaths.clear(); + packageContents.clear(); +} + +var IPathType; + +(function (IPathType) { + IPathType[(IPathType['FILE'] = 1)] = 'FILE'; + IPathType[(IPathType['DIRECTORY'] = 2)] = 'DIRECTORY'; + IPathType[(IPathType['OTHER'] = 3)] = 'OTHER'; +})(IPathType || (IPathType = {})); + +const checkedPaths = new Map(); + +function statSyncCached(path) { + const result = checkedPaths.get(path); + + if (result != null) { + return result; + } + + let stat; + + try { + // @ts-expect-error TS2554 - throwIfNoEntry is only available in recent version of node, but inclusion of the option is a backward compatible no-op. + stat = fs().statSync(path, { + throwIfNoEntry: false + }); + } catch (e) { + if (!(e && (e.code === 'ENOENT' || e.code === 'ENOTDIR'))) { + throw e; + } + } + + if (stat) { + if (stat.isFile() || stat.isFIFO()) { + checkedPaths.set(path, IPathType.FILE); + return IPathType.FILE; + } else if (stat.isDirectory()) { + checkedPaths.set(path, IPathType.DIRECTORY); + return IPathType.DIRECTORY; + } + } + + checkedPaths.set(path, IPathType.OTHER); + return IPathType.OTHER; +} + +const checkedRealpathPaths = new Map(); + +function realpathCached(path) { + let result = checkedRealpathPaths.get(path); + + if (result != null) { + return result; + } + + result = (0, _jestUtil().tryRealpath)(path); + checkedRealpathPaths.set(path, result); + + if (path !== result) { + // also cache the result in case it's ever referenced directly - no reason to `realpath` that as well + checkedRealpathPaths.set(result, result); + } + + return result; +} + +const packageContents = new Map(); + +function readPackageCached(path) { + let result = packageContents.get(path); + + if (result != null) { + return result; + } + + result = JSON.parse(fs().readFileSync(path, 'utf8')); + packageContents.set(path, result); + return result; +} // adapted from +// https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js +// to use cached `fs` calls + +function findClosestPackageJson(start) { + let dir = (0, _path().resolve)('.', start); + + if (!isDirectory(dir)) { + dir = (0, _path().dirname)(dir); + } + + while (true) { + const pkgJsonFile = (0, _path().resolve)(dir, './package.json'); + const hasPackageJson = isFile(pkgJsonFile); + + if (hasPackageJson) { + return pkgJsonFile; + } + + const prevDir = dir; + dir = (0, _path().dirname)(dir); + + if (prevDir === dir) { + return undefined; + } + } +} +/* + * helper functions + */ + +function isFile(file) { + return statSyncCached(file) === IPathType.FILE; +} + +function isDirectory(dir) { + return statSyncCached(dir) === IPathType.DIRECTORY; +} + +function realpathSync(file) { + return realpathCached(file); +} diff --git a/node_modules/jest-resolve/build/index.d.ts b/node_modules/jest-resolve/build/index.d.ts new file mode 100644 index 0000000..0d0af60 --- /dev/null +++ b/node_modules/jest-resolve/build/index.d.ts @@ -0,0 +1,319 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {IModuleMap} from 'jest-haste-map'; + +export declare type AsyncResolver = ( + path: string, + options: ResolverOptions, +) => Promise; + +declare function cachedShouldLoadAsEsm( + path: string, + extensionsToTreatAsEsm: Array, +): boolean; + +declare const defaultResolver: SyncResolver; + +export declare type FindNodeModuleConfig = { + basedir: string; + conditions?: Array; + extensions?: Array; + moduleDirectory?: Array; + paths?: Array; + resolver?: string | null; + rootDir?: string; + throwIfNotFound?: boolean; +}; + +export declare type JestResolver = ResolverSyncObject | ResolverAsyncObject; + +declare interface JSONObject { + [key: string]: JSONValue; +} + +declare type JSONValue = + | string + | number + | boolean + | JSONObject + | Array; + +declare type ModuleNameMapperConfig = { + regex: RegExp; + moduleName: string | Array; +}; + +declare class ModuleNotFoundError extends Error { + code: string; + hint?: string; + requireStack?: Array; + siblingWithSimilarExtensionFound?: boolean; + moduleName?: string; + private _originalMessage?; + constructor(message: string, moduleName?: string); + buildMessage(rootDir: string): void; + static duckType(error: ModuleNotFoundError): ModuleNotFoundError; +} + +/** + * Allows transforming parsed `package.json` contents. + * + * @param pkg - Parsed `package.json` contents. + * @param file - Path to `package.json` file. + * @param dir - Directory that contains the `package.json`. + * + * @returns Transformed `package.json` contents. + */ +export declare type PackageFilter = ( + pkg: PackageJSON, + file: string, + dir: string, +) => PackageJSON; + +export declare type PackageJSON = JSONObject; + +/** + * Allows transforming a path within a package. + * + * @param pkg - Parsed `package.json` contents. + * @param path - Path being resolved. + * @param relativePath - Path relative from the `package.json` location. + * + * @returns Relative path that will be joined from the `package.json` location. + */ +export declare type PathFilter = ( + pkg: PackageJSON, + path: string, + relativePath: string, +) => string; + +export declare type ResolveModuleConfig = { + conditions?: Array; + skipNodeResolution?: boolean; + paths?: Array; +}; + +declare class Resolver { + private readonly _options; + private readonly _moduleMap; + private readonly _moduleIDCache; + private readonly _moduleNameCache; + private readonly _modulePathCache; + private readonly _supportsNativePlatform; + constructor(moduleMap: IModuleMap, options: ResolverConfig); + static ModuleNotFoundError: typeof ModuleNotFoundError; + static tryCastModuleNotFoundError(error: unknown): ModuleNotFoundError | null; + static clearDefaultResolverCache(): void; + static findNodeModule( + path: string, + options: FindNodeModuleConfig, + ): string | null; + static findNodeModuleAsync( + path: string, + options: FindNodeModuleConfig, + ): Promise; + static unstable_shouldLoadAsEsm: typeof cachedShouldLoadAsEsm; + resolveModuleFromDirIfExists( + dirname: string, + moduleName: string, + options?: ResolveModuleConfig, + ): string | null; + resolveModuleFromDirIfExistsAsync( + dirname: string, + moduleName: string, + options?: ResolveModuleConfig, + ): Promise; + resolveModule( + from: string, + moduleName: string, + options?: ResolveModuleConfig, + ): string; + resolveModuleAsync( + from: string, + moduleName: string, + options?: ResolveModuleConfig, + ): Promise; + /** + * _prepareForResolution is shared between the sync and async module resolution + * methods, to try to keep them as DRY as possible. + */ + private _prepareForResolution; + /** + * _getHasteModulePath attempts to return the path to a haste module. + */ + private _getHasteModulePath; + private _throwModNotFoundError; + private _getMapModuleName; + private _isAliasModule; + isCoreModule(moduleName: string): boolean; + getModule(name: string): string | null; + getModulePath(from: string, moduleName: string): string; + getPackage(name: string): string | null; + getMockModule(from: string, name: string): string | null; + getMockModuleAsync(from: string, name: string): Promise; + getModulePaths(from: string): Array; + getModuleID( + virtualMocks: Map, + from: string, + moduleName?: string, + options?: ResolveModuleConfig, + ): string; + getModuleIDAsync( + virtualMocks: Map, + from: string, + moduleName?: string, + options?: ResolveModuleConfig, + ): Promise; + private _getModuleType; + private _getAbsolutePath; + private _getAbsolutePathAsync; + private _getMockPath; + private _getMockPathAsync; + private _getVirtualMockPath; + private _getVirtualMockPathAsync; + private _isModuleResolved; + private _isModuleResolvedAsync; + resolveStubModuleName(from: string, moduleName: string): string | null; + resolveStubModuleNameAsync( + from: string, + moduleName: string, + ): Promise; +} +export default Resolver; + +declare type ResolverAsyncObject = { + sync?: SyncResolver; + async: AsyncResolver; +}; + +declare type ResolverConfig = { + defaultPlatform?: string | null; + extensions: Array; + hasCoreModules: boolean; + moduleDirectories: Array; + moduleNameMapper?: Array | null; + modulePaths?: Array; + platforms?: Array; + resolver?: string | null; + rootDir: string; +}; + +export declare type ResolverOptions = { + /** Directory to begin resolving from. */ + basedir: string; + /** List of export conditions. */ + conditions?: Array; + /** Instance of default resolver. */ + defaultResolver: typeof defaultResolver; + /** List of file extensions to search in order. */ + extensions?: Array; + /** + * List of directory names to be looked up for modules recursively. + * + * @defaultValue + * The default is `['node_modules']`. + */ + moduleDirectory?: Array; + /** + * List of `require.paths` to use if nothing is found in `node_modules`. + * + * @defaultValue + * The default is `undefined`. + */ + paths?: Array; + /** Allows transforming parsed `package.json` contents. */ + packageFilter?: PackageFilter; + /** Allows transforms a path within a package. */ + pathFilter?: PathFilter; + /** Current root directory. */ + rootDir?: string; +}; + +declare type ResolverSyncObject = { + sync: SyncResolver; + async?: AsyncResolver; +}; + +/** + * Finds the runner to use: + * + * 1. looks for jest-runner- relative to project. + * 1. looks for jest-runner- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +export declare const resolveRunner: ( + resolver: string | undefined | null, + { + filePath, + rootDir, + requireResolveFunction, + }: { + filePath: string; + rootDir: string; + requireResolveFunction: (moduleName: string) => string; + }, +) => string; + +export declare const resolveSequencer: ( + resolver: string | undefined | null, + { + filePath, + rootDir, + requireResolveFunction, + }: { + filePath: string; + rootDir: string; + requireResolveFunction: (moduleName: string) => string; + }, +) => string; + +/** + * Finds the test environment to use: + * + * 1. looks for jest-environment- relative to project. + * 1. looks for jest-environment- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +export declare const resolveTestEnvironment: ({ + rootDir, + testEnvironment: filePath, + requireResolveFunction, +}: { + rootDir: string; + testEnvironment: string; + requireResolveFunction: (moduleName: string) => string; +}) => string; + +/** + * Finds the watch plugins to use: + * + * 1. looks for jest-watch- relative to project. + * 1. looks for jest-watch- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +export declare const resolveWatchPlugin: ( + resolver: string | undefined | null, + { + filePath, + rootDir, + requireResolveFunction, + }: { + filePath: string; + rootDir: string; + requireResolveFunction: (moduleName: string) => string; + }, +) => string; + +export declare type SyncResolver = ( + path: string, + options: ResolverOptions, +) => string; + +export {}; diff --git a/node_modules/jest-resolve/build/index.js b/node_modules/jest-resolve/build/index.js new file mode 100644 index 0000000..837877b --- /dev/null +++ b/node_modules/jest-resolve/build/index.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +var _exportNames = {}; +exports.default = void 0; + +var _resolver = _interopRequireDefault(require('./resolver')); + +var _utils = require('./utils'); + +Object.keys(_utils).forEach(function (key) { + if (key === 'default' || key === '__esModule') return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _utils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _utils[key]; + } + }); +}); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var _default = _resolver.default; +exports.default = _default; diff --git a/node_modules/jest-resolve/build/isBuiltinModule.js b/node_modules/jest-resolve/build/isBuiltinModule.js new file mode 100644 index 0000000..cd6a2bc --- /dev/null +++ b/node_modules/jest-resolve/build/isBuiltinModule.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = isBuiltinModule; + +function _module() { + const data = _interopRequireDefault(require('module')); + + _module = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const BUILTIN_MODULES = new Set(_module().default.builtinModules); + +function isBuiltinModule(module) { + return BUILTIN_MODULES.has(module); +} diff --git a/node_modules/jest-resolve/build/nodeModulesPaths.js b/node_modules/jest-resolve/build/nodeModulesPaths.js new file mode 100644 index 0000000..15aae46 --- /dev/null +++ b/node_modules/jest-resolve/build/nodeModulesPaths.js @@ -0,0 +1,128 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = nodeModulesPaths; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * Adapted from: https://github.com/substack/node-resolve + */ +function nodeModulesPaths(basedir, options) { + const modules = + options && options.moduleDirectory + ? Array.from(options.moduleDirectory) + : ['node_modules']; // ensure that `basedir` is an absolute path at this point, + // resolving against the process' current working directory + + const basedirAbs = path().resolve(basedir); + let prefix = '/'; + + if (/^([A-Za-z]:)/.test(basedirAbs)) { + prefix = ''; + } else if (/^\\\\/.test(basedirAbs)) { + prefix = '\\\\'; + } // The node resolution algorithm (as implemented by NodeJS and TypeScript) + // traverses parents of the physical path, not the symlinked path + + let physicalBasedir; + + try { + physicalBasedir = (0, _jestUtil().tryRealpath)(basedirAbs); + } catch { + // realpath can throw, e.g. on mapped drives + physicalBasedir = basedirAbs; + } + + const paths = [physicalBasedir]; + let parsed = path().parse(physicalBasedir); + + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = path().parse(parsed.dir); + } + + const dirs = paths + .reduce( + (dirs, aPath) => + dirs.concat( + modules.map(moduleDir => + path().isAbsolute(moduleDir) + ? aPath === basedirAbs + ? moduleDir + : '' + : path().join(prefix, aPath, moduleDir) + ) + ), + [] + ) + .filter(dir => dir !== ''); + return options.paths ? dirs.concat(options.paths) : dirs; +} diff --git a/node_modules/jest-resolve/build/resolver.js b/node_modules/jest-resolve/build/resolver.js new file mode 100644 index 0000000..23d7625 --- /dev/null +++ b/node_modules/jest-resolve/build/resolver.js @@ -0,0 +1,939 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _slash() { + const data = _interopRequireDefault(require('slash')); + + _slash = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var _ModuleNotFoundError = _interopRequireDefault( + require('./ModuleNotFoundError') +); + +var _defaultResolver = _interopRequireDefault(require('./defaultResolver')); + +var _fileWalkers = require('./fileWalkers'); + +var _isBuiltinModule = _interopRequireDefault(require('./isBuiltinModule')); + +var _nodeModulesPaths = _interopRequireDefault(require('./nodeModulesPaths')); + +var _shouldLoadAsEsm = _interopRequireWildcard(require('./shouldLoadAsEsm')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/prefer-spread-eventually */ +const NATIVE_PLATFORM = 'native'; // We might be inside a symlink. + +const resolvedCwd = (0, _jestUtil().tryRealpath)(process.cwd()); +const {NODE_PATH} = process.env; +const nodePaths = NODE_PATH + ? NODE_PATH.split(path().delimiter) + .filter(Boolean) // The resolver expects absolute paths. + .map(p => path().resolve(resolvedCwd, p)) + : undefined; + +class Resolver { + _options; + _moduleMap; + _moduleIDCache; + _moduleNameCache; + _modulePathCache; + _supportsNativePlatform; + + constructor(moduleMap, options) { + this._options = { + defaultPlatform: options.defaultPlatform, + extensions: options.extensions, + hasCoreModules: + options.hasCoreModules === undefined ? true : options.hasCoreModules, + moduleDirectories: options.moduleDirectories || ['node_modules'], + moduleNameMapper: options.moduleNameMapper, + modulePaths: options.modulePaths, + platforms: options.platforms, + resolver: options.resolver, + rootDir: options.rootDir + }; + this._supportsNativePlatform = options.platforms + ? options.platforms.includes(NATIVE_PLATFORM) + : false; + this._moduleMap = moduleMap; + this._moduleIDCache = new Map(); + this._moduleNameCache = new Map(); + this._modulePathCache = new Map(); + } + + static ModuleNotFoundError = _ModuleNotFoundError.default; + + static tryCastModuleNotFoundError(error) { + if (error instanceof _ModuleNotFoundError.default) { + return error; + } + + const casted = error; + + if (casted.code === 'MODULE_NOT_FOUND') { + return _ModuleNotFoundError.default.duckType(casted); + } + + return null; + } + + static clearDefaultResolverCache() { + (0, _fileWalkers.clearFsCache)(); + (0, _shouldLoadAsEsm.clearCachedLookups)(); + } + + static findNodeModule(path, options) { + const resolverModule = loadResolver(options.resolver); + let resolver = _defaultResolver.default; + + if (typeof resolverModule === 'function') { + resolver = resolverModule; + } else if (typeof resolverModule.sync === 'function') { + resolver = resolverModule.sync; + } + + const paths = options.paths; + + try { + return resolver(path, { + basedir: options.basedir, + conditions: options.conditions, + defaultResolver: _defaultResolver.default, + extensions: options.extensions, + moduleDirectory: options.moduleDirectory, + paths: paths ? (nodePaths || []).concat(paths) : nodePaths, + rootDir: options.rootDir + }); + } catch (e) { + if (options.throwIfNotFound) { + throw e; + } + } + + return null; + } + + static async findNodeModuleAsync(path, options) { + const resolverModule = loadResolver(options.resolver); + let resolver = _defaultResolver.default; + + if (typeof resolverModule === 'function') { + resolver = resolverModule; + } else if ( + typeof resolverModule.async === 'function' || + typeof resolverModule.sync === 'function' + ) { + const asyncOrSync = resolverModule.async || resolverModule.sync; + + if (asyncOrSync == null) { + throw new Error(`Unable to load resolver at ${options.resolver}`); + } + + resolver = asyncOrSync; + } + + const paths = options.paths; + + try { + const result = await resolver(path, { + basedir: options.basedir, + conditions: options.conditions, + defaultResolver: _defaultResolver.default, + extensions: options.extensions, + moduleDirectory: options.moduleDirectory, + paths: paths ? (nodePaths || []).concat(paths) : nodePaths, + rootDir: options.rootDir + }); + return result; + } catch (e) { + if (options.throwIfNotFound) { + throw e; + } + } + + return null; + } // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it + + static unstable_shouldLoadAsEsm = _shouldLoadAsEsm.default; + + resolveModuleFromDirIfExists(dirname, moduleName, options) { + const {extensions, key, moduleDirectory, paths, skipResolution} = + this._prepareForResolution(dirname, moduleName, options); + + let module; // 1. If we have already resolved this module for this directory name, + // return a value from the cache. + + const cacheResult = this._moduleNameCache.get(key); + + if (cacheResult) { + return cacheResult; + } // 2. Check if the module is a haste module. + + module = this.getModule(moduleName); + + if (module) { + this._moduleNameCache.set(key, module); + + return module; + } // 3. Check if the module is a node module and resolve it based on + // the node module resolution algorithm. If skipNodeResolution is given we + // ignore all modules that look like node modules (ie. are not relative + // requires). This enables us to speed up resolution when we build a + // dependency graph because we don't have to look at modules that may not + // exist and aren't mocked. + + const resolveNodeModule = (name, throwIfNotFound = false) => { + // Only skip default resolver + if (this.isCoreModule(name) && !this._options.resolver) { + return name; + } + + return Resolver.findNodeModule(name, { + basedir: dirname, + conditions: options?.conditions, + extensions, + moduleDirectory, + paths, + resolver: this._options.resolver, + rootDir: this._options.rootDir, + throwIfNotFound + }); + }; + + if (!skipResolution) { + module = resolveNodeModule(moduleName, Boolean(process.versions.pnp)); + + if (module) { + this._moduleNameCache.set(key, module); + + return module; + } + } // 4. Resolve "haste packages" which are `package.json` files outside of + // `node_modules` folders anywhere in the file system. + + try { + const hasteModulePath = this._getHasteModulePath(moduleName); + + if (hasteModulePath) { + // try resolving with custom resolver first to support extensions, + // then fallback to require.resolve + const resolvedModule = + resolveNodeModule(hasteModulePath) || + require.resolve(hasteModulePath); + + this._moduleNameCache.set(key, resolvedModule); + + return resolvedModule; + } + } catch {} + + return null; + } + + async resolveModuleFromDirIfExistsAsync(dirname, moduleName, options) { + const {extensions, key, moduleDirectory, paths, skipResolution} = + this._prepareForResolution(dirname, moduleName, options); + + let module; // 1. If we have already resolved this module for this directory name, + // return a value from the cache. + + const cacheResult = this._moduleNameCache.get(key); + + if (cacheResult) { + return cacheResult; + } // 2. Check if the module is a haste module. + + module = this.getModule(moduleName); + + if (module) { + this._moduleNameCache.set(key, module); + + return module; + } // 3. Check if the module is a node module and resolve it based on + // the node module resolution algorithm. If skipNodeResolution is given we + // ignore all modules that look like node modules (ie. are not relative + // requires). This enables us to speed up resolution when we build a + // dependency graph because we don't have to look at modules that may not + // exist and aren't mocked. + + const resolveNodeModule = async (name, throwIfNotFound = false) => { + // Only skip default resolver + if (this.isCoreModule(name) && !this._options.resolver) { + return name; + } + + return await Resolver.findNodeModuleAsync(name, { + basedir: dirname, + conditions: options?.conditions, + extensions, + moduleDirectory, + paths, + resolver: this._options.resolver, + rootDir: this._options.rootDir, + throwIfNotFound + }); + }; + + if (!skipResolution) { + module = await resolveNodeModule( + moduleName, + Boolean(process.versions.pnp) + ); + + if (module) { + this._moduleNameCache.set(key, module); + + return module; + } + } // 4. Resolve "haste packages" which are `package.json` files outside of + // `node_modules` folders anywhere in the file system. + + try { + const hasteModulePath = this._getHasteModulePath(moduleName); + + if (hasteModulePath) { + // try resolving with custom resolver first to support extensions, + // then fallback to require.resolve + const resolvedModule = + (await resolveNodeModule(hasteModulePath)) || // QUESTION: should this be async? + require.resolve(hasteModulePath); + + this._moduleNameCache.set(key, resolvedModule); + + return resolvedModule; + } + } catch {} + + return null; + } + + resolveModule(from, moduleName, options) { + const dirname = path().dirname(from); + const module = + this.resolveStubModuleName(from, moduleName) || + this.resolveModuleFromDirIfExists(dirname, moduleName, options); + if (module) return module; // 5. Throw an error if the module could not be found. `resolve.sync` only + // produces an error based on the dirname but we have the actual current + // module name available. + + this._throwModNotFoundError(from, moduleName); + } + + async resolveModuleAsync(from, moduleName, options) { + const dirname = path().dirname(from); + const module = + (await this.resolveStubModuleNameAsync(from, moduleName)) || + (await this.resolveModuleFromDirIfExistsAsync( + dirname, + moduleName, + options + )); + if (module) return module; // 5. Throw an error if the module could not be found. `resolve` only + // produces an error based on the dirname but we have the actual current + // module name available. + + this._throwModNotFoundError(from, moduleName); + } + /** + * _prepareForResolution is shared between the sync and async module resolution + * methods, to try to keep them as DRY as possible. + */ + + _prepareForResolution(dirname, moduleName, options) { + const paths = options?.paths || this._options.modulePaths; + const moduleDirectory = this._options.moduleDirectories; + const stringifiedOptions = options ? JSON.stringify(options) : ''; + const key = dirname + path().delimiter + moduleName + stringifiedOptions; + const defaultPlatform = this._options.defaultPlatform; + + const extensions = this._options.extensions.slice(); + + if (this._supportsNativePlatform) { + extensions.unshift( + ...this._options.extensions.map(ext => `.${NATIVE_PLATFORM}${ext}`) + ); + } + + if (defaultPlatform) { + extensions.unshift( + ...this._options.extensions.map(ext => `.${defaultPlatform}${ext}`) + ); + } + + const skipResolution = + options && options.skipNodeResolution && !moduleName.includes(path().sep); + return { + extensions, + key, + moduleDirectory, + paths, + skipResolution + }; + } + /** + * _getHasteModulePath attempts to return the path to a haste module. + */ + + _getHasteModulePath(moduleName) { + const parts = moduleName.split('/'); + const hastePackage = this.getPackage(parts.shift()); + + if (hastePackage) { + return path().join.apply( + path(), + [path().dirname(hastePackage)].concat(parts) + ); + } + + return null; + } + + _throwModNotFoundError(from, moduleName) { + const relativePath = + (0, _slash().default)(path().relative(this._options.rootDir, from)) || + '.'; + throw new _ModuleNotFoundError.default( + `Cannot find module '${moduleName}' from '${relativePath}'`, + moduleName + ); + } + + _getMapModuleName(matches) { + return matches + ? moduleName => + moduleName.replace( + /\$([0-9]+)/g, + (_, index) => matches[parseInt(index, 10)] + ) + : moduleName => moduleName; + } + + _isAliasModule(moduleName) { + const moduleNameMapper = this._options.moduleNameMapper; + + if (!moduleNameMapper) { + return false; + } + + return moduleNameMapper.some(({regex}) => regex.test(moduleName)); + } + + isCoreModule(moduleName) { + return ( + this._options.hasCoreModules && + ((0, _isBuiltinModule.default)(moduleName) || + (moduleName.startsWith('node:') && + (0, _isBuiltinModule.default)(moduleName.slice('node:'.length)))) && + !this._isAliasModule(moduleName) + ); + } + + getModule(name) { + return this._moduleMap.getModule( + name, + this._options.defaultPlatform, + this._supportsNativePlatform + ); + } + + getModulePath(from, moduleName) { + if (moduleName[0] !== '.' || path().isAbsolute(moduleName)) { + return moduleName; + } + + return path().normalize(`${path().dirname(from)}/${moduleName}`); + } + + getPackage(name) { + return this._moduleMap.getPackage( + name, + this._options.defaultPlatform, + this._supportsNativePlatform + ); + } + + getMockModule(from, name) { + const mock = this._moduleMap.getMockModule(name); + + if (mock) { + return mock; + } else { + const moduleName = this.resolveStubModuleName(from, name); + + if (moduleName) { + return this.getModule(moduleName) || moduleName; + } + } + + return null; + } + + async getMockModuleAsync(from, name) { + const mock = this._moduleMap.getMockModule(name); + + if (mock) { + return mock; + } else { + const moduleName = await this.resolveStubModuleNameAsync(from, name); + + if (moduleName) { + return this.getModule(moduleName) || moduleName; + } + } + + return null; + } + + getModulePaths(from) { + const cachedModule = this._modulePathCache.get(from); + + if (cachedModule) { + return cachedModule; + } + + const moduleDirectory = this._options.moduleDirectories; + const paths = (0, _nodeModulesPaths.default)(from, { + moduleDirectory + }); + + if (paths[paths.length - 1] === undefined) { + // circumvent node-resolve bug that adds `undefined` as last item. + paths.pop(); + } + + this._modulePathCache.set(from, paths); + + return paths; + } + + getModuleID(virtualMocks, from, moduleName = '', options) { + const stringifiedOptions = options ? JSON.stringify(options) : ''; + const key = from + path().delimiter + moduleName + stringifiedOptions; + + const cachedModuleID = this._moduleIDCache.get(key); + + if (cachedModuleID) { + return cachedModuleID; + } + + const moduleType = this._getModuleType(moduleName); + + const absolutePath = this._getAbsolutePath( + virtualMocks, + from, + moduleName, + options + ); + + const mockPath = this._getMockPath(from, moduleName); + + const sep = path().delimiter; + const id = + moduleType + + sep + + (absolutePath ? absolutePath + sep : '') + + (mockPath ? mockPath + sep : '') + + (stringifiedOptions ? stringifiedOptions + sep : ''); + + this._moduleIDCache.set(key, id); + + return id; + } + + async getModuleIDAsync(virtualMocks, from, moduleName = '', options) { + const stringifiedOptions = options ? JSON.stringify(options) : ''; + const key = from + path().delimiter + moduleName + stringifiedOptions; + + const cachedModuleID = this._moduleIDCache.get(key); + + if (cachedModuleID) { + return cachedModuleID; + } + + if (moduleName.startsWith('data:')) { + return moduleName; + } + + const moduleType = this._getModuleType(moduleName); + + const absolutePath = await this._getAbsolutePathAsync( + virtualMocks, + from, + moduleName, + options + ); + const mockPath = await this._getMockPathAsync(from, moduleName); + const sep = path().delimiter; + const id = + moduleType + + sep + + (absolutePath ? absolutePath + sep : '') + + (mockPath ? mockPath + sep : '') + + (stringifiedOptions ? stringifiedOptions + sep : ''); + + this._moduleIDCache.set(key, id); + + return id; + } + + _getModuleType(moduleName) { + return this.isCoreModule(moduleName) ? 'node' : 'user'; + } + + _getAbsolutePath(virtualMocks, from, moduleName, options) { + if (this.isCoreModule(moduleName)) { + return moduleName; + } + + if (moduleName.startsWith('data:')) { + return moduleName; + } + + return this._isModuleResolved(from, moduleName) + ? this.getModule(moduleName) + : this._getVirtualMockPath(virtualMocks, from, moduleName, options); + } + + async _getAbsolutePathAsync(virtualMocks, from, moduleName, options) { + if (this.isCoreModule(moduleName)) { + return moduleName; + } + + if (moduleName.startsWith('data:')) { + return moduleName; + } + + const isModuleResolved = await this._isModuleResolvedAsync( + from, + moduleName + ); + return isModuleResolved + ? this.getModule(moduleName) + : await this._getVirtualMockPathAsync( + virtualMocks, + from, + moduleName, + options + ); + } + + _getMockPath(from, moduleName) { + return !this.isCoreModule(moduleName) + ? this.getMockModule(from, moduleName) + : null; + } + + async _getMockPathAsync(from, moduleName) { + return !this.isCoreModule(moduleName) + ? await this.getMockModuleAsync(from, moduleName) + : null; + } + + _getVirtualMockPath(virtualMocks, from, moduleName, options) { + const virtualMockPath = this.getModulePath(from, moduleName); + return virtualMocks.get(virtualMockPath) + ? virtualMockPath + : moduleName + ? this.resolveModule(from, moduleName, options) + : from; + } + + async _getVirtualMockPathAsync(virtualMocks, from, moduleName, options) { + const virtualMockPath = this.getModulePath(from, moduleName); + return virtualMocks.get(virtualMockPath) + ? virtualMockPath + : moduleName + ? await this.resolveModuleAsync(from, moduleName, options) + : from; + } + + _isModuleResolved(from, moduleName) { + return !!( + this.getModule(moduleName) || this.getMockModule(from, moduleName) + ); + } + + async _isModuleResolvedAsync(from, moduleName) { + return !!( + this.getModule(moduleName) || + (await this.getMockModuleAsync(from, moduleName)) + ); + } + + resolveStubModuleName(from, moduleName) { + const dirname = path().dirname(from); + + const {extensions, moduleDirectory, paths} = this._prepareForResolution( + dirname, + moduleName + ); + + const moduleNameMapper = this._options.moduleNameMapper; + const resolver = this._options.resolver; + + if (moduleNameMapper) { + for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) { + if (regex.test(moduleName)) { + // Note: once a moduleNameMapper matches the name, it must result + // in a module, or else an error is thrown. + const matches = moduleName.match(regex); + + const mapModuleName = this._getMapModuleName(matches); + + const possibleModuleNames = Array.isArray(mappedModuleName) + ? mappedModuleName + : [mappedModuleName]; + let module = null; + + for (const possibleModuleName of possibleModuleNames) { + const updatedName = mapModuleName(possibleModuleName); + module = + this.getModule(updatedName) || + Resolver.findNodeModule(updatedName, { + basedir: dirname, + extensions, + moduleDirectory, + paths, + resolver, + rootDir: this._options.rootDir + }); + + if (module) { + break; + } + } + + if (!module) { + throw createNoMappedModuleFoundError( + moduleName, + mapModuleName, + mappedModuleName, + regex, + resolver + ); + } + + return module; + } + } + } + + return null; + } + + async resolveStubModuleNameAsync(from, moduleName) { + const dirname = path().dirname(from); + + const {extensions, moduleDirectory, paths} = this._prepareForResolution( + dirname, + moduleName + ); + + const moduleNameMapper = this._options.moduleNameMapper; + const resolver = this._options.resolver; + + if (moduleNameMapper) { + for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) { + if (regex.test(moduleName)) { + // Note: once a moduleNameMapper matches the name, it must result + // in a module, or else an error is thrown. + const matches = moduleName.match(regex); + + const mapModuleName = this._getMapModuleName(matches); + + const possibleModuleNames = Array.isArray(mappedModuleName) + ? mappedModuleName + : [mappedModuleName]; + let module = null; + + for (const possibleModuleName of possibleModuleNames) { + const updatedName = mapModuleName(possibleModuleName); + module = + this.getModule(updatedName) || + (await Resolver.findNodeModuleAsync(updatedName, { + basedir: dirname, + extensions, + moduleDirectory, + paths, + resolver, + rootDir: this._options.rootDir + })); + + if (module) { + break; + } + } + + if (!module) { + throw createNoMappedModuleFoundError( + moduleName, + mapModuleName, + mappedModuleName, + regex, + resolver + ); + } + + return module; + } + } + } + + return null; + } +} + +exports.default = Resolver; + +const createNoMappedModuleFoundError = ( + moduleName, + mapModuleName, + mappedModuleName, + regex, + resolver +) => { + const mappedAs = Array.isArray(mappedModuleName) + ? JSON.stringify(mappedModuleName.map(mapModuleName), null, 2) + : mappedModuleName; + const original = Array.isArray(mappedModuleName) + ? `${ + JSON.stringify(mappedModuleName, null, 6) // using 6 because of misalignment when nested below + .slice(0, -1) + ' '.repeat(4) + }]` /// align last bracket correctly as well + : mappedModuleName; + const error = new Error( + _chalk().default.red(`${_chalk().default.bold('Configuration error')}: + +Could not locate module ${_chalk().default.bold(moduleName)} mapped as: +${_chalk().default.bold(mappedAs)}. + +Please check your configuration for these entries: +{ + "moduleNameMapper": { + "${regex.toString()}": "${_chalk().default.bold(original)}" + }, + "resolver": ${_chalk().default.bold(String(resolver))} +}`) + ); + error.name = ''; + return error; +}; + +function loadResolver(resolver) { + if (resolver == null) { + return _defaultResolver.default; + } + + const loadedResolver = require(resolver); + + if (loadedResolver == null) { + throw new Error(`Resolver located at ${resolver} does not export anything`); + } + + if (typeof loadedResolver === 'function') { + return loadedResolver; + } + + if ( + typeof loadedResolver === 'object' && + (loadedResolver.sync != null || loadedResolver.async != null) + ) { + return loadedResolver; + } + + throw new Error( + `Resolver located at ${resolver} does not export a function or an object with "sync" and "async" props` + ); +} diff --git a/node_modules/jest-resolve/build/shouldLoadAsEsm.js b/node_modules/jest-resolve/build/shouldLoadAsEsm.js new file mode 100644 index 0000000..b53a7d6 --- /dev/null +++ b/node_modules/jest-resolve/build/shouldLoadAsEsm.js @@ -0,0 +1,112 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.clearCachedLookups = clearCachedLookups; +exports.default = cachedShouldLoadAsEsm; + +function _path() { + const data = require('path'); + + _path = function () { + return data; + }; + + return data; +} + +function _vm() { + const data = require('vm'); + + _vm = function () { + return data; + }; + + return data; +} + +var _fileWalkers = require('./fileWalkers'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// @ts-expect-error: experimental, not added to the types +const runtimeSupportsVmModules = typeof _vm().SyntheticModule === 'function'; +const cachedFileLookups = new Map(); +const cachedDirLookups = new Map(); +const cachedChecks = new Map(); + +function clearCachedLookups() { + cachedFileLookups.clear(); + cachedDirLookups.clear(); + cachedChecks.clear(); +} + +function cachedShouldLoadAsEsm(path, extensionsToTreatAsEsm) { + if (!runtimeSupportsVmModules) { + return false; + } + + let cachedLookup = cachedFileLookups.get(path); + + if (cachedLookup === undefined) { + cachedLookup = shouldLoadAsEsm(path, extensionsToTreatAsEsm); + cachedFileLookups.set(path, cachedLookup); + } + + return cachedLookup; +} // this is a bad version of what https://github.com/nodejs/modules/issues/393 would provide + +function shouldLoadAsEsm(path, extensionsToTreatAsEsm) { + const extension = (0, _path().extname)(path); + + if (extension === '.mjs') { + return true; + } + + if (extension === '.cjs') { + return false; + } + + if (extension !== '.js') { + return extensionsToTreatAsEsm.includes(extension); + } + + const cwd = (0, _path().dirname)(path); + let cachedLookup = cachedDirLookups.get(cwd); + + if (cachedLookup === undefined) { + cachedLookup = cachedPkgCheck(cwd); + cachedFileLookups.set(cwd, cachedLookup); + } + + return cachedLookup; +} + +function cachedPkgCheck(cwd) { + const pkgPath = (0, _fileWalkers.findClosestPackageJson)(cwd); + + if (!pkgPath) { + return false; + } + + let hasModuleField = cachedChecks.get(pkgPath); + + if (hasModuleField != null) { + return hasModuleField; + } + + try { + const pkg = (0, _fileWalkers.readPackageCached)(pkgPath); + hasModuleField = pkg.type === 'module'; + } catch { + hasModuleField = false; + } + + cachedChecks.set(pkgPath, hasModuleField); + return hasModuleField; +} diff --git a/node_modules/jest-resolve/build/types.js b/node_modules/jest-resolve/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-resolve/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-resolve/build/utils.js b/node_modules/jest-resolve/build/utils.js new file mode 100644 index 0000000..e05724c --- /dev/null +++ b/node_modules/jest-resolve/build/utils.js @@ -0,0 +1,265 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.resolveWatchPlugin = + exports.resolveTestEnvironment = + exports.resolveSequencer = + exports.resolveRunner = + void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _jestValidate() { + const data = require('jest-validate'); + + _jestValidate = function () { + return data; + }; + + return data; +} + +var _resolver = _interopRequireDefault(require('./resolver')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const BULLET = _chalk().default.bold('\u25cf '); + +const DOCUMENTATION_NOTE = ` ${_chalk().default.bold( + 'Configuration Documentation:' +)} + https://jestjs.io/docs/configuration +`; + +const createValidationError = message => + new (_jestValidate().ValidationError)( + `${BULLET}Validation Error`, + message, + DOCUMENTATION_NOTE + ); + +const replaceRootDirInPath = (rootDir, filePath) => { + if (!/^/.test(filePath)) { + return filePath; + } + + return path().resolve( + rootDir, + path().normalize(`./${filePath.substr(''.length)}`) + ); +}; + +const resolveWithPrefix = ( + resolver, + { + filePath, + humanOptionName, + optionName, + prefix, + requireResolveFunction, + rootDir + } +) => { + const fileName = replaceRootDirInPath(rootDir, filePath); + + let module = _resolver.default.findNodeModule(`${prefix}${fileName}`, { + basedir: rootDir, + resolver: resolver || undefined + }); + + if (module) { + return module; + } + + try { + return requireResolveFunction(`${prefix}${fileName}`); + } catch {} + + module = _resolver.default.findNodeModule(fileName, { + basedir: rootDir, + resolver: resolver || undefined + }); + + if (module) { + return module; + } + + try { + return requireResolveFunction(fileName); + } catch {} + + throw createValidationError( + ` ${humanOptionName} ${_chalk().default.bold( + fileName + )} cannot be found. Make sure the ${_chalk().default.bold( + optionName + )} configuration option points to an existing node module.` + ); +}; +/** + * Finds the test environment to use: + * + * 1. looks for jest-environment- relative to project. + * 1. looks for jest-environment- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ + +const resolveTestEnvironment = ({ + rootDir, + testEnvironment: filePath, + requireResolveFunction +}) => { + // we don't want to resolve the actual `jsdom` module if `jest-environment-jsdom` is not installed, but `jsdom` package is + if (filePath === 'jsdom') { + filePath = 'jest-environment-jsdom'; + } + + try { + return resolveWithPrefix(undefined, { + filePath, + humanOptionName: 'Test environment', + optionName: 'testEnvironment', + prefix: 'jest-environment-', + requireResolveFunction, + rootDir + }); + } catch (error) { + if (filePath === 'jest-environment-jsdom') { + error.message += + '\n\nAs of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.'; + } + + throw error; + } +}; +/** + * Finds the watch plugins to use: + * + * 1. looks for jest-watch- relative to project. + * 1. looks for jest-watch- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ + +exports.resolveTestEnvironment = resolveTestEnvironment; + +const resolveWatchPlugin = ( + resolver, + {filePath, rootDir, requireResolveFunction} +) => + resolveWithPrefix(resolver, { + filePath, + humanOptionName: 'Watch plugin', + optionName: 'watchPlugins', + prefix: 'jest-watch-', + requireResolveFunction, + rootDir + }); +/** + * Finds the runner to use: + * + * 1. looks for jest-runner- relative to project. + * 1. looks for jest-runner- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ + +exports.resolveWatchPlugin = resolveWatchPlugin; + +const resolveRunner = (resolver, {filePath, rootDir, requireResolveFunction}) => + resolveWithPrefix(resolver, { + filePath, + humanOptionName: 'Jest Runner', + optionName: 'runner', + prefix: 'jest-runner-', + requireResolveFunction, + rootDir + }); + +exports.resolveRunner = resolveRunner; + +const resolveSequencer = ( + resolver, + {filePath, rootDir, requireResolveFunction} +) => + resolveWithPrefix(resolver, { + filePath, + humanOptionName: 'Jest Sequencer', + optionName: 'testSequencer', + prefix: 'jest-sequencer-', + requireResolveFunction, + rootDir + }); + +exports.resolveSequencer = resolveSequencer; diff --git a/node_modules/jest-resolve/package.json b/node_modules/jest-resolve/package.json new file mode 100644 index 0000000..f0d30de --- /dev/null +++ b/node_modules/jest-resolve/package.json @@ -0,0 +1,76 @@ +{ + "_from": "jest-resolve@^29.0.1", + "_id": "jest-resolve@29.0.1", + "_inBundle": false, + "_integrity": "sha512-dwb5Z0lLZbptlBtPExqsHfdDamXeiRLv4vdkfPrN84vBwLSWHWcXjlM2JXD/KLSQfljBcXbzI/PDvUJuTQ84Nw==", + "_location": "/jest-resolve", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-resolve@^29.0.1", + "name": "jest-resolve", + "escapedName": "jest-resolve", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/jest-config", + "/jest-runner", + "/jest-runtime" + ], + "_resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.0.1.tgz", + "_shasum": "4f1338eee2ccc7319ffce850e13eb118a9e93ce5", + "_spec": "jest-resolve@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.0.1", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.0.1", + "jest-validate": "^29.0.1", + "resolve": "^1.20.0", + "resolve.exports": "^1.1.0", + "slash": "^3.0.0" + }, + "deprecated": false, + "devDependencies": { + "@tsd/typescript": "~4.7.4", + "@types/graceful-fs": "^4.1.3", + "@types/pnpapi": "^0.0.2", + "@types/resolve": "^1.20.2", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-resolve", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-resolve" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-runner/LICENSE b/node_modules/jest-runner/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-runner/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-runner/build/index.d.ts b/node_modules/jest-runner/build/index.d.ts new file mode 100644 index 0000000..561f032 --- /dev/null +++ b/node_modules/jest-runner/build/index.d.ts @@ -0,0 +1,127 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import {Config} from '@jest/types'; +import type {SerializableError} from '@jest/test-result'; +import {Test} from '@jest/test-result'; +import {TestEvents} from '@jest/test-result'; +import type {TestResult} from '@jest/test-result'; +import {TestWatcher} from 'jest-watcher'; + +declare abstract class BaseTestRunner { + protected readonly _globalConfig: Config.GlobalConfig; + protected readonly _context: TestRunnerContext; + readonly isSerial?: boolean; + abstract readonly supportsEventEmitters: boolean; + constructor(_globalConfig: Config.GlobalConfig, _context: TestRunnerContext); +} + +export declare abstract class CallbackTestRunner + extends BaseTestRunner + implements CallbackTestRunnerInterface +{ + readonly supportsEventEmitters = false; + abstract runTests( + tests: Array, + watcher: TestWatcher, + onStart: OnTestStart, + onResult: OnTestSuccess, + onFailure: OnTestFailure, + options: TestRunnerOptions, + ): Promise; +} + +export declare interface CallbackTestRunnerInterface { + readonly isSerial?: boolean; + readonly supportsEventEmitters?: boolean; + runTests( + tests: Array, + watcher: TestWatcher, + onStart: OnTestStart, + onResult: OnTestSuccess, + onFailure: OnTestFailure, + options: TestRunnerOptions, + ): Promise; +} + +export {Config}; + +export declare abstract class EmittingTestRunner + extends BaseTestRunner + implements EmittingTestRunnerInterface +{ + readonly supportsEventEmitters = true; + abstract runTests( + tests: Array, + watcher: TestWatcher, + options: TestRunnerOptions, + ): Promise; + abstract on( + eventName: Name, + listener: (eventData: TestEvents[Name]) => void | Promise, + ): UnsubscribeFn; +} + +export declare interface EmittingTestRunnerInterface { + readonly isSerial?: boolean; + readonly supportsEventEmitters: true; + runTests( + tests: Array, + watcher: TestWatcher, + options: TestRunnerOptions, + ): Promise; + on( + eventName: Name, + listener: (eventData: TestEvents[Name]) => void | Promise, + ): UnsubscribeFn; +} + +export declare type JestTestRunner = CallbackTestRunner | EmittingTestRunner; + +export declare type OnTestFailure = ( + test: Test, + serializableError: SerializableError, +) => Promise; + +export declare type OnTestStart = (test: Test) => Promise; + +export declare type OnTestSuccess = ( + test: Test, + testResult: TestResult, +) => Promise; + +export {Test}; + +export {TestEvents}; + +declare class TestRunner extends EmittingTestRunner { + #private; + runTests( + tests: Array, + watcher: TestWatcher, + options: TestRunnerOptions, + ): Promise; + on( + eventName: Name, + listener: (eventData: TestEvents[Name]) => void | Promise, + ): UnsubscribeFn; +} +export default TestRunner; + +export declare type TestRunnerContext = { + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; +}; + +export declare type TestRunnerOptions = { + serial: boolean; +}; + +export {TestWatcher}; + +export declare type UnsubscribeFn = () => void; + +export {}; diff --git a/node_modules/jest-runner/build/index.js b/node_modules/jest-runner/build/index.js new file mode 100644 index 0000000..d9348c6 --- /dev/null +++ b/node_modules/jest-runner/build/index.js @@ -0,0 +1,250 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'CallbackTestRunner', { + enumerable: true, + get: function () { + return _types.CallbackTestRunner; + } +}); +Object.defineProperty(exports, 'EmittingTestRunner', { + enumerable: true, + get: function () { + return _types.EmittingTestRunner; + } +}); +exports.default = void 0; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _emittery() { + const data = _interopRequireDefault(require('emittery')); + + _emittery = function () { + return data; + }; + + return data; +} + +function _pLimit() { + const data = _interopRequireDefault(require('p-limit')); + + _pLimit = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _jestWorker() { + const data = require('jest-worker'); + + _jestWorker = function () { + return data; + }; + + return data; +} + +var _runTest = _interopRequireDefault(require('./runTest')); + +var _types = require('./types'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class TestRunner extends _types.EmittingTestRunner { + #eventEmitter = new (_emittery().default)(); + + async runTests(tests, watcher, options) { + return await (options.serial + ? this.#createInBandTestRun(tests, watcher) + : this.#createParallelTestRun(tests, watcher)); + } + + async #createInBandTestRun(tests, watcher) { + process.env.JEST_WORKER_ID = '1'; + const mutex = (0, _pLimit().default)(1); + return tests.reduce( + (promise, test) => + mutex(() => + promise + .then(async () => { + if (watcher.isInterrupted()) { + throw new CancelRun(); + } // `deepCyclicCopy` used here to avoid mem-leak + + const sendMessageToJest = (eventName, args) => + this.#eventEmitter.emit( + eventName, + (0, _jestUtil().deepCyclicCopy)(args, { + keepPrototype: false + }) + ); + + await this.#eventEmitter.emit('test-file-start', [test]); + return (0, _runTest.default)( + test.path, + this._globalConfig, + test.context.config, + test.context.resolver, + this._context, + sendMessageToJest + ); + }) + .then( + result => + this.#eventEmitter.emit('test-file-success', [test, result]), + error => + this.#eventEmitter.emit('test-file-failure', [test, error]) + ) + ), + Promise.resolve() + ); + } + + async #createParallelTestRun(tests, watcher) { + const resolvers = new Map(); + + for (const test of tests) { + if (!resolvers.has(test.context.config.id)) { + resolvers.set(test.context.config.id, { + config: test.context.config, + serializableModuleMap: test.context.moduleMap.toJSON() + }); + } + } + + const worker = new (_jestWorker().Worker)(require.resolve('./testWorker'), { + exposedMethods: ['worker'], + forkOptions: { + serialization: 'json', + stdio: 'pipe' + }, + // The workerIdleMemoryLimit should've been converted to a number during + // the normalization phase. + idleMemoryLimit: + typeof this._globalConfig.workerIdleMemoryLimit === 'number' + ? this._globalConfig.workerIdleMemoryLimit + : undefined, + maxRetries: 3, + numWorkers: this._globalConfig.maxWorkers, + setupArgs: [ + { + serializableResolvers: Array.from(resolvers.values()) + } + ] + }); + if (worker.getStdout()) worker.getStdout().pipe(process.stdout); + if (worker.getStderr()) worker.getStderr().pipe(process.stderr); + const mutex = (0, _pLimit().default)(this._globalConfig.maxWorkers); // Send test suites to workers continuously instead of all at once to track + // the start time of individual tests. + + const runTestInWorker = test => + mutex(async () => { + if (watcher.isInterrupted()) { + return Promise.reject(); + } + + await this.#eventEmitter.emit('test-file-start', [test]); + const promise = worker.worker({ + config: test.context.config, + context: { + ...this._context, + changedFiles: + this._context.changedFiles && + Array.from(this._context.changedFiles), + sourcesRelatedToTestsInChangedFiles: + this._context.sourcesRelatedToTestsInChangedFiles && + Array.from(this._context.sourcesRelatedToTestsInChangedFiles) + }, + globalConfig: this._globalConfig, + path: test.path + }); + + if (promise.UNSTABLE_onCustomMessage) { + // TODO: Get appropriate type for `onCustomMessage` + promise.UNSTABLE_onCustomMessage(([event, payload]) => + this.#eventEmitter.emit(event, payload) + ); + } + + return promise; + }); + + const onInterrupt = new Promise((_, reject) => { + watcher.on('change', state => { + if (state.interrupted) { + reject(new CancelRun()); + } + }); + }); + const runAllTests = Promise.all( + tests.map(test => + runTestInWorker(test).then( + result => + this.#eventEmitter.emit('test-file-success', [test, result]), + error => this.#eventEmitter.emit('test-file-failure', [test, error]) + ) + ) + ); + + const cleanup = async () => { + const {forceExited} = await worker.end(); + + if (forceExited) { + console.error( + _chalk().default.yellow( + 'A worker process has failed to exit gracefully and has been force exited. ' + + 'This is likely caused by tests leaking due to improper teardown. ' + + 'Try running with --detectOpenHandles to find leaks. ' + + 'Active timers can also cause this, ensure that .unref() was called on them.' + ) + ); + } + }; + + return Promise.race([runAllTests, onInterrupt]).then(cleanup, cleanup); + } + + on(eventName, listener) { + return this.#eventEmitter.on(eventName, listener); + } +} + +exports.default = TestRunner; + +class CancelRun extends Error { + constructor(message) { + super(message); + this.name = 'CancelRun'; + } +} diff --git a/node_modules/jest-runner/build/runTest.js b/node_modules/jest-runner/build/runTest.js new file mode 100644 index 0000000..2c58b4c --- /dev/null +++ b/node_modules/jest-runner/build/runTest.js @@ -0,0 +1,507 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = runTest; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _sourceMapSupport() { + const data = _interopRequireDefault(require('source-map-support')); + + _sourceMapSupport = function () { + return data; + }; + + return data; +} + +function _console() { + const data = require('@jest/console'); + + _console = function () { + return data; + }; + + return data; +} + +function _transform() { + const data = require('@jest/transform'); + + _transform = function () { + return data; + }; + + return data; +} + +function docblock() { + const data = _interopRequireWildcard(require('jest-docblock')); + + docblock = function () { + return data; + }; + + return data; +} + +function _jestLeakDetector() { + const data = _interopRequireDefault(require('jest-leak-detector')); + + _jestLeakDetector = function () { + return data; + }; + + return data; +} + +function _jestMessageUtil() { + const data = require('jest-message-util'); + + _jestMessageUtil = function () { + return data; + }; + + return data; +} + +function _jestResolve() { + const data = require('jest-resolve'); + + _jestResolve = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +function freezeConsole(testConsole, config) { + // @ts-expect-error: `_log` is `private` - we should figure out some proper API here + testConsole._log = function fakeConsolePush(_type, message) { + const error = new (_jestUtil().ErrorWithStack)( + `${_chalk().default.red( + `${_chalk().default.bold( + 'Cannot log after tests are done.' + )} Did you forget to wait for something async in your test?` + )}\nAttempted to log "${message}".`, + fakeConsolePush + ); + const formattedError = (0, _jestMessageUtil().formatExecError)( + error, + config, + { + noStackTrace: false + }, + undefined, + true + ); + process.stderr.write(`\n${formattedError}\n`); + process.exitCode = 1; + }; +} // Keeping the core of "runTest" as a separate function (as "runTestInternal") +// is key to be able to detect memory leaks. Since all variables are local to +// the function, when "runTestInternal" finishes its execution, they can all be +// freed, UNLESS something else is leaking them (and that's why we can detect +// the leak!). +// +// If we had all the code in a single function, we should manually nullify all +// references to verify if there is a leak, which is not maintainable and error +// prone. That's why "runTestInternal" CANNOT be inlined inside "runTest". + +async function runTestInternal( + path, + globalConfig, + projectConfig, + resolver, + context, + sendMessageToJest +) { + const testSource = fs().readFileSync(path, 'utf8'); + const docblockPragmas = docblock().parse(docblock().extract(testSource)); + const customEnvironment = docblockPragmas['jest-environment']; + let testEnvironment = projectConfig.testEnvironment; + + if (customEnvironment) { + if (Array.isArray(customEnvironment)) { + throw new Error( + `You can only define a single test environment through docblocks, got "${customEnvironment.join( + ', ' + )}"` + ); + } + + testEnvironment = (0, _jestResolve().resolveTestEnvironment)({ + ...projectConfig, + requireResolveFunction: require.resolve, + testEnvironment: customEnvironment + }); + } + + const cacheFS = new Map([[path, testSource]]); + const transformer = await (0, _transform().createScriptTransformer)( + projectConfig, + cacheFS + ); + const TestEnvironment = await transformer.requireAndTranspileModule( + testEnvironment + ); + const testFramework = await transformer.requireAndTranspileModule( + process.env.JEST_JASMINE === '1' + ? require.resolve('jest-jasmine2') + : projectConfig.testRunner + ); + const Runtime = (0, _jestUtil().interopRequireDefault)( + projectConfig.runtime + ? require(projectConfig.runtime) + : require('jest-runtime') + ).default; + const consoleOut = globalConfig.useStderr ? process.stderr : process.stdout; + + const consoleFormatter = (type, message) => + (0, _console().getConsoleOutput)( + // 4 = the console call is buried 4 stack frames deep + _console().BufferedConsole.write([], type, message, 4), + projectConfig, + globalConfig + ); + + let testConsole; + + if (globalConfig.silent) { + testConsole = new (_console().NullConsole)( + consoleOut, + consoleOut, + consoleFormatter + ); + } else if (globalConfig.verbose) { + testConsole = new (_console().CustomConsole)( + consoleOut, + consoleOut, + consoleFormatter + ); + } else { + testConsole = new (_console().BufferedConsole)(); + } + + let extraTestEnvironmentOptions; + const docblockEnvironmentOptions = + docblockPragmas['jest-environment-options']; + + if (typeof docblockEnvironmentOptions === 'string') { + extraTestEnvironmentOptions = JSON.parse(docblockEnvironmentOptions); + } + + const environment = new TestEnvironment( + { + globalConfig, + projectConfig: extraTestEnvironmentOptions + ? { + ...projectConfig, + testEnvironmentOptions: { + ...projectConfig.testEnvironmentOptions, + ...extraTestEnvironmentOptions + } + } + : projectConfig + }, + { + console: testConsole, + docblockPragmas, + testPath: path + } + ); + + if (typeof environment.getVmContext !== 'function') { + console.error( + `Test environment found at "${testEnvironment}" does not export a "getVmContext" method, which is mandatory from Jest 27. This method is a replacement for "runScript".` + ); + process.exit(1); + } + + const leakDetector = projectConfig.detectLeaks + ? new (_jestLeakDetector().default)(environment) + : null; + (0, _jestUtil().setGlobal)(environment.global, 'console', testConsole); + const runtime = new Runtime( + projectConfig, + environment, + resolver, + transformer, + cacheFS, + { + changedFiles: context.changedFiles, + collectCoverage: globalConfig.collectCoverage, + collectCoverageFrom: globalConfig.collectCoverageFrom, + coverageProvider: globalConfig.coverageProvider, + sourcesRelatedToTestsInChangedFiles: + context.sourcesRelatedToTestsInChangedFiles + }, + path + ); + const start = Date.now(); + + for (const path of projectConfig.setupFiles) { + const esm = runtime.unstable_shouldLoadAsEsm(path); + + if (esm) { + await runtime.unstable_importModule(path); + } else { + const setupFile = runtime.requireModule(path); + + if (typeof setupFile === 'function') { + await setupFile(); + } + } + } + + const sourcemapOptions = { + environment: 'node', + handleUncaughtExceptions: false, + retrieveSourceMap: source => { + const sourceMapSource = runtime.getSourceMaps()?.get(source); + + if (sourceMapSource) { + try { + return { + map: JSON.parse(fs().readFileSync(sourceMapSource, 'utf8')), + url: source + }; + } catch {} + } + + return null; + } + }; // For tests + + runtime + .requireInternalModule(require.resolve('source-map-support')) + .install(sourcemapOptions); // For runtime errors + + _sourceMapSupport().default.install(sourcemapOptions); + + if ( + environment.global && + environment.global.process && + environment.global.process.exit + ) { + const realExit = environment.global.process.exit; + + environment.global.process.exit = function exit(...args) { + const error = new (_jestUtil().ErrorWithStack)( + `process.exit called with "${args.join(', ')}"`, + exit + ); + const formattedError = (0, _jestMessageUtil().formatExecError)( + error, + projectConfig, + { + noStackTrace: false + }, + undefined, + true + ); + process.stderr.write(formattedError); + return realExit(...args); + }; + } // if we don't have `getVmContext` on the env skip coverage + + const collectV8Coverage = + globalConfig.coverageProvider === 'v8' && + typeof environment.getVmContext === 'function'; + + try { + await environment.setup(); + let result; + + try { + if (collectV8Coverage) { + await runtime.collectV8Coverage(); + } + + result = await testFramework( + globalConfig, + projectConfig, + environment, + runtime, + path, + sendMessageToJest + ); + } catch (err) { + // Access stack before uninstalling sourcemaps + err.stack; + throw err; + } finally { + if (collectV8Coverage) { + await runtime.stopCollectingV8Coverage(); + } + } + + freezeConsole(testConsole, projectConfig); + const testCount = + result.numPassingTests + + result.numFailingTests + + result.numPendingTests + + result.numTodoTests; + const end = Date.now(); + const testRuntime = end - start; + result.perfStats = { + end, + runtime: testRuntime, + slow: testRuntime / 1000 > projectConfig.slowTestThreshold, + start + }; + result.testFilePath = path; + result.console = testConsole.getBuffer(); + result.skipped = testCount === result.numPendingTests; + result.displayName = projectConfig.displayName; + const coverage = runtime.getAllCoverageInfoCopy(); + + if (coverage) { + const coverageKeys = Object.keys(coverage); + + if (coverageKeys.length) { + result.coverage = coverage; + } + } + + if (collectV8Coverage) { + const v8Coverage = runtime.getAllV8CoverageInfoCopy(); + + if (v8Coverage && v8Coverage.length > 0) { + result.v8Coverage = v8Coverage; + } + } + + if (globalConfig.logHeapUsage) { + // @ts-expect-error - doesn't exist on globalThis + globalThis.gc?.(); + result.memoryUsage = process.memoryUsage().heapUsed; + } // Delay the resolution to allow log messages to be output. + + return new Promise(resolve => { + setImmediate(() => + resolve({ + leakDetector, + result + }) + ); + }); + } finally { + runtime.teardown(); + await environment.teardown(); + + _sourceMapSupport().default.resetRetrieveHandlers(); + } +} + +async function runTest( + path, + globalConfig, + config, + resolver, + context, + sendMessageToJest +) { + const {leakDetector, result} = await runTestInternal( + path, + globalConfig, + config, + resolver, + context, + sendMessageToJest + ); + + if (leakDetector) { + // We wanna allow a tiny but time to pass to allow last-minute cleanup + await new Promise(resolve => setTimeout(resolve, 100)); // Resolve leak detector, outside the "runTestInternal" closure. + + result.leaks = await leakDetector.isLeaking(); + } else { + result.leaks = false; + } + + return result; +} diff --git a/node_modules/jest-runner/build/testWorker.js b/node_modules/jest-runner/build/testWorker.js new file mode 100644 index 0000000..8614ff3 --- /dev/null +++ b/node_modules/jest-runner/build/testWorker.js @@ -0,0 +1,150 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.setup = setup; +exports.worker = worker; + +function _exit() { + const data = _interopRequireDefault(require('exit')); + + _exit = function () { + return data; + }; + + return data; +} + +function _jestHasteMap() { + const data = _interopRequireDefault(require('jest-haste-map')); + + _jestHasteMap = function () { + return data; + }; + + return data; +} + +function _jestMessageUtil() { + const data = require('jest-message-util'); + + _jestMessageUtil = function () { + return data; + }; + + return data; +} + +function _jestRuntime() { + const data = _interopRequireDefault(require('jest-runtime')); + + _jestRuntime = function () { + return data; + }; + + return data; +} + +function _jestWorker() { + const data = require('jest-worker'); + + _jestWorker = function () { + return data; + }; + + return data; +} + +var _runTest = _interopRequireDefault(require('./runTest')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +// Make sure uncaught errors are logged before we exit. +process.on('uncaughtException', err => { + console.error(err.stack); + (0, _exit().default)(1); +}); + +const formatError = error => { + if (typeof error === 'string') { + const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)( + error + ); + return { + message, + stack, + type: 'Error' + }; + } + + return { + code: error.code || undefined, + message: error.message, + stack: error.stack, + type: 'Error' + }; +}; + +const resolvers = new Map(); + +const getResolver = config => { + const resolver = resolvers.get(config.id); + + if (!resolver) { + throw new Error(`Cannot find resolver for: ${config.id}`); + } + + return resolver; +}; + +function setup(setupData) { + // Module maps that will be needed for the test runs are passed. + for (const { + config, + serializableModuleMap + } of setupData.serializableResolvers) { + const moduleMap = _jestHasteMap() + .default.getStatic(config) + .getModuleMapFromJSON(serializableModuleMap); + + resolvers.set( + config.id, + _jestRuntime().default.createResolver(config, moduleMap) + ); + } +} + +const sendMessageToJest = (eventName, args) => { + (0, _jestWorker().messageParent)([eventName, args]); +}; + +async function worker({config, globalConfig, path, context}) { + try { + return await (0, _runTest.default)( + path, + globalConfig, + config, + getResolver(config), + { + ...context, + changedFiles: context.changedFiles && new Set(context.changedFiles), + sourcesRelatedToTestsInChangedFiles: + context.sourcesRelatedToTestsInChangedFiles && + new Set(context.sourcesRelatedToTestsInChangedFiles) + }, + sendMessageToJest + ); + } catch (error) { + throw formatError(error); + } +} diff --git a/node_modules/jest-runner/build/types.js b/node_modules/jest-runner/build/types.js new file mode 100644 index 0000000..63a3cac --- /dev/null +++ b/node_modules/jest-runner/build/types.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.EmittingTestRunner = exports.CallbackTestRunner = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class BaseTestRunner { + isSerial; + supportsEventEmitters; + + constructor(_globalConfig, _context) { + this._globalConfig = _globalConfig; + this._context = _context; + } +} + +class CallbackTestRunner extends BaseTestRunner { + supportsEventEmitters = false; +} + +exports.CallbackTestRunner = CallbackTestRunner; + +class EmittingTestRunner extends BaseTestRunner { + supportsEventEmitters = true; +} + +exports.EmittingTestRunner = EmittingTestRunner; diff --git a/node_modules/jest-runner/node_modules/p-limit/index.d.ts b/node_modules/jest-runner/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..f348d7f --- /dev/null +++ b/node_modules/jest-runner/node_modules/p-limit/index.d.ts @@ -0,0 +1,42 @@ +declare namespace pLimit { + interface Limit { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + } +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +declare function pLimit(concurrency: number): pLimit.Limit; + +export = pLimit; diff --git a/node_modules/jest-runner/node_modules/p-limit/index.js b/node_modules/jest-runner/node_modules/p-limit/index.js new file mode 100644 index 0000000..c2ae52d --- /dev/null +++ b/node_modules/jest-runner/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +'use strict'; +const Queue = require('yocto-queue'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +module.exports = pLimit; diff --git a/node_modules/jest-runner/node_modules/p-limit/license b/node_modules/jest-runner/node_modules/p-limit/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/jest-runner/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jest-runner/node_modules/p-limit/package.json b/node_modules/jest-runner/node_modules/p-limit/package.json new file mode 100644 index 0000000..cccde0b --- /dev/null +++ b/node_modules/jest-runner/node_modules/p-limit/package.json @@ -0,0 +1,84 @@ +{ + "_from": "p-limit@^3.1.0", + "_id": "p-limit@3.1.0", + "_inBundle": false, + "_integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "_location": "/jest-runner/p-limit", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "p-limit@^3.1.0", + "name": "p-limit", + "escapedName": "p-limit", + "rawSpec": "^3.1.0", + "saveSpec": null, + "fetchSpec": "^3.1.0" + }, + "_requiredBy": [ + "/jest-runner" + ], + "_resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "_shasum": "e1daccbe78d0d1388ca18c64fea38e3e57e3706b", + "_spec": "p-limit@^3.1.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-runner", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/p-limit/issues" + }, + "bundleDependencies": false, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "deprecated": false, + "description": "Run multiple promise-returning & async functions with limited concurrency", + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.4.0", + "in-range": "^2.0.0", + "random-int": "^2.0.1", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/p-limit#readme", + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "license": "MIT", + "name": "p-limit", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/p-limit.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "3.1.0" +} diff --git a/node_modules/jest-runner/node_modules/p-limit/readme.md b/node_modules/jest-runner/node_modules/p-limit/readme.md new file mode 100644 index 0000000..b283c1e --- /dev/null +++ b/node_modules/jest-runner/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +

+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/jest-runner/package.json b/node_modules/jest-runner/package.json new file mode 100644 index 0000000..df595fb --- /dev/null +++ b/node_modules/jest-runner/package.json @@ -0,0 +1,89 @@ +{ + "_from": "jest-runner@^29.0.1", + "_id": "jest-runner@29.0.1", + "_inBundle": false, + "_integrity": "sha512-XeFfPmHtO7HyZyD1uJeO4Oqa8PyTbDHzS1YdGrvsFXk/A5eXinbqA5a42VUEqvsKQgNnKTl5NJD0UtDWg7cQ2A==", + "_location": "/jest-runner", + "_phantomChildren": { + "yocto-queue": "0.1.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-runner@^29.0.1", + "name": "jest-runner", + "escapedName": "jest-runner", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/jest-config" + ], + "_resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.0.1.tgz", + "_shasum": "15bacd13170f3d786168ef8548fdeb96933ea643", + "_spec": "jest-runner@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/console": "^29.0.1", + "@jest/environment": "^29.0.1", + "@jest/test-result": "^29.0.1", + "@jest/transform": "^29.0.1", + "@jest/types": "^29.0.1", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.10.2", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.0.0", + "jest-environment-node": "^29.0.1", + "jest-haste-map": "^29.0.1", + "jest-leak-detector": "^29.0.1", + "jest-message-util": "^29.0.1", + "jest-resolve": "^29.0.1", + "jest-runtime": "^29.0.1", + "jest-util": "^29.0.1", + "jest-watcher": "^29.0.1", + "jest-worker": "^29.0.1", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "deprecated": false, + "devDependencies": { + "@tsd/typescript": "~4.7.4", + "@types/exit": "^0.1.30", + "@types/graceful-fs": "^4.1.3", + "@types/source-map-support": "^0.5.0", + "jest-jasmine2": "^29.0.1", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-runner", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-runner" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-runtime/LICENSE b/node_modules/jest-runtime/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-runtime/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-runtime/build/helpers.js b/node_modules/jest-runtime/build/helpers.js new file mode 100644 index 0000000..f736c46 --- /dev/null +++ b/node_modules/jest-runtime/build/helpers.js @@ -0,0 +1,156 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.findSiblingsWithFileExtension = + exports.decodePossibleOutsideJestVmPath = + exports.createOutsideJestVmPath = + void 0; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _glob() { + const data = _interopRequireDefault(require('glob')); + + _glob = function () { + return data; + }; + + return data; +} + +function _slash() { + const data = _interopRequireDefault(require('slash')); + + _slash = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const OUTSIDE_JEST_VM_PROTOCOL = 'jest-main:'; // String manipulation is easier here, fileURLToPath is only in newer Nodes, +// plus setting non-standard protocols on URL objects is difficult. + +const createOutsideJestVmPath = path => + `${OUTSIDE_JEST_VM_PROTOCOL}//${encodeURIComponent(path)}`; + +exports.createOutsideJestVmPath = createOutsideJestVmPath; + +const decodePossibleOutsideJestVmPath = outsideJestVmPath => { + if (outsideJestVmPath.startsWith(OUTSIDE_JEST_VM_PROTOCOL)) { + return decodeURIComponent( + outsideJestVmPath.replace( + new RegExp(`^${OUTSIDE_JEST_VM_PROTOCOL}//`), + '' + ) + ); + } + + return undefined; +}; + +exports.decodePossibleOutsideJestVmPath = decodePossibleOutsideJestVmPath; + +const findSiblingsWithFileExtension = ( + moduleFileExtensions, + from, + moduleName +) => { + if (!path().isAbsolute(moduleName) && path().extname(moduleName) === '') { + const dirname = path().dirname(from); + const pathToModule = path().resolve(dirname, moduleName); + + try { + const slashedDirname = (0, _slash().default)(dirname); + + const matches = _glob() + .default.sync(`${pathToModule}.*`) + .map(match => (0, _slash().default)(match)) + .map(match => { + const relativePath = path().posix.relative(slashedDirname, match); + return path().posix.dirname(match) === slashedDirname + ? `./${relativePath}` + : relativePath; + }) + .map(match => `\t'${match}'`) + .join('\n'); + + if (matches) { + const foundMessage = `\n\nHowever, Jest was able to find:\n${matches}`; + const mappedModuleFileExtensions = moduleFileExtensions + .map(ext => `'${ext}'`) + .join(', '); + return ( + `${foundMessage}\n\nYou might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ` + + `[${mappedModuleFileExtensions}].\n\nSee https://jestjs.io/docs/configuration#modulefileextensions-arraystring` + ); + } + } catch {} + } + + return ''; +}; + +exports.findSiblingsWithFileExtension = findSiblingsWithFileExtension; diff --git a/node_modules/jest-runtime/build/index.d.ts b/node_modules/jest-runtime/build/index.d.ts new file mode 100644 index 0000000..61732db --- /dev/null +++ b/node_modules/jest-runtime/build/index.d.ts @@ -0,0 +1,183 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import {CallerTransformOptions} from '@jest/transform'; +import type {Config} from '@jest/types'; +import type {expect as expect_2} from '@jest/globals'; +import type {Global} from '@jest/types'; +import HasteMap from 'jest-haste-map'; +import {IModuleMap} from 'jest-haste-map'; +import type {JestEnvironment} from '@jest/environment'; +import Resolver from 'jest-resolve'; +import {ScriptTransformer} from '@jest/transform'; +import {shouldInstrument} from '@jest/transform'; +import {ShouldInstrumentOptions} from '@jest/transform'; +import type {SourceMapRegistry} from '@jest/source-map'; +import type {TestContext} from '@jest/test-result'; +import type {V8CoverageResult} from '@jest/test-result'; + +declare type HasteMapOptions = { + console?: Console; + maxWorkers: number; + resetCache: boolean; + watch?: boolean; + watchman: boolean; +}; + +declare interface InternalModuleOptions + extends Required { + isInternalModule: boolean; +} + +declare interface JestGlobals extends Global.TestFrameworkGlobals { + expect: typeof expect_2; +} + +declare class Runtime { + private readonly _cacheFS; + private readonly _config; + private readonly _coverageOptions; + private _currentlyExecutingModulePath; + private readonly _environment; + private readonly _explicitShouldMock; + private readonly _explicitShouldMockModule; + private _fakeTimersImplementation; + private readonly _internalModuleRegistry; + private _isCurrentlyExecutingManualMock; + private _mainModule; + private readonly _mockFactories; + private readonly _mockMetaDataCache; + private _mockRegistry; + private _isolatedMockRegistry; + private _moduleMockRegistry; + private readonly _moduleMockFactories; + private readonly _moduleMocker; + private _isolatedModuleRegistry; + private _moduleRegistry; + private readonly _esmoduleRegistry; + private readonly _cjsNamedExports; + private readonly _esmModuleLinkingMap; + private readonly _testPath; + private readonly _resolver; + private _shouldAutoMock; + private readonly _shouldMockModuleCache; + private readonly _shouldUnmockTransitiveDependenciesCache; + private readonly _sourceMapRegistry; + private readonly _scriptTransformer; + private readonly _fileTransforms; + private readonly _fileTransformsMutex; + private _v8CoverageInstrumenter; + private _v8CoverageResult; + private _v8CoverageSources; + private readonly _transitiveShouldMock; + private _unmockList; + private readonly _virtualMocks; + private readonly _virtualModuleMocks; + private _moduleImplementation?; + private readonly jestObjectCaches; + private jestGlobals?; + private readonly esmConditions; + private readonly cjsConditions; + private isTornDown; + constructor( + config: Config.ProjectConfig, + environment: JestEnvironment, + resolver: Resolver, + transformer: ScriptTransformer, + cacheFS: Map, + coverageOptions: ShouldInstrumentOptions, + testPath: string, + ); + static shouldInstrument: typeof shouldInstrument; + static createContext( + config: Config.ProjectConfig, + options: { + console?: Console; + maxWorkers: number; + watch?: boolean; + watchman: boolean; + }, + ): Promise; + static createHasteMap( + config: Config.ProjectConfig, + options?: HasteMapOptions, + ): Promise; + static createResolver( + config: Config.ProjectConfig, + moduleMap: IModuleMap, + ): Resolver; + static runCLI(): Promise; + static getCLIOptions(): never; + unstable_shouldLoadAsEsm(path: string): boolean; + private loadEsmModule; + private resolveModule; + private linkAndEvaluateModule; + unstable_importModule(from: string, moduleName?: string): Promise; + private loadCjsAsEsm; + private importMock; + private getExportsOfCjs; + requireModule( + from: string, + moduleName?: string, + options?: InternalModuleOptions, + isRequireActual?: boolean, + ): T; + requireInternalModule(from: string, to?: string): T; + requireActual(from: string, moduleName: string): T; + requireMock(from: string, moduleName: string): T; + private _loadModule; + private _getFullTransformationOptions; + requireModuleOrMock(from: string, moduleName: string): T; + isolateModules(fn: () => void): void; + resetModules(): void; + collectV8Coverage(): Promise; + stopCollectingV8Coverage(): Promise; + getAllCoverageInfoCopy(): JestEnvironment['global']['__coverage__']; + getAllV8CoverageInfoCopy(): V8CoverageResult; + getSourceMaps(): SourceMapRegistry; + setMock( + from: string, + moduleName: string, + mockFactory: () => unknown, + options?: { + virtual?: boolean; + }, + ): void; + private setModuleMock; + restoreAllMocks(): void; + resetAllMocks(): void; + clearAllMocks(): void; + teardown(): void; + private _resolveCjsModule; + private _resolveModule; + private _requireResolve; + private _requireResolvePaths; + private _execModule; + private transformFile; + private transformFileAsync; + private createScriptFromCode; + private _requireCoreModule; + private _importCoreModule; + private _getMockedNativeModule; + private _generateMock; + private _shouldMockCjs; + private _shouldMockModule; + private _createRequireImplementation; + private _createJestObjectFor; + private _logFormattedReferenceError; + private wrapCodeInModuleWrapper; + private constructModuleWrapperStart; + private constructInjectedModuleParameters; + private handleExecutionError; + private getGlobalsForCjs; + private getGlobalsForEsm; + private getGlobalsFromEnvironment; + private readFile; + setGlobalsForRuntime(globals: JestGlobals): void; +} +export default Runtime; + +export {}; diff --git a/node_modules/jest-runtime/build/index.js b/node_modules/jest-runtime/build/index.js new file mode 100644 index 0000000..db39773 --- /dev/null +++ b/node_modules/jest-runtime/build/index.js @@ -0,0 +1,2462 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _module() { + const data = _interopRequireDefault(require('module')); + + _module = function () { + return data; + }; + + return data; +} + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _url() { + const data = require('url'); + + _url = function () { + return data; + }; + + return data; +} + +function _vm() { + const data = require('vm'); + + _vm = function () { + return data; + }; + + return data; +} + +function _cjsModuleLexer() { + const data = require('cjs-module-lexer'); + + _cjsModuleLexer = function () { + return data; + }; + + return data; +} + +function _collectV8Coverage() { + const data = require('collect-v8-coverage'); + + _collectV8Coverage = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _slash() { + const data = _interopRequireDefault(require('slash')); + + _slash = function () { + return data; + }; + + return data; +} + +function _stripBom() { + const data = _interopRequireDefault(require('strip-bom')); + + _stripBom = function () { + return data; + }; + + return data; +} + +function _transform() { + const data = require('@jest/transform'); + + _transform = function () { + return data; + }; + + return data; +} + +function _jestHasteMap() { + const data = _interopRequireDefault(require('jest-haste-map')); + + _jestHasteMap = function () { + return data; + }; + + return data; +} + +function _jestMessageUtil() { + const data = require('jest-message-util'); + + _jestMessageUtil = function () { + return data; + }; + + return data; +} + +function _jestRegexUtil() { + const data = require('jest-regex-util'); + + _jestRegexUtil = function () { + return data; + }; + + return data; +} + +function _jestResolve() { + const data = _interopRequireDefault(require('jest-resolve')); + + _jestResolve = function () { + return data; + }; + + return data; +} + +function _jestSnapshot() { + const data = require('jest-snapshot'); + + _jestSnapshot = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var _helpers = require('./helpers'); + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const esmIsAvailable = typeof _vm().SourceTextModule === 'function'; +const dataURIRegex = + /^data:(?text\/javascript|application\/json|application\/wasm)(?:;(?charset=utf-8|base64))?,(?.*)$/; +const defaultTransformOptions = { + isInternalModule: false, + supportsDynamicImport: esmIsAvailable, + supportsExportNamespaceFrom: false, + supportsStaticESM: false, + supportsTopLevelAwait: false +}; +// These are modules that we know +// * are safe to require from the outside (not stateful, not prone to errors passing in instances from different realms), and +// * take sufficiently long to require to warrant an optimization. +// When required from the outside, they use the worker's require cache and are thus +// only loaded once per worker, not once per test file. +// Use /benchmarks/test-file-overhead to measure the impact. +// Note that this only applies when they are required in an internal context; +// users who require one of these modules in their tests will still get the module from inside the VM. +// Prefer listing a module here only if it is impractical to use the jest-resolve-outside-vm-option where it is required, +// e.g. because there are many require sites spread across the dependency graph. +const INTERNAL_MODULE_REQUIRE_OUTSIDE_OPTIMIZED_MODULES = new Set(['chalk']); +const JEST_RESOLVE_OUTSIDE_VM_OPTION = Symbol.for( + 'jest-resolve-outside-vm-option' +); +const testTimeoutSymbol = Symbol.for('TEST_TIMEOUT_SYMBOL'); +const retryTimesSymbol = Symbol.for('RETRY_TIMES'); +const logErrorsBeforeRetrySymbol = Symbol.for('LOG_ERRORS_BEFORE_RETRY'); +const NODE_MODULES = `${path().sep}node_modules${path().sep}`; + +const getModuleNameMapper = config => { + if ( + Array.isArray(config.moduleNameMapper) && + config.moduleNameMapper.length + ) { + return config.moduleNameMapper.map(([regex, moduleName]) => ({ + moduleName, + regex: new RegExp(regex) + })); + } + + return null; +}; + +const unmockRegExpCache = new WeakMap(); +const EVAL_RESULT_VARIABLE = 'Object.'; +const runtimeSupportsVmModules = typeof _vm().SyntheticModule === 'function'; + +const supportsNodeColonModulePrefixInRequire = (() => { + try { + require('node:fs'); + + return true; + } catch { + return false; + } +})(); + +class Runtime { + _cacheFS; + _config; + _coverageOptions; + _currentlyExecutingModulePath; + _environment; + _explicitShouldMock; + _explicitShouldMockModule; + _fakeTimersImplementation; + _internalModuleRegistry; + _isCurrentlyExecutingManualMock; + _mainModule; + _mockFactories; + _mockMetaDataCache; + _mockRegistry; + _isolatedMockRegistry; + _moduleMockRegistry; + _moduleMockFactories; + _moduleMocker; + _isolatedModuleRegistry; + _moduleRegistry; + _esmoduleRegistry; + _cjsNamedExports; + _esmModuleLinkingMap; + _testPath; + _resolver; + _shouldAutoMock; + _shouldMockModuleCache; + _shouldUnmockTransitiveDependenciesCache; + _sourceMapRegistry; + _scriptTransformer; + _fileTransforms; + _fileTransformsMutex; + _v8CoverageInstrumenter; + _v8CoverageResult; + _v8CoverageSources; + _transitiveShouldMock; + _unmockList; + _virtualMocks; + _virtualModuleMocks; + _moduleImplementation; + jestObjectCaches; + jestGlobals; + esmConditions; + cjsConditions; + isTornDown = false; + + constructor( + config, + environment, + resolver, + transformer, + cacheFS, + coverageOptions, + testPath + ) { + this._cacheFS = cacheFS; + this._config = config; + this._coverageOptions = coverageOptions; + this._currentlyExecutingModulePath = ''; + this._environment = environment; + this._explicitShouldMock = new Map(); + this._explicitShouldMockModule = new Map(); + this._internalModuleRegistry = new Map(); + this._isCurrentlyExecutingManualMock = null; + this._mainModule = null; + this._mockFactories = new Map(); + this._mockRegistry = new Map(); + this._moduleMockRegistry = new Map(); + this._moduleMockFactories = new Map(); + invariant( + this._environment.moduleMocker, + '`moduleMocker` must be set on an environment when created' + ); + this._moduleMocker = this._environment.moduleMocker; + this._isolatedModuleRegistry = null; + this._isolatedMockRegistry = null; + this._moduleRegistry = new Map(); + this._esmoduleRegistry = new Map(); + this._cjsNamedExports = new Map(); + this._esmModuleLinkingMap = new WeakMap(); + this._testPath = testPath; + this._resolver = resolver; + this._scriptTransformer = transformer; + this._shouldAutoMock = config.automock; + this._sourceMapRegistry = new Map(); + this._fileTransforms = new Map(); + this._fileTransformsMutex = new Map(); + this._virtualMocks = new Map(); + this._virtualModuleMocks = new Map(); + this.jestObjectCaches = new Map(); + this._mockMetaDataCache = new Map(); + this._shouldMockModuleCache = new Map(); + this._shouldUnmockTransitiveDependenciesCache = new Map(); + this._transitiveShouldMock = new Map(); + this._fakeTimersImplementation = config.fakeTimers.legacyFakeTimers + ? this._environment.fakeTimers + : this._environment.fakeTimersModern; + this._unmockList = unmockRegExpCache.get(config); + + if (!this._unmockList && config.unmockedModulePathPatterns) { + this._unmockList = new RegExp( + config.unmockedModulePathPatterns.join('|') + ); + unmockRegExpCache.set(config, this._unmockList); + } + + const envExportConditions = this._environment.exportConditions?.() ?? []; + this.esmConditions = Array.from( + new Set(['import', 'default', ...envExportConditions]) + ); + this.cjsConditions = Array.from( + new Set(['require', 'default', ...envExportConditions]) + ); + + if (config.automock) { + config.setupFiles.forEach(filePath => { + if (filePath.includes(NODE_MODULES)) { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + filePath, + undefined, // shouldn't really matter, but in theory this will make sure the caching is correct + { + conditions: this.unstable_shouldLoadAsEsm(filePath) + ? this.esmConditions + : this.cjsConditions + } + ); + + this._transitiveShouldMock.set(moduleID, false); + } + }); + } + + this.resetModules(); + } + + static shouldInstrument = _transform().shouldInstrument; + + static async createContext(config, options) { + (0, _jestUtil().createDirectory)(config.cacheDirectory); + const instance = await Runtime.createHasteMap(config, { + console: options.console, + maxWorkers: options.maxWorkers, + resetCache: !config.cache, + watch: options.watch, + watchman: options.watchman + }); + const hasteMap = await instance.build(); + return { + config, + hasteFS: hasteMap.hasteFS, + moduleMap: hasteMap.moduleMap, + resolver: Runtime.createResolver(config, hasteMap.moduleMap) + }; + } + + static createHasteMap(config, options) { + const ignorePatternParts = [ + ...config.modulePathIgnorePatterns, + ...(options && options.watch ? config.watchPathIgnorePatterns : []), + config.cacheDirectory.startsWith(config.rootDir + path().sep) && + config.cacheDirectory + ].filter(Boolean); + const ignorePattern = + ignorePatternParts.length > 0 + ? new RegExp(ignorePatternParts.join('|')) + : undefined; + return _jestHasteMap().default.create({ + cacheDirectory: config.cacheDirectory, + computeSha1: config.haste.computeSha1, + console: options?.console, + dependencyExtractor: config.dependencyExtractor, + enableSymlinks: config.haste.enableSymlinks, + extensions: [_jestSnapshot().EXTENSION].concat( + config.moduleFileExtensions + ), + forceNodeFilesystemAPI: config.haste.forceNodeFilesystemAPI, + hasteImplModulePath: config.haste.hasteImplModulePath, + hasteMapModulePath: config.haste.hasteMapModulePath, + id: config.id, + ignorePattern, + maxWorkers: options?.maxWorkers || 1, + mocksPattern: (0, _jestRegexUtil().escapePathForRegex)( + `${path().sep}__mocks__${path().sep}` + ), + platforms: config.haste.platforms || ['ios', 'android'], + resetCache: options?.resetCache, + retainAllFiles: config.haste.retainAllFiles || false, + rootDir: config.rootDir, + roots: config.roots, + throwOnModuleCollision: config.haste.throwOnModuleCollision, + useWatchman: options?.watchman, + watch: options?.watch + }); + } + + static createResolver(config, moduleMap) { + return new (_jestResolve().default)(moduleMap, { + defaultPlatform: config.haste.defaultPlatform, + extensions: config.moduleFileExtensions.map(extension => `.${extension}`), + hasCoreModules: true, + moduleDirectories: config.moduleDirectories, + moduleNameMapper: getModuleNameMapper(config), + modulePaths: config.modulePaths, + platforms: config.haste.platforms, + resolver: config.resolver, + rootDir: config.rootDir + }); + } + + static async runCLI() { + throw new Error('The jest-runtime CLI has been moved into jest-repl'); + } + + static getCLIOptions() { + throw new Error('The jest-runtime CLI has been moved into jest-repl'); + } // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it + + unstable_shouldLoadAsEsm(path) { + return _jestResolve().default.unstable_shouldLoadAsEsm( + path, + this._config.extensionsToTreatAsEsm + ); + } // not async _now_, but transform will be + + async loadEsmModule(modulePath, query = '') { + const cacheKey = modulePath + query; + + if (this._fileTransformsMutex.has(cacheKey)) { + await this._fileTransformsMutex.get(cacheKey); + } + + if (!this._esmoduleRegistry.has(cacheKey)) { + invariant( + typeof this._environment.getVmContext === 'function', + 'ES Modules are only supported if your test environment has the `getVmContext` function' + ); + + const context = this._environment.getVmContext(); + + invariant(context, 'Test environment has been torn down'); + let transformResolve; + let transformReject; + + this._fileTransformsMutex.set( + cacheKey, + new Promise((resolve, reject) => { + transformResolve = resolve; + transformReject = reject; + }) + ); + + invariant( + transformResolve && transformReject, + 'Promise initialization should be sync - please report this bug to Jest!' + ); + + if (this._resolver.isCoreModule(modulePath)) { + const core = this._importCoreModule(modulePath, context); + + this._esmoduleRegistry.set(cacheKey, core); + + transformResolve(); + return core; + } + + const transformedCode = await this.transformFileAsync(modulePath, { + isInternalModule: false, + supportsDynamicImport: true, + supportsExportNamespaceFrom: true, + supportsStaticESM: true, + supportsTopLevelAwait: true + }); + + try { + const module = new (_vm().SourceTextModule)(transformedCode, { + context, + identifier: modulePath, + importModuleDynamically: async (specifier, referencingModule) => { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const module = await this.resolveModule( + specifier, + referencingModule.identifier, + referencingModule.context + ); + return this.linkAndEvaluateModule(module); + }, + initializeImportMeta: meta => { + meta.url = (0, _url().pathToFileURL)(modulePath).href; + let jest = this.jestObjectCaches.get(modulePath); + + if (!jest) { + jest = this._createJestObjectFor(modulePath); + this.jestObjectCaches.set(modulePath, jest); + } + + meta.jest = jest; + } + }); + invariant( + !this._esmoduleRegistry.has(cacheKey), + `Module cache already has entry ${cacheKey}. This is a bug in Jest, please report it!` + ); + + this._esmoduleRegistry.set(cacheKey, module); + + transformResolve(); + } catch (error) { + transformReject(error); + throw error; + } + } + + const module = this._esmoduleRegistry.get(cacheKey); + + invariant( + module, + 'Module cache does not contain module. This is a bug in Jest, please open up an issue' + ); + return module; + } + + async resolveModule(specifier, referencingIdentifier, context) { + if (this.isTornDown) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + + process.exitCode = 1; // @ts-expect-error - exiting + + return; + } + + if (specifier === '@jest/globals') { + const fromCache = this._esmoduleRegistry.get('@jest/globals'); + + if (fromCache) { + return fromCache; + } + + const globals = this.getGlobalsForEsm(referencingIdentifier, context); + + this._esmoduleRegistry.set('@jest/globals', globals); + + return globals; + } + + if (specifier.startsWith('data:')) { + if ( + await this._shouldMockModule( + referencingIdentifier, + specifier, + this._explicitShouldMockModule + ) + ) { + return this.importMock(referencingIdentifier, specifier, context); + } + + const fromCache = this._esmoduleRegistry.get(specifier); + + if (fromCache) { + return fromCache; + } + + const match = specifier.match(dataURIRegex); + + if (!match || !match.groups) { + throw new Error('Invalid data URI'); + } + + const mime = match.groups.mime; + + if (mime === 'application/wasm') { + throw new Error('WASM is currently not supported'); + } + + const encoding = match.groups.encoding; + let code = match.groups.code; + + if (!encoding || encoding === 'charset=utf-8') { + code = decodeURIComponent(code); + } else if (encoding === 'base64') { + code = Buffer.from(code, 'base64').toString(); + } else { + throw new Error(`Invalid data URI encoding: ${encoding}`); + } + + let module; + + if (mime === 'application/json') { + module = new (_vm().SyntheticModule)( + ['default'], + function () { + const obj = JSON.parse(code); // @ts-expect-error: TS doesn't know what `this` is + + this.setExport('default', obj); + }, + { + context, + identifier: specifier + } + ); + } else { + module = new (_vm().SourceTextModule)(code, { + context, + identifier: specifier, + importModuleDynamically: async (specifier, referencingModule) => { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const module = await this.resolveModule( + specifier, + referencingModule.identifier, + referencingModule.context + ); + return this.linkAndEvaluateModule(module); + }, + + initializeImportMeta(meta) { + // no `jest` here as it's not loaded in a file + meta.url = specifier; + } + }); + } + + this._esmoduleRegistry.set(specifier, module); + + return module; + } + + if (specifier.startsWith('file://')) { + specifier = (0, _url().fileURLToPath)(specifier); + } + + const [path, query] = specifier.split('?'); + + if ( + await this._shouldMockModule( + referencingIdentifier, + path, + this._explicitShouldMockModule + ) + ) { + return this.importMock(referencingIdentifier, path, context); + } + + const resolved = await this._resolveModule(referencingIdentifier, path); + + if ( + this._resolver.isCoreModule(resolved) || + this.unstable_shouldLoadAsEsm(resolved) + ) { + return this.loadEsmModule(resolved, query); + } + + return this.loadCjsAsEsm(referencingIdentifier, resolved, context); + } + + async linkAndEvaluateModule(module) { + if (this.isTornDown) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + + process.exitCode = 1; + return; + } + + if (module.status === 'unlinked') { + // since we might attempt to link the same module in parallel, stick the promise in a weak map so every call to + // this method can await it + this._esmModuleLinkingMap.set( + module, + module.link((specifier, referencingModule) => + this.resolveModule( + specifier, + referencingModule.identifier, + referencingModule.context + ) + ) + ); + } + + await this._esmModuleLinkingMap.get(module); + + if (module.status === 'linked') { + await module.evaluate(); + } + + return module; + } + + async unstable_importModule(from, moduleName) { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const [path, query] = (moduleName ?? '').split('?'); + const modulePath = await this._resolveModule(from, path); + const module = await this.loadEsmModule(modulePath, query); + return this.linkAndEvaluateModule(module); + } + + loadCjsAsEsm(from, modulePath, context) { + // CJS loaded via `import` should share cache with other CJS: https://github.com/nodejs/modules/issues/503 + const cjs = this.requireModuleOrMock(from, modulePath); + const parsedExports = this.getExportsOfCjs(modulePath); + const cjsExports = [...parsedExports].filter(exportName => { + // we don't wanna respect any exports _named_ default as a named export + if (exportName === 'default') { + return false; + } + + return Object.hasOwnProperty.call(cjs, exportName); + }); + const module = new (_vm().SyntheticModule)( + [...cjsExports, 'default'], + function () { + cjsExports.forEach(exportName => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(exportName, cjs[exportName]); + }); // @ts-expect-error: TS doesn't know what `this` is + + this.setExport('default', cjs); + }, + { + context, + identifier: modulePath + } + ); + return evaluateSyntheticModule(module); + } + + async importMock(from, moduleName, context) { + const moduleID = await this._resolver.getModuleIDAsync( + this._virtualModuleMocks, + from, + moduleName, + { + conditions: this.esmConditions + } + ); + + if (this._moduleMockRegistry.has(moduleID)) { + return this._moduleMockRegistry.get(moduleID); + } + + if (this._moduleMockFactories.has(moduleID)) { + const invokedFactory = await this._moduleMockFactories.get( + moduleID // has check above makes this ok + )(); + const module = new (_vm().SyntheticModule)( + Object.keys(invokedFactory), + function () { + Object.entries(invokedFactory).forEach(([key, value]) => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(key, value); + }); + }, + { + context, + identifier: moduleName + } + ); + + this._moduleMockRegistry.set(moduleID, module); + + return evaluateSyntheticModule(module); + } + + throw new Error('Attempting to import a mock without a factory'); + } + + getExportsOfCjs(modulePath) { + const cachedNamedExports = this._cjsNamedExports.get(modulePath); + + if (cachedNamedExports) { + return cachedNamedExports; + } + + const transformedCode = + this._fileTransforms.get(modulePath)?.code ?? this.readFile(modulePath); + const {exports, reexports} = (0, _cjsModuleLexer().parse)(transformedCode); + const namedExports = new Set(exports); + reexports.forEach(reexport => { + const resolved = this._resolveCjsModule(modulePath, reexport); + + const exports = this.getExportsOfCjs(resolved); + exports.forEach(namedExports.add, namedExports); + }); + + this._cjsNamedExports.set(modulePath, namedExports); + + return namedExports; + } + + requireModule(from, moduleName, options, isRequireActual = false) { + const isInternal = options?.isInternalModule ?? false; + + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + + let modulePath; // Some old tests rely on this mocking behavior. Ideally we'll change this + // to be more explicit. + + const moduleResource = moduleName && this._resolver.getModule(moduleName); + + const manualMock = + moduleName && this._resolver.getMockModule(from, moduleName); + + if ( + !options?.isInternalModule && + !isRequireActual && + !moduleResource && + manualMock && + manualMock !== this._isCurrentlyExecutingManualMock && + this._explicitShouldMock.get(moduleID) !== false + ) { + modulePath = manualMock; + } + + if (moduleName && this._resolver.isCoreModule(moduleName)) { + return this._requireCoreModule( + moduleName, + supportsNodeColonModulePrefixInRequire + ); + } + + if (!modulePath) { + modulePath = this._resolveCjsModule(from, moduleName); + } + + if (this.unstable_shouldLoadAsEsm(modulePath)) { + // Node includes more info in the message + const error = new Error( + `Must use import to load ES Module: ${modulePath}` + ); + error.code = 'ERR_REQUIRE_ESM'; + throw error; + } + + let moduleRegistry; + + if (isInternal) { + moduleRegistry = this._internalModuleRegistry; + } else if (this._isolatedModuleRegistry) { + moduleRegistry = this._isolatedModuleRegistry; + } else { + moduleRegistry = this._moduleRegistry; + } + + const module = moduleRegistry.get(modulePath); + + if (module) { + return module.exports; + } // We must register the pre-allocated module object first so that any + // circular dependencies that may arise while evaluating the module can + // be satisfied. + + const localModule = { + children: [], + exports: {}, + filename: modulePath, + id: modulePath, + loaded: false, + path: path().dirname(modulePath) + }; + moduleRegistry.set(modulePath, localModule); + + try { + this._loadModule( + localModule, + from, + moduleName, + modulePath, + options, + moduleRegistry + ); + } catch (error) { + moduleRegistry.delete(modulePath); + throw error; + } + + return localModule.exports; + } + + requireInternalModule(from, to) { + if (to) { + const require = ( + _module().default.createRequire ?? + _module().default.createRequireFromPath + )(from); + + if (INTERNAL_MODULE_REQUIRE_OUTSIDE_OPTIMIZED_MODULES.has(to)) { + return require(to); + } + + const outsideJestVmPath = (0, _helpers.decodePossibleOutsideJestVmPath)( + to + ); + + if (outsideJestVmPath) { + return require(outsideJestVmPath); + } + } + + return this.requireModule(from, to, { + isInternalModule: true, + supportsDynamicImport: esmIsAvailable, + supportsExportNamespaceFrom: false, + supportsStaticESM: false, + supportsTopLevelAwait: false + }); + } + + requireActual(from, moduleName) { + return this.requireModule(from, moduleName, undefined, true); + } + + requireMock(from, moduleName) { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + + if (this._isolatedMockRegistry?.has(moduleID)) { + return this._isolatedMockRegistry.get(moduleID); + } else if (this._mockRegistry.has(moduleID)) { + return this._mockRegistry.get(moduleID); + } + + const mockRegistry = this._isolatedMockRegistry || this._mockRegistry; + + if (this._mockFactories.has(moduleID)) { + // has check above makes this ok + const module = this._mockFactories.get(moduleID)(); + + mockRegistry.set(moduleID, module); + return module; + } + + const manualMockOrStub = this._resolver.getMockModule(from, moduleName); + + let modulePath = + this._resolver.getMockModule(from, moduleName) || + this._resolveCjsModule(from, moduleName); + + let isManualMock = + manualMockOrStub && + !this._resolver.resolveStubModuleName(from, moduleName); + + if (!isManualMock) { + // If the actual module file has a __mocks__ dir sitting immediately next + // to it, look to see if there is a manual mock for this file. + // + // subDir1/my_module.js + // subDir1/__mocks__/my_module.js + // subDir2/my_module.js + // subDir2/__mocks__/my_module.js + // + // Where some other module does a relative require into each of the + // respective subDir{1,2} directories and expects a manual mock + // corresponding to that particular my_module.js file. + const moduleDir = path().dirname(modulePath); + const moduleFileName = path().basename(modulePath); + const potentialManualMock = path().join( + moduleDir, + '__mocks__', + moduleFileName + ); + + if (fs().existsSync(potentialManualMock)) { + isManualMock = true; + modulePath = potentialManualMock; + } + } + + if (isManualMock) { + const localModule = { + children: [], + exports: {}, + filename: modulePath, + id: modulePath, + loaded: false, + path: path().dirname(modulePath) + }; + + this._loadModule( + localModule, + from, + moduleName, + modulePath, + undefined, + mockRegistry + ); + + mockRegistry.set(moduleID, localModule.exports); + } else { + // Look for a real module to generate an automock from + mockRegistry.set(moduleID, this._generateMock(from, moduleName)); + } + + return mockRegistry.get(moduleID); + } + + _loadModule( + localModule, + from, + moduleName, + modulePath, + options, + moduleRegistry + ) { + if (path().extname(modulePath) === '.json') { + const text = (0, _stripBom().default)(this.readFile(modulePath)); + + const transformedFile = this._scriptTransformer.transformJson( + modulePath, + this._getFullTransformationOptions(options), + text + ); + + localModule.exports = + this._environment.global.JSON.parse(transformedFile); + } else if (path().extname(modulePath) === '.node') { + localModule.exports = require(modulePath); + } else { + // Only include the fromPath if a moduleName is given. Else treat as root. + const fromPath = moduleName ? from : null; + + this._execModule(localModule, options, moduleRegistry, fromPath); + } + + localModule.loaded = true; + } + + _getFullTransformationOptions(options = defaultTransformOptions) { + return {...options, ...this._coverageOptions}; + } + + requireModuleOrMock(from, moduleName) { + // this module is unmockable + if (moduleName === '@jest/globals') { + // @ts-expect-error: we don't care that it's not assignable to T + return this.getGlobalsForCjs(from); + } + + try { + if (this._shouldMockCjs(from, moduleName, this._explicitShouldMock)) { + return this.requireMock(from, moduleName); + } else { + return this.requireModule(from, moduleName); + } + } catch (e) { + const moduleNotFound = + _jestResolve().default.tryCastModuleNotFoundError(e); + + if (moduleNotFound) { + if ( + moduleNotFound.siblingWithSimilarExtensionFound === null || + moduleNotFound.siblingWithSimilarExtensionFound === undefined + ) { + moduleNotFound.hint = (0, _helpers.findSiblingsWithFileExtension)( + this._config.moduleFileExtensions, + from, + moduleNotFound.moduleName || moduleName + ); + moduleNotFound.siblingWithSimilarExtensionFound = Boolean( + moduleNotFound.hint + ); + } + + moduleNotFound.buildMessage(this._config.rootDir); + throw moduleNotFound; + } + + throw e; + } + } + + isolateModules(fn) { + if (this._isolatedModuleRegistry || this._isolatedMockRegistry) { + throw new Error( + 'isolateModules cannot be nested inside another isolateModules.' + ); + } + + this._isolatedModuleRegistry = new Map(); + this._isolatedMockRegistry = new Map(); + + try { + fn(); + } finally { + // might be cleared within the callback + this._isolatedModuleRegistry?.clear(); + this._isolatedMockRegistry?.clear(); + this._isolatedModuleRegistry = null; + this._isolatedMockRegistry = null; + } + } + + resetModules() { + this._isolatedModuleRegistry?.clear(); + this._isolatedMockRegistry?.clear(); + this._isolatedModuleRegistry = null; + this._isolatedMockRegistry = null; + + this._mockRegistry.clear(); + + this._moduleRegistry.clear(); + + this._esmoduleRegistry.clear(); + + this._cjsNamedExports.clear(); + + this._moduleMockRegistry.clear(); + + this._cacheFS.clear(); + + if ( + this._coverageOptions.collectCoverage && + this._coverageOptions.coverageProvider === 'v8' && + this._v8CoverageSources + ) { + this._v8CoverageSources = new Map([ + ...this._v8CoverageSources, + ...this._fileTransforms + ]); + } + + this._fileTransforms.clear(); + + if (this._environment) { + if (this._environment.global) { + const envGlobal = this._environment.global; + Object.keys(envGlobal).forEach(key => { + const globalMock = envGlobal[key]; + + if ( + ((typeof globalMock === 'object' && globalMock !== null) || + typeof globalMock === 'function') && + globalMock._isMockFunction === true + ) { + globalMock.mockClear(); + } + }); + } + + if (this._environment.fakeTimers) { + this._environment.fakeTimers.clearAllTimers(); + } + } + } + + async collectV8Coverage() { + this._v8CoverageInstrumenter = + new (_collectV8Coverage().CoverageInstrumenter)(); + this._v8CoverageSources = new Map(); + await this._v8CoverageInstrumenter.startInstrumenting(); + } + + async stopCollectingV8Coverage() { + if (!this._v8CoverageInstrumenter || !this._v8CoverageSources) { + throw new Error('You need to call `collectV8Coverage` first.'); + } + + this._v8CoverageResult = + await this._v8CoverageInstrumenter.stopInstrumenting(); + this._v8CoverageSources = new Map([ + ...this._v8CoverageSources, + ...this._fileTransforms + ]); + } + + getAllCoverageInfoCopy() { + return (0, _jestUtil().deepCyclicCopy)( + this._environment.global.__coverage__ + ); + } + + getAllV8CoverageInfoCopy() { + if (!this._v8CoverageResult || !this._v8CoverageSources) { + throw new Error('You need to call `stopCollectingV8Coverage` first.'); + } + + return this._v8CoverageResult + .filter(res => res.url.startsWith('file://')) + .map(res => ({...res, url: (0, _url().fileURLToPath)(res.url)})) + .filter( + ( + res // TODO: will this work on windows? It might be better if `shouldInstrument` deals with it anyways + ) => + res.url.startsWith(this._config.rootDir) && + this._v8CoverageSources.has(res.url) && + (0, _transform().shouldInstrument)( + res.url, + this._coverageOptions, + this._config + ) + ) + .map(result => { + const transformedFile = this._v8CoverageSources.get(result.url); + + return { + codeTransformResult: transformedFile, + result + }; + }); + } + + getSourceMaps() { + return this._sourceMapRegistry; + } + + setMock(from, moduleName, mockFactory, options) { + if (options?.virtual) { + const mockPath = this._resolver.getModulePath(from, moduleName); + + this._virtualMocks.set(mockPath, true); + } + + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + + this._explicitShouldMock.set(moduleID, true); + + this._mockFactories.set(moduleID, mockFactory); + } + + setModuleMock(from, moduleName, mockFactory, options) { + if (options?.virtual) { + const mockPath = this._resolver.getModulePath(from, moduleName); + + this._virtualModuleMocks.set(mockPath, true); + } + + const moduleID = this._resolver.getModuleID( + this._virtualModuleMocks, + from, + moduleName, + { + conditions: this.esmConditions + } + ); + + this._explicitShouldMockModule.set(moduleID, true); + + this._moduleMockFactories.set(moduleID, mockFactory); + } + + restoreAllMocks() { + this._moduleMocker.restoreAllMocks(); + } + + resetAllMocks() { + this._moduleMocker.resetAllMocks(); + } + + clearAllMocks() { + this._moduleMocker.clearAllMocks(); + } + + teardown() { + this.restoreAllMocks(); + this.resetAllMocks(); + this.resetModules(); + + this._internalModuleRegistry.clear(); + + this._mainModule = null; + + this._mockFactories.clear(); + + this._moduleMockFactories.clear(); + + this._mockMetaDataCache.clear(); + + this._shouldMockModuleCache.clear(); + + this._shouldUnmockTransitiveDependenciesCache.clear(); + + this._explicitShouldMock.clear(); + + this._explicitShouldMockModule.clear(); + + this._transitiveShouldMock.clear(); + + this._virtualMocks.clear(); + + this._virtualModuleMocks.clear(); + + this._cacheFS.clear(); + + this._unmockList = undefined; + + this._sourceMapRegistry.clear(); + + this._fileTransforms.clear(); + + this._fileTransformsMutex.clear(); + + this.jestObjectCaches.clear(); + this._v8CoverageSources?.clear(); + this._v8CoverageResult = []; + this._v8CoverageInstrumenter = undefined; + this._moduleImplementation = undefined; + this.isTornDown = true; + } + + _resolveCjsModule(from, to) { + return to + ? this._resolver.resolveModule(from, to, { + conditions: this.cjsConditions + }) + : from; + } + + _resolveModule(from, to) { + return to + ? this._resolver.resolveModuleAsync(from, to, { + conditions: this.esmConditions + }) + : from; + } + + _requireResolve(from, moduleName, options = {}) { + if (moduleName == null) { + throw new Error( + 'The first argument to require.resolve must be a string. Received null or undefined.' + ); + } + + if (path().isAbsolute(moduleName)) { + const module = this._resolver.resolveModuleFromDirIfExists( + moduleName, + moduleName, + { + conditions: this.cjsConditions, + paths: [] + } + ); + + if (module) { + return module; + } + } else { + const {paths} = options; + + if (paths) { + for (const p of paths) { + const absolutePath = path().resolve(from, '..', p); + + const module = this._resolver.resolveModuleFromDirIfExists( + absolutePath, + moduleName, // required to also resolve files without leading './' directly in the path + { + conditions: this.cjsConditions, + paths: [absolutePath] + } + ); + + if (module) { + return module; + } + } + + throw new (_jestResolve().default.ModuleNotFoundError)( + `Cannot resolve module '${moduleName}' from paths ['${paths.join( + "', '" + )}'] from ${from}` + ); + } + } + + try { + return this._resolveCjsModule(from, moduleName); + } catch (err) { + const module = this._resolver.getMockModule(from, moduleName); + + if (module) { + return module; + } else { + throw err; + } + } + } + + _requireResolvePaths(from, moduleName) { + if (moduleName == null) { + throw new Error( + 'The first argument to require.resolve.paths must be a string. Received null or undefined.' + ); + } + + if (!moduleName.length) { + throw new Error( + 'The first argument to require.resolve.paths must not be the empty string.' + ); + } + + if (moduleName[0] === '.') { + return [path().resolve(from, '..')]; + } + + if (this._resolver.isCoreModule(moduleName)) { + return null; + } + + return this._resolver.getModulePaths(path().resolve(from, '..')); + } + + _execModule(localModule, options, moduleRegistry, from) { + if (this.isTornDown) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + + process.exitCode = 1; + return; + } // If the environment was disposed, prevent this module from being executed. + + if (!this._environment.global) { + return; + } + + const module = localModule; + const filename = module.filename; + const lastExecutingModulePath = this._currentlyExecutingModulePath; + this._currentlyExecutingModulePath = filename; + const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock; + this._isCurrentlyExecutingManualMock = filename; + module.children = []; + Object.defineProperty(module, 'parent', { + enumerable: true, + + get() { + const key = from || ''; + return moduleRegistry.get(key) || null; + } + }); + module.paths = this._resolver.getModulePaths(module.path); + Object.defineProperty(module, 'require', { + value: this._createRequireImplementation(module, options) + }); + const transformedCode = this.transformFile(filename, options); + let compiledFunction = null; + const script = this.createScriptFromCode(transformedCode, filename); + let runScript = null; + + const vmContext = this._environment.getVmContext(); + + if (vmContext) { + runScript = script.runInContext(vmContext, { + filename + }); + } + + if (runScript !== null) { + compiledFunction = runScript[EVAL_RESULT_VARIABLE]; + } + + if (compiledFunction === null) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + + process.exitCode = 1; + return; + } + + const jestObject = this._createJestObjectFor(filename); + + this.jestObjectCaches.set(filename, jestObject); + const lastArgs = [ + this._config.injectGlobals ? jestObject : undefined, // jest object + ...this._config.sandboxInjectedGlobals.map(globalVariable => { + if (this._environment.global[globalVariable]) { + return this._environment.global[globalVariable]; + } + + throw new Error( + `You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.` + ); + }) + ]; + + if (!this._mainModule && filename === this._testPath) { + this._mainModule = module; + } + + Object.defineProperty(module, 'main', { + enumerable: true, + value: this._mainModule + }); + + try { + compiledFunction.call( + module.exports, + module, // module object + module.exports, // module exports + module.require, // require implementation + module.path, // __dirname + module.filename, // __filename + lastArgs[0], + ...lastArgs.slice(1).filter(notEmpty) + ); + } catch (error) { + this.handleExecutionError(error, module); + } + + this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock; + this._currentlyExecutingModulePath = lastExecutingModulePath; + } + + transformFile(filename, options) { + const source = this.readFile(filename); + + if (options?.isInternalModule) { + return source; + } + + let transformedFile = this._fileTransforms.get(filename); + + if (transformedFile) { + return transformedFile.code; + } + + transformedFile = this._scriptTransformer.transform( + filename, + this._getFullTransformationOptions(options), + source + ); + + this._fileTransforms.set(filename, { + ...transformedFile, + wrapperLength: this.constructModuleWrapperStart().length + }); + + if (transformedFile.sourceMapPath) { + this._sourceMapRegistry.set(filename, transformedFile.sourceMapPath); + } + + return transformedFile.code; + } + + async transformFileAsync(filename, options) { + const source = this.readFile(filename); + + if (options?.isInternalModule) { + return source; + } + + let transformedFile = this._fileTransforms.get(filename); + + if (transformedFile) { + return transformedFile.code; + } + + transformedFile = await this._scriptTransformer.transformAsync( + filename, + this._getFullTransformationOptions(options), + source + ); + + this._fileTransforms.set(filename, {...transformedFile, wrapperLength: 0}); + + if (transformedFile.sourceMapPath) { + this._sourceMapRegistry.set(filename, transformedFile.sourceMapPath); + } + + return transformedFile.code; + } + + createScriptFromCode(scriptSource, filename) { + try { + const scriptFilename = this._resolver.isCoreModule(filename) + ? `jest-nodejs-core-${filename}` + : filename; + return new (_vm().Script)(this.wrapCodeInModuleWrapper(scriptSource), { + displayErrors: true, + filename: scriptFilename, + // @ts-expect-error: Experimental ESM API + importModuleDynamically: async specifier => { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const context = this._environment.getVmContext?.(); + invariant(context, 'Test environment has been torn down'); + const module = await this.resolveModule( + specifier, + scriptFilename, + context + ); + return this.linkAndEvaluateModule(module); + } + }); + } catch (e) { + throw (0, _transform().handlePotentialSyntaxError)(e); + } + } + + _requireCoreModule(moduleName, supportPrefix) { + const moduleWithoutNodePrefix = + supportPrefix && moduleName.startsWith('node:') + ? moduleName.slice('node:'.length) + : moduleName; + + if (moduleWithoutNodePrefix === 'process') { + return this._environment.global.process; + } + + if (moduleWithoutNodePrefix === 'module') { + return this._getMockedNativeModule(); + } + + return require(moduleWithoutNodePrefix); + } + + _importCoreModule(moduleName, context) { + const required = this._requireCoreModule(moduleName, true); + + const module = new (_vm().SyntheticModule)( + ['default', ...Object.keys(required)], + function () { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport('default', required); + Object.entries(required).forEach(([key, value]) => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(key, value); + }); + }, // should identifier be `node://${moduleName}`? + { + context, + identifier: moduleName + } + ); + return evaluateSyntheticModule(module); + } + + _getMockedNativeModule() { + if (this._moduleImplementation) { + return this._moduleImplementation; + } + + const createRequire = modulePath => { + const filename = + typeof modulePath === 'string' + ? modulePath.startsWith('file:///') + ? (0, _url().fileURLToPath)(new (_url().URL)(modulePath)) + : modulePath + : (0, _url().fileURLToPath)(modulePath); + + if (!path().isAbsolute(filename)) { + const error = new TypeError( + `The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received '${filename}'` + ); + error.code = 'ERR_INVALID_ARG_TYPE'; + throw error; + } + + return this._createRequireImplementation({ + children: [], + exports: {}, + filename, + id: filename, + loaded: false, + path: path().dirname(filename) + }); + }; // should we implement the class ourselves? + + class Module extends _module().default.Module {} + + Object.entries(_module().default.Module).forEach(([key, value]) => { + // @ts-expect-error: no index signature + Module[key] = value; + }); + Module.Module = Module; + + if ('createRequire' in _module().default) { + Module.createRequire = createRequire; + } + + if ('createRequireFromPath' in _module().default) { + Module.createRequireFromPath = function createRequireFromPath(filename) { + if (typeof filename !== 'string') { + const error = new TypeError( + `The argument 'filename' must be string. Received '${filename}'.${ + filename instanceof _url().URL + ? ' Use createRequire for URL filename.' + : '' + }` + ); + error.code = 'ERR_INVALID_ARG_TYPE'; + throw error; + } + + return createRequire(filename); + }; + } + + if ('syncBuiltinESMExports' in _module().default) { + // cast since TS seems very confused about whether it exists or not + Module.syncBuiltinESMExports = // eslint-disable-next-line @typescript-eslint/no-empty-function + function syncBuiltinESMExports() {}; + } + + this._moduleImplementation = Module; + return Module; + } + + _generateMock(from, moduleName) { + const modulePath = + this._resolver.resolveStubModuleName(from, moduleName) || + this._resolveCjsModule(from, moduleName); + + if (!this._mockMetaDataCache.has(modulePath)) { + // This allows us to handle circular dependencies while generating an + // automock + this._mockMetaDataCache.set( + modulePath, + this._moduleMocker.getMetadata({}) || {} + ); // In order to avoid it being possible for automocking to potentially + // cause side-effects within the module environment, we need to execute + // the module in isolation. This could cause issues if the module being + // mocked has calls into side-effectful APIs on another module. + + const origMockRegistry = this._mockRegistry; + const origModuleRegistry = this._moduleRegistry; + this._mockRegistry = new Map(); + this._moduleRegistry = new Map(); + const moduleExports = this.requireModule(from, moduleName); // Restore the "real" module/mock registries + + this._mockRegistry = origMockRegistry; + this._moduleRegistry = origModuleRegistry; + + const mockMetadata = this._moduleMocker.getMetadata(moduleExports); + + if (mockMetadata == null) { + throw new Error( + `Failed to get mock metadata: ${modulePath}\n\n` + + 'See: https://jestjs.io/docs/manual-mocks#content' + ); + } + + this._mockMetaDataCache.set(modulePath, mockMetadata); + } + + return this._moduleMocker.generateFromMetadata( + // added above if missing + this._mockMetaDataCache.get(modulePath) + ); + } + + _shouldMockCjs(from, moduleName, explicitShouldMock) { + const options = { + conditions: this.cjsConditions + }; + + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + options + ); + + const key = from + path().delimiter + moduleID; + + if (explicitShouldMock.has(moduleID)) { + // guaranteed by `has` above + return explicitShouldMock.get(moduleID); + } + + if ( + !this._shouldAutoMock || + this._resolver.isCoreModule(moduleName) || + this._shouldUnmockTransitiveDependenciesCache.get(key) + ) { + return false; + } + + if (this._shouldMockModuleCache.has(moduleID)) { + // guaranteed by `has` above + return this._shouldMockModuleCache.get(moduleID); + } + + let modulePath; + + try { + modulePath = this._resolveCjsModule(from, moduleName); + } catch (e) { + const manualMock = this._resolver.getMockModule(from, moduleName); + + if (manualMock) { + this._shouldMockModuleCache.set(moduleID, true); + + return true; + } + + throw e; + } + + if (this._unmockList && this._unmockList.test(modulePath)) { + this._shouldMockModuleCache.set(moduleID, false); + + return false; + } // transitive unmocking for package managers that store flat packages (npm3) + + const currentModuleID = this._resolver.getModuleID( + this._virtualMocks, + from, + undefined, + options + ); + + if ( + this._transitiveShouldMock.get(currentModuleID) === false || + (from.includes(NODE_MODULES) && + modulePath.includes(NODE_MODULES) && + ((this._unmockList && this._unmockList.test(from)) || + explicitShouldMock.get(currentModuleID) === false)) + ) { + this._transitiveShouldMock.set(moduleID, false); + + this._shouldUnmockTransitiveDependenciesCache.set(key, true); + + return false; + } + + this._shouldMockModuleCache.set(moduleID, true); + + return true; + } + + async _shouldMockModule(from, moduleName, explicitShouldMock) { + const options = { + conditions: this.esmConditions + }; + const moduleID = await this._resolver.getModuleIDAsync( + this._virtualMocks, + from, + moduleName, + options + ); + const key = from + path().delimiter + moduleID; + + if (explicitShouldMock.has(moduleID)) { + // guaranteed by `has` above + return explicitShouldMock.get(moduleID); + } + + if ( + !this._shouldAutoMock || + this._resolver.isCoreModule(moduleName) || + this._shouldUnmockTransitiveDependenciesCache.get(key) + ) { + return false; + } + + if (this._shouldMockModuleCache.has(moduleID)) { + // guaranteed by `has` above + return this._shouldMockModuleCache.get(moduleID); + } + + let modulePath; + + try { + modulePath = await this._resolveModule(from, moduleName); + } catch (e) { + const manualMock = await this._resolver.getMockModuleAsync( + from, + moduleName + ); + + if (manualMock) { + this._shouldMockModuleCache.set(moduleID, true); + + return true; + } + + throw e; + } + + if (this._unmockList && this._unmockList.test(modulePath)) { + this._shouldMockModuleCache.set(moduleID, false); + + return false; + } // transitive unmocking for package managers that store flat packages (npm3) + + const currentModuleID = await this._resolver.getModuleIDAsync( + this._virtualMocks, + from, + undefined, + options + ); + + if ( + this._transitiveShouldMock.get(currentModuleID) === false || + (from.includes(NODE_MODULES) && + modulePath.includes(NODE_MODULES) && + ((this._unmockList && this._unmockList.test(from)) || + explicitShouldMock.get(currentModuleID) === false)) + ) { + this._transitiveShouldMock.set(moduleID, false); + + this._shouldUnmockTransitiveDependenciesCache.set(key, true); + + return false; + } + + this._shouldMockModuleCache.set(moduleID, true); + + return true; + } + + _createRequireImplementation(from, options) { + const resolve = (moduleName, resolveOptions) => { + const resolved = this._requireResolve( + from.filename, + moduleName, + resolveOptions + ); + + if ( + resolveOptions?.[JEST_RESOLVE_OUTSIDE_VM_OPTION] && + options?.isInternalModule + ) { + return (0, _helpers.createOutsideJestVmPath)(resolved); + } + + return resolved; + }; + + resolve.paths = moduleName => + this._requireResolvePaths(from.filename, moduleName); + + const moduleRequire = options?.isInternalModule + ? moduleName => this.requireInternalModule(from.filename, moduleName) + : this.requireModuleOrMock.bind(this, from.filename); + moduleRequire.extensions = Object.create(null); + moduleRequire.resolve = resolve; + + moduleRequire.cache = (() => { + // TODO: consider warning somehow that this does nothing. We should support deletions, anyways + const notPermittedMethod = () => true; + + return new Proxy(Object.create(null), { + defineProperty: notPermittedMethod, + deleteProperty: notPermittedMethod, + get: (_target, key) => + typeof key === 'string' ? this._moduleRegistry.get(key) : undefined, + + getOwnPropertyDescriptor() { + return { + configurable: true, + enumerable: true + }; + }, + + has: (_target, key) => + typeof key === 'string' && this._moduleRegistry.has(key), + ownKeys: () => Array.from(this._moduleRegistry.keys()), + set: notPermittedMethod + }); + })(); + + Object.defineProperty(moduleRequire, 'main', { + enumerable: true, + value: this._mainModule + }); + return moduleRequire; + } + + _createJestObjectFor(from) { + const disableAutomock = () => { + this._shouldAutoMock = false; + return jestObject; + }; + + const enableAutomock = () => { + this._shouldAutoMock = true; + return jestObject; + }; + + const unmock = moduleName => { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + + this._explicitShouldMock.set(moduleID, false); + + return jestObject; + }; + + const deepUnmock = moduleName => { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + + this._explicitShouldMock.set(moduleID, false); + + this._transitiveShouldMock.set(moduleID, false); + + return jestObject; + }; + + const mock = (moduleName, mockFactory, options) => { + if (mockFactory !== undefined) { + return setMockFactory(moduleName, mockFactory, options); + } + + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + + this._explicitShouldMock.set(moduleID, true); + + return jestObject; + }; + + const setMockFactory = (moduleName, mockFactory, options) => { + this.setMock(from, moduleName, mockFactory, options); + return jestObject; + }; + + const mockModule = (moduleName, mockFactory, options) => { + if (typeof mockFactory !== 'function') { + throw new Error('`unstable_mockModule` must be passed a mock factory'); + } + + this.setModuleMock(from, moduleName, mockFactory, options); + return jestObject; + }; + + const clearAllMocks = () => { + this.clearAllMocks(); + return jestObject; + }; + + const resetAllMocks = () => { + this.resetAllMocks(); + return jestObject; + }; + + const restoreAllMocks = () => { + this.restoreAllMocks(); + return jestObject; + }; + + const _getFakeTimers = () => { + if ( + this.isTornDown || + !(this._environment.fakeTimers || this._environment.fakeTimersModern) + ) { + this._logFormattedReferenceError( + 'You are trying to access a property or method of the Jest environment after it has been torn down.' + ); + + process.exitCode = 1; + } + + return this._fakeTimersImplementation; + }; + + const useFakeTimers = fakeTimersConfig => { + fakeTimersConfig = {...this._config.fakeTimers, ...fakeTimersConfig}; + + if (fakeTimersConfig?.legacyFakeTimers) { + this._fakeTimersImplementation = this._environment.fakeTimers; + } else { + this._fakeTimersImplementation = this._environment.fakeTimersModern; + } + + this._fakeTimersImplementation.useFakeTimers(fakeTimersConfig); + + return jestObject; + }; + + const useRealTimers = () => { + _getFakeTimers().useRealTimers(); + + return jestObject; + }; + + const resetModules = () => { + this.resetModules(); + return jestObject; + }; + + const isolateModules = fn => { + this.isolateModules(fn); + return jestObject; + }; + + const fn = this._moduleMocker.fn.bind(this._moduleMocker); + + const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker); + + const mocked = + this._moduleMocker.mocked?.bind(this._moduleMocker) ?? + (() => { + throw new Error( + 'Your test environment does not support `mocked`, please update it.' + ); + }); + + const setTimeout = timeout => { + this._environment.global[testTimeoutSymbol] = timeout; + return jestObject; + }; + + const retryTimes = (numTestRetries, options) => { + this._environment.global[retryTimesSymbol] = numTestRetries; + this._environment.global[logErrorsBeforeRetrySymbol] = + options?.logErrorsBeforeRetry; + return jestObject; + }; + + const jestObject = { + advanceTimersByTime: msToRun => + _getFakeTimers().advanceTimersByTime(msToRun), + advanceTimersToNextTimer: steps => + _getFakeTimers().advanceTimersToNextTimer(steps), + autoMockOff: disableAutomock, + autoMockOn: enableAutomock, + clearAllMocks, + clearAllTimers: () => _getFakeTimers().clearAllTimers(), + createMockFromModule: moduleName => this._generateMock(from, moduleName), + deepUnmock, + disableAutomock, + doMock: mock, + dontMock: unmock, + enableAutomock, + fn, + genMockFromModule: moduleName => this._generateMock(from, moduleName), + getRealSystemTime: () => { + const fakeTimers = _getFakeTimers(); + + if (fakeTimers === this._environment.fakeTimersModern) { + return fakeTimers.getRealSystemTime(); + } else { + throw new TypeError( + '`jest.getRealSystemTime()` is not available when using legacy fake timers.' + ); + } + }, + getTimerCount: () => _getFakeTimers().getTimerCount(), + isMockFunction: this._moduleMocker.isMockFunction, + isolateModules, + mock, + mocked, + requireActual: this.requireActual.bind(this, from), + requireMock: this.requireMock.bind(this, from), + resetAllMocks, + resetModules, + restoreAllMocks, + retryTimes, + runAllImmediates: () => { + const fakeTimers = _getFakeTimers(); + + if (fakeTimers === this._environment.fakeTimers) { + fakeTimers.runAllImmediates(); + } else { + throw new TypeError( + '`jest.runAllImmediates()` is only available when using legacy fake timers.' + ); + } + }, + runAllTicks: () => _getFakeTimers().runAllTicks(), + runAllTimers: () => _getFakeTimers().runAllTimers(), + runOnlyPendingTimers: () => _getFakeTimers().runOnlyPendingTimers(), + setMock: (moduleName, mock) => setMockFactory(moduleName, () => mock), + setSystemTime: now => { + const fakeTimers = _getFakeTimers(); + + if (fakeTimers === this._environment.fakeTimersModern) { + fakeTimers.setSystemTime(now); + } else { + throw new TypeError( + '`jest.setSystemTime()` is not available when using legacy fake timers.' + ); + } + }, + setTimeout, + spyOn, + unmock, + unstable_mockModule: mockModule, + useFakeTimers, + useRealTimers + }; + return jestObject; + } + + _logFormattedReferenceError(errorMessage) { + const testPath = this._testPath + ? ` From ${(0, _slash().default)( + path().relative(this._config.rootDir, this._testPath) + )}.` + : ''; + const originalStack = new ReferenceError(`${errorMessage}${testPath}`).stack + .split('\n') // Remove this file from the stack (jest-message-utils will keep one line) + .filter(line => line.indexOf(__filename) === -1) + .join('\n'); + const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)( + originalStack + ); + console.error( + `\n${message}\n${(0, _jestMessageUtil().formatStackTrace)( + stack, + this._config, + { + noStackTrace: false + } + )}` + ); + } + + wrapCodeInModuleWrapper(content) { + return `${this.constructModuleWrapperStart() + content}\n}});`; + } + + constructModuleWrapperStart() { + const args = this.constructInjectedModuleParameters(); + return `({"${EVAL_RESULT_VARIABLE}":function(${args.join(',')}){`; + } + + constructInjectedModuleParameters() { + return [ + 'module', + 'exports', + 'require', + '__dirname', + '__filename', + this._config.injectGlobals ? 'jest' : undefined, + ...this._config.sandboxInjectedGlobals + ].filter(notEmpty); + } + + handleExecutionError(e, module) { + const moduleNotFoundError = + _jestResolve().default.tryCastModuleNotFoundError(e); + + if (moduleNotFoundError) { + if (!moduleNotFoundError.requireStack) { + moduleNotFoundError.requireStack = [module.filename || module.id]; + + for (let cursor = module.parent; cursor; cursor = cursor.parent) { + moduleNotFoundError.requireStack.push(cursor.filename || cursor.id); + } + + moduleNotFoundError.buildMessage(this._config.rootDir); + } + + throw moduleNotFoundError; + } + + throw e; + } + + getGlobalsForCjs(from) { + const jest = this.jestObjectCaches.get(from); + invariant(jest, 'There should always be a Jest object already'); + return {...this.getGlobalsFromEnvironment(), jest}; + } + + getGlobalsForEsm(from, context) { + let jest = this.jestObjectCaches.get(from); + + if (!jest) { + jest = this._createJestObjectFor(from); + this.jestObjectCaches.set(from, jest); + } + + const globals = {...this.getGlobalsFromEnvironment(), jest}; + const module = new (_vm().SyntheticModule)( + Object.keys(globals), + function () { + Object.entries(globals).forEach(([key, value]) => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(key, value); + }); + }, + { + context, + identifier: '@jest/globals' + } + ); + return evaluateSyntheticModule(module); + } + + getGlobalsFromEnvironment() { + if (this.jestGlobals) { + return {...this.jestGlobals}; + } + + return { + afterAll: this._environment.global.afterAll, + afterEach: this._environment.global.afterEach, + beforeAll: this._environment.global.beforeAll, + beforeEach: this._environment.global.beforeEach, + describe: this._environment.global.describe, + expect: this._environment.global.expect, + fdescribe: this._environment.global.fdescribe, + fit: this._environment.global.fit, + it: this._environment.global.it, + test: this._environment.global.test, + xdescribe: this._environment.global.xdescribe, + xit: this._environment.global.xit, + xtest: this._environment.global.xtest + }; + } + + readFile(filename) { + let source = this._cacheFS.get(filename); + + if (!source) { + source = fs().readFileSync(filename, 'utf8'); + + this._cacheFS.set(filename, source); + } + + return source; + } + + setGlobalsForRuntime(globals) { + this.jestGlobals = globals; + } +} + +exports.default = Runtime; + +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +function notEmpty(value) { + return value !== null && value !== undefined; +} + +async function evaluateSyntheticModule(module) { + await module.link(() => { + throw new Error('This should never happen'); + }); + await module.evaluate(); + return module; +} diff --git a/node_modules/jest-runtime/package.json b/node_modules/jest-runtime/package.json new file mode 100644 index 0000000..1b1c4f8 --- /dev/null +++ b/node_modules/jest-runtime/package.json @@ -0,0 +1,87 @@ +{ + "_from": "jest-runtime@^29.0.1", + "_id": "jest-runtime@29.0.1", + "_inBundle": false, + "_integrity": "sha512-yDgz5OE0Rm44PUAfTqwA6cDFnTYnVcYbRpPECsokSASQ0I5RXpnKPVr2g0CYZWKzbsXqqtmM7TIk7CAutZJ7gQ==", + "_location": "/jest-runtime", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-runtime@^29.0.1", + "name": "jest-runtime", + "escapedName": "jest-runtime", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/jest-circus", + "/jest-runner" + ], + "_resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.0.1.tgz", + "_shasum": "cafdc10834c45c50105eecb0ded8677ce741e2af", + "_spec": "jest-runtime@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/environment": "^29.0.1", + "@jest/fake-timers": "^29.0.1", + "@jest/globals": "^29.0.1", + "@jest/source-map": "^29.0.0", + "@jest/test-result": "^29.0.1", + "@jest/transform": "^29.0.1", + "@jest/types": "^29.0.1", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.0.1", + "jest-message-util": "^29.0.1", + "jest-mock": "^29.0.1", + "jest-regex-util": "^29.0.0", + "jest-resolve": "^29.0.1", + "jest-snapshot": "^29.0.1", + "jest-util": "^29.0.1", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "deprecated": false, + "devDependencies": { + "@jest/test-utils": "^29.0.1", + "@types/glob": "^7.1.1", + "@types/graceful-fs": "^4.1.3", + "jest-environment-node": "^29.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-runtime", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-runtime" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-snapshot/LICENSE b/node_modules/jest-snapshot/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-snapshot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-snapshot/build/InlineSnapshots.js b/node_modules/jest-snapshot/build/InlineSnapshots.js new file mode 100644 index 0000000..e0fb225 --- /dev/null +++ b/node_modules/jest-snapshot/build/InlineSnapshots.js @@ -0,0 +1,449 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.saveInlineSnapshots = saveInlineSnapshots; + +var path = _interopRequireWildcard(require('path')); + +var _types = require('@babel/types'); + +var fs = _interopRequireWildcard(require('graceful-fs')); + +var _semver = _interopRequireDefault(require('semver')); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestWriteFile = + globalThis[Symbol.for('jest-native-write-file')] || fs.writeFileSync; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestReadFile = + globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync; + +// prettier-ignore +const babelTraverse = // @ts-expect-error requireOutside Babel transform +require(require.resolve('@babel/traverse', { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for('jest-resolve-outside-vm-option')]: true +})).default; // prettier-ignore + +const generate = // @ts-expect-error requireOutside Babel transform + require(require.resolve('@babel/generator', { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for( + 'jest-resolve-outside-vm-option' + )]: true + })).default; // @ts-expect-error requireOutside Babel transform + +const {file, templateElement, templateLiteral} = require(require.resolve( + '@babel/types', + { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for( + 'jest-resolve-outside-vm-option' + )]: true + } +)); // @ts-expect-error requireOutside Babel transform + +const {parseSync} = require(require.resolve('@babel/core', { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for( + 'jest-resolve-outside-vm-option' + )]: true +})); + +function saveInlineSnapshots(snapshots, rootDir, prettierPath) { + let prettier = null; + + if (prettierPath) { + try { + // @ts-expect-error requireOutside Babel transform + prettier = require(require.resolve(prettierPath, { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for( + 'jest-resolve-outside-vm-option' + )]: true + })); + } catch { + // Continue even if prettier is not installed. + } + } + + const snapshotsByFile = groupSnapshotsByFile(snapshots); + + for (const sourceFilePath of Object.keys(snapshotsByFile)) { + saveSnapshotsForFile( + snapshotsByFile[sourceFilePath], + sourceFilePath, + rootDir, + prettier && _semver.default.gte(prettier.version, '1.5.0') + ? prettier + : undefined + ); + } +} + +const saveSnapshotsForFile = (snapshots, sourceFilePath, rootDir, prettier) => { + const sourceFile = jestReadFile(sourceFilePath, 'utf8'); // TypeScript projects may not have a babel config; make sure they can be parsed anyway. + + const presets = [require.resolve('babel-preset-current-node-syntax')]; + const plugins = []; + + if (/\.tsx?$/.test(sourceFilePath)) { + plugins.push([ + require.resolve('@babel/plugin-syntax-typescript'), + { + isTSX: sourceFilePath.endsWith('x') + }, // unique name to make sure Babel does not complain about a possible duplicate plugin. + 'TypeScript syntax plugin added by Jest snapshot' + ]); + } // Record the matcher names seen during traversal and pass them down one + // by one to formatting parser. + + const snapshotMatcherNames = []; + let ast = null; + + try { + ast = parseSync(sourceFile, { + filename: sourceFilePath, + plugins, + presets, + root: rootDir + }); + } catch (error) { + // attempt to recover from missing jsx plugin + if (error.message.includes('@babel/plugin-syntax-jsx')) { + try { + const jsxSyntaxPlugin = [ + require.resolve('@babel/plugin-syntax-jsx'), + {}, // unique name to make sure Babel does not complain about a possible duplicate plugin. + 'JSX syntax plugin added by Jest snapshot' + ]; + ast = parseSync(sourceFile, { + filename: sourceFilePath, + plugins: [...plugins, jsxSyntaxPlugin], + presets, + root: rootDir + }); + } catch { + throw error; + } + } else { + throw error; + } + } + + if (!ast) { + throw new Error(`jest-snapshot: Failed to parse ${sourceFilePath}`); + } + + traverseAst(snapshots, ast, snapshotMatcherNames); // substitute in the snapshots in reverse order, so slice calculations aren't thrown off. + + const sourceFileWithSnapshots = snapshots.reduceRight( + (sourceSoFar, nextSnapshot) => { + if ( + !nextSnapshot.node || + typeof nextSnapshot.node.start !== 'number' || + typeof nextSnapshot.node.end !== 'number' + ) { + throw new Error('Jest: no snapshot insert location found'); + } + + return ( + sourceSoFar.slice(0, nextSnapshot.node.start) + + generate(nextSnapshot.node, { + retainLines: true + }).code.trim() + + sourceSoFar.slice(nextSnapshot.node.end) + ); + }, + sourceFile + ); + const newSourceFile = prettier + ? runPrettier( + prettier, + sourceFilePath, + sourceFileWithSnapshots, + snapshotMatcherNames + ) + : sourceFileWithSnapshots; + + if (newSourceFile !== sourceFile) { + jestWriteFile(sourceFilePath, newSourceFile); + } +}; + +const groupSnapshotsBy = createKey => snapshots => + snapshots.reduce((object, inlineSnapshot) => { + const key = createKey(inlineSnapshot); + return {...object, [key]: (object[key] || []).concat(inlineSnapshot)}; + }, {}); + +const groupSnapshotsByFrame = groupSnapshotsBy(({frame: {line, column}}) => + typeof line === 'number' && typeof column === 'number' + ? `${line}:${column - 1}` + : '' +); +const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file); + +const indent = (snapshot, numIndents, indentation) => { + const lines = snapshot.split('\n'); // Prevent re-indentation of inline snapshots. + + if ( + lines.length >= 2 && + lines[1].startsWith(indentation.repeat(numIndents + 1)) + ) { + return snapshot; + } + + return lines + .map((line, index) => { + if (index === 0) { + // First line is either a 1-line snapshot or a blank line. + return line; + } else if (index !== lines.length - 1) { + // Do not indent empty lines. + if (line === '') { + return line; + } // Not last line, indent one level deeper than expect call. + + return indentation.repeat(numIndents + 1) + line; + } else { + // The last line should be placed on the same level as the expect call. + return indentation.repeat(numIndents) + line; + } + }) + .join('\n'); +}; + +const resolveAst = fileOrProgram => { + // Flow uses a 'Program' parent node, babel expects a 'File'. + let ast = fileOrProgram; + + if (ast.type !== 'File') { + ast = file(ast, ast.comments, ast.tokens); + delete ast.program.comments; + } + + return ast; +}; + +const traverseAst = (snapshots, fileOrProgram, snapshotMatcherNames) => { + const ast = resolveAst(fileOrProgram); + const groupedSnapshots = groupSnapshotsByFrame(snapshots); + const remainingSnapshots = new Set(snapshots.map(({snapshot}) => snapshot)); + babelTraverse(ast, { + CallExpression({node}) { + const {arguments: args, callee} = node; + + if ( + callee.type !== 'MemberExpression' || + callee.property.type !== 'Identifier' || + callee.property.loc == null + ) { + return; + } + + const {line, column} = callee.property.loc.start; + const snapshotsForFrame = groupedSnapshots[`${line}:${column}`]; + + if (!snapshotsForFrame) { + return; + } + + if (snapshotsForFrame.length > 1) { + throw new Error( + 'Jest: Multiple inline snapshots for the same call are not supported.' + ); + } + + snapshotMatcherNames.push(callee.property.name); + const snapshotIndex = args.findIndex( + ({type}) => type === 'TemplateLiteral' + ); + const values = snapshotsForFrame.map(inlineSnapshot => { + inlineSnapshot.node = node; + const {snapshot} = inlineSnapshot; + remainingSnapshots.delete(snapshot); + return templateLiteral( + [ + templateElement({ + raw: (0, _utils.escapeBacktickString)(snapshot) + }) + ], + [] + ); + }); + const replacementNode = values[0]; + + if (snapshotIndex > -1) { + args[snapshotIndex] = replacementNode; + } else { + args.push(replacementNode); + } + } + }); + + if (remainingSnapshots.size) { + throw new Error("Jest: Couldn't locate all inline snapshots."); + } +}; + +const runPrettier = ( + prettier, + sourceFilePath, + sourceFileWithSnapshots, + snapshotMatcherNames +) => { + // Resolve project configuration. + // For older versions of Prettier, do not load configuration. + const config = prettier.resolveConfig + ? prettier.resolveConfig.sync(sourceFilePath, { + editorconfig: true + }) + : null; // Detect the parser for the test file. + // For older versions of Prettier, fallback to a simple parser detection. + // @ts-expect-error - `inferredParser` is `string` + + const inferredParser = prettier.getFileInfo + ? prettier.getFileInfo.sync(sourceFilePath).inferredParser + : (config && typeof config.parser === 'string' && config.parser) || + simpleDetectParser(sourceFilePath); + + if (!inferredParser) { + throw new Error( + `Could not infer Prettier parser for file ${sourceFilePath}` + ); + } // Snapshots have now been inserted. Run prettier to make sure that the code is + // formatted, except snapshot indentation. Snapshots cannot be formatted until + // after the initial format because we don't know where the call expression + // will be placed (specifically its indentation), so we have to do two + // prettier.format calls back-to-back. + + return prettier.format( + prettier.format(sourceFileWithSnapshots, { + ...config, + filepath: sourceFilePath + }), + { + ...config, + filepath: sourceFilePath, + parser: createFormattingParser(snapshotMatcherNames, inferredParser) + } + ); +}; // This parser formats snapshots to the correct indentation. + +const createFormattingParser = + (snapshotMatcherNames, inferredParser) => (text, parsers, options) => { + // Workaround for https://github.com/prettier/prettier/issues/3150 + options.parser = inferredParser; + const ast = resolveAst(parsers[inferredParser](text, options)); + babelTraverse(ast, { + CallExpression({node: {arguments: args, callee}, parent}) { + if ( + callee.type !== 'MemberExpression' || + callee.property.type !== 'Identifier' || + !snapshotMatcherNames.includes(callee.property.name) || + !callee.loc || + callee.computed + ) { + return; + } + + let snapshotIndex; + let snapshot; + + for (let i = 0; i < args.length; i++) { + const node = args[i]; + + if (node.type === 'TemplateLiteral') { + snapshotIndex = i; + snapshot = node.quasis[0].value.raw; + } + } + + if (snapshot === undefined || snapshotIndex === undefined) { + return; + } + + const startColumn = + (0, _types.isAwaitExpression)(parent) && parent.loc + ? parent.loc.start.column + : callee.loc.start.column; + const useSpaces = !options.useTabs; + snapshot = indent( + snapshot, + Math.ceil( + useSpaces + ? startColumn / (options.tabWidth ?? 1) // Each tab is 2 characters. + : startColumn / 2 + ), + useSpaces ? ' '.repeat(options.tabWidth ?? 1) : '\t' + ); + const replacementNode = templateLiteral( + [ + templateElement({ + raw: snapshot + }) + ], + [] + ); + args[snapshotIndex] = replacementNode; + } + }); + return ast; + }; + +const simpleDetectParser = filePath => { + const extname = path.extname(filePath); + + if (/\.tsx?$/.test(extname)) { + return 'typescript'; + } + + return 'babel'; +}; diff --git a/node_modules/jest-snapshot/build/SnapshotResolver.js b/node_modules/jest-snapshot/build/SnapshotResolver.js new file mode 100644 index 0000000..aa61b11 --- /dev/null +++ b/node_modules/jest-snapshot/build/SnapshotResolver.js @@ -0,0 +1,170 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.isSnapshotPath = + exports.buildSnapshotResolver = + exports.EXTENSION = + exports.DOT_EXTENSION = + void 0; + +var path = _interopRequireWildcard(require('path')); + +var _chalk = _interopRequireDefault(require('chalk')); + +var _transform = require('@jest/transform'); + +var _jestUtil = require('jest-util'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const EXTENSION = 'snap'; +exports.EXTENSION = EXTENSION; +const DOT_EXTENSION = `.${EXTENSION}`; +exports.DOT_EXTENSION = DOT_EXTENSION; + +const isSnapshotPath = path => path.endsWith(DOT_EXTENSION); + +exports.isSnapshotPath = isSnapshotPath; +const cache = new Map(); + +const buildSnapshotResolver = async ( + config, + localRequire = (0, _transform.createTranspilingRequire)(config) +) => { + const key = config.rootDir; + const resolver = + cache.get(key) ?? + (await createSnapshotResolver(await localRequire, config.snapshotResolver)); + cache.set(key, resolver); + return resolver; +}; + +exports.buildSnapshotResolver = buildSnapshotResolver; + +async function createSnapshotResolver(localRequire, snapshotResolverPath) { + return typeof snapshotResolverPath === 'string' + ? await createCustomSnapshotResolver(snapshotResolverPath, localRequire) + : createDefaultSnapshotResolver(); +} + +function createDefaultSnapshotResolver() { + return { + resolveSnapshotPath: testPath => + path.join( + path.join(path.dirname(testPath), '__snapshots__'), + path.basename(testPath) + DOT_EXTENSION + ), + resolveTestPath: snapshotPath => + path.resolve( + path.dirname(snapshotPath), + '..', + path.basename(snapshotPath, DOT_EXTENSION) + ), + testPathForConsistencyCheck: path.posix.join( + 'consistency_check', + '__tests__', + 'example.test.js' + ) + }; +} + +async function createCustomSnapshotResolver( + snapshotResolverPath, + localRequire +) { + const custom = (0, _jestUtil.interopRequireDefault)( + await localRequire(snapshotResolverPath) + ).default; + const keys = [ + ['resolveSnapshotPath', 'function'], + ['resolveTestPath', 'function'], + ['testPathForConsistencyCheck', 'string'] + ]; + keys.forEach(([propName, requiredType]) => { + if (typeof custom[propName] !== requiredType) { + throw new TypeError(mustImplement(propName, requiredType)); + } + }); + const customResolver = { + resolveSnapshotPath: testPath => + custom.resolveSnapshotPath(testPath, DOT_EXTENSION), + resolveTestPath: snapshotPath => + custom.resolveTestPath(snapshotPath, DOT_EXTENSION), + testPathForConsistencyCheck: custom.testPathForConsistencyCheck + }; + verifyConsistentTransformations(customResolver); + return customResolver; +} + +function mustImplement(propName, requiredType) { + return `${_chalk.default.bold( + `Custom snapshot resolver must implement a \`${propName}\` as a ${requiredType}.` + )}\nDocumentation: https://jestjs.io/docs/configuration#snapshotresolver-string`; +} + +function verifyConsistentTransformations(custom) { + const resolvedSnapshotPath = custom.resolveSnapshotPath( + custom.testPathForConsistencyCheck + ); + const resolvedTestPath = custom.resolveTestPath(resolvedSnapshotPath); + + if (resolvedTestPath !== custom.testPathForConsistencyCheck) { + throw new Error( + _chalk.default.bold( + `Custom snapshot resolver functions must transform paths consistently, i.e. expects resolveTestPath(resolveSnapshotPath('${custom.testPathForConsistencyCheck}')) === ${resolvedTestPath}` + ) + ); + } +} diff --git a/node_modules/jest-snapshot/build/State.js b/node_modules/jest-snapshot/build/State.js new file mode 100644 index 0000000..1db8ffe --- /dev/null +++ b/node_modules/jest-snapshot/build/State.js @@ -0,0 +1,320 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var fs = _interopRequireWildcard(require('graceful-fs')); + +var _jestMessageUtil = require('jest-message-util'); + +var _InlineSnapshots = require('./InlineSnapshots'); + +var _utils = require('./utils'); + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestExistsFile = + globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync; + +class SnapshotState { + _counters; + _dirty; // @ts-expect-error - seemingly unused? + + _index; + _updateSnapshot; + _snapshotData; + _initialData; + _snapshotPath; + _inlineSnapshots; + _uncheckedKeys; + _prettierPath; + _rootDir; + snapshotFormat; + added; + expand; + matched; + unmatched; + updated; + + constructor(snapshotPath, options) { + this._snapshotPath = snapshotPath; + const {data, dirty} = (0, _utils.getSnapshotData)( + this._snapshotPath, + options.updateSnapshot + ); + this._initialData = data; + this._snapshotData = data; + this._dirty = dirty; + this._prettierPath = options.prettierPath ?? null; + this._inlineSnapshots = []; + this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); + this._counters = new Map(); + this._index = 0; + this.expand = options.expand || false; + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this._updateSnapshot = options.updateSnapshot; + this.updated = 0; + this.snapshotFormat = options.snapshotFormat; + this._rootDir = options.rootDir; + } + + markSnapshotsAsCheckedForTest(testName) { + this._uncheckedKeys.forEach(uncheckedKey => { + if ((0, _utils.keyToTestName)(uncheckedKey) === testName) { + this._uncheckedKeys.delete(uncheckedKey); + } + }); + } + + _addSnapshot(key, receivedSerialized, options) { + this._dirty = true; + + if (options.isInline) { + const error = options.error || new Error(); + const lines = (0, _jestMessageUtil.getStackTraceLines)( + (0, _utils.removeLinesBeforeExternalMatcherTrap)(error.stack || '') + ); + const frame = (0, _jestMessageUtil.getTopFrame)(lines); + + if (!frame) { + throw new Error( + "Jest: Couldn't infer stack frame for inline snapshot." + ); + } + + this._inlineSnapshots.push({ + frame, + snapshot: receivedSerialized + }); + } else { + this._snapshotData[key] = receivedSerialized; + } + } + + clear() { + this._snapshotData = this._initialData; + this._inlineSnapshots = []; + this._counters = new Map(); + this._index = 0; + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this.updated = 0; + } + + save() { + const hasExternalSnapshots = Object.keys(this._snapshotData).length; + const hasInlineSnapshots = this._inlineSnapshots.length; + const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots; + const status = { + deleted: false, + saved: false + }; + + if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { + if (hasExternalSnapshots) { + (0, _utils.saveSnapshotFile)(this._snapshotData, this._snapshotPath); + } + + if (hasInlineSnapshots) { + (0, _InlineSnapshots.saveInlineSnapshots)( + this._inlineSnapshots, + this._rootDir, + this._prettierPath + ); + } + + status.saved = true; + } else if (!hasExternalSnapshots && jestExistsFile(this._snapshotPath)) { + if (this._updateSnapshot === 'all') { + fs.unlinkSync(this._snapshotPath); + } + + status.deleted = true; + } + + return status; + } + + getUncheckedCount() { + return this._uncheckedKeys.size || 0; + } + + getUncheckedKeys() { + return Array.from(this._uncheckedKeys); + } + + removeUncheckedKeys() { + if (this._updateSnapshot === 'all' && this._uncheckedKeys.size) { + this._dirty = true; + + this._uncheckedKeys.forEach(key => delete this._snapshotData[key]); + + this._uncheckedKeys.clear(); + } + } + + match({testName, received, key, inlineSnapshot, isInline, error}) { + this._counters.set(testName, (this._counters.get(testName) || 0) + 1); + + const count = Number(this._counters.get(testName)); + + if (!key) { + key = (0, _utils.testNameToKey)(testName, count); + } // Do not mark the snapshot as "checked" if the snapshot is inline and + // there's an external snapshot. This way the external snapshot can be + // removed with `--updateSnapshot`. + + if (!(isInline && this._snapshotData[key] !== undefined)) { + this._uncheckedKeys.delete(key); + } + + const receivedSerialized = (0, _utils.addExtraLineBreaks)( + (0, _utils.serialize)(received, undefined, this.snapshotFormat) + ); + const expected = isInline ? inlineSnapshot : this._snapshotData[key]; + const pass = expected === receivedSerialized; + const hasSnapshot = expected !== undefined; + const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath); + + if (pass && !isInline) { + // Executing a snapshot file as JavaScript and writing the strings back + // when other snapshots have changed loses the proper escaping for some + // characters. Since we check every snapshot in every test, use the newly + // generated formatted string. + // Note that this is only relevant when a snapshot is added and the dirty + // flag is set. + this._snapshotData[key] = receivedSerialized; + } // These are the conditions on when to write snapshots: + // * There's no snapshot file in a non-CI environment. + // * There is a snapshot file and we decided to update the snapshot. + // * There is a snapshot file, but it doesn't have this snaphsot. + // These are the conditions on when not to write snapshots: + // * The update flag is set to 'none'. + // * There's no snapshot file or a file without this snapshot on a CI environment. + + if ( + (hasSnapshot && this._updateSnapshot === 'all') || + ((!hasSnapshot || !snapshotIsPersisted) && + (this._updateSnapshot === 'new' || this._updateSnapshot === 'all')) + ) { + if (this._updateSnapshot === 'all') { + if (!pass) { + if (hasSnapshot) { + this.updated++; + } else { + this.added++; + } + + this._addSnapshot(key, receivedSerialized, { + error, + isInline + }); + } else { + this.matched++; + } + } else { + this._addSnapshot(key, receivedSerialized, { + error, + isInline + }); + + this.added++; + } + + return { + actual: '', + count, + expected: '', + key, + pass: true + }; + } else { + if (!pass) { + this.unmatched++; + return { + actual: (0, _utils.removeExtraLineBreaks)(receivedSerialized), + count, + expected: + expected !== undefined + ? (0, _utils.removeExtraLineBreaks)(expected) + : undefined, + key, + pass: false + }; + } else { + this.matched++; + return { + actual: '', + count, + expected: '', + key, + pass: true + }; + } + } + } + + fail(testName, _received, key) { + this._counters.set(testName, (this._counters.get(testName) || 0) + 1); + + const count = Number(this._counters.get(testName)); + + if (!key) { + key = (0, _utils.testNameToKey)(testName, count); + } + + this._uncheckedKeys.delete(key); + + this.unmatched++; + return key; + } +} + +exports.default = SnapshotState; diff --git a/node_modules/jest-snapshot/build/colors.js b/node_modules/jest-snapshot/build/colors.js new file mode 100644 index 0000000..897ea87 --- /dev/null +++ b/node_modules/jest-snapshot/build/colors.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.bForeground3 = + exports.bForeground2 = + exports.bBackground3 = + exports.bBackground2 = + exports.aForeground3 = + exports.aForeground2 = + exports.aBackground3 = + exports.aBackground2 = + void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// https://jonasjacek.github.io/colors/ +const aForeground2 = 90; +exports.aForeground2 = aForeground2; +const aBackground2 = 225; +exports.aBackground2 = aBackground2; +const bForeground2 = 23; +exports.bForeground2 = bForeground2; +const bBackground2 = 195; +exports.bBackground2 = bBackground2; +const aForeground3 = [0x80, 0, 0x80]; +exports.aForeground3 = aForeground3; +const aBackground3 = [0xff, 0xd7, 0xff]; +exports.aBackground3 = aBackground3; +const bForeground3 = [0, 0x5f, 0x5f]; +exports.bForeground3 = bForeground3; +const bBackground3 = [0xd7, 0xff, 0xff]; +exports.bBackground3 = bBackground3; diff --git a/node_modules/jest-snapshot/build/dedentLines.js b/node_modules/jest-snapshot/build/dedentLines.js new file mode 100644 index 0000000..48bd412 --- /dev/null +++ b/node_modules/jest-snapshot/build/dedentLines.js @@ -0,0 +1,149 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.dedentLines = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const getIndentationLength = line => { + const result = /^( {2})+/.exec(line); + return result === null ? 0 : result[0].length; +}; + +const dedentLine = line => line.slice(getIndentationLength(line)); // Return true if: +// "key": "value has multiple lines\n… +// "key has multiple lines\n… + +const hasUnmatchedDoubleQuoteMarks = string => { + let n = 0; + let i = string.indexOf('"', 0); + + while (i !== -1) { + if (i === 0 || string[i - 1] !== '\\') { + n += 1; + } + + i = string.indexOf('"', i + 1); + } + + return n % 2 !== 0; +}; + +const isFirstLineOfTag = line => /^( {2})* { + let line = input[output.length]; + output.push(dedentLine(line)); + + if (line.includes('>')) { + return true; + } + + while (output.length < input.length) { + line = input[output.length]; + + if (hasUnmatchedDoubleQuoteMarks(line)) { + return false; // because props include a multiline string + } else if (isFirstLineOfTag(line)) { + // Recursion only if props have markup. + if (!dedentMarkup(input, output)) { + return false; + } + } else { + output.push(dedentLine(line)); + + if (line.includes('>')) { + return true; + } + } + } + + return false; +}; // Push dedented lines of markup onto output and return true; +// otherwise return false because: +// * props include a multiline string +// * text has more than one adjacent line +// * markup does not close + +const dedentMarkup = (input, output) => { + let line = input[output.length]; + + if (!dedentStartTag(input, output)) { + return false; + } + + if (input[output.length - 1].includes('/>')) { + return true; + } + + let isText = false; + const stack = []; + stack.push(getIndentationLength(line)); + + while (stack.length > 0 && output.length < input.length) { + line = input[output.length]; + + if (isFirstLineOfTag(line)) { + if (line.includes('')) { + stack.push(getIndentationLength(line)); + } + } + + isText = false; + } else { + if (isText) { + return false; // because text has more than one adjacent line + } + + const indentationLengthOfTag = stack[stack.length - 1]; + output.push(line.slice(indentationLengthOfTag + 2)); + isText = true; + } + } + + return stack.length === 0; +}; // Return lines unindented by heuristic; +// otherwise return null because: +// * props include a multiline string +// * text has more than one adjacent line +// * markup does not close + +const dedentLines = input => { + const output = []; + + while (output.length < input.length) { + const line = input[output.length]; + + if (hasUnmatchedDoubleQuoteMarks(line)) { + return null; + } else if (isFirstLineOfTag(line)) { + if (!dedentMarkup(input, output)) { + return null; + } + } else { + output.push(dedentLine(line)); + } + } + + return output; +}; + +exports.dedentLines = dedentLines; diff --git a/node_modules/jest-snapshot/build/index.d.ts b/node_modules/jest-snapshot/build/index.d.ts new file mode 100644 index 0000000..780099a --- /dev/null +++ b/node_modules/jest-snapshot/build/index.d.ts @@ -0,0 +1,170 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {FS} from 'jest-haste-map'; +import type {MatcherContext} from 'expect'; +import type {MatcherFunctionWithContext} from 'expect'; +import {Plugin as Plugin_2} from 'pretty-format'; +import {Plugins} from 'pretty-format'; +import type {PrettyFormatOptions} from 'pretty-format'; + +export declare const addSerializer: (plugin: Plugin_2) => void; + +export declare const buildSnapshotResolver: ( + config: Config.ProjectConfig, + localRequire?: Promise | LocalRequire, +) => Promise; + +export declare const cleanup: ( + hasteFS: FS, + update: Config.SnapshotUpdateState, + snapshotResolver: SnapshotResolver, + testPathIgnorePatterns?: Config.ProjectConfig['testPathIgnorePatterns'], +) => { + filesRemoved: number; + filesRemovedList: Array; +}; + +declare interface Context extends MatcherContext { + snapshotState: SnapshotState; +} + +export declare const EXTENSION = 'snap'; + +export declare const getSerializers: () => Plugins; + +export declare const isSnapshotPath: (path: string) => boolean; + +declare type LocalRequire = (module: string) => unknown; + +declare type SaveStatus = { + deleted: boolean; + saved: boolean; +}; + +declare type SnapshotFormat = Omit; + +export declare interface SnapshotMatchers, T> { + /** + * This ensures that a value matches the most recent snapshot with property matchers. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchSnapshot(hint?: string): R; + /** + * This ensures that a value matches the most recent snapshot. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchSnapshot>( + propertyMatchers: Partial, + hint?: string, + ): R; + /** + * This ensures that a value matches the most recent snapshot with property matchers. + * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchInlineSnapshot(snapshot?: string): R; + /** + * This ensures that a value matches the most recent snapshot with property matchers. + * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchInlineSnapshot>( + propertyMatchers: Partial, + snapshot?: string, + ): R; + /** + * Used to test that a function throws a error matching the most recent snapshot when it is called. + */ + toThrowErrorMatchingSnapshot(hint?: string): R; + /** + * Used to test that a function throws a error matching the most recent snapshot when it is called. + * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. + */ + toThrowErrorMatchingInlineSnapshot(snapshot?: string): R; +} + +declare type SnapshotMatchOptions = { + readonly testName: string; + readonly received: unknown; + readonly key?: string; + readonly inlineSnapshot?: string; + readonly isInline: boolean; + readonly error?: Error; +}; + +export declare type SnapshotResolver = { + /** Resolves from `testPath` to snapshot path. */ + resolveSnapshotPath(testPath: string, snapshotExtension?: string): string; + /** Resolves from `snapshotPath` to test path. */ + resolveTestPath(snapshotPath: string, snapshotExtension?: string): string; + /** Example test path, used for preflight consistency check of the implementation above. */ + testPathForConsistencyCheck: string; +}; + +declare type SnapshotReturnOptions = { + readonly actual: string; + readonly count: number; + readonly expected?: string; + readonly key: string; + readonly pass: boolean; +}; + +export declare class SnapshotState { + private _counters; + private _dirty; + private _index; + private readonly _updateSnapshot; + private _snapshotData; + private readonly _initialData; + private readonly _snapshotPath; + private _inlineSnapshots; + private readonly _uncheckedKeys; + private readonly _prettierPath; + private readonly _rootDir; + readonly snapshotFormat: SnapshotFormat; + added: number; + expand: boolean; + matched: number; + unmatched: number; + updated: number; + constructor(snapshotPath: string, options: SnapshotStateOptions); + markSnapshotsAsCheckedForTest(testName: string): void; + private _addSnapshot; + clear(): void; + save(): SaveStatus; + getUncheckedCount(): number; + getUncheckedKeys(): Array; + removeUncheckedKeys(): void; + match({ + testName, + received, + key, + inlineSnapshot, + isInline, + error, + }: SnapshotMatchOptions): SnapshotReturnOptions; + fail(testName: string, _received: unknown, key?: string): string; +} + +declare type SnapshotStateOptions = { + readonly updateSnapshot: Config.SnapshotUpdateState; + readonly prettierPath?: string | null; + readonly expand?: boolean; + readonly snapshotFormat: SnapshotFormat; + readonly rootDir: string; +}; + +export declare const toMatchInlineSnapshot: MatcherFunctionWithContext; + +export declare const toMatchSnapshot: MatcherFunctionWithContext; + +export declare const toThrowErrorMatchingInlineSnapshot: MatcherFunctionWithContext; + +export declare const toThrowErrorMatchingSnapshot: MatcherFunctionWithContext; + +export {}; diff --git a/node_modules/jest-snapshot/build/index.js b/node_modules/jest-snapshot/build/index.js new file mode 100644 index 0000000..f326705 --- /dev/null +++ b/node_modules/jest-snapshot/build/index.js @@ -0,0 +1,635 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'EXTENSION', { + enumerable: true, + get: function () { + return _SnapshotResolver.EXTENSION; + } +}); +Object.defineProperty(exports, 'SnapshotState', { + enumerable: true, + get: function () { + return _State.default; + } +}); +Object.defineProperty(exports, 'addSerializer', { + enumerable: true, + get: function () { + return _plugins.addSerializer; + } +}); +Object.defineProperty(exports, 'buildSnapshotResolver', { + enumerable: true, + get: function () { + return _SnapshotResolver.buildSnapshotResolver; + } +}); +exports.cleanup = void 0; +Object.defineProperty(exports, 'getSerializers', { + enumerable: true, + get: function () { + return _plugins.getSerializers; + } +}); +Object.defineProperty(exports, 'isSnapshotPath', { + enumerable: true, + get: function () { + return _SnapshotResolver.isSnapshotPath; + } +}); +exports.toThrowErrorMatchingSnapshot = + exports.toThrowErrorMatchingInlineSnapshot = + exports.toMatchSnapshot = + exports.toMatchInlineSnapshot = + void 0; + +var fs = _interopRequireWildcard(require('graceful-fs')); + +var _jestMatcherUtils = require('jest-matcher-utils'); + +var _SnapshotResolver = require('./SnapshotResolver'); + +var _printSnapshot = require('./printSnapshot'); + +var _utils = require('./utils'); + +var _plugins = require('./plugins'); + +var _State = _interopRequireDefault(require('./State')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestExistsFile = + globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync; +const DID_NOT_THROW = 'Received function did not throw'; // same as toThrow + +const NOT_SNAPSHOT_MATCHERS = `Snapshot matchers cannot be used with ${(0, +_jestMatcherUtils.BOLD_WEIGHT)('not')}`; +const INDENTATION_REGEX = /^([^\S\n]*)\S/m; // Display name in report when matcher fails same as in snapshot file, +// but with optional hint argument in bold weight. + +const printSnapshotName = (concatenatedBlockNames = '', hint = '', count) => { + const hasNames = concatenatedBlockNames.length !== 0; + const hasHint = hint.length !== 0; + return `Snapshot name: \`${ + hasNames ? (0, _utils.escapeBacktickString)(concatenatedBlockNames) : '' + }${hasNames && hasHint ? ': ' : ''}${ + hasHint + ? (0, _jestMatcherUtils.BOLD_WEIGHT)( + (0, _utils.escapeBacktickString)(hint) + ) + : '' + } ${count}\``; +}; + +function stripAddedIndentation(inlineSnapshot) { + // Find indentation if exists. + const match = inlineSnapshot.match(INDENTATION_REGEX); + + if (!match || !match[1]) { + // No indentation. + return inlineSnapshot; + } + + const indentation = match[1]; + const lines = inlineSnapshot.split('\n'); + + if (lines.length <= 2) { + // Must be at least 3 lines. + return inlineSnapshot; + } + + if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') { + // If not blank first and last lines, abort. + return inlineSnapshot; + } + + for (let i = 1; i < lines.length - 1; i++) { + if (lines[i] !== '') { + if (lines[i].indexOf(indentation) !== 0) { + // All lines except first and last should either be blank or have the same + // indent as the first line (or more). If this isn't the case we don't + // want to touch the snapshot at all. + return inlineSnapshot; + } + + lines[i] = lines[i].substring(indentation.length); + } + } // Last line is a special case because it won't have the same indent as others + // but may still have been given some indent to line up. + + lines[lines.length - 1] = ''; // Return inline snapshot, now at indent 0. + + inlineSnapshot = lines.join('\n'); + return inlineSnapshot; +} + +const fileExists = (filePath, hasteFS) => + hasteFS.exists(filePath) || jestExistsFile(filePath); + +const cleanup = (hasteFS, update, snapshotResolver, testPathIgnorePatterns) => { + const pattern = `\\.${_SnapshotResolver.EXTENSION}$`; + const files = hasteFS.matchFiles(pattern); + let testIgnorePatternsRegex = null; + + if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) { + testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|')); + } + + const list = files.filter(snapshotFile => { + const testPath = snapshotResolver.resolveTestPath(snapshotFile); // ignore snapshots of ignored tests + + if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) { + return false; + } + + if (!fileExists(testPath, hasteFS)) { + if (update === 'all') { + fs.unlinkSync(snapshotFile); + } + + return true; + } + + return false; + }); + return { + filesRemoved: list.length, + filesRemovedList: list + }; +}; + +exports.cleanup = cleanup; + +const toMatchSnapshot = function (received, propertiesOrHint, hint) { + const matcherName = 'toMatchSnapshot'; + let properties; + const length = arguments.length; + + if (length === 2 && typeof propertiesOrHint === 'string') { + hint = propertiesOrHint; + } else if (length >= 2) { + if (typeof propertiesOrHint !== 'object' || propertiesOrHint === null) { + const options = { + isNot: this.isNot, + promise: this.promise + }; + let printedWithType = (0, _jestMatcherUtils.printWithType)( + 'Expected properties', + propertiesOrHint, + _printSnapshot.printExpected + ); + + if (length === 3) { + options.secondArgument = 'hint'; + options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT; + + if (propertiesOrHint == null) { + printedWithType += + "\n\nTo provide a hint without properties: toMatchSnapshot('hint')"; + } + } + + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.PROPERTIES_ARG, + options + ), + `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)( + 'properties' + )} must be an object`, + printedWithType + ) + ); + } // Future breaking change: Snapshot hint must be a string + // if (arguments.length === 3 && typeof hint !== 'string') {} + + properties = propertiesOrHint; + } + + return _toMatchSnapshot({ + context: this, + hint, + isInline: false, + matcherName, + properties, + received + }); +}; + +exports.toMatchSnapshot = toMatchSnapshot; + +const toMatchInlineSnapshot = function ( + received, + propertiesOrSnapshot, + inlineSnapshot +) { + const matcherName = 'toMatchInlineSnapshot'; + let properties; + const length = arguments.length; + + if (length === 2 && typeof propertiesOrSnapshot === 'string') { + inlineSnapshot = propertiesOrSnapshot; + } else if (length >= 2) { + const options = { + isNot: this.isNot, + promise: this.promise + }; + + if (length === 3) { + options.secondArgument = _printSnapshot.SNAPSHOT_ARG; + options.secondArgumentColor = _printSnapshot.noColor; + } + + if ( + typeof propertiesOrSnapshot !== 'object' || + propertiesOrSnapshot === null + ) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.PROPERTIES_ARG, + options + ), + `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)( + 'properties' + )} must be an object`, + (0, _jestMatcherUtils.printWithType)( + 'Expected properties', + propertiesOrSnapshot, + _printSnapshot.printExpected + ) + ) + ); + } + + if (length === 3 && typeof inlineSnapshot !== 'string') { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.PROPERTIES_ARG, + options + ), + 'Inline snapshot must be a string', + (0, _jestMatcherUtils.printWithType)( + 'Inline snapshot', + inlineSnapshot, + _utils.serialize + ) + ) + ); + } + + properties = propertiesOrSnapshot; + } + + return _toMatchSnapshot({ + context: this, + inlineSnapshot: + inlineSnapshot !== undefined + ? stripAddedIndentation(inlineSnapshot) + : undefined, + isInline: true, + matcherName, + properties, + received + }); +}; + +exports.toMatchInlineSnapshot = toMatchInlineSnapshot; + +const _toMatchSnapshot = config => { + const {context, hint, inlineSnapshot, isInline, matcherName, properties} = + config; + let {received} = config; + context.dontThrow && context.dontThrow(); + const {currentTestName, isNot, snapshotState} = context; + + if (isNot) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _printSnapshot.matcherHintFromConfig)(config, false), + NOT_SNAPSHOT_MATCHERS + ) + ); + } + + if (snapshotState == null) { + // Because the state is the problem, this is not a matcher error. + // Call generic stringify from jest-matcher-utils package + // because uninitialized snapshot state does not need snapshot serializers. + throw new Error( + `${(0, _printSnapshot.matcherHintFromConfig)(config, false)}\n\n` + + 'Snapshot state must be initialized' + + `\n\n${(0, _jestMatcherUtils.printWithType)( + 'Snapshot state', + snapshotState, + _jestMatcherUtils.stringify + )}` + ); + } + + const fullTestName = + currentTestName && hint + ? `${currentTestName}: ${hint}` + : currentTestName || ''; // future BREAKING change: || hint + + if (typeof properties === 'object') { + if (typeof received !== 'object' || received === null) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _printSnapshot.matcherHintFromConfig)(config, false), + `${(0, _jestMatcherUtils.RECEIVED_COLOR)( + 'received' + )} value must be an object when the matcher has ${(0, + _jestMatcherUtils.EXPECTED_COLOR)('properties')}`, + (0, _jestMatcherUtils.printWithType)( + 'Received', + received, + _printSnapshot.printReceived + ) + ) + ); + } + + const propertyPass = context.equals(received, properties, [ + context.utils.iterableEquality, + context.utils.subsetEquality + ]); + + if (!propertyPass) { + const key = snapshotState.fail(fullTestName, received); + const matched = /(\d+)$/.exec(key); + const count = matched === null ? 1 : Number(matched[1]); + + const message = () => + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + false + )}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n${(0, + _printSnapshot.printPropertiesAndReceived)( + properties, + received, + snapshotState.expand + )}`; + + return { + message, + name: matcherName, + pass: false + }; + } else { + received = (0, _utils.deepMerge)(received, properties); + } + } + + const result = snapshotState.match({ + error: context.error, + inlineSnapshot, + isInline, + received, + testName: fullTestName + }); + const {actual, count, expected, pass} = result; + + if (pass) { + return { + message: () => '', + pass: true + }; + } + + const message = + expected === undefined + ? () => + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + true + )}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n` + + `New snapshot was ${(0, _jestMatcherUtils.BOLD_WEIGHT)( + 'not written' + )}. The update flag ` + + 'must be explicitly passed to write a new snapshot.\n\n' + + 'This is likely because this test is run in a continuous integration ' + + '(CI) environment in which snapshots are not written by default.\n\n' + + `Received:${actual.includes('\n') ? '\n' : ' '}${(0, + _printSnapshot.bReceivedColor)(actual)}` + : () => + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + true + )}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n${(0, + _printSnapshot.printSnapshotAndReceived)( + expected, + actual, + received, + snapshotState.expand, + snapshotState.snapshotFormat + )}`; // Passing the actual and expected objects so that a custom reporter + // could access them, for example in order to display a custom visual diff, + // or create a different error message + + return { + actual, + expected, + message, + name: matcherName, + pass: false + }; +}; + +const toThrowErrorMatchingSnapshot = function (received, hint, fromPromise) { + const matcherName = 'toThrowErrorMatchingSnapshot'; // Future breaking change: Snapshot hint must be a string + // if (hint !== undefined && typeof hint !== string) {} + + return _toThrowErrorMatchingSnapshot( + { + context: this, + hint, + isInline: false, + matcherName, + received + }, + fromPromise + ); +}; + +exports.toThrowErrorMatchingSnapshot = toThrowErrorMatchingSnapshot; + +const toThrowErrorMatchingInlineSnapshot = function ( + received, + inlineSnapshot, + fromPromise +) { + const matcherName = 'toThrowErrorMatchingInlineSnapshot'; + + if (inlineSnapshot !== undefined && typeof inlineSnapshot !== 'string') { + const options = { + expectedColor: _printSnapshot.noColor, + isNot: this.isNot, + promise: this.promise + }; + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.SNAPSHOT_ARG, + options + ), + 'Inline snapshot must be a string', + (0, _jestMatcherUtils.printWithType)( + 'Inline snapshot', + inlineSnapshot, + _utils.serialize + ) + ) + ); + } + + return _toThrowErrorMatchingSnapshot( + { + context: this, + inlineSnapshot: + inlineSnapshot !== undefined + ? stripAddedIndentation(inlineSnapshot) + : undefined, + isInline: true, + matcherName, + received + }, + fromPromise + ); +}; + +exports.toThrowErrorMatchingInlineSnapshot = toThrowErrorMatchingInlineSnapshot; + +const _toThrowErrorMatchingSnapshot = (config, fromPromise) => { + const {context, hint, inlineSnapshot, isInline, matcherName, received} = + config; + context.dontThrow && context.dontThrow(); + const {isNot, promise} = context; + + if (!fromPromise) { + if (typeof received !== 'function') { + const options = { + isNot, + promise + }; + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + '', + options + ), + `${(0, _jestMatcherUtils.RECEIVED_COLOR)( + 'received' + )} value must be a function`, + (0, _jestMatcherUtils.printWithType)( + 'Received', + received, + _printSnapshot.printReceived + ) + ) + ); + } + } + + if (isNot) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _printSnapshot.matcherHintFromConfig)(config, false), + NOT_SNAPSHOT_MATCHERS + ) + ); + } + + let error; + + if (fromPromise) { + error = received; + } else { + try { + received(); + } catch (e) { + error = e; + } + } + + if (error === undefined) { + // Because the received value is a function, this is not a matcher error. + throw new Error( + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + false + )}\n\n${DID_NOT_THROW}` + ); + } + + return _toMatchSnapshot({ + context, + hint, + inlineSnapshot, + isInline, + matcherName, + received: error.message + }); +}; diff --git a/node_modules/jest-snapshot/build/mockSerializer.js b/node_modules/jest-snapshot/build/mockSerializer.js new file mode 100644 index 0000000..060d249 --- /dev/null +++ b/node_modules/jest-snapshot/build/mockSerializer.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const serialize = (val, config, indentation, depth, refs, printer) => { + // Serialize a non-default name, even if config.printFunctionName is false. + const name = val.getMockName(); + const nameString = name === 'jest.fn()' ? '' : ` ${name}`; + let callsString = ''; + + if (val.mock.calls.length !== 0) { + const indentationNext = indentation + config.indent; + callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer( + val.mock.calls, + config, + indentationNext, + depth, + refs + )}${config.min ? ', ' : ','}${ + config.spacingOuter + }${indentationNext}"results": ${printer( + val.mock.results, + config, + indentationNext, + depth, + refs + )}${config.min ? '' : ','}${config.spacingOuter}${indentation}}`; + } + + return `[MockFunction${nameString}]${callsString}`; +}; + +exports.serialize = serialize; + +const test = val => val && !!val._isMockFunction; + +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/jest-snapshot/build/plugins.js b/node_modules/jest-snapshot/build/plugins.js new file mode 100644 index 0000000..6a3625b --- /dev/null +++ b/node_modules/jest-snapshot/build/plugins.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getSerializers = exports.addSerializer = void 0; + +var _prettyFormat = require('pretty-format'); + +var _mockSerializer = _interopRequireDefault(require('./mockSerializer')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const { + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent, + AsymmetricMatcher +} = _prettyFormat.plugins; +let PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + _mockSerializer.default, + AsymmetricMatcher +]; // Prepend to list so the last added is the first tested. + +const addSerializer = plugin => { + PLUGINS = [plugin].concat(PLUGINS); +}; + +exports.addSerializer = addSerializer; + +const getSerializers = () => PLUGINS; + +exports.getSerializers = getSerializers; diff --git a/node_modules/jest-snapshot/build/printSnapshot.js b/node_modules/jest-snapshot/build/printSnapshot.js new file mode 100644 index 0000000..5609843 --- /dev/null +++ b/node_modules/jest-snapshot/build/printSnapshot.js @@ -0,0 +1,382 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printSnapshotAndReceived = + exports.printReceived = + exports.printPropertiesAndReceived = + exports.printExpected = + exports.noColor = + exports.matcherHintFromConfig = + exports.getSnapshotColorForChalkInstance = + exports.getReceivedColorForChalkInstance = + exports.bReceivedColor = + exports.aSnapshotColor = + exports.SNAPSHOT_ARG = + exports.PROPERTIES_ARG = + exports.HINT_ARG = + void 0; + +var _chalk = _interopRequireDefault(require('chalk')); + +var _expectUtils = require('@jest/expect-utils'); + +var _jestDiff = require('jest-diff'); + +var _jestGetType = require('jest-get-type'); + +var _jestMatcherUtils = require('jest-matcher-utils'); + +var _prettyFormat = require('pretty-format'); + +var _colors = require('./colors'); + +var _dedentLines = require('./dedentLines'); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const getSnapshotColorForChalkInstance = chalkInstance => { + const level = chalkInstance.level; + + if (level === 3) { + return chalkInstance + .rgb( + _colors.aForeground3[0], + _colors.aForeground3[1], + _colors.aForeground3[2] + ) + .bgRgb( + _colors.aBackground3[0], + _colors.aBackground3[1], + _colors.aBackground3[2] + ); + } + + if (level === 2) { + return chalkInstance + .ansi256(_colors.aForeground2) + .bgAnsi256(_colors.aBackground2); + } + + return chalkInstance.magenta.bgYellowBright; +}; + +exports.getSnapshotColorForChalkInstance = getSnapshotColorForChalkInstance; + +const getReceivedColorForChalkInstance = chalkInstance => { + const level = chalkInstance.level; + + if (level === 3) { + return chalkInstance + .rgb( + _colors.bForeground3[0], + _colors.bForeground3[1], + _colors.bForeground3[2] + ) + .bgRgb( + _colors.bBackground3[0], + _colors.bBackground3[1], + _colors.bBackground3[2] + ); + } + + if (level === 2) { + return chalkInstance + .ansi256(_colors.bForeground2) + .bgAnsi256(_colors.bBackground2); + } + + return chalkInstance.cyan.bgWhiteBright; // also known as teal +}; + +exports.getReceivedColorForChalkInstance = getReceivedColorForChalkInstance; +const aSnapshotColor = getSnapshotColorForChalkInstance(_chalk.default); +exports.aSnapshotColor = aSnapshotColor; +const bReceivedColor = getReceivedColorForChalkInstance(_chalk.default); +exports.bReceivedColor = bReceivedColor; + +const noColor = string => string; + +exports.noColor = noColor; +const HINT_ARG = 'hint'; +exports.HINT_ARG = HINT_ARG; +const SNAPSHOT_ARG = 'snapshot'; +exports.SNAPSHOT_ARG = SNAPSHOT_ARG; +const PROPERTIES_ARG = 'properties'; +exports.PROPERTIES_ARG = PROPERTIES_ARG; + +const matcherHintFromConfig = ( + {context: {isNot, promise}, hint, inlineSnapshot, matcherName, properties}, + isUpdatable +) => { + const options = { + isNot, + promise + }; + + if (isUpdatable) { + options.receivedColor = bReceivedColor; + } + + let expectedArgument = ''; + + if (typeof properties === 'object') { + expectedArgument = PROPERTIES_ARG; + + if (isUpdatable) { + options.expectedColor = noColor; + } + + if (typeof hint === 'string' && hint.length !== 0) { + options.secondArgument = HINT_ARG; + options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT; + } else if (typeof inlineSnapshot === 'string') { + options.secondArgument = SNAPSHOT_ARG; + + if (isUpdatable) { + options.secondArgumentColor = aSnapshotColor; + } else { + options.secondArgumentColor = noColor; + } + } + } else { + if (typeof hint === 'string' && hint.length !== 0) { + expectedArgument = HINT_ARG; + options.expectedColor = _jestMatcherUtils.BOLD_WEIGHT; + } else if (typeof inlineSnapshot === 'string') { + expectedArgument = SNAPSHOT_ARG; + + if (isUpdatable) { + options.expectedColor = aSnapshotColor; + } + } + } + + return (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + expectedArgument, + options + ); +}; // Given array of diffs, return string: +// * include common substrings +// * exclude change substrings which have opposite op +// * include change substrings which have argument op +// with change color only if there is a common substring + +exports.matcherHintFromConfig = matcherHintFromConfig; + +const joinDiffs = (diffs, op, hasCommon) => + diffs.reduce( + (reduced, diff) => + reduced + + (diff[0] === _jestDiff.DIFF_EQUAL + ? diff[1] + : diff[0] !== op + ? '' + : hasCommon + ? (0, _jestMatcherUtils.INVERTED_COLOR)(diff[1]) + : diff[1]), + '' + ); + +const isLineDiffable = received => { + const receivedType = (0, _jestGetType.getType)(received); + + if ((0, _jestGetType.isPrimitive)(received)) { + return typeof received === 'string'; + } + + if ( + receivedType === 'date' || + receivedType === 'function' || + receivedType === 'regexp' + ) { + return false; + } + + if (received instanceof Error) { + return false; + } + + if ( + receivedType === 'object' && + typeof received.asymmetricMatch === 'function' + ) { + return false; + } + + return true; +}; + +const printExpected = val => + (0, _jestMatcherUtils.EXPECTED_COLOR)((0, _utils.minify)(val)); + +exports.printExpected = printExpected; + +const printReceived = val => + (0, _jestMatcherUtils.RECEIVED_COLOR)((0, _utils.minify)(val)); + +exports.printReceived = printReceived; + +const printPropertiesAndReceived = ( + properties, + received, + expand // CLI options: true if `--expand` or false if `--no-expand` +) => { + const aAnnotation = 'Expected properties'; + const bAnnotation = 'Received value'; + + if (isLineDiffable(properties) && isLineDiffable(received)) { + return (0, _jestDiff.diffLinesUnified)( + (0, _utils.serialize)(properties).split('\n'), + (0, _utils.serialize)( + (0, _expectUtils.getObjectSubset)(received, properties) + ).split('\n'), + { + aAnnotation, + aColor: _jestMatcherUtils.EXPECTED_COLOR, + bAnnotation, + bColor: _jestMatcherUtils.RECEIVED_COLOR, + changeLineTrailingSpaceColor: _chalk.default.bgYellow, + commonLineTrailingSpaceColor: _chalk.default.bgYellow, + emptyFirstOrLastLinePlaceholder: '↵', + // U+21B5 + expand, + includeChangeCounts: true + } + ); + } + + const printLabel = (0, _jestMatcherUtils.getLabelPrinter)( + aAnnotation, + bAnnotation + ); + return `${printLabel(aAnnotation) + printExpected(properties)}\n${printLabel( + bAnnotation + )}${printReceived(received)}`; +}; + +exports.printPropertiesAndReceived = printPropertiesAndReceived; +const MAX_DIFF_STRING_LENGTH = 20000; + +const printSnapshotAndReceived = (a, b, received, expand, snapshotFormat) => { + const aAnnotation = 'Snapshot'; + const bAnnotation = 'Received'; + const aColor = aSnapshotColor; + const bColor = bReceivedColor; + const options = { + aAnnotation, + aColor, + bAnnotation, + bColor, + changeLineTrailingSpaceColor: noColor, + commonLineTrailingSpaceColor: _chalk.default.bgYellow, + emptyFirstOrLastLinePlaceholder: '↵', + // U+21B5 + expand, + includeChangeCounts: true + }; + + if (typeof received === 'string') { + if ( + a.length >= 2 && + a.startsWith('"') && + a.endsWith('"') && + b === (0, _prettyFormat.format)(received) + ) { + // If snapshot looks like default serialization of a string + // and received is string which has default serialization. + if (!a.includes('\n') && !b.includes('\n')) { + // If neither string is multiline, + // display as labels and quoted strings. + let aQuoted = a; + let bQuoted = b; + + if ( + a.length - 2 <= MAX_DIFF_STRING_LENGTH && + b.length - 2 <= MAX_DIFF_STRING_LENGTH + ) { + const diffs = (0, _jestDiff.diffStringsRaw)( + a.slice(1, -1), + b.slice(1, -1), + true + ); + const hasCommon = diffs.some( + diff => diff[0] === _jestDiff.DIFF_EQUAL + ); + aQuoted = `"${joinDiffs(diffs, _jestDiff.DIFF_DELETE, hasCommon)}"`; + bQuoted = `"${joinDiffs(diffs, _jestDiff.DIFF_INSERT, hasCommon)}"`; + } + + const printLabel = (0, _jestMatcherUtils.getLabelPrinter)( + aAnnotation, + bAnnotation + ); + return `${printLabel(aAnnotation) + aColor(aQuoted)}\n${printLabel( + bAnnotation + )}${bColor(bQuoted)}`; + } // Else either string is multiline, so display as unquoted strings. + + a = (0, _utils.deserializeString)(a); // hypothetical expected string + + b = received; // not serialized + } // Else expected had custom serialization or was not a string + // or received has custom serialization. + + return a.length <= MAX_DIFF_STRING_LENGTH && + b.length <= MAX_DIFF_STRING_LENGTH + ? (0, _jestDiff.diffStringsUnified)(a, b, options) + : (0, _jestDiff.diffLinesUnified)(a.split('\n'), b.split('\n'), options); + } + + if (isLineDiffable(received)) { + const aLines2 = a.split('\n'); + const bLines2 = b.split('\n'); // Fall through to fix a regression for custom serializers + // like jest-snapshot-serializer-raw that ignore the indent option. + + const b0 = (0, _utils.serialize)(received, 0, snapshotFormat); + + if (b0 !== b) { + const aLines0 = (0, _dedentLines.dedentLines)(aLines2); + + if (aLines0 !== null) { + // Compare lines without indentation. + const bLines0 = b0.split('\n'); + return (0, _jestDiff.diffLinesUnified2)( + aLines2, + bLines2, + aLines0, + bLines0, + options + ); + } + } // Fall back because: + // * props include a multiline string + // * text has more than one adjacent line + // * markup does not close + + return (0, _jestDiff.diffLinesUnified)(aLines2, bLines2, options); + } + + const printLabel = (0, _jestMatcherUtils.getLabelPrinter)( + aAnnotation, + bAnnotation + ); + return `${printLabel(aAnnotation) + aColor(a)}\n${printLabel( + bAnnotation + )}${bColor(b)}`; +}; + +exports.printSnapshotAndReceived = printSnapshotAndReceived; diff --git a/node_modules/jest-snapshot/build/types.js b/node_modules/jest-snapshot/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-snapshot/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-snapshot/build/utils.js b/node_modules/jest-snapshot/build/utils.js new file mode 100644 index 0000000..7ddadb3 --- /dev/null +++ b/node_modules/jest-snapshot/build/utils.js @@ -0,0 +1,356 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.testNameToKey = + exports.serialize = + exports.saveSnapshotFile = + exports.removeLinesBeforeExternalMatcherTrap = + exports.removeExtraLineBreaks = + exports.minify = + exports.keyToTestName = + exports.getSnapshotData = + exports.escapeBacktickString = + exports.ensureDirectoryExists = + exports.deserializeString = + exports.deepMerge = + exports.addExtraLineBreaks = + exports.SNAPSHOT_VERSION_WARNING = + exports.SNAPSHOT_VERSION = + exports.SNAPSHOT_GUIDE_LINK = + void 0; + +var path = _interopRequireWildcard(require('path')); + +var _chalk = _interopRequireDefault(require('chalk')); + +var fs = _interopRequireWildcard(require('graceful-fs')); + +var _naturalCompare = _interopRequireDefault(require('natural-compare')); + +var _prettyFormat = require('pretty-format'); + +var _plugins = require('./plugins'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestWriteFile = + globalThis[Symbol.for('jest-native-write-file')] || fs.writeFileSync; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestReadFile = + globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestExistsFile = + globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync; +const SNAPSHOT_VERSION = '1'; +exports.SNAPSHOT_VERSION = SNAPSHOT_VERSION; +const SNAPSHOT_VERSION_REGEXP = /^\/\/ Jest Snapshot v(.+),/; +const SNAPSHOT_GUIDE_LINK = 'https://goo.gl/fbAQLP'; +exports.SNAPSHOT_GUIDE_LINK = SNAPSHOT_GUIDE_LINK; + +const SNAPSHOT_VERSION_WARNING = _chalk.default.yellow( + `${_chalk.default.bold('Warning')}: Before you upgrade snapshots, ` + + 'we recommend that you revert any local changes to tests or other code, ' + + 'to ensure that you do not store invalid state.' +); + +exports.SNAPSHOT_VERSION_WARNING = SNAPSHOT_VERSION_WARNING; + +const writeSnapshotVersion = () => + `// Jest Snapshot v${SNAPSHOT_VERSION}, ${SNAPSHOT_GUIDE_LINK}`; + +const validateSnapshotVersion = snapshotContents => { + const versionTest = SNAPSHOT_VERSION_REGEXP.exec(snapshotContents); + const version = versionTest && versionTest[1]; + + if (!version) { + return new Error( + _chalk.default.red( + `${_chalk.default.bold( + 'Outdated snapshot' + )}: No snapshot header found. ` + + 'Jest 19 introduced versioned snapshots to ensure all developers ' + + 'on a project are using the same version of Jest. ' + + 'Please update all snapshots during this upgrade of Jest.\n\n' + ) + SNAPSHOT_VERSION_WARNING + ); + } + + if (version < SNAPSHOT_VERSION) { + return new Error( // eslint-disable-next-line prefer-template + _chalk.default.red( + `${_chalk.default.red.bold( + 'Outdated snapshot' + )}: The version of the snapshot ` + + 'file associated with this test is outdated. The snapshot file ' + + 'version ensures that all developers on a project are using ' + + 'the same version of Jest. ' + + 'Please update all snapshots during this upgrade of Jest.' + ) + + '\n\n' + + `Expected: v${SNAPSHOT_VERSION}\n` + + `Received: v${version}\n\n` + + SNAPSHOT_VERSION_WARNING + ); + } + + if (version > SNAPSHOT_VERSION) { + return new Error( // eslint-disable-next-line prefer-template + _chalk.default.red( + `${_chalk.default.red.bold( + 'Outdated Jest version' + )}: The version of this ` + + 'snapshot file indicates that this project is meant to be used ' + + 'with a newer version of Jest. The snapshot file version ensures ' + + 'that all developers on a project are using the same version of ' + + 'Jest. Please update your version of Jest and re-run the tests.' + ) + + '\n\n' + + `Expected: v${SNAPSHOT_VERSION}\n` + + `Received: v${version}` + ); + } + + return null; +}; + +function isObject(item) { + return item != null && typeof item === 'object' && !Array.isArray(item); +} + +const testNameToKey = (testName, count) => `${testName} ${count}`; + +exports.testNameToKey = testNameToKey; + +const keyToTestName = key => { + if (!/ \d+$/.test(key)) { + throw new Error('Snapshot keys must end with a number.'); + } + + return key.replace(/ \d+$/, ''); +}; + +exports.keyToTestName = keyToTestName; + +const getSnapshotData = (snapshotPath, update) => { + const data = Object.create(null); + let snapshotContents = ''; + let dirty = false; + + if (jestExistsFile(snapshotPath)) { + try { + snapshotContents = jestReadFile(snapshotPath, 'utf8'); // eslint-disable-next-line no-new-func + + const populate = new Function('exports', snapshotContents); + populate(data); + } catch {} + } + + const validationResult = validateSnapshotVersion(snapshotContents); + const isInvalid = snapshotContents && validationResult; + + if (update === 'none' && isInvalid) { + throw validationResult; + } + + if ((update === 'all' || update === 'new') && isInvalid) { + dirty = true; + } + + return { + data, + dirty + }; +}; // Add extra line breaks at beginning and end of multiline snapshot +// to make the content easier to read. + +exports.getSnapshotData = getSnapshotData; + +const addExtraLineBreaks = string => + string.includes('\n') ? `\n${string}\n` : string; // Remove extra line breaks at beginning and end of multiline snapshot. +// Instead of trim, which can remove additional newlines or spaces +// at beginning or end of the content from a custom serializer. + +exports.addExtraLineBreaks = addExtraLineBreaks; + +const removeExtraLineBreaks = string => + string.length > 2 && string.startsWith('\n') && string.endsWith('\n') + ? string.slice(1, -1) + : string; + +exports.removeExtraLineBreaks = removeExtraLineBreaks; + +const removeLinesBeforeExternalMatcherTrap = stack => { + const lines = stack.split('\n'); + + for (let i = 0; i < lines.length; i += 1) { + // It's a function name specified in `packages/expect/src/index.ts` + // for external custom matchers. + if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__')) { + return lines.slice(i + 1).join('\n'); + } + } + + return stack; +}; + +exports.removeLinesBeforeExternalMatcherTrap = + removeLinesBeforeExternalMatcherTrap; +const escapeRegex = true; +const printFunctionName = false; + +const serialize = (val, indent = 2, formatOverrides = {}) => + normalizeNewlines( + (0, _prettyFormat.format)(val, { + escapeRegex, + indent, + plugins: (0, _plugins.getSerializers)(), + printFunctionName, + ...formatOverrides + }) + ); + +exports.serialize = serialize; + +const minify = val => + (0, _prettyFormat.format)(val, { + escapeRegex, + min: true, + plugins: (0, _plugins.getSerializers)(), + printFunctionName + }); // Remove double quote marks and unescape double quotes and backslashes. + +exports.minify = minify; + +const deserializeString = stringified => + stringified.slice(1, -1).replace(/\\("|\\)/g, '$1'); + +exports.deserializeString = deserializeString; + +const escapeBacktickString = str => str.replace(/`|\\|\${/g, '\\$&'); + +exports.escapeBacktickString = escapeBacktickString; + +const printBacktickString = str => `\`${escapeBacktickString(str)}\``; + +const ensureDirectoryExists = filePath => { + try { + fs.mkdirSync(path.join(path.dirname(filePath)), { + recursive: true + }); + } catch {} +}; + +exports.ensureDirectoryExists = ensureDirectoryExists; + +const normalizeNewlines = string => string.replace(/\r\n|\r/g, '\n'); + +const saveSnapshotFile = (snapshotData, snapshotPath) => { + const snapshots = Object.keys(snapshotData) + .sort(_naturalCompare.default) + .map( + key => + `exports[${printBacktickString(key)}] = ${printBacktickString( + normalizeNewlines(snapshotData[key]) + )};` + ); + ensureDirectoryExists(snapshotPath); + jestWriteFile( + snapshotPath, + `${writeSnapshotVersion()}\n\n${snapshots.join('\n\n')}\n` + ); +}; + +exports.saveSnapshotFile = saveSnapshotFile; + +const deepMergeArray = (target, source) => { + const mergedOutput = Array.from(target); + source.forEach((sourceElement, index) => { + const targetElement = mergedOutput[index]; + + if (Array.isArray(target[index])) { + mergedOutput[index] = deepMergeArray(target[index], sourceElement); + } else if (isObject(targetElement)) { + mergedOutput[index] = deepMerge(target[index], sourceElement); + } else { + // Source does not exist in target or target is primitive and cannot be deep merged + mergedOutput[index] = sourceElement; + } + }); + return mergedOutput; +}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + +const deepMerge = (target, source) => { + if (isObject(target) && isObject(source)) { + const mergedOutput = {...target}; + Object.keys(source).forEach(key => { + if (isObject(source[key]) && !source[key].$$typeof) { + if (!(key in target)) + Object.assign(mergedOutput, { + [key]: source[key] + }); + else mergedOutput[key] = deepMerge(target[key], source[key]); + } else if (Array.isArray(source[key])) { + mergedOutput[key] = deepMergeArray(target[key], source[key]); + } else { + Object.assign(mergedOutput, { + [key]: source[key] + }); + } + }); + return mergedOutput; + } else if (Array.isArray(target) && Array.isArray(source)) { + return deepMergeArray(target, source); + } + + return target; +}; + +exports.deepMerge = deepMerge; diff --git a/node_modules/jest-snapshot/node_modules/.bin/semver b/node_modules/jest-snapshot/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/jest-snapshot/node_modules/semver/LICENSE b/node_modules/jest-snapshot/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/jest-snapshot/node_modules/semver/README.md b/node_modules/jest-snapshot/node_modules/semver/README.md new file mode 100644 index 0000000..df54e7a --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/README.md @@ -0,0 +1,568 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about, if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const simplifyRange = require('semver/ranges/simplify') +const rangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless + `includePrerelease` is specified, in which case any version at all + satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need, if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` diff --git a/node_modules/jest-snapshot/node_modules/semver/bin/semver.js b/node_modules/jest-snapshot/node_modules/semver/bin/semver.js new file mode 100755 index 0000000..8d1b557 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/bin/semver.js @@ -0,0 +1,183 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +const semver = require('../') + +let reverse = false + +let options = {} + +const main = () => { + if (!argv.length) { + return help() + } + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + const value = a.slice(indexOfEqualSign + 1) + a = a.slice(0, indexOfEqualSign) + argv.unshift(value) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) { + return fail() + } + if (inc && (versions.length !== 1 || range.length)) { + return failInc() + } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) { + return fail() + } + } + return success(versions) +} + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const success = () => { + const compare = reverse ? 'rcompare' : 'compare' + versions.sort((a, b) => { + return semver[compare](a, b, options) + }).map((v) => { + return semver.clean(v, options) + }).map((v) => { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach((v, i, _) => { + console.log(v) + }) +} + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/comparator.js b/node_modules/jest-snapshot/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..62cd204 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/comparator.js @@ -0,0 +1,136 @@ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false, + } + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + const sameSemVer = this.semver.version === comp.semver.version + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<') + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>') + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const { re, t } = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/index.js b/node_modules/jest-snapshot/node_modules/semver/classes/index.js new file mode 100644 index 0000000..5e3f5c9 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/index.js @@ -0,0 +1,5 @@ +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js'), +} diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/range.js b/node_modules/jest-snapshot/node_modules/semver/classes/range.js new file mode 100644 index 0000000..7dc24bc --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/range.js @@ -0,0 +1,519 @@ +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.format() + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim() + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim() + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(',') + const memoKey = `parseRange:${memoOpts}:${range}` + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} +module.exports = Range + +const LRU = require('lru-cache') +const cache = new LRU({ max: 1000 }) + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = require('../internal/re') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceTilde(c, options) + }).join(' ') + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceCaret(c, options) + }).join(' ') + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map((c) => { + return replaceXRange(c, options) + }).join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp.trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return (`${from} ${to}`).trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/semver.js b/node_modules/jest-snapshot/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..af62955 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/semver.js @@ -0,0 +1,287 @@ +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format() + this.raw = this.version + return this + } +} + +module.exports = SemVer diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/clean.js b/node_modules/jest-snapshot/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..811fe6b --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/clean.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/cmp.js b/node_modules/jest-snapshot/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..4011909 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/cmp.js @@ -0,0 +1,52 @@ +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/coerce.js b/node_modules/jest-snapshot/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..2e01452 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/coerce.js @@ -0,0 +1,52 @@ +const SemVer = require('../classes/semver') +const parse = require('./parse') +const { re, t } = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) +} +module.exports = coerce diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/compare-build.js b/node_modules/jest-snapshot/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..9eb881b --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/compare-build.js @@ -0,0 +1,7 @@ +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/compare-loose.js b/node_modules/jest-snapshot/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..4881fbe --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/compare.js b/node_modules/jest-snapshot/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..748b7af --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/compare.js @@ -0,0 +1,5 @@ +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/diff.js b/node_modules/jest-snapshot/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..87200ef --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/diff.js @@ -0,0 +1,23 @@ +const parse = require('./parse') +const eq = require('./eq') + +const diff = (version1, version2) => { + if (eq(version1, version2)) { + return null + } else { + const v1 = parse(version1) + const v2 = parse(version2) + const hasPre = v1.prerelease.length || v2.prerelease.length + const prefix = hasPre ? 'pre' : '' + const defaultResult = hasPre ? 'prerelease' : '' + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} +module.exports = diff diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/eq.js b/node_modules/jest-snapshot/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..271fed9 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/eq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/gt.js b/node_modules/jest-snapshot/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..d9b2156 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/gt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/gte.js b/node_modules/jest-snapshot/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..5aeaa63 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/gte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/inc.js b/node_modules/jest-snapshot/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..62d1da2 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/inc.js @@ -0,0 +1,18 @@ +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/lt.js b/node_modules/jest-snapshot/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..b440ab7 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/lt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/lte.js b/node_modules/jest-snapshot/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..6dcc956 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/lte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/major.js b/node_modules/jest-snapshot/node_modules/semver/functions/major.js new file mode 100644 index 0000000..4283165 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/major.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/minor.js b/node_modules/jest-snapshot/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..57b3455 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/minor.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/neq.js b/node_modules/jest-snapshot/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..f944c01 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/neq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/parse.js b/node_modules/jest-snapshot/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..a66663a --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/parse.js @@ -0,0 +1,33 @@ +const { MAX_LENGTH } = require('../internal/constants') +const { re, t } = require('../internal/re') +const SemVer = require('../classes/semver') + +const parseOptions = require('../internal/parse-options') +const parse = (version, options) => { + options = parseOptions(options) + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +module.exports = parse diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/patch.js b/node_modules/jest-snapshot/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..63afca2 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/patch.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/prerelease.js b/node_modules/jest-snapshot/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..06aa132 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/prerelease.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/rcompare.js b/node_modules/jest-snapshot/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..0ac509e --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/rcompare.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/rsort.js b/node_modules/jest-snapshot/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..82404c5 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/rsort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/satisfies.js b/node_modules/jest-snapshot/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..50af1c1 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/satisfies.js @@ -0,0 +1,10 @@ +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/sort.js b/node_modules/jest-snapshot/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..4d10917 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/sort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/valid.js b/node_modules/jest-snapshot/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..f27bae1 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/valid.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/jest-snapshot/node_modules/semver/index.js b/node_modules/jest-snapshot/node_modules/semver/index.js new file mode 100644 index 0000000..57e2ae6 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/index.js @@ -0,0 +1,48 @@ +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +module.exports = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: require('./internal/constants').SEMVER_SPEC_VERSION, + SemVer: require('./classes/semver'), + compareIdentifiers: require('./internal/identifiers').compareIdentifiers, + rcompareIdentifiers: require('./internal/identifiers').rcompareIdentifiers, + parse: require('./functions/parse'), + valid: require('./functions/valid'), + clean: require('./functions/clean'), + inc: require('./functions/inc'), + diff: require('./functions/diff'), + major: require('./functions/major'), + minor: require('./functions/minor'), + patch: require('./functions/patch'), + prerelease: require('./functions/prerelease'), + compare: require('./functions/compare'), + rcompare: require('./functions/rcompare'), + compareLoose: require('./functions/compare-loose'), + compareBuild: require('./functions/compare-build'), + sort: require('./functions/sort'), + rsort: require('./functions/rsort'), + gt: require('./functions/gt'), + lt: require('./functions/lt'), + eq: require('./functions/eq'), + neq: require('./functions/neq'), + gte: require('./functions/gte'), + lte: require('./functions/lte'), + cmp: require('./functions/cmp'), + coerce: require('./functions/coerce'), + Comparator: require('./classes/comparator'), + Range: require('./classes/range'), + satisfies: require('./functions/satisfies'), + toComparators: require('./ranges/to-comparators'), + maxSatisfying: require('./ranges/max-satisfying'), + minSatisfying: require('./ranges/min-satisfying'), + minVersion: require('./ranges/min-version'), + validRange: require('./ranges/valid'), + outside: require('./ranges/outside'), + gtr: require('./ranges/gtr'), + ltr: require('./ranges/ltr'), + intersects: require('./ranges/intersects'), + simplifyRange: require('./ranges/simplify'), + subset: require('./ranges/subset'), +} diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/constants.js b/node_modules/jest-snapshot/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..4f0de59 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/constants.js @@ -0,0 +1,17 @@ +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +module.exports = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH, +} diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/debug.js b/node_modules/jest-snapshot/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..1c00e13 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/debug.js @@ -0,0 +1,9 @@ +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/identifiers.js b/node_modules/jest-snapshot/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..e612d0a --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/identifiers.js @@ -0,0 +1,23 @@ +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/parse-options.js b/node_modules/jest-snapshot/node_modules/semver/internal/parse-options.js new file mode 100644 index 0000000..bbd9ec7 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/parse-options.js @@ -0,0 +1,11 @@ +// parse out just the options we care about so we always get a consistent +// obj with keys in a consistent order. +const opts = ['includePrerelease', 'loose', 'rtl'] +const parseOptions = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((o, k) => { + o[k] = true + return o + }, {}) +module.exports = parseOptions diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/re.js b/node_modules/jest-snapshot/node_modules/semver/internal/re.js new file mode 100644 index 0000000..ed88398 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/re.js @@ -0,0 +1,182 @@ +const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const createToken = (name, value, isGlobal) => { + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') diff --git a/node_modules/jest-snapshot/node_modules/semver/package.json b/node_modules/jest-snapshot/node_modules/semver/package.json new file mode 100644 index 0000000..1063eba --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/package.json @@ -0,0 +1,106 @@ +{ + "_from": "semver@^7.3.5", + "_id": "semver@7.3.7", + "_inBundle": false, + "_integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "_location": "/jest-snapshot/semver", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "semver@^7.3.5", + "name": "semver", + "escapedName": "semver", + "rawSpec": "^7.3.5", + "saveSpec": null, + "fetchSpec": "^7.3.5" + }, + "_requiredBy": [ + "/jest-snapshot" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", + "_shasum": "12c5b649afdbf9049707796e22a4028814ce523f", + "_spec": "semver@^7.3.5", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-snapshot", + "author": { + "name": "GitHub Inc." + }, + "bin": { + "semver": "bin/semver.js" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "bundleDependencies": false, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "deprecated": false, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "@npmcli/eslint-config": "^3.0.1", + "@npmcli/template-oss": "3.3.2", + "tap": "^16.0.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "bin/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "index.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "lint": "eslint \"**/*.js\"", + "lintfix": "npm run lint -- --fix", + "postlint": "template-oss-check", + "postpublish": "git push origin --follow-tags", + "posttest": "npm run lint", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "preversion": "npm test", + "snap": "tap", + "template-oss-apply": "template-oss-apply --force", + "test": "tap" + }, + "tap": { + "check-coverage": true, + "coverage-map": "map.js" + }, + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "3.3.2", + "engines": ">=10", + "ciVersions": [ + "10.0.0", + "10.x", + "12.x", + "14.x", + "16.x" + ], + "distPaths": [ + "bin/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ] + }, + "version": "7.3.7" +} diff --git a/node_modules/jest-snapshot/node_modules/semver/preload.js b/node_modules/jest-snapshot/node_modules/semver/preload.js new file mode 100644 index 0000000..947cd4f --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/preload.js @@ -0,0 +1,2 @@ +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/jest-snapshot/node_modules/semver/range.bnf b/node_modules/jest-snapshot/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/gtr.js b/node_modules/jest-snapshot/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..db7e355 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/gtr.js @@ -0,0 +1,4 @@ +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/intersects.js b/node_modules/jest-snapshot/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..3d1a6f3 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/intersects.js @@ -0,0 +1,7 @@ +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} +module.exports = intersects diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/ltr.js b/node_modules/jest-snapshot/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..528a885 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/ltr.js @@ -0,0 +1,4 @@ +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/max-satisfying.js b/node_modules/jest-snapshot/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..6e3d993 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,25 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/min-satisfying.js b/node_modules/jest-snapshot/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..9b60974 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,24 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/min-version.js b/node_modules/jest-snapshot/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..350e1f7 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/min-version.js @@ -0,0 +1,61 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/outside.js b/node_modules/jest-snapshot/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..ae99b10 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/outside.js @@ -0,0 +1,80 @@ +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const { ANY } = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/simplify.js b/node_modules/jest-snapshot/node_modules/semver/ranges/simplify.js new file mode 100644 index 0000000..618d5b6 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/simplify.js @@ -0,0 +1,47 @@ +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/subset.js b/node_modules/jest-snapshot/node_modules/semver/ranges/subset.js new file mode 100644 index 0000000..e0dea43 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/subset.js @@ -0,0 +1,244 @@ +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = [new Comparator('>=0.0.0-0')] + } else { + sub = [new Comparator('>=0.0.0')] + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = [new Comparator('>=0.0.0')] + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/to-comparators.js b/node_modules/jest-snapshot/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..6c8bc7e --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,8 @@ +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/valid.js b/node_modules/jest-snapshot/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..365f356 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/valid.js @@ -0,0 +1,11 @@ +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/jest-snapshot/package.json b/node_modules/jest-snapshot/package.json new file mode 100644 index 0000000..ac29064 --- /dev/null +++ b/node_modules/jest-snapshot/package.json @@ -0,0 +1,100 @@ +{ + "_from": "jest-snapshot@^29.0.1", + "_id": "jest-snapshot@29.0.1", + "_inBundle": false, + "_integrity": "sha512-OuYGp+lsh7RhB3DDX36z/pzrGm2F740e5ERG9PQpJyDknCRtWdhaehBQyMqDnsQdKkvC2zOcetcxskiHjO7e8Q==", + "_location": "/jest-snapshot", + "_phantomChildren": { + "lru-cache": "6.0.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-snapshot@^29.0.1", + "name": "jest-snapshot", + "escapedName": "jest-snapshot", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/@jest/expect", + "/jest-circus", + "/jest-resolve-dependencies", + "/jest-runtime" + ], + "_resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.0.1.tgz", + "_shasum": "ed455cb7e56fb43e2d451edd902d622349d6afed", + "_spec": "jest-snapshot@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/traverse": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.0.1", + "@jest/transform": "^29.0.1", + "@jest/types": "^29.0.1", + "@types/babel__traverse": "^7.0.6", + "@types/prettier": "^2.1.5", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.0.1", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.0.1", + "jest-get-type": "^29.0.0", + "jest-haste-map": "^29.0.1", + "jest-matcher-utils": "^29.0.1", + "jest-message-util": "^29.0.1", + "jest-util": "^29.0.1", + "natural-compare": "^1.4.0", + "pretty-format": "^29.0.1", + "semver": "^7.3.5" + }, + "deprecated": false, + "devDependencies": { + "@babel/preset-flow": "^7.7.2", + "@babel/preset-react": "^7.12.1", + "@jest/test-utils": "^29.0.1", + "@tsd/typescript": "~4.7.4", + "@types/graceful-fs": "^4.1.3", + "@types/natural-compare": "^1.4.0", + "@types/semver": "^7.1.0", + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "prettier": "^2.1.1", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-snapshot", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-snapshot" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-util/LICENSE b/node_modules/jest-util/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-util/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-util/build/ErrorWithStack.js b/node_modules/jest-util/build/ErrorWithStack.js new file mode 100644 index 0000000..87f6deb --- /dev/null +++ b/node_modules/jest-util/build/ErrorWithStack.js @@ -0,0 +1,33 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class ErrorWithStack extends Error { + constructor(message, callsite, stackLimit) { + // Ensure we have a large stack length so we get full details. + const originalStackLimit = Error.stackTraceLimit; + + if (stackLimit) { + Error.stackTraceLimit = Math.max(stackLimit, originalStackLimit || 10); + } + + super(message); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, callsite); + } + + Error.stackTraceLimit = originalStackLimit; + } +} + +exports.default = ErrorWithStack; diff --git a/node_modules/jest-util/build/clearLine.js b/node_modules/jest-util/build/clearLine.js new file mode 100644 index 0000000..36c258a --- /dev/null +++ b/node_modules/jest-util/build/clearLine.js @@ -0,0 +1,18 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = clearLine; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function clearLine(stream) { + if (stream.isTTY) { + stream.write('\x1b[999D\x1b[K'); + } +} diff --git a/node_modules/jest-util/build/convertDescriptorToString.js b/node_modules/jest-util/build/convertDescriptorToString.js new file mode 100644 index 0000000..a2b7066 --- /dev/null +++ b/node_modules/jest-util/build/convertDescriptorToString.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = convertDescriptorToString; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function convertDescriptorToString(descriptor) { + switch (typeof descriptor) { + case 'function': + if (descriptor.name) { + return descriptor.name; + } + + break; + + case 'number': + case 'undefined': + return `${descriptor}`; + + case 'string': + return descriptor; + } + + throw new Error( + `Invalid first argument, ${descriptor}. It must be a named class, named function, number, or string.` + ); +} diff --git a/node_modules/jest-util/build/createDirectory.js b/node_modules/jest-util/build/createDirectory.js new file mode 100644 index 0000000..d2a28b7 --- /dev/null +++ b/node_modules/jest-util/build/createDirectory.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = createDirectory; + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function createDirectory(path) { + try { + fs().mkdirSync(path, { + recursive: true + }); + } catch (e) { + if (e.code !== 'EEXIST') { + throw e; + } + } +} diff --git a/node_modules/jest-util/build/createProcessObject.js b/node_modules/jest-util/build/createProcessObject.js new file mode 100644 index 0000000..ec35a42 --- /dev/null +++ b/node_modules/jest-util/build/createProcessObject.js @@ -0,0 +1,124 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = createProcessObject; + +var _deepCyclicCopy = _interopRequireDefault(require('./deepCyclicCopy')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const BLACKLIST = new Set(['env', 'mainModule', '_events']); +const isWin32 = process.platform === 'win32'; +const proto = Object.getPrototypeOf(process.env); // The "process.env" object has a bunch of particularities: first, it does not +// directly extend from Object; second, it converts any assigned value to a +// string; and third, it is case-insensitive in Windows. We use a proxy here to +// mimic it (see https://nodejs.org/api/process.html#process_process_env). + +function createProcessEnv() { + const real = Object.create(proto); + const lookup = {}; + + function deletePropertyWin32(_target, key) { + for (const name in real) { + if (Object.prototype.hasOwnProperty.call(real, name)) { + if (typeof key === 'string') { + if (name.toLowerCase() === key.toLowerCase()) { + delete real[name]; + delete lookup[name.toLowerCase()]; + } + } else { + if (key === name) { + delete real[name]; + delete lookup[name]; + } + } + } + } + + return true; + } + + function deleteProperty(_target, key) { + delete real[key]; + delete lookup[key]; + return true; + } + + function getProperty(_target, key) { + return real[key]; + } + + function getPropertyWin32(_target, key) { + if (typeof key === 'string') { + return lookup[key in proto ? key : key.toLowerCase()]; + } else { + return real[key]; + } + } + + const proxy = new Proxy(real, { + deleteProperty: isWin32 ? deletePropertyWin32 : deleteProperty, + get: isWin32 ? getPropertyWin32 : getProperty, + + set(_target, key, value) { + const strValue = `${value}`; + + if (typeof key === 'string') { + lookup[key.toLowerCase()] = strValue; + } + + real[key] = strValue; + return true; + } + }); + return Object.assign(proxy, process.env); +} + +function createProcessObject() { + const process = require('process'); + + const newProcess = (0, _deepCyclicCopy.default)(process, { + blacklist: BLACKLIST, + keepPrototype: true + }); + + try { + // This fails on Node 12, but it's already set to 'process' + newProcess[Symbol.toStringTag] = 'process'; + } catch (e) { + // Make sure it's actually set instead of potentially ignoring errors + if (newProcess[Symbol.toStringTag] !== 'process') { + e.message = `Unable to set toStringTag on process. Please open up an issue at https://github.com/facebook/jest\n\n${e.message}`; + throw e; + } + } // Sequentially execute all constructors over the object. + + let proto = process; + + while ((proto = Object.getPrototypeOf(proto))) { + if (typeof proto.constructor === 'function') { + proto.constructor.call(newProcess); + } + } + + newProcess.env = createProcessEnv(); + + newProcess.send = () => true; + + Object.defineProperty(newProcess, 'domain', { + get() { + return process.domain; + } + }); + return newProcess; +} diff --git a/node_modules/jest-util/build/deepCyclicCopy.js b/node_modules/jest-util/build/deepCyclicCopy.js new file mode 100644 index 0000000..7a81dbc --- /dev/null +++ b/node_modules/jest-util/build/deepCyclicCopy.js @@ -0,0 +1,84 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = deepCyclicCopy; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const EMPTY = new Set(); + +function deepCyclicCopy( + value, + options = { + blacklist: EMPTY, + keepPrototype: false + }, + cycles = new WeakMap() +) { + if (typeof value !== 'object' || value === null || Buffer.isBuffer(value)) { + return value; + } else if (cycles.has(value)) { + return cycles.get(value); + } else if (Array.isArray(value)) { + return deepCyclicCopyArray(value, options, cycles); + } else { + return deepCyclicCopyObject(value, options, cycles); + } +} + +function deepCyclicCopyObject(object, options, cycles) { + const newObject = options.keepPrototype + ? Object.create(Object.getPrototypeOf(object)) + : {}; + const descriptors = Object.getOwnPropertyDescriptors(object); + cycles.set(object, newObject); + Object.keys(descriptors).forEach(key => { + if (options.blacklist && options.blacklist.has(key)) { + delete descriptors[key]; + return; + } + + const descriptor = descriptors[key]; + + if (typeof descriptor.value !== 'undefined') { + descriptor.value = deepCyclicCopy( + descriptor.value, + { + blacklist: EMPTY, + keepPrototype: options.keepPrototype + }, + cycles + ); + } + + descriptor.configurable = true; + }); + return Object.defineProperties(newObject, descriptors); +} + +function deepCyclicCopyArray(array, options, cycles) { + const newArray = options.keepPrototype + ? new (Object.getPrototypeOf(array).constructor)(array.length) + : []; + const length = array.length; + cycles.set(array, newArray); + + for (let i = 0; i < length; i++) { + newArray[i] = deepCyclicCopy( + array[i], + { + blacklist: EMPTY, + keepPrototype: options.keepPrototype + }, + cycles + ); + } + + return newArray; +} diff --git a/node_modules/jest-util/build/formatTime.js b/node_modules/jest-util/build/formatTime.js new file mode 100644 index 0000000..fad4b8c --- /dev/null +++ b/node_modules/jest-util/build/formatTime.js @@ -0,0 +1,24 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = formatTime; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function formatTime(time, prefixPower = -3, padLeftLength = 0) { + const prefixes = ['n', 'μ', 'm', '']; + const prefixIndex = Math.max( + 0, + Math.min( + Math.trunc(prefixPower / 3) + prefixes.length - 1, + prefixes.length - 1 + ) + ); + return `${String(time).padStart(padLeftLength)} ${prefixes[prefixIndex]}s`; +} diff --git a/node_modules/jest-util/build/globsToMatcher.js b/node_modules/jest-util/build/globsToMatcher.js new file mode 100644 index 0000000..b359fd5 --- /dev/null +++ b/node_modules/jest-util/build/globsToMatcher.js @@ -0,0 +1,108 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = globsToMatcher; + +function _picomatch() { + const data = _interopRequireDefault(require('picomatch')); + + _picomatch = function () { + return data; + }; + + return data; +} + +var _replacePathSepForGlob = _interopRequireDefault( + require('./replacePathSepForGlob') +); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const globsToMatchersMap = new Map(); +const picomatchOptions = { + dot: true +}; +/** + * Converts a list of globs into a function that matches a path against the + * globs. + * + * Every time picomatch is called, it will parse the glob strings and turn + * them into regexp instances. Instead of calling picomatch repeatedly with + * the same globs, we can use this function which will build the picomatch + * matchers ahead of time and then have an optimized path for determining + * whether an individual path matches. + * + * This function is intended to match the behavior of `micromatch()`. + * + * @example + * const isMatch = globsToMatcher(['*.js', '!*.test.js']); + * isMatch('pizza.js'); // true + * isMatch('pizza.test.js'); // false + */ + +function globsToMatcher(globs) { + if (globs.length === 0) { + // Since there were no globs given, we can simply have a fast path here and + // return with a very simple function. + return () => false; + } + + const matchers = globs.map(glob => { + if (!globsToMatchersMap.has(glob)) { + const isMatch = (0, _picomatch().default)(glob, picomatchOptions, true); + const matcher = { + isMatch, + // Matchers that are negated have different behavior than matchers that + // are not negated, so we need to store this information ahead of time. + negated: isMatch.state.negated || !!isMatch.state.negatedExtglob + }; + globsToMatchersMap.set(glob, matcher); + } + + return globsToMatchersMap.get(glob); + }); + return path => { + const replacedPath = (0, _replacePathSepForGlob.default)(path); + let kept = undefined; + let negatives = 0; + + for (let i = 0; i < matchers.length; i++) { + const {isMatch, negated} = matchers[i]; + + if (negated) { + negatives++; + } + + const matched = isMatch(replacedPath); + + if (!matched && negated) { + // The path was not matched, and the matcher is a negated matcher, so we + // want to omit the path. This means that the negative matcher is + // filtering the path out. + kept = false; + } else if (matched && !negated) { + // The path was matched, and the matcher is not a negated matcher, so we + // want to keep the path. + kept = true; + } + } // If all of the globs were negative globs, then we want to include the path + // as long as it was not explicitly not kept. Otherwise only include + // the path if it was kept. This allows sets of globs that are all negated + // to allow some paths to be matched, while sets of globs that are mixed + // negated and non-negated to cause the negated matchers to only omit paths + // and not keep them. + + return negatives === matchers.length ? kept !== false : !!kept; + }; +} diff --git a/node_modules/jest-util/build/index.d.ts b/node_modules/jest-util/build/index.d.ts new file mode 100644 index 0000000..a69dbe5 --- /dev/null +++ b/node_modules/jest-util/build/index.d.ts @@ -0,0 +1,125 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {Config} from '@jest/types'; +import type {Global} from '@jest/types'; + +declare const ARROW = ' \u203A '; + +declare const CLEAR: string; + +export declare function clearLine(stream: NodeJS.WriteStream): void; + +export declare function convertDescriptorToString( + descriptor: Global.BlockNameLike | undefined, +): string; + +export declare function createDirectory(path: string): void; + +export declare function deepCyclicCopy( + value: T, + options?: DeepCyclicCopyOptions, + cycles?: WeakMap, +): T; + +declare type DeepCyclicCopyOptions = { + blacklist?: Set; + keepPrototype?: boolean; +}; + +export declare class ErrorWithStack extends Error { + constructor( + message: string | undefined, + callsite: (...args: Array) => unknown, + stackLimit?: number, + ); +} + +export declare function formatTime( + time: number, + prefixPower?: number, + padLeftLength?: number, +): string; + +/** + * Converts a list of globs into a function that matches a path against the + * globs. + * + * Every time picomatch is called, it will parse the glob strings and turn + * them into regexp instances. Instead of calling picomatch repeatedly with + * the same globs, we can use this function which will build the picomatch + * matchers ahead of time and then have an optimized path for determining + * whether an individual path matches. + * + * This function is intended to match the behavior of `micromatch()`. + * + * @example + * const isMatch = globsToMatcher(['*.js', '!*.test.js']); + * isMatch('pizza.js'); // true + * isMatch('pizza.test.js'); // false + */ +export declare function globsToMatcher(globs: Array): Matcher; + +declare const ICONS: { + failed: string; + pending: string; + success: string; + todo: string; +}; + +export declare function installCommonGlobals( + globalObject: typeof globalThis, + globals: Config.ConfigGlobals, +): typeof globalThis & Config.ConfigGlobals; + +export declare function interopRequireDefault(obj: any): any; + +export declare const isInteractive: boolean; + +export declare const isPromise: ( + candidate: unknown, +) => candidate is Promise; + +declare type Matcher = (str: string) => boolean; + +export declare function pluralize(word: string, count: number): string; + +declare namespace preRunMessage { + export {print_2 as print, remove}; +} +export {preRunMessage}; + +declare function print_2(stream: NodeJS.WriteStream): void; + +declare function remove(stream: NodeJS.WriteStream): void; + +export declare function replacePathSepForGlob(path: string): string; + +export declare function requireOrImportModule( + filePath: string, + applyInteropRequireDefault?: boolean, +): Promise; + +export declare function setGlobal( + globalToMutate: typeof globalThis | Global.Global, + key: string, + value: unknown, +): void; + +declare namespace specialChars { + export {ARROW, ICONS, CLEAR}; +} +export {specialChars}; + +export declare function testPathPatternToRegExp( + testPathPattern: Config.GlobalConfig['testPathPattern'], +): RegExp; + +export declare function tryRealpath(path: string): string; + +export {}; diff --git a/node_modules/jest-util/build/index.js b/node_modules/jest-util/build/index.js new file mode 100644 index 0000000..f23c93a --- /dev/null +++ b/node_modules/jest-util/build/index.js @@ -0,0 +1,209 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'ErrorWithStack', { + enumerable: true, + get: function () { + return _ErrorWithStack.default; + } +}); +Object.defineProperty(exports, 'clearLine', { + enumerable: true, + get: function () { + return _clearLine.default; + } +}); +Object.defineProperty(exports, 'convertDescriptorToString', { + enumerable: true, + get: function () { + return _convertDescriptorToString.default; + } +}); +Object.defineProperty(exports, 'createDirectory', { + enumerable: true, + get: function () { + return _createDirectory.default; + } +}); +Object.defineProperty(exports, 'deepCyclicCopy', { + enumerable: true, + get: function () { + return _deepCyclicCopy.default; + } +}); +Object.defineProperty(exports, 'formatTime', { + enumerable: true, + get: function () { + return _formatTime.default; + } +}); +Object.defineProperty(exports, 'globsToMatcher', { + enumerable: true, + get: function () { + return _globsToMatcher.default; + } +}); +Object.defineProperty(exports, 'installCommonGlobals', { + enumerable: true, + get: function () { + return _installCommonGlobals.default; + } +}); +Object.defineProperty(exports, 'interopRequireDefault', { + enumerable: true, + get: function () { + return _interopRequireDefault.default; + } +}); +Object.defineProperty(exports, 'isInteractive', { + enumerable: true, + get: function () { + return _isInteractive.default; + } +}); +Object.defineProperty(exports, 'isPromise', { + enumerable: true, + get: function () { + return _isPromise.default; + } +}); +Object.defineProperty(exports, 'pluralize', { + enumerable: true, + get: function () { + return _pluralize.default; + } +}); +exports.preRunMessage = void 0; +Object.defineProperty(exports, 'replacePathSepForGlob', { + enumerable: true, + get: function () { + return _replacePathSepForGlob.default; + } +}); +Object.defineProperty(exports, 'requireOrImportModule', { + enumerable: true, + get: function () { + return _requireOrImportModule.default; + } +}); +Object.defineProperty(exports, 'setGlobal', { + enumerable: true, + get: function () { + return _setGlobal.default; + } +}); +exports.specialChars = void 0; +Object.defineProperty(exports, 'testPathPatternToRegExp', { + enumerable: true, + get: function () { + return _testPathPatternToRegExp.default; + } +}); +Object.defineProperty(exports, 'tryRealpath', { + enumerable: true, + get: function () { + return _tryRealpath.default; + } +}); + +var preRunMessage = _interopRequireWildcard(require('./preRunMessage')); + +exports.preRunMessage = preRunMessage; + +var specialChars = _interopRequireWildcard(require('./specialChars')); + +exports.specialChars = specialChars; + +var _clearLine = _interopRequireDefault2(require('./clearLine')); + +var _createDirectory = _interopRequireDefault2(require('./createDirectory')); + +var _ErrorWithStack = _interopRequireDefault2(require('./ErrorWithStack')); + +var _installCommonGlobals = _interopRequireDefault2( + require('./installCommonGlobals') +); + +var _interopRequireDefault = _interopRequireDefault2( + require('./interopRequireDefault') +); + +var _isInteractive = _interopRequireDefault2(require('./isInteractive')); + +var _isPromise = _interopRequireDefault2(require('./isPromise')); + +var _setGlobal = _interopRequireDefault2(require('./setGlobal')); + +var _deepCyclicCopy = _interopRequireDefault2(require('./deepCyclicCopy')); + +var _convertDescriptorToString = _interopRequireDefault2( + require('./convertDescriptorToString') +); + +var _replacePathSepForGlob = _interopRequireDefault2( + require('./replacePathSepForGlob') +); + +var _testPathPatternToRegExp = _interopRequireDefault2( + require('./testPathPatternToRegExp') +); + +var _globsToMatcher = _interopRequireDefault2(require('./globsToMatcher')); + +var _pluralize = _interopRequireDefault2(require('./pluralize')); + +var _formatTime = _interopRequireDefault2(require('./formatTime')); + +var _tryRealpath = _interopRequireDefault2(require('./tryRealpath')); + +var _requireOrImportModule = _interopRequireDefault2( + require('./requireOrImportModule') +); + +function _interopRequireDefault2(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} diff --git a/node_modules/jest-util/build/installCommonGlobals.js b/node_modules/jest-util/build/installCommonGlobals.js new file mode 100644 index 0000000..6435f75 --- /dev/null +++ b/node_modules/jest-util/build/installCommonGlobals.js @@ -0,0 +1,123 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = installCommonGlobals; + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +var _createProcessObject = _interopRequireDefault( + require('./createProcessObject') +); + +var _deepCyclicCopy = _interopRequireDefault(require('./deepCyclicCopy')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const DTRACE = Object.keys(globalThis).filter(key => key.startsWith('DTRACE')); + +function installCommonGlobals(globalObject, globals) { + globalObject.process = (0, _createProcessObject.default)(); + const symbol = globalObject.Symbol; // Keep a reference to some globals that Jest needs + + Object.defineProperties(globalObject, { + [symbol.for('jest-native-promise')]: { + enumerable: false, + value: Promise, + writable: false + }, + [symbol.for('jest-native-now')]: { + enumerable: false, + value: globalObject.Date.now.bind(globalObject.Date), + writable: false + }, + [symbol.for('jest-native-read-file')]: { + enumerable: false, + value: fs().readFileSync.bind(fs()), + writable: false + }, + [symbol.for('jest-native-write-file')]: { + enumerable: false, + value: fs().writeFileSync.bind(fs()), + writable: false + }, + [symbol.for('jest-native-exists-file')]: { + enumerable: false, + value: fs().existsSync.bind(fs()), + writable: false + }, + 'jest-symbol-do-not-touch': { + enumerable: false, + value: symbol, + writable: false + } + }); // Forward some APIs. + + DTRACE.forEach(dtrace => { + // @ts-expect-error: no index + globalObject[dtrace] = function (...args) { + // @ts-expect-error: no index + return globalThis[dtrace].apply(this, args); + }; + }); + return Object.assign(globalObject, (0, _deepCyclicCopy.default)(globals)); +} diff --git a/node_modules/jest-util/build/interopRequireDefault.js b/node_modules/jest-util/build/interopRequireDefault.js new file mode 100644 index 0000000..69f2eba --- /dev/null +++ b/node_modules/jest-util/build/interopRequireDefault.js @@ -0,0 +1,22 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = interopRequireDefault; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// copied from https://github.com/babel/babel/blob/56044c7851d583d498f919e9546caddf8f80a72f/packages/babel-helpers/src/helpers.js#L558-L562 +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function interopRequireDefault(obj) { + return obj && obj.__esModule + ? obj + : { + default: obj + }; +} diff --git a/node_modules/jest-util/build/isInteractive.js b/node_modules/jest-util/build/isInteractive.js new file mode 100644 index 0000000..bc25399 --- /dev/null +++ b/node_modules/jest-util/build/isInteractive.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _ciInfo() { + const data = require('ci-info'); + + _ciInfo = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var _default = + !!process.stdout.isTTY && process.env.TERM !== 'dumb' && !_ciInfo().isCI; + +exports.default = _default; diff --git a/node_modules/jest-util/build/isPromise.js b/node_modules/jest-util/build/isPromise.js new file mode 100644 index 0000000..5a72020 --- /dev/null +++ b/node_modules/jest-util/build/isPromise.js @@ -0,0 +1,20 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// capture globalThis.Promise before it may potentially be overwritten +const Promise = globalThis.Promise; // see ES2015 spec 25.4.4.5, https://stackoverflow.com/a/38339199 + +const isPromise = candidate => Promise.resolve(candidate) === candidate; + +var _default = isPromise; +exports.default = _default; diff --git a/node_modules/jest-util/build/pluralize.js b/node_modules/jest-util/build/pluralize.js new file mode 100644 index 0000000..55f533e --- /dev/null +++ b/node_modules/jest-util/build/pluralize.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = pluralize; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function pluralize(word, count) { + return `${count} ${word}${count === 1 ? '' : 's'}`; +} diff --git a/node_modules/jest-util/build/preRunMessage.js b/node_modules/jest-util/build/preRunMessage.js new file mode 100644 index 0000000..6febca4 --- /dev/null +++ b/node_modules/jest-util/build/preRunMessage.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.print = print; +exports.remove = remove; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +var _clearLine = _interopRequireDefault(require('./clearLine')); + +var _isInteractive = _interopRequireDefault(require('./isInteractive')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function print(stream) { + if (_isInteractive.default) { + stream.write( + _chalk().default.bold.dim('Determining test suites to run...') + ); + } +} + +function remove(stream) { + if (_isInteractive.default) { + (0, _clearLine.default)(stream); + } +} diff --git a/node_modules/jest-util/build/replacePathSepForGlob.js b/node_modules/jest-util/build/replacePathSepForGlob.js new file mode 100644 index 0000000..b7a1d0f --- /dev/null +++ b/node_modules/jest-util/build/replacePathSepForGlob.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = replacePathSepForGlob; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function replacePathSepForGlob(path) { + return path.replace(/\\(?![{}()+?.^$])/g, '/'); +} diff --git a/node_modules/jest-util/build/requireOrImportModule.js b/node_modules/jest-util/build/requireOrImportModule.js new file mode 100644 index 0000000..14bb2a3 --- /dev/null +++ b/node_modules/jest-util/build/requireOrImportModule.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = requireOrImportModule; + +function _path() { + const data = require('path'); + + _path = function () { + return data; + }; + + return data; +} + +function _url() { + const data = require('url'); + + _url = function () { + return data; + }; + + return data; +} + +var _interopRequireDefault = _interopRequireDefault2( + require('./interopRequireDefault') +); + +function _interopRequireDefault2(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +async function requireOrImportModule( + filePath, + applyInteropRequireDefault = true +) { + if (!(0, _path().isAbsolute)(filePath) && filePath[0] === '.') { + throw new Error( + `Jest: requireOrImportModule path must be absolute, was "${filePath}"` + ); + } + + try { + const requiredModule = require(filePath); + + if (!applyInteropRequireDefault) { + return requiredModule; + } + + return (0, _interopRequireDefault.default)(requiredModule).default; + } catch (error) { + if (error.code === 'ERR_REQUIRE_ESM') { + try { + const moduleUrl = (0, _url().pathToFileURL)(filePath); // node `import()` supports URL, but TypeScript doesn't know that + + const importedModule = await import(moduleUrl.href); + + if (!applyInteropRequireDefault) { + return importedModule; + } + + if (!importedModule.default) { + throw new Error( + `Jest: Failed to load ESM at ${filePath} - did you use a default export?` + ); + } + + return importedModule.default; + } catch (innerError) { + if (innerError.message === 'Not supported') { + throw new Error( + `Jest: Your version of Node does not support dynamic import - please enable it or use a .cjs file extension for file ${filePath}` + ); + } + + throw innerError; + } + } else { + throw error; + } + } +} diff --git a/node_modules/jest-util/build/setGlobal.js b/node_modules/jest-util/build/setGlobal.js new file mode 100644 index 0000000..7fdd77e --- /dev/null +++ b/node_modules/jest-util/build/setGlobal.js @@ -0,0 +1,17 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = setGlobal; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function setGlobal(globalToMutate, key, value) { + // @ts-expect-error: no index + globalToMutate[key] = value; +} diff --git a/node_modules/jest-util/build/specialChars.js b/node_modules/jest-util/build/specialChars.js new file mode 100644 index 0000000..b859ebd --- /dev/null +++ b/node_modules/jest-util/build/specialChars.js @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.ICONS = exports.CLEAR = exports.ARROW = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const isWindows = process.platform === 'win32'; +const ARROW = ' \u203A '; +exports.ARROW = ARROW; +const ICONS = { + failed: isWindows ? '\u00D7' : '\u2715', + pending: '\u25CB', + success: isWindows ? '\u221A' : '\u2713', + todo: '\u270E' +}; +exports.ICONS = ICONS; +const CLEAR = isWindows ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H'; +exports.CLEAR = CLEAR; diff --git a/node_modules/jest-util/build/testPathPatternToRegExp.js b/node_modules/jest-util/build/testPathPatternToRegExp.js new file mode 100644 index 0000000..5d64c62 --- /dev/null +++ b/node_modules/jest-util/build/testPathPatternToRegExp.js @@ -0,0 +1,19 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = testPathPatternToRegExp; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Because we serialize/deserialize globalConfig when we spawn workers, +// we can't pass regular expression. Using this shared function on both sides +// will ensure that we produce consistent regexp for testPathPattern. +function testPathPatternToRegExp(testPathPattern) { + return new RegExp(testPathPattern, 'i'); +} diff --git a/node_modules/jest-util/build/tryRealpath.js b/node_modules/jest-util/build/tryRealpath.js new file mode 100644 index 0000000..e65c34f --- /dev/null +++ b/node_modules/jest-util/build/tryRealpath.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = tryRealpath; + +function _gracefulFs() { + const data = require('graceful-fs'); + + _gracefulFs = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function tryRealpath(path) { + try { + path = _gracefulFs().realpathSync.native(path); + } catch (error) { + if (error.code !== 'ENOENT' && error.code !== 'EISDIR') { + throw error; + } + } + + return path; +} diff --git a/node_modules/jest-util/package.json b/node_modules/jest-util/package.json new file mode 100644 index 0000000..7aa69de --- /dev/null +++ b/node_modules/jest-util/package.json @@ -0,0 +1,83 @@ +{ + "_from": "jest-util@^29.0.1", + "_id": "jest-util@29.0.1", + "_inBundle": false, + "_integrity": "sha512-GIWkgNfkeA9d84rORDHPGGTFBrRD13A38QVSKE0bVrGSnoR1KDn8Kqz+0yI5kezMgbT/7zrWaruWP1Kbghlb2A==", + "_location": "/jest-util", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-util@^29.0.1", + "name": "jest-util", + "escapedName": "jest-util", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/console", + "/@jest/core", + "/@jest/fake-timers", + "/@jest/reporters", + "/@jest/transform", + "/expect", + "/jest-circus", + "/jest-config", + "/jest-each", + "/jest-environment-node", + "/jest-haste-map", + "/jest-resolve", + "/jest-runner", + "/jest-runtime", + "/jest-snapshot", + "/jest-watcher", + "/jest/jest-cli" + ], + "_resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.0.1.tgz", + "_shasum": "f854a4a8877c7817316c4afbc2a851ceb2e71598", + "_spec": "jest-util@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/types": "^29.0.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "deprecated": false, + "devDependencies": { + "@types/graceful-fs": "^4.1.3", + "@types/picomatch": "^2.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-util", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-util" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-validate/LICENSE b/node_modules/jest-validate/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-validate/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-validate/README.md b/node_modules/jest-validate/README.md new file mode 100644 index 0000000..2406bd5 --- /dev/null +++ b/node_modules/jest-validate/README.md @@ -0,0 +1,196 @@ +# jest-validate + +Generic configuration validation tool that helps you with warnings, errors and deprecation messages as well as showing users examples of correct configuration. + +```bash +npm install --save jest-validate +``` + +## Usage + +```js +import {validate} from 'jest-validate'; + +validate(config, validationOptions); // => {hasDeprecationWarnings: boolean, isValid: boolean} +``` + +Where `ValidationOptions` are: + +```ts +type ValidationOptions = { + comment?: string; + condition?: (option: unknown, validOption: unknown) => boolean; + deprecate?: ( + config: Record, + option: string, + deprecatedOptions: DeprecatedOptions, + options: ValidationOptions, + ) => boolean; + deprecatedConfig?: DeprecatedOptions; + error?: ( + option: string, + received: unknown, + defaultValue: unknown, + options: ValidationOptions, + path?: Array, + ) => void; + exampleConfig: Record; + recursive?: boolean; + recursiveBlacklist?: Array; + recursiveDenylist?: Array; + title?: Title; + unknown?: ( + config: Record, + exampleConfig: Record, + option: string, + options: ValidationOptions, + path?: Array, + ) => void; +}; + +type Title = { + deprecation?: string; + error?: string; + warning?: string; +}; +``` + +`exampleConfig` is the only option required. + +## API + +By default `jest-validate` will print generic warning and error messages. You can however customize this behavior by providing `options: ValidationOptions` object as a second argument: + +Almost anything can be overwritten to suite your needs. + +### Options + +- `recursiveDenylist` – optional array of string keyPaths that should be excluded from deep (recursive) validation. +- `comment` – optional string to be rendered below error/warning message. +- `condition` – an optional function with validation condition. +- `deprecate`, `error`, `unknown` – optional functions responsible for displaying warning and error messages. +- `deprecatedConfig` – optional object with deprecated config keys. +- `exampleConfig` – the only **required** option with configuration against which you'd like to test. +- `recursive` - optional boolean determining whether recursively compare `exampleConfig` to `config` (default: `true`). +- `title` – optional object of titles for errors and messages. + +You will find examples of `condition`, `deprecate`, `error`, `unknown`, and `deprecatedConfig` inside source of this repository, named respectively. + +## exampleConfig syntax + +`exampleConfig` should be an object with key/value pairs that contain an example of a valid value for each key. A configuration value is considered valid when: + +- it matches the JavaScript type of the example value, e.g. `string`, `number`, `array`, `boolean`, `function`, or `object` +- it is `null` or `undefined` +- it matches the Javascript type of any of arguments passed to `MultipleValidOptions(...)` + +The last condition is a special syntax that allows validating where more than one type is permissible; see example below. It's acceptable to have multiple values of the same type in the example, so you can also use this syntax to provide more than one example. When a validation failure occurs, the error message will show all other values in the array as examples. + +## Examples + +Minimal example: + +```js +validate(config, {exampleConfig}); +``` + +Example with slight modifications: + +```js +validate(config, { + comment: ' Documentation: http://custom-docs.com', + deprecatedConfig, + exampleConfig, + title: { + deprecation: 'Custom Deprecation', + // leaving 'error' and 'warning' as default + }, +}); +``` + +This will output: + +#### Warning: + +```bash +● Validation Warning: + + Unknown option transformx with value "/node_modules/babel-jest" was found. + This is either a typing error or a user mistake. Fixing it will remove this message. + + Documentation: http://custom-docs.com +``` + +#### Error: + +```bash +● Validation Error: + + Option transform must be of type: + object + but instead received: + string + + Example: + { + "transform": { + "\\.js$": "/preprocessor.js" + } + } + + Documentation: http://custom-docs.com +``` + +## Example validating multiple types + +```js +import {multipleValidOptions} from 'jest-validate'; + +validate(config, { + // `bar` will accept either a string or a number + bar: multipleValidOptions('string is ok', 2), +}); +``` + +#### Error: + +```bash +● Validation Error: + + Option foo must be of type: + string or number + but instead received: + array + + Example: + { + "bar": "string is ok" + } + + or + + { + "bar": 2 + } + + Documentation: http://custom-docs.com +``` + +#### Deprecation + +Based on `deprecatedConfig` object with proper deprecation messages. Note custom title: + +```bash +Custom Deprecation: + + Option scriptPreprocessor was replaced by transform, which support multiple preprocessors. + + Jest now treats your current configuration as: + { + "transform": {".*": "xxx"} + } + + Please update your configuration. + + Documentation: http://custom-docs.com +``` diff --git a/node_modules/jest-validate/build/condition.js b/node_modules/jest-validate/build/condition.js new file mode 100644 index 0000000..9a7d29c --- /dev/null +++ b/node_modules/jest-validate/build/condition.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getValues = getValues; +exports.multipleValidOptions = multipleValidOptions; +exports.validationCondition = validationCondition; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const toString = Object.prototype.toString; +const MULTIPLE_VALID_OPTIONS_SYMBOL = Symbol('JEST_MULTIPLE_VALID_OPTIONS'); + +function validationConditionSingle(option, validOption) { + return ( + option === null || + option === undefined || + (typeof option === 'function' && typeof validOption === 'function') || + toString.call(option) === toString.call(validOption) + ); +} + +function getValues(validOption) { + if ( + Array.isArray(validOption) && // @ts-expect-error: no index signature + validOption[MULTIPLE_VALID_OPTIONS_SYMBOL] + ) { + return validOption; + } + + return [validOption]; +} + +function validationCondition(option, validOption) { + return getValues(validOption).some(e => validationConditionSingle(option, e)); +} + +function multipleValidOptions(...args) { + const options = [...args]; // @ts-expect-error: no index signature + + options[MULTIPLE_VALID_OPTIONS_SYMBOL] = true; + return options; +} diff --git a/node_modules/jest-validate/build/defaultConfig.js b/node_modules/jest-validate/build/defaultConfig.js new file mode 100644 index 0000000..e179c05 --- /dev/null +++ b/node_modules/jest-validate/build/defaultConfig.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _condition = require('./condition'); + +var _deprecated = require('./deprecated'); + +var _errors = require('./errors'); + +var _utils = require('./utils'); + +var _warnings = require('./warnings'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const validationOptions = { + comment: '', + condition: _condition.validationCondition, + deprecate: _deprecated.deprecationWarning, + deprecatedConfig: {}, + error: _errors.errorMessage, + exampleConfig: {}, + recursive: true, + // Allow NPM-sanctioned comments in package.json. Use a "//" key. + recursiveDenylist: ['//'], + title: { + deprecation: _utils.DEPRECATION, + error: _utils.ERROR, + warning: _utils.WARNING + }, + unknown: _warnings.unknownOptionWarning +}; +var _default = validationOptions; +exports.default = _default; diff --git a/node_modules/jest-validate/build/deprecated.js b/node_modules/jest-validate/build/deprecated.js new file mode 100644 index 0000000..08be871 --- /dev/null +++ b/node_modules/jest-validate/build/deprecated.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.deprecationWarning = void 0; + +var _utils = require('./utils'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const deprecationMessage = (message, options) => { + const comment = options.comment; + const name = + (options.title && options.title.deprecation) || _utils.DEPRECATION; + (0, _utils.logValidationWarning)(name, message, comment); +}; + +const deprecationWarning = (config, option, deprecatedOptions, options) => { + if (option in deprecatedOptions) { + deprecationMessage(deprecatedOptions[option](config), options); + return true; + } + + return false; +}; + +exports.deprecationWarning = deprecationWarning; diff --git a/node_modules/jest-validate/build/errors.js b/node_modules/jest-validate/build/errors.js new file mode 100644 index 0000000..a1d99e1 --- /dev/null +++ b/node_modules/jest-validate/build/errors.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.errorMessage = void 0; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _jestGetType() { + const data = require('jest-get-type'); + + _jestGetType = function () { + return data; + }; + + return data; +} + +var _condition = require('./condition'); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const errorMessage = (option, received, defaultValue, options, path) => { + const conditions = (0, _condition.getValues)(defaultValue); + const validTypes = Array.from( + new Set(conditions.map(_jestGetType().getType)) + ); + const message = ` Option ${_chalk().default.bold( + `"${path && path.length > 0 ? `${path.join('.')}.` : ''}${option}"` + )} must be of type: + ${validTypes.map(e => _chalk().default.bold.green(e)).join(' or ')} + but instead received: + ${_chalk().default.bold.red((0, _jestGetType().getType)(received))} + + Example: +${formatExamples(option, conditions)}`; + const comment = options.comment; + const name = (options.title && options.title.error) || _utils.ERROR; + throw new _utils.ValidationError(name, message, comment); +}; + +exports.errorMessage = errorMessage; + +function formatExamples(option, examples) { + return examples.map( + e => ` { + ${_chalk().default.bold(`"${option}"`)}: ${_chalk().default.bold( + (0, _utils.formatPrettyObject)(e) + )} + }` + ).join(` + + or + +`); +} diff --git a/node_modules/jest-validate/build/exampleConfig.js b/node_modules/jest-validate/build/exampleConfig.js new file mode 100644 index 0000000..90b43c1 --- /dev/null +++ b/node_modules/jest-validate/build/exampleConfig.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const config = { + comment: ' A comment', + condition: () => true, + deprecate: () => false, + deprecatedConfig: { + key: () => 'Deprecation message' + }, + // eslint-disable-next-line @typescript-eslint/no-empty-function + error: () => {}, + exampleConfig: { + key: 'value', + test: 'case' + }, + recursive: true, + recursiveDenylist: [], + title: { + deprecation: 'Deprecation Warning', + error: 'Validation Error', + warning: 'Validation Warning' + }, + // eslint-disable-next-line @typescript-eslint/no-empty-function + unknown: () => {} +}; +var _default = config; +exports.default = _default; diff --git a/node_modules/jest-validate/build/index.d.ts b/node_modules/jest-validate/build/index.d.ts new file mode 100644 index 0000000..fd531b2 --- /dev/null +++ b/node_modules/jest-validate/build/index.d.ts @@ -0,0 +1,90 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {Options} from 'yargs'; + +export declare const createDidYouMeanMessage: ( + unrecognized: string, + allowedOptions: Array, +) => string; + +declare type DeprecatedOptionFunc = (arg: Record) => string; + +export declare type DeprecatedOptions = Record; + +export declare const format: (value: unknown) => string; + +export declare const logValidationWarning: ( + name: string, + message: string, + comment?: string | null, +) => void; + +export declare function multipleValidOptions>( + ...args: T +): T[number]; + +declare type Title = { + deprecation?: string; + error?: string; + warning?: string; +}; + +export declare const validate: ( + config: Record, + options: ValidationOptions, +) => { + hasDeprecationWarnings: boolean; + isValid: boolean; +}; + +export declare function validateCLIOptions( + argv: Config.Argv, + options: { + deprecationEntries: DeprecatedOptions; + [s: string]: Options; + }, + rawArgv?: Array, +): boolean; + +export declare class ValidationError extends Error { + name: string; + message: string; + constructor(name: string, message: string, comment?: string | null); +} + +declare type ValidationOptions = { + comment?: string; + condition?: (option: unknown, validOption: unknown) => boolean; + deprecate?: ( + config: Record, + option: string, + deprecatedOptions: DeprecatedOptions, + options: ValidationOptions, + ) => boolean; + deprecatedConfig?: DeprecatedOptions; + error?: ( + option: string, + received: unknown, + defaultValue: unknown, + options: ValidationOptions, + path?: Array, + ) => void; + exampleConfig: Record; + recursive?: boolean; + recursiveDenylist?: Array; + title?: Title; + unknown?: ( + config: Record, + exampleConfig: Record, + option: string, + options: ValidationOptions, + path?: Array, + ) => void; +}; + +export {}; diff --git a/node_modules/jest-validate/build/index.js b/node_modules/jest-validate/build/index.js new file mode 100644 index 0000000..56c5bea --- /dev/null +++ b/node_modules/jest-validate/build/index.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'ValidationError', { + enumerable: true, + get: function () { + return _utils.ValidationError; + } +}); +Object.defineProperty(exports, 'createDidYouMeanMessage', { + enumerable: true, + get: function () { + return _utils.createDidYouMeanMessage; + } +}); +Object.defineProperty(exports, 'format', { + enumerable: true, + get: function () { + return _utils.format; + } +}); +Object.defineProperty(exports, 'logValidationWarning', { + enumerable: true, + get: function () { + return _utils.logValidationWarning; + } +}); +Object.defineProperty(exports, 'multipleValidOptions', { + enumerable: true, + get: function () { + return _condition.multipleValidOptions; + } +}); +Object.defineProperty(exports, 'validate', { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, 'validateCLIOptions', { + enumerable: true, + get: function () { + return _validateCLIOptions.default; + } +}); + +var _utils = require('./utils'); + +var _validate = _interopRequireDefault(require('./validate')); + +var _validateCLIOptions = _interopRequireDefault( + require('./validateCLIOptions') +); + +var _condition = require('./condition'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/jest-validate/build/types.js b/node_modules/jest-validate/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-validate/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-validate/build/utils.js b/node_modules/jest-validate/build/utils.js new file mode 100644 index 0000000..686a466 --- /dev/null +++ b/node_modules/jest-validate/build/utils.js @@ -0,0 +1,120 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.logValidationWarning = + exports.formatPrettyObject = + exports.format = + exports.createDidYouMeanMessage = + exports.WARNING = + exports.ValidationError = + exports.ERROR = + exports.DEPRECATION = + void 0; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _leven() { + const data = _interopRequireDefault(require('leven')); + + _leven = function () { + return data; + }; + + return data; +} + +function _prettyFormat() { + const data = require('pretty-format'); + + _prettyFormat = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const BULLET = _chalk().default.bold('\u25cf'); + +const DEPRECATION = `${BULLET} Deprecation Warning`; +exports.DEPRECATION = DEPRECATION; +const ERROR = `${BULLET} Validation Error`; +exports.ERROR = ERROR; +const WARNING = `${BULLET} Validation Warning`; +exports.WARNING = WARNING; + +const format = value => + typeof value === 'function' + ? value.toString() + : (0, _prettyFormat().format)(value, { + min: true + }); + +exports.format = format; + +const formatPrettyObject = value => + typeof value === 'function' + ? value.toString() + : JSON.stringify(value, null, 2).split('\n').join('\n '); + +exports.formatPrettyObject = formatPrettyObject; + +class ValidationError extends Error { + name; + message; + + constructor(name, message, comment) { + super(); + comment = comment ? `\n\n${comment}` : '\n'; + this.name = ''; + this.message = _chalk().default.red( + `${_chalk().default.bold(name)}:\n\n${message}${comment}` + ); // eslint-disable-next-line @typescript-eslint/no-empty-function + + Error.captureStackTrace(this, () => {}); + } +} + +exports.ValidationError = ValidationError; + +const logValidationWarning = (name, message, comment) => { + comment = comment ? `\n\n${comment}` : '\n'; + console.warn( + _chalk().default.yellow( + `${_chalk().default.bold(name)}:\n\n${message}${comment}` + ) + ); +}; + +exports.logValidationWarning = logValidationWarning; + +const createDidYouMeanMessage = (unrecognized, allowedOptions) => { + const suggestion = allowedOptions.find(option => { + const steps = (0, _leven().default)(option, unrecognized); + return steps < 3; + }); + return suggestion + ? `Did you mean ${_chalk().default.bold(format(suggestion))}?` + : ''; +}; + +exports.createDidYouMeanMessage = createDidYouMeanMessage; diff --git a/node_modules/jest-validate/build/validate.js b/node_modules/jest-validate/build/validate.js new file mode 100644 index 0000000..799a366 --- /dev/null +++ b/node_modules/jest-validate/build/validate.js @@ -0,0 +1,131 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _defaultConfig = _interopRequireDefault(require('./defaultConfig')); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +let hasDeprecationWarnings = false; + +const shouldSkipValidationForPath = (path, key, denylist) => + denylist ? denylist.includes([...path, key].join('.')) : false; + +const _validate = (config, exampleConfig, options, path = []) => { + if ( + typeof config !== 'object' || + config == null || + typeof exampleConfig !== 'object' || + exampleConfig == null + ) { + return { + hasDeprecationWarnings + }; + } + + for (const key in config) { + if ( + options.deprecatedConfig && + key in options.deprecatedConfig && + typeof options.deprecate === 'function' + ) { + const isDeprecatedKey = options.deprecate( + config, + key, + options.deprecatedConfig, + options + ); + hasDeprecationWarnings = hasDeprecationWarnings || isDeprecatedKey; + } else if (allowsMultipleTypes(key)) { + const value = config[key]; + + if ( + typeof options.condition === 'function' && + typeof options.error === 'function' + ) { + if (key === 'maxWorkers' && !isOfTypeStringOrNumber(value)) { + throw new _utils.ValidationError( + 'Validation Error', + `${key} has to be of type string or number`, + 'maxWorkers=50% or\nmaxWorkers=3' + ); + } + } + } else if (Object.hasOwnProperty.call(exampleConfig, key)) { + if ( + typeof options.condition === 'function' && + typeof options.error === 'function' && + !options.condition(config[key], exampleConfig[key]) + ) { + options.error(key, config[key], exampleConfig[key], options, path); + } + } else if ( + shouldSkipValidationForPath(path, key, options.recursiveDenylist) + ) { + // skip validating unknown options inside blacklisted paths + } else { + options.unknown && + options.unknown(config, exampleConfig, key, options, path); + } + + if ( + options.recursive && + !Array.isArray(exampleConfig[key]) && + options.recursiveDenylist && + !shouldSkipValidationForPath(path, key, options.recursiveDenylist) + ) { + _validate(config[key], exampleConfig[key], options, [...path, key]); + } + } + + return { + hasDeprecationWarnings + }; +}; + +const allowsMultipleTypes = key => key === 'maxWorkers'; + +const isOfTypeStringOrNumber = value => + typeof value === 'number' || typeof value === 'string'; + +const validate = (config, options) => { + hasDeprecationWarnings = false; // Preserve default denylist entries even with user-supplied denylist + + const combinedDenylist = [ + ...(_defaultConfig.default.recursiveDenylist || []), + ...(options.recursiveDenylist || []) + ]; + const defaultedOptions = Object.assign({ + ..._defaultConfig.default, + ...options, + recursiveDenylist: combinedDenylist, + title: options.title || _defaultConfig.default.title + }); + + const {hasDeprecationWarnings: hdw} = _validate( + config, + options.exampleConfig, + defaultedOptions + ); + + return { + hasDeprecationWarnings: hdw, + isValid: true + }; +}; + +var _default = validate; +exports.default = _default; diff --git a/node_modules/jest-validate/build/validateCLIOptions.js b/node_modules/jest-validate/build/validateCLIOptions.js new file mode 100644 index 0000000..faf1ed5 --- /dev/null +++ b/node_modules/jest-validate/build/validateCLIOptions.js @@ -0,0 +1,140 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.DOCUMENTATION_NOTE = void 0; +exports.default = validateCLIOptions; + +function _camelcase() { + const data = _interopRequireDefault(require('camelcase')); + + _camelcase = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +var _defaultConfig = _interopRequireDefault(require('./defaultConfig')); + +var _deprecated = require('./deprecated'); + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const BULLET = _chalk().default.bold('\u25cf'); + +const DOCUMENTATION_NOTE = ` ${_chalk().default.bold( + 'CLI Options Documentation:' +)} + https://jestjs.io/docs/cli +`; +exports.DOCUMENTATION_NOTE = DOCUMENTATION_NOTE; + +const createCLIValidationError = (unrecognizedOptions, allowedOptions) => { + let title = `${BULLET} Unrecognized CLI Parameter`; + let message; + const comment = + ` ${_chalk().default.bold('CLI Options Documentation')}:\n` + + ' https://jestjs.io/docs/cli\n'; + + if (unrecognizedOptions.length === 1) { + const unrecognized = unrecognizedOptions[0]; + const didYouMeanMessage = + unrecognized.length > 1 + ? (0, _utils.createDidYouMeanMessage)( + unrecognized, + Array.from(allowedOptions) + ) + : ''; + message = ` Unrecognized option ${_chalk().default.bold( + (0, _utils.format)(unrecognized) + )}.${didYouMeanMessage ? ` ${didYouMeanMessage}` : ''}`; + } else { + title += 's'; + message = + ' Following options were not recognized:\n' + + ` ${_chalk().default.bold((0, _utils.format)(unrecognizedOptions))}`; + } + + return new _utils.ValidationError(title, message, comment); +}; + +const logDeprecatedOptions = (deprecatedOptions, deprecationEntries, argv) => { + deprecatedOptions.forEach(opt => { + (0, _deprecated.deprecationWarning)(argv, opt, deprecationEntries, { + ..._defaultConfig.default, + comment: DOCUMENTATION_NOTE + }); + }); +}; + +function validateCLIOptions(argv, options, rawArgv = []) { + const yargsSpecialOptions = ['$0', '_', 'help', 'h']; + const deprecationEntries = options.deprecationEntries || {}; + const allowedOptions = Object.keys(options).reduce( + (acc, option) => acc.add(option).add(options[option].alias || option), + new Set(yargsSpecialOptions) + ); + const unrecognizedOptions = Object.keys(argv).filter( + arg => + !allowedOptions.has( + (0, _camelcase().default)(arg, { + locale: 'en-US' + }) + ) && + !allowedOptions.has(arg) && + (!rawArgv.length || rawArgv.includes(arg)), + [] + ); + + if (unrecognizedOptions.length) { + throw createCLIValidationError(unrecognizedOptions, allowedOptions); + } + + const CLIDeprecations = Object.keys(deprecationEntries).reduce( + (acc, entry) => { + if (options[entry]) { + acc[entry] = deprecationEntries[entry]; + const alias = options[entry].alias; + + if (alias) { + acc[alias] = deprecationEntries[entry]; + } + } + + return acc; + }, + {} + ); + const deprecations = new Set(Object.keys(CLIDeprecations)); + const deprecatedOptions = Object.keys(argv).filter( + arg => deprecations.has(arg) && argv[arg] != null + ); + + if (deprecatedOptions.length) { + logDeprecatedOptions(deprecatedOptions, CLIDeprecations, argv); + } + + return true; +} diff --git a/node_modules/jest-validate/build/warnings.js b/node_modules/jest-validate/build/warnings.js new file mode 100644 index 0000000..dad221e --- /dev/null +++ b/node_modules/jest-validate/build/warnings.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.unknownOptionWarning = void 0; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +var _utils = require('./utils'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const unknownOptionWarning = (config, exampleConfig, option, options, path) => { + const didYouMean = (0, _utils.createDidYouMeanMessage)( + option, + Object.keys(exampleConfig) + ); + const message = ` Unknown option ${_chalk().default.bold( + `"${path && path.length > 0 ? `${path.join('.')}.` : ''}${option}"` + )} with value ${_chalk().default.bold( + (0, _utils.format)(config[option]) + )} was found.${ + didYouMean && ` ${didYouMean}` + }\n This is probably a typing mistake. Fixing it will remove this message.`; + const comment = options.comment; + const name = (options.title && options.title.warning) || _utils.WARNING; + (0, _utils.logValidationWarning)(name, message, comment); +}; + +exports.unknownOptionWarning = unknownOptionWarning; diff --git a/node_modules/jest-validate/node_modules/camelcase/index.d.ts b/node_modules/jest-validate/node_modules/camelcase/index.d.ts new file mode 100644 index 0000000..9db94e5 --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/index.d.ts @@ -0,0 +1,103 @@ +declare namespace camelcase { + interface Options { + /** + Uppercase the first character: `foo-bar` → `FooBar`. + + @default false + */ + readonly pascalCase?: boolean; + + /** + Preserve the consecutive uppercase characters: `foo-BAR` → `FooBAR`. + + @default false + */ + readonly preserveConsecutiveUppercase?: boolean; + + /** + The locale parameter indicates the locale to be used to convert to upper/lower case according to any locale-specific case mappings. If multiple locales are given in an array, the best available locale is used. + + Setting `locale: false` ignores the platform locale and uses the [Unicode Default Case Conversion](https://unicode-org.github.io/icu/userguide/transforms/casemappings.html#simple-single-character-case-mapping) algorithm. + + Default: The host environment’s current locale. + + @example + ``` + import camelCase = require('camelcase'); + + camelCase('lorem-ipsum', {locale: 'en-US'}); + //=> 'loremIpsum' + camelCase('lorem-ipsum', {locale: 'tr-TR'}); + //=> 'loremİpsum' + camelCase('lorem-ipsum', {locale: ['en-US', 'en-GB']}); + //=> 'loremIpsum' + camelCase('lorem-ipsum', {locale: ['tr', 'TR', 'tr-TR']}); + //=> 'loremİpsum' + ``` + */ + readonly locale?: false | string | readonly string[]; + } +} + +/** +Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`. + +Correctly handles Unicode strings. + +@param input - String to convert to camel case. + +@example +``` +import camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('розовый_пушистый_единорог'); +//=> 'розовыйПушистыйЕдинорог' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('Foo-BAR', {preserveConsecutiveUppercase: true}); +//=> 'fooBAR' + +camelCase('fooBAR', {pascalCase: true, preserveConsecutiveUppercase: true})); +//=> 'FooBAR' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' + +camelCase(['foo', 'BAR'], {pascalCase: true, preserveConsecutiveUppercase: true}) +//=> 'FooBAR' + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' +``` +*/ +declare function camelcase( + input: string | readonly string[], + options?: camelcase.Options +): string; + +export = camelcase; diff --git a/node_modules/jest-validate/node_modules/camelcase/index.js b/node_modules/jest-validate/node_modules/camelcase/index.js new file mode 100644 index 0000000..6ff4ee8 --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/index.js @@ -0,0 +1,113 @@ +'use strict'; + +const UPPERCASE = /[\p{Lu}]/u; +const LOWERCASE = /[\p{Ll}]/u; +const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; +const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; +const SEPARATORS = /[_.\- ]+/; + +const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); +const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); +const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); + +const preserveCamelCase = (string, toLowerCase, toUpperCase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && UPPERCASE.test(character)) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } + + return string; +}; + +const preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; + + return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); +}; + +const postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + + return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) + .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + const toLowerCase = options.locale === false ? + string => string.toLowerCase() : + string => string.toLocaleLowerCase(options.locale); + const toUpperCase = options.locale === false ? + string => string.toUpperCase() : + string => string.toLocaleUpperCase(options.locale); + + if (input.length === 1) { + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } + + const hasUpperCase = input !== toLowerCase(input); + + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase); + } + + input = input.replace(LEADING_SEPARATORS, ''); + + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input, toLowerCase); + } else { + input = toLowerCase(input); + } + + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + + return postProcess(input, toUpperCase); +}; + +module.exports = camelCase; +// TODO: Remove this for the next major release +module.exports.default = camelCase; diff --git a/node_modules/jest-validate/node_modules/camelcase/license b/node_modules/jest-validate/node_modules/camelcase/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jest-validate/node_modules/camelcase/package.json b/node_modules/jest-validate/node_modules/camelcase/package.json new file mode 100644 index 0000000..860ea9e --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/package.json @@ -0,0 +1,76 @@ +{ + "_from": "camelcase@^6.2.0", + "_id": "camelcase@6.3.0", + "_inBundle": false, + "_integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "_location": "/jest-validate/camelcase", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "camelcase@^6.2.0", + "name": "camelcase", + "escapedName": "camelcase", + "rawSpec": "^6.2.0", + "saveSpec": null, + "fetchSpec": "^6.2.0" + }, + "_requiredBy": [ + "/jest-validate" + ], + "_resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "_shasum": "5685b95eb209ac9c0c177467778c9c84df58ba9a", + "_spec": "camelcase@^6.2.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-validate", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/camelcase/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.11.0", + "xo": "^0.28.3" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/camelcase#readme", + "keywords": [ + "camelcase", + "camel-case", + "camel", + "case", + "dash", + "hyphen", + "dot", + "underscore", + "separator", + "string", + "text", + "convert", + "pascalcase", + "pascal-case" + ], + "license": "MIT", + "name": "camelcase", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/camelcase.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "6.3.0" +} diff --git a/node_modules/jest-validate/node_modules/camelcase/readme.md b/node_modules/jest-validate/node_modules/camelcase/readme.md new file mode 100644 index 0000000..0ff8f9e --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/readme.md @@ -0,0 +1,144 @@ +# camelcase + +> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar` + +Correctly handles Unicode strings. + +If you use this on untrusted user input, don't forget to limit the length to something reasonable. + +## Install + +``` +$ npm install camelcase +``` + +*If you need to support Firefox < 78, stay on version 5 as version 6 uses regex features not available in Firefox < 78.* + +## Usage + +```js +const camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('розовый_пушистый_единорог'); +//=> 'розовыйПушистыйЕдинорог' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('Foo-BAR', {preserveConsecutiveUppercase: true}); +//=> 'fooBAR' + +camelCase('fooBAR', {pascalCase: true, preserveConsecutiveUppercase: true})); +//=> 'FooBAR' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' + +camelCase(['foo', 'BAR'], {pascalCase: true, preserveConsecutiveUppercase: true}) +//=> 'FooBAR' + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' +``` + +## API + +### camelCase(input, options?) + +#### input + +Type: `string | string[]` + +String to convert to camel case. + +#### options + +Type: `object` + +##### pascalCase + +Type: `boolean`\ +Default: `false` + +Uppercase the first character: `foo-bar` → `FooBar` + +##### preserveConsecutiveUppercase + +Type: `boolean`\ +Default: `false` + +Preserve the consecutive uppercase characters: `foo-BAR` → `FooBAR`. + +##### locale + +Type: `false | string | string[]`\ +Default: The host environment’s current locale. + +The locale parameter indicates the locale to be used to convert to upper/lower case according to any locale-specific case mappings. If multiple locales are given in an array, the best available locale is used. + +```js +const camelCase = require('camelcase'); + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' + +camelCase('lorem-ipsum', {locale: 'tr-TR'}); +//=> 'loremİpsum' + +camelCase('lorem-ipsum', {locale: ['en-US', 'en-GB']}); +//=> 'loremIpsum' + +camelCase('lorem-ipsum', {locale: ['tr', 'TR', 'tr-TR']}); +//=> 'loremİpsum' +``` + +Setting `locale: false` ignores the platform locale and uses the [Unicode Default Case Conversion](https://unicode-org.github.io/icu/userguide/transforms/casemappings.html#simple-single-character-case-mapping) algorithm: + +```js +const camelCase = require('camelcase'); + +// On a platform with 'tr-TR' + +camelCase('lorem-ipsum'); +//=> 'loremİpsum' + +camelCase('lorem-ipsum', {locale: false}); +//=> 'loremIpsum' +``` + +## camelcase for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of camelcase and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-camelcase?utm_source=npm-camelcase&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Related + +- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module +- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase +- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string +- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one +- [camelcase-keys](https://github.com/sindresorhus/camelcase-keys) - Convert object keys to camel case diff --git a/node_modules/jest-validate/package.json b/node_modules/jest-validate/package.json new file mode 100644 index 0000000..213dc20 --- /dev/null +++ b/node_modules/jest-validate/package.json @@ -0,0 +1,70 @@ +{ + "_from": "jest-validate@^29.0.1", + "_id": "jest-validate@29.0.1", + "_inBundle": false, + "_integrity": "sha512-mS4q7F738YXZFWBPqE+NjHU/gEOs7IBIFQ8i9zq5EO691cLrUbLhFq4larf8/lNcmauRO71tn/+DTW2y+MrLow==", + "_location": "/jest-validate", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-validate@^29.0.1", + "name": "jest-validate", + "escapedName": "jest-validate", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/jest-config", + "/jest-resolve", + "/jest/jest-cli" + ], + "_resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.0.1.tgz", + "_shasum": "8de8ff9d65507c0477964fd39c5b0a1778e3103d", + "_spec": "jest-validate@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/types": "^29.0.1", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.0.0", + "leven": "^3.1.0", + "pretty-format": "^29.0.1" + }, + "deprecated": false, + "description": "Generic configuration validation tool that helps you with warnings, errors and deprecation messages as well as showing users examples of correct configuration.", + "devDependencies": { + "@types/yargs": "^17.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-validate", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-validate" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-watcher/LICENSE b/node_modules/jest-watcher/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-watcher/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-watcher/build/BaseWatchPlugin.js b/node_modules/jest-watcher/build/BaseWatchPlugin.js new file mode 100644 index 0000000..58f1a02 --- /dev/null +++ b/node_modules/jest-watcher/build/BaseWatchPlugin.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class BaseWatchPlugin { + _stdin; + _stdout; + + constructor({stdin, stdout}) { + this._stdin = stdin; + this._stdout = stdout; + } // eslint-disable-next-line @typescript-eslint/no-empty-function + + apply(_hooks) {} + + getUsageInfo(_globalConfig) { + return null; + } // eslint-disable-next-line @typescript-eslint/no-empty-function + + onKey(_key) {} + + run(_globalConfig, _updateConfigAndRun) { + return Promise.resolve(); + } +} + +var _default = BaseWatchPlugin; +exports.default = _default; diff --git a/node_modules/jest-watcher/build/JestHooks.js b/node_modules/jest-watcher/build/JestHooks.js new file mode 100644 index 0000000..fb8f321 --- /dev/null +++ b/node_modules/jest-watcher/build/JestHooks.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class JestHooks { + _listeners; + _subscriber; + _emitter; + + constructor() { + this._listeners = { + onFileChange: [], + onTestRunComplete: [], + shouldRunTestSuite: [] + }; + this._subscriber = { + onFileChange: fn => { + this._listeners.onFileChange.push(fn); + }, + onTestRunComplete: fn => { + this._listeners.onTestRunComplete.push(fn); + }, + shouldRunTestSuite: fn => { + this._listeners.shouldRunTestSuite.push(fn); + } + }; + this._emitter = { + onFileChange: fs => + this._listeners.onFileChange.forEach(listener => listener(fs)), + onTestRunComplete: results => + this._listeners.onTestRunComplete.forEach(listener => + listener(results) + ), + shouldRunTestSuite: async testSuiteInfo => { + const result = await Promise.all( + this._listeners.shouldRunTestSuite.map(listener => + listener(testSuiteInfo) + ) + ); + return result.every(Boolean); + } + }; + } + + isUsed(hook) { + return this._listeners[hook]?.length > 0; + } + + getSubscriber() { + return this._subscriber; + } + + getEmitter() { + return this._emitter; + } +} + +var _default = JestHooks; +exports.default = _default; diff --git a/node_modules/jest-watcher/build/PatternPrompt.js b/node_modules/jest-watcher/build/PatternPrompt.js new file mode 100644 index 0000000..7b8554a --- /dev/null +++ b/node_modules/jest-watcher/build/PatternPrompt.js @@ -0,0 +1,98 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _ansiEscapes() { + const data = _interopRequireDefault(require('ansi-escapes')); + + _ansiEscapes = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const {CLEAR} = _jestUtil().specialChars; + +const usage = entity => + `\n${_chalk().default.bold('Pattern Mode Usage')}\n` + + ` ${_chalk().default.dim('\u203A Press')} Esc ${_chalk().default.dim( + 'to exit pattern mode.' + )}\n` + + ` ${_chalk().default.dim('\u203A Press')} Enter ` + + `${_chalk().default.dim(`to filter by a ${entity} regex pattern.`)}\n` + + '\n'; + +const usageRows = usage('').split('\n').length; + +class PatternPrompt { + _currentUsageRows; + + constructor(_pipe, _prompt, _entityName = '') { + this._pipe = _pipe; + this._prompt = _prompt; + this._entityName = _entityName; + this._currentUsageRows = usageRows; + } + + run(onSuccess, onCancel, options) { + this._pipe.write(_ansiEscapes().default.cursorHide); + + this._pipe.write(CLEAR); + + if (options && options.header) { + this._pipe.write(`${options.header}\n`); + + this._currentUsageRows = usageRows + options.header.split('\n').length; + } else { + this._currentUsageRows = usageRows; + } + + this._pipe.write(usage(this._entityName)); + + this._pipe.write(_ansiEscapes().default.cursorShow); + + this._prompt.enter(this._onChange.bind(this), onSuccess, onCancel); + } + + _onChange(_pattern, _options) { + this._pipe.write(_ansiEscapes().default.eraseLine); + + this._pipe.write(_ansiEscapes().default.cursorLeft); + } +} + +exports.default = PatternPrompt; diff --git a/node_modules/jest-watcher/build/TestWatcher.js b/node_modules/jest-watcher/build/TestWatcher.js new file mode 100644 index 0000000..b5d5a54 --- /dev/null +++ b/node_modules/jest-watcher/build/TestWatcher.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _emittery() { + const data = _interopRequireDefault(require('emittery')); + + _emittery = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class TestWatcher extends _emittery().default { + state; + _isWatchMode; + + constructor({isWatchMode}) { + super(); + this.state = { + interrupted: false + }; + this._isWatchMode = isWatchMode; + } + + async setState(state) { + Object.assign(this.state, state); + await this.emit('change', this.state); + } + + isInterrupted() { + return this.state.interrupted; + } + + isWatchMode() { + return this._isWatchMode; + } +} + +exports.default = TestWatcher; diff --git a/node_modules/jest-watcher/build/constants.js b/node_modules/jest-watcher/build/constants.js new file mode 100644 index 0000000..78cc215 --- /dev/null +++ b/node_modules/jest-watcher/build/constants.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.KEYS = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const isWindows = process.platform === 'win32'; +const KEYS = { + ARROW_DOWN: '\u001b[B', + ARROW_LEFT: '\u001b[D', + ARROW_RIGHT: '\u001b[C', + ARROW_UP: '\u001b[A', + BACKSPACE: Buffer.from(isWindows ? '08' : '7f', 'hex').toString(), + CONTROL_C: '\u0003', + CONTROL_D: '\u0004', + CONTROL_U: '\u0015', + ENTER: '\r', + ESCAPE: '\u001b' +}; +exports.KEYS = KEYS; diff --git a/node_modules/jest-watcher/build/index.d.ts b/node_modules/jest-watcher/build/index.d.ts new file mode 100644 index 0000000..1cf33cf --- /dev/null +++ b/node_modules/jest-watcher/build/index.d.ts @@ -0,0 +1,222 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {AggregatedResult} from '@jest/test-result'; +import type {Config} from '@jest/types'; +import Emittery = require('emittery'); + +export declare type AllowedConfigOptions = Partial< + Pick< + Config.GlobalConfig, + | 'bail' + | 'changedSince' + | 'collectCoverage' + | 'collectCoverageFrom' + | 'coverageDirectory' + | 'coverageReporters' + | 'findRelatedTests' + | 'nonFlagArgs' + | 'notify' + | 'notifyMode' + | 'onlyFailures' + | 'reporters' + | 'testNamePattern' + | 'testPathPattern' + | 'updateSnapshot' + | 'verbose' + > & { + mode: 'watch' | 'watchAll'; + } +>; + +declare type AvailableHooks = + | 'onFileChange' + | 'onTestRunComplete' + | 'shouldRunTestSuite'; + +export declare abstract class BaseWatchPlugin implements WatchPlugin { + protected _stdin: NodeJS.ReadStream; + protected _stdout: NodeJS.WriteStream; + constructor({ + stdin, + stdout, + }: { + stdin: NodeJS.ReadStream; + stdout: NodeJS.WriteStream; + }); + apply(_hooks: JestHookSubscriber): void; + getUsageInfo(_globalConfig: Config.GlobalConfig): UsageData | null; + onKey(_key: string): void; + run( + _globalConfig: Config.GlobalConfig, + _updateConfigAndRun: UpdateConfigCallback, + ): Promise; +} + +declare type FileChange = (fs: JestHookExposedFS) => void; + +export declare class JestHook { + private _listeners; + private _subscriber; + private _emitter; + constructor(); + isUsed(hook: AvailableHooks): boolean; + getSubscriber(): Readonly; + getEmitter(): Readonly; +} + +export declare type JestHookEmitter = { + onFileChange: (fs: JestHookExposedFS) => void; + onTestRunComplete: (results: AggregatedResult) => void; + shouldRunTestSuite: ( + testSuiteInfo: TestSuiteInfo, + ) => Promise | boolean; +}; + +declare type JestHookExposedFS = { + projects: Array<{ + config: Config.ProjectConfig; + testPaths: Array; + }>; +}; + +export declare type JestHookSubscriber = { + onFileChange: (fn: FileChange) => void; + onTestRunComplete: (fn: TestRunComplete) => void; + shouldRunTestSuite: (fn: ShouldRunTestSuite) => void; +}; + +export declare const KEYS: { + ARROW_DOWN: string; + ARROW_LEFT: string; + ARROW_RIGHT: string; + ARROW_UP: string; + BACKSPACE: string; + CONTROL_C: string; + CONTROL_D: string; + CONTROL_U: string; + ENTER: string; + ESCAPE: string; +}; + +export declare abstract class PatternPrompt { + protected _pipe: NodeJS.WritableStream; + protected _prompt: Prompt; + protected _entityName: string; + protected _currentUsageRows: number; + constructor( + _pipe: NodeJS.WritableStream, + _prompt: Prompt, + _entityName?: string, + ); + run( + onSuccess: (value: string) => void, + onCancel: () => void, + options?: { + header: string; + }, + ): void; + protected _onChange(_pattern: string, _options: ScrollOptions_2): void; +} + +export declare function printPatternCaret( + pattern: string, + pipe: NodeJS.WritableStream, +): void; + +export declare function printRestoredPatternCaret( + pattern: string, + currentUsageRows: number, + pipe: NodeJS.WritableStream, +): void; + +export declare class Prompt { + private _entering; + private _value; + private _onChange; + private _onSuccess; + private _onCancel; + private _offset; + private _promptLength; + private _selection; + constructor(); + private _onResize; + enter( + onChange: (pattern: string, options: ScrollOptions_2) => void, + onSuccess: (pattern: string) => void, + onCancel: () => void, + ): void; + setPromptLength(length: number): void; + setPromptSelection(selected: string): void; + put(key: string): void; + abort(): void; + isEntering(): boolean; +} + +declare type ScrollOptions_2 = { + offset: number; + max: number; +}; +export {ScrollOptions_2 as ScrollOptions}; + +declare type ShouldRunTestSuite = ( + testSuiteInfo: TestSuiteInfo, +) => Promise; + +declare type State = { + interrupted: boolean; +}; + +declare type TestRunComplete = (results: AggregatedResult) => void; + +declare type TestSuiteInfo = { + config: Config.ProjectConfig; + duration?: number; + testPath: string; +}; + +export declare class TestWatcher extends Emittery<{ + change: State; +}> { + state: State; + private _isWatchMode; + constructor({isWatchMode}: {isWatchMode: boolean}); + setState(state: State): Promise; + isInterrupted(): boolean; + isWatchMode(): boolean; +} + +export declare type UpdateConfigCallback = ( + config?: AllowedConfigOptions, +) => void; + +export declare type UsageData = { + key: string; + prompt: string; +}; + +export declare interface WatchPlugin { + isInternal?: boolean; + apply?: (hooks: JestHookSubscriber) => void; + getUsageInfo?: (globalConfig: Config.GlobalConfig) => UsageData | null; + onKey?: (value: string) => void; + run?: ( + globalConfig: Config.GlobalConfig, + updateConfigAndRun: UpdateConfigCallback, + ) => Promise; +} + +export declare interface WatchPluginClass { + new (options: { + config: Record; + stdin: NodeJS.ReadStream; + stdout: NodeJS.WriteStream; + }): WatchPlugin; +} + +export {}; diff --git a/node_modules/jest-watcher/build/index.js b/node_modules/jest-watcher/build/index.js new file mode 100644 index 0000000..177e6ed --- /dev/null +++ b/node_modules/jest-watcher/build/index.js @@ -0,0 +1,84 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +var _exportNames = { + BaseWatchPlugin: true, + JestHook: true, + PatternPrompt: true, + TestWatcher: true, + Prompt: true +}; +Object.defineProperty(exports, 'BaseWatchPlugin', { + enumerable: true, + get: function () { + return _BaseWatchPlugin.default; + } +}); +Object.defineProperty(exports, 'JestHook', { + enumerable: true, + get: function () { + return _JestHooks.default; + } +}); +Object.defineProperty(exports, 'PatternPrompt', { + enumerable: true, + get: function () { + return _PatternPrompt.default; + } +}); +Object.defineProperty(exports, 'Prompt', { + enumerable: true, + get: function () { + return _Prompt.default; + } +}); +Object.defineProperty(exports, 'TestWatcher', { + enumerable: true, + get: function () { + return _TestWatcher.default; + } +}); + +var _BaseWatchPlugin = _interopRequireDefault(require('./BaseWatchPlugin')); + +var _JestHooks = _interopRequireDefault(require('./JestHooks')); + +var _PatternPrompt = _interopRequireDefault(require('./PatternPrompt')); + +var _TestWatcher = _interopRequireDefault(require('./TestWatcher')); + +var _constants = require('./constants'); + +Object.keys(_constants).forEach(function (key) { + if (key === 'default' || key === '__esModule') return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _constants[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _constants[key]; + } + }); +}); + +var _Prompt = _interopRequireDefault(require('./lib/Prompt')); + +var _patternModeHelpers = require('./lib/patternModeHelpers'); + +Object.keys(_patternModeHelpers).forEach(function (key) { + if (key === 'default' || key === '__esModule') return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _patternModeHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _patternModeHelpers[key]; + } + }); +}); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/jest-watcher/build/lib/Prompt.js b/node_modules/jest-watcher/build/lib/Prompt.js new file mode 100644 index 0000000..cfa5c60 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/Prompt.js @@ -0,0 +1,145 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _constants = require('../constants'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class Prompt { + _entering; + _value; + _onChange; + _onSuccess; + _onCancel; + _offset; + _promptLength; + _selection; + + constructor() { + // Copied from `enter` to satisfy TS + this._entering = true; + this._value = ''; + this._selection = null; + this._offset = -1; + this._promptLength = 0; + /* eslint-disable @typescript-eslint/no-empty-function */ + + this._onChange = () => {}; + + this._onSuccess = () => {}; + + this._onCancel = () => {}; + /* eslint-enable */ + } + + _onResize = () => { + this._onChange(); + }; + + enter(onChange, onSuccess, onCancel) { + this._entering = true; + this._value = ''; + this._onSuccess = onSuccess; + this._onCancel = onCancel; + this._selection = null; + this._offset = -1; + this._promptLength = 0; + + this._onChange = () => + onChange(this._value, { + max: 10, + offset: this._offset + }); + + this._onChange(); + + process.stdout.on('resize', this._onResize); + } + + setPromptLength(length) { + this._promptLength = length; + } + + setPromptSelection(selected) { + this._selection = selected; + } + + put(key) { + switch (key) { + case _constants.KEYS.ENTER: + this._entering = false; + + this._onSuccess(this._selection || this._value); + + this.abort(); + break; + + case _constants.KEYS.ESCAPE: + this._entering = false; + + this._onCancel(this._value); + + this.abort(); + break; + + case _constants.KEYS.ARROW_DOWN: + this._offset = Math.min(this._offset + 1, this._promptLength - 1); + + this._onChange(); + + break; + + case _constants.KEYS.ARROW_UP: + this._offset = Math.max(this._offset - 1, -1); + + this._onChange(); + + break; + + case _constants.KEYS.ARROW_LEFT: + case _constants.KEYS.ARROW_RIGHT: + break; + + case _constants.KEYS.CONTROL_U: + this._value = ''; + this._offset = -1; + this._selection = null; + + this._onChange(); + + break; + + default: + this._value = + key === _constants.KEYS.BACKSPACE + ? this._value.slice(0, -1) + : this._value + key; + this._offset = -1; + this._selection = null; + + this._onChange(); + + break; + } + } + + abort() { + this._entering = false; + this._value = ''; + process.stdout.removeListener('resize', this._onResize); + } + + isEntering() { + return this._entering; + } +} + +exports.default = Prompt; diff --git a/node_modules/jest-watcher/build/lib/colorize.js b/node_modules/jest-watcher/build/lib/colorize.js new file mode 100644 index 0000000..456f220 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/colorize.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = colorize; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function colorize(str, start, end) { + return ( + _chalk().default.dim(str.slice(0, start)) + + _chalk().default.reset(str.slice(start, end)) + + _chalk().default.dim(str.slice(end)) + ); +} diff --git a/node_modules/jest-watcher/build/lib/formatTestNameByPattern.js b/node_modules/jest-watcher/build/lib/formatTestNameByPattern.js new file mode 100644 index 0000000..7137225 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/formatTestNameByPattern.js @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = formatTestNameByPattern; + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +var _colorize = _interopRequireDefault(require('./colorize')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const DOTS = '...'; +const ENTER = '⏎'; + +function formatTestNameByPattern(testName, pattern, width) { + const inlineTestName = testName.replace(/(\r\n|\n|\r)/gm, ENTER); + let regexp; + + try { + regexp = new RegExp(pattern, 'i'); + } catch { + return _chalk().default.dim(inlineTestName); + } + + const match = inlineTestName.match(regexp); + + if (!match) { + return _chalk().default.dim(inlineTestName); + } + + const startPatternIndex = Math.max(match.index || 0, 0); + const endPatternIndex = startPatternIndex + match[0].length; + + if (inlineTestName.length <= width) { + return (0, _colorize.default)( + inlineTestName, + startPatternIndex, + endPatternIndex + ); + } + + const slicedTestName = inlineTestName.slice(0, width - DOTS.length); + + if (startPatternIndex < slicedTestName.length) { + if (endPatternIndex > slicedTestName.length) { + return (0, _colorize.default)( + slicedTestName + DOTS, + startPatternIndex, + slicedTestName.length + DOTS.length + ); + } else { + return (0, _colorize.default)( + slicedTestName + DOTS, + Math.min(startPatternIndex, slicedTestName.length), + endPatternIndex + ); + } + } + + return `${_chalk().default.dim(slicedTestName)}${_chalk().default.reset( + DOTS + )}`; +} diff --git a/node_modules/jest-watcher/build/lib/patternModeHelpers.js b/node_modules/jest-watcher/build/lib/patternModeHelpers.js new file mode 100644 index 0000000..145b358 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/patternModeHelpers.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printPatternCaret = printPatternCaret; +exports.printRestoredPatternCaret = printRestoredPatternCaret; + +function _ansiEscapes() { + const data = _interopRequireDefault(require('ansi-escapes')); + + _ansiEscapes = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _stringLength() { + const data = _interopRequireDefault(require('string-length')); + + _stringLength = function () { + return data; + }; + + return data; +} + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function printPatternCaret(pattern, pipe) { + const inputText = `${_chalk().default.dim(' pattern \u203A')} ${pattern}`; + pipe.write(_ansiEscapes().default.eraseDown); + pipe.write(inputText); + pipe.write(_ansiEscapes().default.cursorSavePosition); +} + +function printRestoredPatternCaret(pattern, currentUsageRows, pipe) { + const inputText = `${_chalk().default.dim(' pattern \u203A')} ${pattern}`; + pipe.write( + _ansiEscapes().default.cursorTo( + (0, _stringLength().default)(inputText), + currentUsageRows - 1 + ) + ); + pipe.write(_ansiEscapes().default.cursorRestorePosition); +} diff --git a/node_modules/jest-watcher/build/lib/scroll.js b/node_modules/jest-watcher/build/lib/scroll.js new file mode 100644 index 0000000..4a54504 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/scroll.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = scroll; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function scroll(size, {offset, max}) { + let start = 0; + let index = Math.min(offset, size); + const halfScreen = max / 2; + + if (index <= halfScreen) { + start = 0; + } else { + if (size >= max) { + start = Math.min(index - halfScreen - 1, size - max); + } + + index = Math.min(index - start, size); + } + + return { + end: Math.min(size, start + max), + index, + start + }; +} diff --git a/node_modules/jest-watcher/build/types.js b/node_modules/jest-watcher/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-watcher/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-watcher/package.json b/node_modules/jest-watcher/package.json new file mode 100644 index 0000000..1ce306d --- /dev/null +++ b/node_modules/jest-watcher/package.json @@ -0,0 +1,67 @@ +{ + "_from": "jest-watcher@^29.0.1", + "_id": "jest-watcher@29.0.1", + "_inBundle": false, + "_integrity": "sha512-0LBWDL3sZ+vyHRYxjqm2irhfwhUXHonjLSbd0oDeGq44U1e1uUh3icWNXYF8HO/UEnOoa6+OJDncLUXP2Hdg9A==", + "_location": "/jest-watcher", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-watcher@^29.0.1", + "name": "jest-watcher", + "escapedName": "jest-watcher", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/core", + "/jest-runner" + ], + "_resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.0.1.tgz", + "_shasum": "63adeb8887a0562ed8f990f413b830ef48a8db94", + "_spec": "jest-watcher@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/core", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/test-result": "^29.0.1", + "@jest/types": "^29.0.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.10.2", + "jest-util": "^29.0.1", + "string-length": "^4.0.1" + }, + "deprecated": false, + "description": "Delightful JavaScript Testing.", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://jestjs.io/", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-watcher", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-watcher" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest-worker/LICENSE b/node_modules/jest-worker/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-worker/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest-worker/README.md b/node_modules/jest-worker/README.md new file mode 100644 index 0000000..1277ed8 --- /dev/null +++ b/node_modules/jest-worker/README.md @@ -0,0 +1,266 @@ +# jest-worker + +Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers. + +The module works by providing an absolute path of the module to be loaded in all forked processes. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous. + +The module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it. + +The list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the "minimal example" section for a valid one. + +## Install + +```sh +yarn add jest-worker +``` + +## Example + +This example covers the minimal usage: + +### File `parent.js` + +```js +import {Worker as JestWorker} from 'jest-worker'; + +async function main() { + const worker = new JestWorker(require.resolve('./worker')); + const result = await worker.hello('Alice'); // "Hello, Alice" +} + +main(); +``` + +### File `worker.js` + +```js +export function hello(param) { + return `Hello, ${param}`; +} +``` + +## Experimental worker + +Node shipped with [`worker_threads`](https://nodejs.org/api/worker_threads.html), a "threading API" that uses `SharedArrayBuffers` to communicate between the main process and its child threads. This feature can significantly improve the communication time between parent and child processes in `jest-worker`. + +To use `worker_threads` instead of default `child_process` you have to pass `enableWorkerThreads: true` when instantiating the worker. + +## API + +The `Worker` export is a constructor that is initialized by passing the worker path, plus an options object. + +### `workerPath: string` (required) + +Node module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one. + +### `options: Object` (optional) + +#### `computeWorkerKey: (method: string, ...args: Array) => string | null` (optional) + +Every time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`. + +The callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the "bound worker usage" section. + +By default, no process is bound to any worker. + +#### `enableWorkerThreads: boolean` (optional) + +By default, `jest-worker` will use `child_process` threads to spawn new Node.js processes. If you prefer [`worker_threads`](https://nodejs.org/api/worker_threads.html) instead, pass `enableWorkerThreads: true`. + +#### `exposedMethods: ReadonlyArray` (optional) + +List of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist. + +#### `forkOptions: ForkOptions` (optional) + +Allow customizing all options passed to `child_process.fork`. By default, some values are set (`cwd`, `env`, `execArgv` and `serialization`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options). + +#### `idleMemoryLimit: number` (optional) + +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); + +After the worker has executed a task the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. If no limit is set this process does not occur. The limit can be specified in 2 ways: + +- `<= 1` - The value is assumed to be a percentage of system memory. So 0.5 sets the memory limit of the worker to half of the total system memory +- `\> 1` - Assumed to be a fixed byte value. Because of the previous rule if you wanted a value of 1 byte (I don't know why) you could use `1.1`. + +#### `maxRetries: number` (optional) + +Maximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries. + +#### `numWorkers: number` (optional) + +Amount of workers to spawn. Defaults to the number of CPUs minus 1. + +#### `resourceLimits: ResourceLimits` (optional) + +The `resourceLimits` option which will be passed to `worker_threads` workers. + +#### `silent: Boolean` (optional) + +Set to false for `stdout` and `stderr` to be logged to console. + +By default this is true. + +#### `setupArgs: Array` (optional) + +The arguments that will be passed to the `setup` method during initialization. + +#### `taskQueue: TaskQueue` (optional) + +The task queue defines in which order tasks (method calls) are processed by the workers. `jest-worker` ships with a `FifoQueue` and `PriorityQueue`: + +- `FifoQueue` (default): Processes the method calls (tasks) in the call order. +- `PriorityQueue`: Processes the method calls by a computed priority in natural ordering (lower priorities first). Tasks with the same priority are processed in any order (FIFO not guaranteed). The constructor accepts a single argument, the function that is passed the name of the called function and the arguments and returns a numerical value for the priority: `new require('jest-worker').PriorityQueue((method, filename) => filename.length)`. + +#### `WorkerPool: new (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional) + +Provide a custom WorkerPool class to be used for spawning child processes. + +#### `workerSchedulingPolicy: 'round-robin' | 'in-order'` (optional) + +Specifies the policy how tasks are assigned to workers if multiple workers are _idle_: + +- `round-robin` (default): The task will be sequentially distributed onto the workers. The first task is assigned to the worker 1, the second to the worker 2, to ensure that the work is distributed across workers. +- `in-order`: The task will be assigned to the first free worker starting with worker 1 and only assign the work to worker 2 if the worker 1 is busy. + +Tasks are always assigned to the first free worker as soon as tasks start to queue up. The scheduling policy does not define the task scheduling which is always first-in, first-out. + +## JestWorker + +### Methods + +The returned `JestWorker` instance has all the exposed methods, plus some additional ones to interact with the workers itself: + +#### `getStdout(): Readable` + +Returns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`. + +#### `getStderr(): Readable` + +Returns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`. + +#### `end()` + +Finishes the workers by killing all workers. No further calls can be done to the `Worker` instance. + +Returns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans. + +**Note:** + +`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution. + +Consider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily. + +### Worker IDs + +Each worker has a unique id (index that starts with `'1'`), which is available inside the worker as `process.env.JEST_WORKER_ID`. + +## Setting up and tearing down the child process + +The child process can define two special methods (both of them can be asynchronous): + +- `setup()`: If defined, it's executed before the first call to any method in the child. +- `teardown()`: If defined, it's executed when the farm ends. + +# More examples + +## Standard usage + +This example covers the standard usage: + +### File `parent.js` + +```js +import {Worker as JestWorker} from 'jest-worker'; + +async function main() { + const myWorker = new JestWorker(require.resolve('./worker'), { + exposedMethods: ['foo', 'bar', 'getWorkerId'], + numWorkers: 4, + }); + + console.log(await myWorker.foo('Alice')); // "Hello from foo: Alice" + console.log(await myWorker.bar('Bob')); // "Hello from bar: Bob" + console.log(await myWorker.getWorkerId()); // "3" -> this message has sent from the 3rd worker + + const {forceExited} = await myWorker.end(); + if (forceExited) { + console.error('Workers failed to exit gracefully'); + } +} + +main(); +``` + +### File `worker.js` + +```js +export function foo(param) { + return `Hello from foo: ${param}`; +} + +export function bar(param) { + return `Hello from bar: ${param}`; +} + +export function getWorkerId() { + return process.env.JEST_WORKER_ID; +} +``` + +## Bound worker usage: + +This example covers the usage with a `computeWorkerKey` method: + +### File `parent.js` + +```js +import {Worker as JestWorker} from 'jest-worker'; + +async function main() { + const myWorker = new JestWorker(require.resolve('./worker'), { + computeWorkerKey: (method, filename) => filename, + }); + + // Transform the given file, within the first available worker. + console.log(await myWorker.transform('/tmp/foo.js')); + + // Wait a bit. + await sleep(10000); + + // Transform the same file again. Will immediately return because the + // transformed file is cached in the worker, and `computeWorkerKey` ensures + // the same worker that processed the file the first time will process it now. + console.log(await myWorker.transform('/tmp/foo.js')); + + const {forceExited} = await myWorker.end(); + if (forceExited) { + console.error('Workers failed to exit gracefully'); + } +} + +main(); +``` + +### File `worker.js` + +```js +import babel from '@babel/core'; + +const cache = Object.create(null); + +export function transform(filename) { + if (cache[filename]) { + return cache[filename]; + } + + // jest-worker can handle both immediate results and thenables. If a + // thenable is returned, it will be await'ed until it resolves. + return babel.transformFileAsync(filename).then(result => { + cache[filename] = result; + + return result; + }); +} +``` diff --git a/node_modules/jest-worker/build/Farm.js b/node_modules/jest-worker/build/Farm.js new file mode 100644 index 0000000..783c8a1 --- /dev/null +++ b/node_modules/jest-worker/build/Farm.js @@ -0,0 +1,188 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _FifoQueue = _interopRequireDefault(require('./FifoQueue')); + +var _types = require('./types'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class Farm { + _computeWorkerKey; + _workerSchedulingPolicy; + _cacheKeys = Object.create(null); + _locks = []; + _offset = 0; + _taskQueue; + + constructor(_numOfWorkers, _callback, options = {}) { + this._numOfWorkers = _numOfWorkers; + this._callback = _callback; + this._computeWorkerKey = options.computeWorkerKey; + this._workerSchedulingPolicy = + options.workerSchedulingPolicy ?? 'round-robin'; + this._taskQueue = options.taskQueue ?? new _FifoQueue.default(); + } + + doWork(method, ...args) { + const customMessageListeners = new Set(); + + const addCustomMessageListener = listener => { + customMessageListeners.add(listener); + return () => { + customMessageListeners.delete(listener); + }; + }; + + const onCustomMessage = message => { + customMessageListeners.forEach(listener => listener(message)); + }; + + const promise = new Promise( // Bind args to this function so it won't reference to the parent scope. + // This prevents a memory leak in v8, because otherwise the function will + // retain args for the closure. + ((args, resolve, reject) => { + const computeWorkerKey = this._computeWorkerKey; + const request = [_types.CHILD_MESSAGE_CALL, false, method, args]; + let worker = null; + let hash = null; + + if (computeWorkerKey) { + hash = computeWorkerKey.call(this, method, ...args); + worker = hash == null ? null : this._cacheKeys[hash]; + } + + const onStart = worker => { + if (hash != null) { + this._cacheKeys[hash] = worker; + } + }; + + const onEnd = (error, result) => { + customMessageListeners.clear(); + + if (error) { + reject(error); + } else { + resolve(result); + } + }; + + const task = { + onCustomMessage, + onEnd, + onStart, + request + }; + + if (worker) { + this._taskQueue.enqueue(task, worker.getWorkerId()); + + this._process(worker.getWorkerId()); + } else { + this._push(task); + } + }).bind(null, args) + ); + promise.UNSTABLE_onCustomMessage = addCustomMessageListener; + return promise; + } + + _process(workerId) { + if (this._isLocked(workerId)) { + return this; + } + + const task = this._taskQueue.dequeue(workerId); + + if (!task) { + return this; + } + + if (task.request[1]) { + throw new Error('Queue implementation returned processed task'); + } // Reference the task object outside so it won't be retained by onEnd, + // and other properties of the task object, such as task.request can be + // garbage collected. + + let taskOnEnd = task.onEnd; + + const onEnd = (error, result) => { + if (taskOnEnd) { + taskOnEnd(error, result); + } + + taskOnEnd = null; + + this._unlock(workerId); + + this._process(workerId); + }; + + task.request[1] = true; + + this._lock(workerId); + + this._callback( + workerId, + task.request, + task.onStart, + onEnd, + task.onCustomMessage + ); + + return this; + } + + _push(task) { + this._taskQueue.enqueue(task); + + const offset = this._getNextWorkerOffset(); + + for (let i = 0; i < this._numOfWorkers; i++) { + this._process((offset + i) % this._numOfWorkers); + + if (task.request[1]) { + break; + } + } + + return this; + } + + _getNextWorkerOffset() { + switch (this._workerSchedulingPolicy) { + case 'in-order': + return 0; + + case 'round-robin': + return this._offset++; + } + } + + _lock(workerId) { + this._locks[workerId] = true; + } + + _unlock(workerId) { + this._locks[workerId] = false; + } + + _isLocked(workerId) { + return this._locks[workerId]; + } +} + +exports.default = Farm; diff --git a/node_modules/jest-worker/build/FifoQueue.js b/node_modules/jest-worker/build/FifoQueue.js new file mode 100644 index 0000000..93e9f11 --- /dev/null +++ b/node_modules/jest-worker/build/FifoQueue.js @@ -0,0 +1,108 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * First-in, First-out task queue that manages a dedicated pool + * for each worker as well as a shared queue. The FIFO ordering is guaranteed + * across the worker specific and shared queue. + */ +class FifoQueue { + _workerQueues = []; + _sharedQueue = new InternalQueue(); + + enqueue(task, workerId) { + if (workerId == null) { + this._sharedQueue.enqueue(task); + + return; + } + + let workerQueue = this._workerQueues[workerId]; + + if (workerQueue == null) { + workerQueue = this._workerQueues[workerId] = new InternalQueue(); + } + + const sharedTop = this._sharedQueue.peekLast(); + + const item = { + previousSharedTask: sharedTop, + task + }; + workerQueue.enqueue(item); + } + + dequeue(workerId) { + const workerTop = this._workerQueues[workerId]?.peek(); + const sharedTaskIsProcessed = + workerTop?.previousSharedTask?.request[1] ?? true; // Process the top task from the shared queue if + // - there's no task in the worker specific queue or + // - if the non-worker-specific task after which this worker specific task + // has been queued wasn't processed yet + + if (workerTop != null && sharedTaskIsProcessed) { + return this._workerQueues[workerId]?.dequeue()?.task ?? null; + } + + return this._sharedQueue.dequeue(); + } +} + +exports.default = FifoQueue; + +/** + * FIFO queue for a single worker / shared queue. + */ +class InternalQueue { + _head = null; + _last = null; + + enqueue(value) { + const item = { + next: null, + value + }; + + if (this._last == null) { + this._head = item; + } else { + this._last.next = item; + } + + this._last = item; + } + + dequeue() { + if (this._head == null) { + return null; + } + + const item = this._head; + this._head = item.next; + + if (this._head == null) { + this._last = null; + } + + return item.value; + } + + peek() { + return this._head?.value ?? null; + } + + peekLast() { + return this._last?.value ?? null; + } +} diff --git a/node_modules/jest-worker/build/PriorityQueue.js b/node_modules/jest-worker/build/PriorityQueue.js new file mode 100644 index 0000000..a6efaac --- /dev/null +++ b/node_modules/jest-worker/build/PriorityQueue.js @@ -0,0 +1,158 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Priority queue that processes tasks in natural ordering (lower priority first) + * according to the priority computed by the function passed in the constructor. + * + * FIFO ordering isn't guaranteed for tasks with the same priority. + * + * Worker specific tasks with the same priority as a non-worker specific task + * are always processed first. + */ +class PriorityQueue { + _queue = []; + _sharedQueue = new MinHeap(); + + constructor(_computePriority) { + this._computePriority = _computePriority; + } + + enqueue(task, workerId) { + if (workerId == null) { + this._enqueue(task, this._sharedQueue); + } else { + const queue = this._getWorkerQueue(workerId); + + this._enqueue(task, queue); + } + } + + _enqueue(task, queue) { + const item = { + priority: this._computePriority(task.request[2], ...task.request[3]), + task + }; + queue.add(item); + } + + dequeue(workerId) { + const workerQueue = this._getWorkerQueue(workerId); + + const workerTop = workerQueue.peek(); + + const sharedTop = this._sharedQueue.peek(); // use the task from the worker queue if there's no task in the shared queue + // or if the priority of the worker queue is smaller or equal to the + // priority of the top task in the shared queue. The tasks of the + // worker specific queue are preferred because no other worker can pick this + // specific task up. + + if ( + sharedTop == null || + (workerTop != null && workerTop.priority <= sharedTop.priority) + ) { + return workerQueue.poll()?.task ?? null; + } + + return this._sharedQueue.poll().task; + } + + _getWorkerQueue(workerId) { + let queue = this._queue[workerId]; + + if (queue == null) { + queue = this._queue[workerId] = new MinHeap(); + } + + return queue; + } +} + +exports.default = PriorityQueue; + +class MinHeap { + _heap = []; + + peek() { + return this._heap[0] ?? null; + } + + add(item) { + const nodes = this._heap; + nodes.push(item); + + if (nodes.length === 1) { + return; + } + + let currentIndex = nodes.length - 1; // Bubble up the added node as long as the parent is bigger + + while (currentIndex > 0) { + const parentIndex = Math.floor((currentIndex + 1) / 2) - 1; + const parent = nodes[parentIndex]; + + if (parent.priority <= item.priority) { + break; + } + + nodes[currentIndex] = parent; + nodes[parentIndex] = item; + currentIndex = parentIndex; + } + } + + poll() { + const nodes = this._heap; + const result = nodes[0]; + const lastElement = nodes.pop(); // heap was empty or removed the last element + + if (result == null || nodes.length === 0) { + return result ?? null; + } + + let index = 0; + nodes[0] = lastElement ?? null; + const element = nodes[0]; + + while (true) { + let swapIndex = null; + const rightChildIndex = (index + 1) * 2; + const leftChildIndex = rightChildIndex - 1; + const rightChild = nodes[rightChildIndex]; + const leftChild = nodes[leftChildIndex]; // if the left child is smaller, swap with the left + + if (leftChild != null && leftChild.priority < element.priority) { + swapIndex = leftChildIndex; + } // If the right child is smaller or the right child is smaller than the left + // then swap with the right child + + if ( + rightChild != null && + rightChild.priority < (swapIndex == null ? element : leftChild).priority + ) { + swapIndex = rightChildIndex; + } + + if (swapIndex == null) { + break; + } + + nodes[index] = nodes[swapIndex]; + nodes[swapIndex] = element; + index = swapIndex; + } + + return result; + } +} diff --git a/node_modules/jest-worker/build/WorkerPool.js b/node_modules/jest-worker/build/WorkerPool.js new file mode 100644 index 0000000..3de7034 --- /dev/null +++ b/node_modules/jest-worker/build/WorkerPool.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +var _BaseWorkerPool = _interopRequireDefault(require('./base/BaseWorkerPool')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class WorkerPool extends _BaseWorkerPool.default { + send(workerId, request, onStart, onEnd, onCustomMessage) { + this.getWorkerById(workerId).send(request, onStart, onEnd, onCustomMessage); + } + + createWorker(workerOptions) { + let Worker; + + if (this._options.enableWorkerThreads) { + Worker = require('./workers/NodeThreadsWorker').default; + } else { + Worker = require('./workers/ChildProcessWorker').default; + } + + return new Worker(workerOptions); + } +} + +var _default = WorkerPool; +exports.default = _default; diff --git a/node_modules/jest-worker/build/base/BaseWorkerPool.js b/node_modules/jest-worker/build/base/BaseWorkerPool.js new file mode 100644 index 0000000..d3d1e41 --- /dev/null +++ b/node_modules/jest-worker/build/base/BaseWorkerPool.js @@ -0,0 +1,135 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _mergeStream() { + const data = _interopRequireDefault(require('merge-stream')); + + _mergeStream = function () { + return data; + }; + + return data; +} + +var _types = require('../types'); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// How long to wait for the child process to terminate +// after CHILD_MESSAGE_END before sending force exiting. +const FORCE_EXIT_DELAY = 500; +/* istanbul ignore next */ +// eslint-disable-next-line @typescript-eslint/no-empty-function + +const emptyMethod = () => {}; + +class BaseWorkerPool { + _stderr; + _stdout; + _options; + _workers; + + constructor(workerPath, options) { + this._options = options; + this._workers = new Array(options.numWorkers); + const stdout = (0, _mergeStream().default)(); + const stderr = (0, _mergeStream().default)(); + const {forkOptions, maxRetries, resourceLimits, setupArgs} = options; + + for (let i = 0; i < options.numWorkers; i++) { + const workerOptions = { + forkOptions, + idleMemoryLimit: this._options.idleMemoryLimit, + maxRetries, + resourceLimits, + setupArgs, + workerId: i, + workerPath + }; + const worker = this.createWorker(workerOptions); + const workerStdout = worker.getStdout(); + const workerStderr = worker.getStderr(); + + if (workerStdout) { + stdout.add(workerStdout); + } + + if (workerStderr) { + stderr.add(workerStderr); + } + + this._workers[i] = worker; + } + + this._stdout = stdout; + this._stderr = stderr; + } + + getStderr() { + return this._stderr; + } + + getStdout() { + return this._stdout; + } + + getWorkers() { + return this._workers; + } + + getWorkerById(workerId) { + return this._workers[workerId]; + } + + createWorker(_workerOptions) { + throw Error('Missing method createWorker in WorkerPool'); + } + + async end() { + // We do not cache the request object here. If so, it would only be only + // processed by one of the workers, and we want them all to close. + const workerExitPromises = this._workers.map(async worker => { + worker.send( + [_types.CHILD_MESSAGE_END, false], + emptyMethod, + emptyMethod, + emptyMethod + ); // Schedule a force exit in case worker fails to exit gracefully so + // await worker.waitForExit() never takes longer than FORCE_EXIT_DELAY + + let forceExited = false; + const forceExitTimeout = setTimeout(() => { + worker.forceExit(); + forceExited = true; + }, FORCE_EXIT_DELAY); + await worker.waitForExit(); // Worker ideally exited gracefully, don't send force exit then + + clearTimeout(forceExitTimeout); + return forceExited; + }); + + const workerExits = await Promise.all(workerExitPromises); + return workerExits.reduce( + (result, forceExited) => ({ + forceExited: result.forceExited || forceExited + }), + { + forceExited: false + } + ); + } +} + +exports.default = BaseWorkerPool; diff --git a/node_modules/jest-worker/build/index.d.ts b/node_modules/jest-worker/build/index.d.ts new file mode 100644 index 0000000..a8dee2e --- /dev/null +++ b/node_modules/jest-worker/build/index.d.ts @@ -0,0 +1,352 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {EventEmitter} from 'events'; +import type {ForkOptions} from 'child_process'; +import type {ResourceLimits} from 'worker_threads'; + +declare const CHILD_MESSAGE_CALL = 1; + +declare const CHILD_MESSAGE_END = 2; + +declare const CHILD_MESSAGE_INITIALIZE = 0; + +declare const CHILD_MESSAGE_MEM_USAGE = 3; + +declare type ChildMessage = + | ChildMessageInitialize + | ChildMessageCall + | ChildMessageEnd + | ChildMessageMemUsage; + +declare type ChildMessageCall = [ + typeof CHILD_MESSAGE_CALL, + boolean, + string, + Array, +]; + +declare type ChildMessageEnd = [typeof CHILD_MESSAGE_END, boolean]; + +declare type ChildMessageInitialize = [ + typeof CHILD_MESSAGE_INITIALIZE, + boolean, + string, + // file + Array | undefined, + // setupArgs + MessagePort_2 | undefined, +]; + +declare type ChildMessageMemUsage = [typeof CHILD_MESSAGE_MEM_USAGE]; + +declare type ComputeTaskPriorityCallback = ( + method: string, + ...args: Array +) => number; + +declare type ExcludeReservedKeys = Exclude; + +/** + * First-in, First-out task queue that manages a dedicated pool + * for each worker as well as a shared queue. The FIFO ordering is guaranteed + * across the worker specific and shared queue. + */ +export declare class FifoQueue implements TaskQueue { + private _workerQueues; + private _sharedQueue; + enqueue(task: QueueChildMessage, workerId?: number): void; + dequeue(workerId: number): QueueChildMessage | null; +} + +declare type FunctionLike = (...args: any) => unknown; + +declare type HeapItem = { + priority: number; +}; + +export declare type JestWorkerFarm> = + Worker_2 & WorkerModule; + +export declare function messageParent( + message: unknown, + parentProcess?: NodeJS.Process, +): void; + +declare type MessagePort_2 = typeof EventEmitter & { + postMessage(message: unknown): void; +}; + +declare type MethodLikeKeys = { + [K in keyof T]: T[K] extends FunctionLike ? K : never; +}[keyof T]; + +declare class MinHeap { + private _heap; + peek(): TItem | null; + add(item: TItem): void; + poll(): TItem | null; +} + +declare type OnCustomMessage = (message: Array | unknown) => void; + +declare type OnEnd = (err: Error | null, result: unknown) => void; + +declare type OnStart = (worker: WorkerInterface) => void; + +declare type OnStateChangeHandler = ( + state: WorkerStates, + oldState: WorkerStates, +) => void; + +declare type PoolExitResult = { + forceExited: boolean; +}; + +/** + * Priority queue that processes tasks in natural ordering (lower priority first) + * according to the priority computed by the function passed in the constructor. + * + * FIFO ordering isn't guaranteed for tasks with the same priority. + * + * Worker specific tasks with the same priority as a non-worker specific task + * are always processed first. + */ +export declare class PriorityQueue implements TaskQueue { + private _computePriority; + private _queue; + private _sharedQueue; + constructor(_computePriority: ComputeTaskPriorityCallback); + enqueue(task: QueueChildMessage, workerId?: number): void; + _enqueue(task: QueueChildMessage, queue: MinHeap): void; + dequeue(workerId: number): QueueChildMessage | null; + _getWorkerQueue(workerId: number): MinHeap; +} + +export declare interface PromiseWithCustomMessage extends Promise { + UNSTABLE_onCustomMessage?: (listener: OnCustomMessage) => () => void; +} + +declare type Promisify = ReturnType extends Promise< + infer R +> + ? (...args: Parameters) => Promise + : (...args: Parameters) => Promise>; + +declare type QueueChildMessage = { + request: ChildMessageCall; + onStart: OnStart; + onEnd: OnEnd; + onCustomMessage: OnCustomMessage; +}; + +declare type QueueItem = { + task: QueueChildMessage; + priority: number; +}; + +declare type ReservedKeys = + | 'end' + | 'getStderr' + | 'getStdout' + | 'setup' + | 'teardown'; + +export declare interface TaskQueue { + /** + * Enqueues the task in the queue for the specified worker or adds it to the + * queue shared by all workers + * @param task the task to queue + * @param workerId the id of the worker that should process this task or undefined + * if there's no preference. + */ + enqueue(task: QueueChildMessage, workerId?: number): void; + /** + * Dequeues the next item from the queue for the specified worker + * @param workerId the id of the worker for which the next task should be retrieved + */ + dequeue(workerId: number): QueueChildMessage | null; +} + +/** + * The Jest farm (publicly called "Worker") is a class that allows you to queue + * methods across multiple child processes, in order to parallelize work. This + * is done by providing an absolute path to a module that will be loaded on each + * of the child processes, and bridged to the main process. + * + * Bridged methods are specified by using the "exposedMethods" property of the + * "options" object. This is an array of strings, where each of them corresponds + * to the exported name in the loaded module. + * + * You can also control the amount of workers by using the "numWorkers" property + * of the "options" object, and the settings passed to fork the process through + * the "forkOptions" property. The amount of workers defaults to the amount of + * CPUS minus one. + * + * Queueing calls can be done in two ways: + * - Standard method: calls will be redirected to the first available worker, + * so they will get executed as soon as they can. + * + * - Sticky method: if a "computeWorkerKey" method is provided within the + * config, the resulting string of this method will be used as a key. + * Every time this key is returned, it is guaranteed that your job will be + * processed by the same worker. This is specially useful if your workers + * are caching results. + */ +declare class Worker_2 { + private _ending; + private _farm; + private _options; + private _workerPool; + constructor(workerPath: string, options?: WorkerFarmOptions); + private _bindExposedWorkerMethods; + private _callFunctionWithArgs; + getStderr(): NodeJS.ReadableStream; + getStdout(): NodeJS.ReadableStream; + end(): Promise; +} +export {Worker_2 as Worker}; + +declare type WorkerCallback = ( + workerId: number, + request: ChildMessage, + onStart: OnStart, + onEnd: OnEnd, + onCustomMessage: OnCustomMessage, +) => void; + +declare enum WorkerEvents { + STATE_CHANGE = 'state-change', +} + +export declare type WorkerFarmOptions = { + computeWorkerKey?: (method: string, ...args: Array) => string | null; + enableWorkerThreads?: boolean; + exposedMethods?: ReadonlyArray; + forkOptions?: ForkOptions; + maxRetries?: number; + numWorkers?: number; + resourceLimits?: ResourceLimits; + setupArgs?: Array; + taskQueue?: TaskQueue; + WorkerPool?: new ( + workerPath: string, + options?: WorkerPoolOptions, + ) => WorkerPoolInterface; + workerSchedulingPolicy?: WorkerSchedulingPolicy; + idleMemoryLimit?: number; +}; + +declare interface WorkerInterface { + get state(): WorkerStates; + send( + request: ChildMessage, + onProcessStart: OnStart, + onProcessEnd: OnEnd, + onCustomMessage: OnCustomMessage, + ): void; + waitForExit(): Promise; + forceExit(): void; + getWorkerId(): number; + getStderr(): NodeJS.ReadableStream | null; + getStdout(): NodeJS.ReadableStream | null; + /** + * Some system level identifier for the worker. IE, process id, thread id, etc. + */ + getWorkerSystemId(): number; + getMemoryUsage(): Promise; + /** + * Checks to see if the child worker is actually running. + */ + isWorkerRunning(): boolean; + /** + * When the worker child is started and ready to start handling requests. + * + * @remarks + * This mostly exists to help with testing so that you don't check the status + * of things like isWorkerRunning before it actually is. + */ + waitForWorkerReady(): Promise; +} + +declare type WorkerModule = { + [K in keyof T as Extract< + ExcludeReservedKeys, + MethodLikeKeys + >]: T[K] extends FunctionLike ? Promisify : never; +}; + +declare type WorkerOptions_2 = { + forkOptions: ForkOptions; + resourceLimits: ResourceLimits; + setupArgs: Array; + maxRetries: number; + workerId: number; + workerData?: unknown; + workerPath: string; + /** + * After a job has executed the memory usage it should return to. + * + * @remarks + * Note this is different from ResourceLimits in that it checks at idle, after + * a job is complete. So you could have a resource limit of 500MB but an idle + * limit of 50MB. The latter will only trigger if after a job has completed the + * memory usage hasn't returned back down under 50MB. + */ + idleMemoryLimit?: number; + /** + * This mainly exists so the path can be changed during testing. + * https://github.com/facebook/jest/issues/9543 + */ + childWorkerPath?: string; + /** + * This is useful for debugging individual tests allowing you to see + * the raw output of the worker. + */ + silent?: boolean; + /** + * Used to immediately bind event handlers. + */ + on?: { + [WorkerEvents.STATE_CHANGE]: + | OnStateChangeHandler + | ReadonlyArray; + }; +}; + +export declare interface WorkerPoolInterface { + getStderr(): NodeJS.ReadableStream; + getStdout(): NodeJS.ReadableStream; + getWorkers(): Array; + createWorker(options: WorkerOptions_2): WorkerInterface; + send: WorkerCallback; + end(): Promise; +} + +export declare type WorkerPoolOptions = { + setupArgs: Array; + forkOptions: ForkOptions; + resourceLimits: ResourceLimits; + maxRetries: number; + numWorkers: number; + enableWorkerThreads: boolean; + idleMemoryLimit?: number; +}; + +declare type WorkerSchedulingPolicy = 'round-robin' | 'in-order'; + +declare enum WorkerStates { + STARTING = 'starting', + OK = 'ok', + OUT_OF_MEMORY = 'oom', + RESTARTING = 'restarting', + SHUTTING_DOWN = 'shutting-down', + SHUT_DOWN = 'shut-down', +} + +export {}; diff --git a/node_modules/jest-worker/build/index.js b/node_modules/jest-worker/build/index.js new file mode 100644 index 0000000..c653e78 --- /dev/null +++ b/node_modules/jest-worker/build/index.js @@ -0,0 +1,196 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'FifoQueue', { + enumerable: true, + get: function () { + return _FifoQueue.default; + } +}); +Object.defineProperty(exports, 'PriorityQueue', { + enumerable: true, + get: function () { + return _PriorityQueue.default; + } +}); +exports.Worker = void 0; +Object.defineProperty(exports, 'messageParent', { + enumerable: true, + get: function () { + return _messageParent.default; + } +}); + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require('path'); + + _path = function () { + return data; + }; + + return data; +} + +var _Farm = _interopRequireDefault(require('./Farm')); + +var _WorkerPool = _interopRequireDefault(require('./WorkerPool')); + +var _PriorityQueue = _interopRequireDefault(require('./PriorityQueue')); + +var _FifoQueue = _interopRequireDefault(require('./FifoQueue')); + +var _messageParent = _interopRequireDefault(require('./workers/messageParent')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function getExposedMethods(workerPath, options) { + let exposedMethods = options.exposedMethods; // If no methods list is given, try getting it by auto-requiring the module. + + if (!exposedMethods) { + const module = require(workerPath); + + exposedMethods = Object.keys(module).filter( + name => typeof module[name] === 'function' + ); + + if (typeof module === 'function') { + exposedMethods = [...exposedMethods, 'default']; + } + } + + return exposedMethods; +} +/** + * The Jest farm (publicly called "Worker") is a class that allows you to queue + * methods across multiple child processes, in order to parallelize work. This + * is done by providing an absolute path to a module that will be loaded on each + * of the child processes, and bridged to the main process. + * + * Bridged methods are specified by using the "exposedMethods" property of the + * "options" object. This is an array of strings, where each of them corresponds + * to the exported name in the loaded module. + * + * You can also control the amount of workers by using the "numWorkers" property + * of the "options" object, and the settings passed to fork the process through + * the "forkOptions" property. The amount of workers defaults to the amount of + * CPUS minus one. + * + * Queueing calls can be done in two ways: + * - Standard method: calls will be redirected to the first available worker, + * so they will get executed as soon as they can. + * + * - Sticky method: if a "computeWorkerKey" method is provided within the + * config, the resulting string of this method will be used as a key. + * Every time this key is returned, it is guaranteed that your job will be + * processed by the same worker. This is specially useful if your workers + * are caching results. + */ + +class Worker { + _ending; + _farm; + _options; + _workerPool; + + constructor(workerPath, options) { + this._options = {...options}; + this._ending = false; + + if (!(0, _path().isAbsolute)(workerPath)) { + throw new Error(`'workerPath' must be absolute, got '${workerPath}'`); + } + + const workerPoolOptions = { + enableWorkerThreads: this._options.enableWorkerThreads ?? false, + forkOptions: this._options.forkOptions ?? {}, + idleMemoryLimit: this._options.idleMemoryLimit, + maxRetries: this._options.maxRetries ?? 3, + numWorkers: + this._options.numWorkers ?? Math.max((0, _os().cpus)().length - 1, 1), + resourceLimits: this._options.resourceLimits ?? {}, + setupArgs: this._options.setupArgs ?? [] + }; + + if (this._options.WorkerPool) { + this._workerPool = new this._options.WorkerPool( + workerPath, + workerPoolOptions + ); + } else { + this._workerPool = new _WorkerPool.default(workerPath, workerPoolOptions); + } + + this._farm = new _Farm.default( + workerPoolOptions.numWorkers, + this._workerPool.send.bind(this._workerPool), + { + computeWorkerKey: this._options.computeWorkerKey, + taskQueue: this._options.taskQueue, + workerSchedulingPolicy: this._options.workerSchedulingPolicy + } + ); + + this._bindExposedWorkerMethods(workerPath, this._options); + } + + _bindExposedWorkerMethods(workerPath, options) { + getExposedMethods(workerPath, options).forEach(name => { + if (name.startsWith('_')) { + return; + } // eslint-disable-next-line no-prototype-builtins + + if (this.constructor.prototype.hasOwnProperty(name)) { + throw new TypeError(`Cannot define a method called ${name}`); + } // @ts-expect-error: dynamic extension of the class instance is expected. + + this[name] = this._callFunctionWithArgs.bind(this, name); + }); + } + + _callFunctionWithArgs(method, ...args) { + if (this._ending) { + throw new Error('Farm is ended, no more calls can be done to it'); + } + + return this._farm.doWork(method, ...args); + } + + getStderr() { + return this._workerPool.getStderr(); + } + + getStdout() { + return this._workerPool.getStdout(); + } + + async end() { + if (this._ending) { + throw new Error('Farm is ended, no more calls can be done to it'); + } + + this._ending = true; + return this._workerPool.end(); + } +} + +exports.Worker = Worker; diff --git a/node_modules/jest-worker/build/types.js b/node_modules/jest-worker/build/types.js new file mode 100644 index 0000000..b6849f7 --- /dev/null +++ b/node_modules/jest-worker/build/types.js @@ -0,0 +1,63 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.WorkerStates = + exports.WorkerEvents = + exports.PARENT_MESSAGE_SETUP_ERROR = + exports.PARENT_MESSAGE_OK = + exports.PARENT_MESSAGE_MEM_USAGE = + exports.PARENT_MESSAGE_CUSTOM = + exports.PARENT_MESSAGE_CLIENT_ERROR = + exports.CHILD_MESSAGE_MEM_USAGE = + exports.CHILD_MESSAGE_INITIALIZE = + exports.CHILD_MESSAGE_END = + exports.CHILD_MESSAGE_CALL = + void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// Because of the dynamic nature of a worker communication process, all messages +// coming from any of the other processes cannot be typed. Thus, many types +// include "unknown" as a TS type, which is (unfortunately) correct here. +const CHILD_MESSAGE_INITIALIZE = 0; +exports.CHILD_MESSAGE_INITIALIZE = CHILD_MESSAGE_INITIALIZE; +const CHILD_MESSAGE_CALL = 1; +exports.CHILD_MESSAGE_CALL = CHILD_MESSAGE_CALL; +const CHILD_MESSAGE_END = 2; +exports.CHILD_MESSAGE_END = CHILD_MESSAGE_END; +const CHILD_MESSAGE_MEM_USAGE = 3; +exports.CHILD_MESSAGE_MEM_USAGE = CHILD_MESSAGE_MEM_USAGE; +const PARENT_MESSAGE_OK = 0; +exports.PARENT_MESSAGE_OK = PARENT_MESSAGE_OK; +const PARENT_MESSAGE_CLIENT_ERROR = 1; +exports.PARENT_MESSAGE_CLIENT_ERROR = PARENT_MESSAGE_CLIENT_ERROR; +const PARENT_MESSAGE_SETUP_ERROR = 2; +exports.PARENT_MESSAGE_SETUP_ERROR = PARENT_MESSAGE_SETUP_ERROR; +const PARENT_MESSAGE_CUSTOM = 3; +exports.PARENT_MESSAGE_CUSTOM = PARENT_MESSAGE_CUSTOM; +const PARENT_MESSAGE_MEM_USAGE = 4; +exports.PARENT_MESSAGE_MEM_USAGE = PARENT_MESSAGE_MEM_USAGE; +let WorkerStates; +exports.WorkerStates = WorkerStates; + +(function (WorkerStates) { + WorkerStates['STARTING'] = 'starting'; + WorkerStates['OK'] = 'ok'; + WorkerStates['OUT_OF_MEMORY'] = 'oom'; + WorkerStates['RESTARTING'] = 'restarting'; + WorkerStates['SHUTTING_DOWN'] = 'shutting-down'; + WorkerStates['SHUT_DOWN'] = 'shut-down'; +})(WorkerStates || (exports.WorkerStates = WorkerStates = {})); + +let WorkerEvents; +exports.WorkerEvents = WorkerEvents; + +(function (WorkerEvents) { + WorkerEvents['STATE_CHANGE'] = 'state-change'; +})(WorkerEvents || (exports.WorkerEvents = WorkerEvents = {})); diff --git a/node_modules/jest-worker/build/workers/ChildProcessWorker.js b/node_modules/jest-worker/build/workers/ChildProcessWorker.js new file mode 100644 index 0000000..8165460 --- /dev/null +++ b/node_modules/jest-worker/build/workers/ChildProcessWorker.js @@ -0,0 +1,534 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = exports.SIGKILL_DELAY = void 0; + +function _child_process() { + const data = require('child_process'); + + _child_process = function () { + return data; + }; + + return data; +} + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +function _mergeStream() { + const data = _interopRequireDefault(require('merge-stream')); + + _mergeStream = function () { + return data; + }; + + return data; +} + +function _supportsColor() { + const data = require('supports-color'); + + _supportsColor = function () { + return data; + }; + + return data; +} + +var _types = require('../types'); + +var _WorkerAbstract = _interopRequireDefault(require('./WorkerAbstract')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const SIGNAL_BASE_EXIT_CODE = 128; +const SIGKILL_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 9; +const SIGTERM_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 15; // How long to wait after SIGTERM before sending SIGKILL + +const SIGKILL_DELAY = 500; +/** + * This class wraps the child process and provides a nice interface to + * communicate with. It takes care of: + * + * - Re-spawning the process if it dies. + * - Queues calls while the worker is busy. + * - Re-sends the requests if the worker blew up. + * + * The reason for queueing them here (since childProcess.send also has an + * internal queue) is because the worker could be doing asynchronous work, and + * this would lead to the child process to read its receiving buffer and start a + * second call. By queueing calls here, we don't send the next call to the + * children until we receive the result of the previous one. + * + * As soon as a request starts to be processed by a worker, its "processed" + * field is changed to "true", so that other workers which might encounter the + * same call skip it. + */ + +exports.SIGKILL_DELAY = SIGKILL_DELAY; + +class ChildProcessWorker extends _WorkerAbstract.default { + _child; + _options; + _request; + _retries; + _onProcessEnd; + _onCustomMessage; + _stdout; + _stderr; + _stderrBuffer = []; + _memoryUsagePromise; + _resolveMemoryUsage; + _childIdleMemoryUsage; + _childIdleMemoryUsageLimit; + _memoryUsageCheck = false; + _childWorkerPath; + + constructor(options) { + super(options); + this._options = options; + this._request = null; + this._stdout = null; + this._stderr = null; + this._childIdleMemoryUsage = null; + this._childIdleMemoryUsageLimit = options.idleMemoryLimit || null; + this._childWorkerPath = + options.childWorkerPath || require.resolve('./processChild'); + this.state = _types.WorkerStates.STARTING; + this.initialize(); + } + + initialize() { + if ( + this.state === _types.WorkerStates.OUT_OF_MEMORY || + this.state === _types.WorkerStates.SHUTTING_DOWN || + this.state === _types.WorkerStates.SHUT_DOWN + ) { + return; + } + + if (this._child && this._child.connected) { + this._child.kill('SIGKILL'); + } + + this.state = _types.WorkerStates.STARTING; + const forceColor = _supportsColor().stdout + ? { + FORCE_COLOR: '1' + } + : {}; + const silent = this._options.silent ?? true; + + if (!silent) { + // NOTE: Detecting an out of memory crash is independent of idle memory usage monitoring. We want to + // monitor for a crash occurring so that it can be handled as required and so we can tell the difference + // between an OOM crash and another kind of crash. We need to do this because if a worker crashes due to + // an OOM event sometimes it isn't seen by the worker pool and it just sits there waiting for the worker + // to respond and it never will. + console.warn('Unable to detect out of memory event if silent === false'); + } + + this._stderrBuffer = []; + const options = { + cwd: process.cwd(), + env: { + ...process.env, + JEST_WORKER_ID: String(this._options.workerId + 1), + // 0-indexed workerId, 1-indexed JEST_WORKER_ID + ...forceColor + }, + // Suppress --debug / --inspect flags while preserving others (like --harmony). + execArgv: process.execArgv.filter(v => !/^--(debug|inspect)/.test(v)), + // default to advanced serialization in order to match worker threads + serialization: 'advanced', + silent, + ...this._options.forkOptions + }; + this._child = (0, _child_process().fork)( + this._childWorkerPath, + [], + options + ); + + if (this._child.stdout) { + if (!this._stdout) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stdout = (0, _mergeStream().default)(this._getFakeStream()); + } + + this._stdout.add(this._child.stdout); + } + + if (this._child.stderr) { + if (!this._stderr) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stderr = (0, _mergeStream().default)(this._getFakeStream()); + } + + this._stderr.add(this._child.stderr); + + this._child.stderr.on('data', this.stderrDataHandler.bind(this)); + } + + this._child.on('message', this._onMessage.bind(this)); + + this._child.on('exit', this._onExit.bind(this)); + + this._child.on('disconnect', this._onDisconnect.bind(this)); + + this._child.send([ + _types.CHILD_MESSAGE_INITIALIZE, + false, + this._options.workerPath, + this._options.setupArgs + ]); + + this._retries++; // If we exceeded the amount of retries, we will emulate an error reply + // coming from the child. This avoids code duplication related with cleaning + // the queue, and scheduling the next call. + + if (this._retries > this._options.maxRetries) { + const error = new Error( + `Jest worker encountered ${this._retries} child process exceptions, exceeding retry limit` + ); + + this._onMessage([ + _types.PARENT_MESSAGE_CLIENT_ERROR, + error.name, + error.message, + error.stack, + { + type: 'WorkerError' + } + ]); // Clear the request so we don't keep executing it. + + this._request = null; + } + + this.state = _types.WorkerStates.OK; + + if (this._resolveWorkerReady) { + this._resolveWorkerReady(); + } + } + + stderrDataHandler(chunk) { + if (chunk) { + this._stderrBuffer.push(Buffer.from(chunk)); + } + + this._detectOutOfMemoryCrash(); + + if (this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + this.killChild(); + + this._shutdown(); + } + } + + _detectOutOfMemoryCrash() { + try { + const bufferStr = Buffer.concat(this._stderrBuffer).toString('utf8'); + + if ( + bufferStr.includes('heap out of memory') || + bufferStr.includes('allocation failure;') || + bufferStr.includes('Last few GCs') + ) { + if ( + this.state === _types.WorkerStates.OK || + this.state === _types.WorkerStates.STARTING + ) { + this.state = _types.WorkerStates.OUT_OF_MEMORY; + } + } + } catch (err) { + console.error('Error looking for out of memory crash', err); + } + } + + _onDisconnect() { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + + this._detectOutOfMemoryCrash(); + + if (this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this.killChild(); + + this._shutdown(); + } + } + + _onMessage(response) { + // TODO: Add appropriate type check + let error; + + switch (response[0]) { + case _types.PARENT_MESSAGE_OK: + this._onProcessEnd(null, response[1]); + + break; + + case _types.PARENT_MESSAGE_CLIENT_ERROR: + error = response[4]; + + if (error != null && typeof error === 'object') { + const extra = error; // @ts-expect-error: no index + + const NativeCtor = globalThis[response[1]]; + const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error; + error = new Ctor(response[2]); + error.type = response[1]; + error.stack = response[3]; + + for (const key in extra) { + error[key] = extra[key]; + } + } + + this._onProcessEnd(error, null); + + break; + + case _types.PARENT_MESSAGE_SETUP_ERROR: + error = new Error(`Error when calling setup: ${response[2]}`); + error.type = response[1]; + error.stack = response[3]; + + this._onProcessEnd(error, null); + + break; + + case _types.PARENT_MESSAGE_CUSTOM: + this._onCustomMessage(response[1]); + + break; + + case _types.PARENT_MESSAGE_MEM_USAGE: + this._childIdleMemoryUsage = response[1]; + + if (this._resolveMemoryUsage) { + this._resolveMemoryUsage(response[1]); + + this._resolveMemoryUsage = undefined; + this._memoryUsagePromise = undefined; + } + + this._performRestartIfRequired(); + + break; + + default: + throw new TypeError(`Unexpected response from worker: ${response[0]}`); + } + } + + _performRestartIfRequired() { + if (this._memoryUsageCheck) { + this._memoryUsageCheck = false; + let limit = this._childIdleMemoryUsageLimit; // TODO: At some point it would make sense to make use of + // stringToBytes found in jest-config, however as this + // package does not have any dependencies on an other jest + // packages that can wait until some other time. + + if (limit && limit > 0 && limit <= 1) { + limit = Math.floor((0, _os().totalmem)() * limit); + } else if (limit) { + limit = Math.floor(limit); + } + + if ( + limit && + this._childIdleMemoryUsage && + this._childIdleMemoryUsage > limit + ) { + this.state = _types.WorkerStates.RESTARTING; + this.killChild(); + } + } + } + + _onExit(exitCode) { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + + this._detectOutOfMemoryCrash(); + + if (exitCode !== 0 && this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this._onProcessEnd( + new Error('Jest worker ran out of memory and crashed'), + null + ); + + this._shutdown(); + } else if ( + (exitCode !== 0 && + exitCode !== null && + exitCode !== SIGTERM_EXIT_CODE && + exitCode !== SIGKILL_EXIT_CODE && + this.state !== _types.WorkerStates.SHUTTING_DOWN) || + this.state === _types.WorkerStates.RESTARTING + ) { + this.state = _types.WorkerStates.RESTARTING; + this.initialize(); + + if (this._request) { + this._child.send(this._request); + } + } else { + this._shutdown(); + } + } + + send(request, onProcessStart, onProcessEnd, onCustomMessage) { + this._stderrBuffer = []; + onProcessStart(this); + + this._onProcessEnd = (...args) => { + const hasRequest = !!this._request; // Clean the request to avoid sending past requests to workers that fail + // while waiting for a new request (timers, unhandled rejections...) + + this._request = null; + + if ( + this._childIdleMemoryUsageLimit && + this._child.connected && + hasRequest + ) { + this.checkMemoryUsage(); + } + + return onProcessEnd(...args); + }; + + this._onCustomMessage = (...arg) => onCustomMessage(...arg); + + this._request = request; + this._retries = 0; // eslint-disable-next-line @typescript-eslint/no-empty-function + + this._child.send(request, () => {}); + } + + waitForExit() { + return this._exitPromise; + } + + killChild() { + // We store a reference so that there's no way we can accidentally + // kill a new worker that has been spawned. + const childToKill = this._child; + childToKill.kill('SIGTERM'); + return setTimeout(() => childToKill.kill('SIGKILL'), SIGKILL_DELAY); + } + + forceExit() { + this.state = _types.WorkerStates.SHUTTING_DOWN; + const sigkillTimeout = this.killChild(); + + this._exitPromise.then(() => clearTimeout(sigkillTimeout)); + } + + getWorkerId() { + return this._options.workerId; + } + /** + * Gets the process id of the worker. + * + * @returns Process id. + */ + + getWorkerSystemId() { + return this._child.pid; + } + + getStdout() { + return this._stdout; + } + + getStderr() { + return this._stderr; + } + /** + * Gets the last reported memory usage. + * + * @returns Memory usage in bytes. + */ + + getMemoryUsage() { + if (!this._memoryUsagePromise) { + let rejectCallback; + const promise = new Promise((resolve, reject) => { + this._resolveMemoryUsage = resolve; + rejectCallback = reject; + }); + this._memoryUsagePromise = promise; + + if (!this._child.connected && rejectCallback) { + rejectCallback(new Error('Child process is not running.')); + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + return promise; + } + + this._child.send([_types.CHILD_MESSAGE_MEM_USAGE], err => { + if (err && rejectCallback) { + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + rejectCallback(err); + } + }); + + return promise; + } + + return this._memoryUsagePromise; + } + /** + * Gets updated memory usage and restarts if required + */ + + checkMemoryUsage() { + if (this._childIdleMemoryUsageLimit) { + this._memoryUsageCheck = true; + + this._child.send([_types.CHILD_MESSAGE_MEM_USAGE], err => { + if (err) { + console.error('Unable to check memory usage', err); + } + }); + } else { + console.warn( + 'Memory usage of workers can only be checked if a limit is set' + ); + } + } + + isWorkerRunning() { + return this._child.connected && !this._child.killed; + } +} + +exports.default = ChildProcessWorker; diff --git a/node_modules/jest-worker/build/workers/NodeThreadsWorker.js b/node_modules/jest-worker/build/workers/NodeThreadsWorker.js new file mode 100644 index 0000000..a01902d --- /dev/null +++ b/node_modules/jest-worker/build/workers/NodeThreadsWorker.js @@ -0,0 +1,414 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _os() { + const data = require('os'); + + _os = function () { + return data; + }; + + return data; +} + +function _worker_threads() { + const data = require('worker_threads'); + + _worker_threads = function () { + return data; + }; + + return data; +} + +function _mergeStream() { + const data = _interopRequireDefault(require('merge-stream')); + + _mergeStream = function () { + return data; + }; + + return data; +} + +var _types = require('../types'); + +var _WorkerAbstract = _interopRequireDefault(require('./WorkerAbstract')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class ExperimentalWorker extends _WorkerAbstract.default { + _worker; + _options; + _request; + _retries; + _onProcessEnd; + _onCustomMessage; + _stdout; + _stderr; + _memoryUsagePromise; + _resolveMemoryUsage; + _childWorkerPath; + _childIdleMemoryUsage; + _childIdleMemoryUsageLimit; + _memoryUsageCheck = false; + + constructor(options) { + super(options); + this._options = options; + this._request = null; + this._stdout = null; + this._stderr = null; + this._childWorkerPath = + options.childWorkerPath || require.resolve('./threadChild'); + this._childIdleMemoryUsage = null; + this._childIdleMemoryUsageLimit = options.idleMemoryLimit || null; + this.initialize(); + } + + initialize() { + if ( + this.state === _types.WorkerStates.OUT_OF_MEMORY || + this.state === _types.WorkerStates.SHUTTING_DOWN || + this.state === _types.WorkerStates.SHUT_DOWN + ) { + return; + } + + if (this._worker) { + this._worker.terminate(); + } + + this.state = _types.WorkerStates.STARTING; + this._worker = new (_worker_threads().Worker)(this._childWorkerPath, { + eval: false, + resourceLimits: this._options.resourceLimits, + stderr: true, + stdout: true, + workerData: this._options.workerData, + ...this._options.forkOptions + }); + + if (this._worker.stdout) { + if (!this._stdout) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stdout = (0, _mergeStream().default)(this._getFakeStream()); + } + + this._stdout.add(this._worker.stdout); + } + + if (this._worker.stderr) { + if (!this._stderr) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stderr = (0, _mergeStream().default)(this._getFakeStream()); + } + + this._stderr.add(this._worker.stderr); + } // This can be useful for debugging. + + if (!(this._options.silent ?? true)) { + this._worker.stdout.setEncoding('utf8'); // eslint-disable-next-line no-console + + this._worker.stdout.on('data', console.log); + + this._worker.stderr.setEncoding('utf8'); + + this._worker.stderr.on('data', console.error); + } + + this._worker.on('message', this._onMessage.bind(this)); + + this._worker.on('exit', this._onExit.bind(this)); + + this._worker.on('error', this._onError.bind(this)); + + this._worker.postMessage([ + _types.CHILD_MESSAGE_INITIALIZE, + false, + this._options.workerPath, + this._options.setupArgs, + String(this._options.workerId + 1) // 0-indexed workerId, 1-indexed JEST_WORKER_ID + ]); + + this._retries++; // If we exceeded the amount of retries, we will emulate an error reply + // coming from the child. This avoids code duplication related with cleaning + // the queue, and scheduling the next call. + + if (this._retries > this._options.maxRetries) { + const error = new Error('Call retries were exceeded'); + + this._onMessage([ + _types.PARENT_MESSAGE_CLIENT_ERROR, + error.name, + error.message, + error.stack, + { + type: 'WorkerError' + } + ]); + } + + this.state = _types.WorkerStates.OK; + + if (this._resolveWorkerReady) { + this._resolveWorkerReady(); + } + } + + _onError(error) { + if (error.message.includes('heap out of memory')) { + this.state = _types.WorkerStates.OUT_OF_MEMORY; // Threads don't behave like processes, they don't crash when they run out of + // memory. But for consistency we want them to behave like processes so we call + // terminate to simulate a crash happening that was not planned + + this._worker.terminate(); + } + } + + _onMessage(response) { + let error; + + switch (response[0]) { + case _types.PARENT_MESSAGE_OK: + this._onProcessEnd(null, response[1]); + + break; + + case _types.PARENT_MESSAGE_CLIENT_ERROR: + error = response[4]; + + if (error != null && typeof error === 'object') { + const extra = error; // @ts-expect-error: no index + + const NativeCtor = globalThis[response[1]]; + const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error; + error = new Ctor(response[2]); + error.type = response[1]; + error.stack = response[3]; + + for (const key in extra) { + // @ts-expect-error: no index + error[key] = extra[key]; + } + } + + this._onProcessEnd(error, null); + + break; + + case _types.PARENT_MESSAGE_SETUP_ERROR: + error = new Error(`Error when calling setup: ${response[2]}`); // @ts-expect-error: adding custom properties to errors. + + error.type = response[1]; + error.stack = response[3]; + + this._onProcessEnd(error, null); + + break; + + case _types.PARENT_MESSAGE_CUSTOM: + this._onCustomMessage(response[1]); + + break; + + case _types.PARENT_MESSAGE_MEM_USAGE: + this._childIdleMemoryUsage = response[1]; + + if (this._resolveMemoryUsage) { + this._resolveMemoryUsage(response[1]); + + this._resolveMemoryUsage = undefined; + this._memoryUsagePromise = undefined; + } + + this._performRestartIfRequired(); + + break; + + default: + throw new TypeError(`Unexpected response from worker: ${response[0]}`); + } + } + + _onExit(exitCode) { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + + if (exitCode !== 0 && this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this._onProcessEnd( + new Error('Jest worker ran out of memory and crashed'), + null + ); + + this._shutdown(); + } else if ( + (exitCode !== 0 && + this.state !== _types.WorkerStates.SHUTTING_DOWN && + this.state !== _types.WorkerStates.SHUT_DOWN) || + this.state === _types.WorkerStates.RESTARTING + ) { + this.initialize(); + + if (this._request) { + this._worker.postMessage(this._request); + } + } else { + this._shutdown(); + } + } + + waitForExit() { + return this._exitPromise; + } + + forceExit() { + this.state = _types.WorkerStates.SHUTTING_DOWN; + + this._worker.terminate(); + } + + send(request, onProcessStart, onProcessEnd, onCustomMessage) { + onProcessStart(this); + + this._onProcessEnd = (...args) => { + const hasRequest = !!this._request; // Clean the request to avoid sending past requests to workers that fail + // while waiting for a new request (timers, unhandled rejections...) + + this._request = null; + + if (this._childIdleMemoryUsageLimit && hasRequest) { + this.checkMemoryUsage(); + } + + const res = onProcessEnd?.(...args); // Clean up the reference so related closures can be garbage collected. + + onProcessEnd = null; + return res; + }; + + this._onCustomMessage = (...arg) => onCustomMessage(...arg); + + this._request = request; + this._retries = 0; + + this._worker.postMessage(request); + } + + getWorkerId() { + return this._options.workerId; + } + + getStdout() { + return this._stdout; + } + + getStderr() { + return this._stderr; + } + + _performRestartIfRequired() { + if (this._memoryUsageCheck) { + this._memoryUsageCheck = false; + let limit = this._childIdleMemoryUsageLimit; // TODO: At some point it would make sense to make use of + // stringToBytes found in jest-config, however as this + // package does not have any dependencies on an other jest + // packages that can wait until some other time. + + if (limit && limit > 0 && limit <= 1) { + limit = Math.floor((0, _os().totalmem)() * limit); + } else if (limit) { + limit = Math.floor(limit); + } + + if ( + limit && + this._childIdleMemoryUsage && + this._childIdleMemoryUsage > limit + ) { + this.state = _types.WorkerStates.RESTARTING; + + this._worker.terminate(); + } + } + } + /** + * Gets the last reported memory usage. + * + * @returns Memory usage in bytes. + */ + + getMemoryUsage() { + if (!this._memoryUsagePromise) { + let rejectCallback; + const promise = new Promise((resolve, reject) => { + this._resolveMemoryUsage = resolve; + rejectCallback = reject; + }); + this._memoryUsagePromise = promise; + + if (!this._worker.threadId) { + rejectCallback(new Error('Child process is not running.')); + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + return promise; + } + + try { + this._worker.postMessage([_types.CHILD_MESSAGE_MEM_USAGE]); + } catch (err) { + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + rejectCallback(err); + } + + return promise; + } + + return this._memoryUsagePromise; + } + /** + * Gets updated memory usage and restarts if required + */ + + checkMemoryUsage() { + if (this._childIdleMemoryUsageLimit) { + this._memoryUsageCheck = true; + + this._worker.postMessage([_types.CHILD_MESSAGE_MEM_USAGE]); + } else { + console.warn( + 'Memory usage of workers can only be checked if a limit is set' + ); + } + } + /** + * Gets the thread id of the worker. + * + * @returns Thread id. + */ + + getWorkerSystemId() { + return this._worker.threadId; + } + + isWorkerRunning() { + return this._worker.threadId >= 0; + } +} + +exports.default = ExperimentalWorker; diff --git a/node_modules/jest-worker/build/workers/WorkerAbstract.js b/node_modules/jest-worker/build/workers/WorkerAbstract.js new file mode 100644 index 0000000..3b2ba3a --- /dev/null +++ b/node_modules/jest-worker/build/workers/WorkerAbstract.js @@ -0,0 +1,156 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _stream() { + const data = require('stream'); + + _stream = function () { + return data; + }; + + return data; +} + +var _types = require('../types'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class WorkerAbstract extends _stream().EventEmitter { + /** + * DO NOT WRITE TO THIS DIRECTLY. + * Use this.state getter/setters so events are emitted correctly. + */ + #state = _types.WorkerStates.STARTING; + _fakeStream = null; + _exitPromise; + _resolveExitPromise; + _workerReadyPromise; + _resolveWorkerReady; + + get state() { + return this.#state; + } + + set state(value) { + if (this.#state !== value) { + const oldState = this.#state; + this.#state = value; + this.emit(_types.WorkerEvents.STATE_CHANGE, value, oldState); + } + } + + constructor(options) { + super(); + + if (typeof options.on === 'object') { + for (const [event, handlers] of Object.entries(options.on)) { + // Can't do Array.isArray on a ReadonlyArray. + // https://github.com/microsoft/TypeScript/issues/17002 + if (typeof handlers === 'function') { + super.on(event, handlers); + } else { + for (const handler of handlers) { + super.on(event, handler); + } + } + } + } + + this._exitPromise = new Promise(resolve => { + this._resolveExitPromise = resolve; + }); + + this._exitPromise.then(() => { + this.state = _types.WorkerStates.SHUT_DOWN; + }); + } + /** + * Wait for the worker child process to be ready to handle requests. + * + * @returns Promise which resolves when ready. + */ + + waitForWorkerReady() { + if (!this._workerReadyPromise) { + this._workerReadyPromise = new Promise((resolve, reject) => { + let settled = false; + let to; + + switch (this.state) { + case _types.WorkerStates.OUT_OF_MEMORY: + case _types.WorkerStates.SHUTTING_DOWN: + case _types.WorkerStates.SHUT_DOWN: + settled = true; + reject( + new Error( + `Worker state means it will never be ready: ${this.state}` + ) + ); + break; + + case _types.WorkerStates.STARTING: + case _types.WorkerStates.RESTARTING: + this._resolveWorkerReady = () => { + settled = true; + resolve(); + + if (to) { + clearTimeout(to); + } + }; + + break; + + case _types.WorkerStates.OK: + settled = true; + resolve(); + break; + } + + if (!settled) { + to = setTimeout(() => { + if (!settled) { + reject(new Error('Timeout starting worker')); + } + }, 500); + } + }); + } + + return this._workerReadyPromise; + } + /** + * Used to shut down the current working instance once the children have been + * killed off. + */ + + _shutdown() { + this.state === _types.WorkerStates.SHUT_DOWN; // End the permanent stream so the merged stream end too + + if (this._fakeStream) { + this._fakeStream.end(); + + this._fakeStream = null; + } + + this._resolveExitPromise(); + } + + _getFakeStream() { + if (!this._fakeStream) { + this._fakeStream = new (_stream().PassThrough)(); + } + + return this._fakeStream; + } +} + +exports.default = WorkerAbstract; diff --git a/node_modules/jest-worker/build/workers/messageParent.js b/node_modules/jest-worker/build/workers/messageParent.js new file mode 100644 index 0000000..11a77f7 --- /dev/null +++ b/node_modules/jest-worker/build/workers/messageParent.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = messageParent; + +function _worker_threads() { + const data = require('worker_threads'); + + _worker_threads = function () { + return data; + }; + + return data; +} + +var _types = require('../types'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function messageParent(message, parentProcess = process) { + if (!_worker_threads().isMainThread && _worker_threads().parentPort != null) { + _worker_threads().parentPort.postMessage([ + _types.PARENT_MESSAGE_CUSTOM, + message + ]); + } else if (typeof parentProcess.send === 'function') { + parentProcess.send([_types.PARENT_MESSAGE_CUSTOM, message]); + } else { + throw new Error('"messageParent" can only be used inside a worker'); + } +} diff --git a/node_modules/jest-worker/build/workers/processChild.js b/node_modules/jest-worker/build/workers/processChild.js new file mode 100644 index 0000000..0164072 --- /dev/null +++ b/node_modules/jest-worker/build/workers/processChild.js @@ -0,0 +1,161 @@ +'use strict'; + +var _types = require('../types'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +let file = null; +let setupArgs = []; +let initialized = false; +/** + * This file is a small bootstrapper for workers. It sets up the communication + * between the worker and the parent process, interpreting parent messages and + * sending results back. + * + * The file loaded will be lazily initialized the first time any of the workers + * is called. This is done for optimal performance: if the farm is initialized, + * but no call is made to it, child Node processes will be consuming the least + * possible amount of memory. + * + * If an invalid message is detected, the child will exit (by throwing) with a + * non-zero exit code. + */ + +const messageListener = request => { + switch (request[0]) { + case _types.CHILD_MESSAGE_INITIALIZE: + const init = request; + file = init[2]; + setupArgs = request[3]; + break; + + case _types.CHILD_MESSAGE_CALL: + const call = request; + execMethod(call[2], call[3]); + break; + + case _types.CHILD_MESSAGE_END: + end(); + break; + + case _types.CHILD_MESSAGE_MEM_USAGE: + reportMemoryUsage(); + break; + + default: + throw new TypeError( + `Unexpected request from parent process: ${request[0]}` + ); + } +}; + +process.on('message', messageListener); + +function reportSuccess(result) { + if (!process || !process.send) { + throw new Error('Child can only be used on a forked process'); + } + + process.send([_types.PARENT_MESSAGE_OK, result]); +} + +function reportClientError(error) { + return reportError(error, _types.PARENT_MESSAGE_CLIENT_ERROR); +} + +function reportInitializeError(error) { + return reportError(error, _types.PARENT_MESSAGE_SETUP_ERROR); +} + +function reportMemoryUsage() { + if (!process || !process.send) { + throw new Error('Child can only be used on a forked process'); + } + + const msg = [_types.PARENT_MESSAGE_MEM_USAGE, process.memoryUsage().heapUsed]; + process.send(msg); +} + +function reportError(error, type) { + if (!process || !process.send) { + throw new Error('Child can only be used on a forked process'); + } + + if (error == null) { + error = new Error('"null" or "undefined" thrown'); + } + + process.send([ + type, + error.constructor && error.constructor.name, + error.message, + error.stack, + typeof error === 'object' ? {...error} : error + ]); +} + +function end() { + const main = require(file); + + if (!main.teardown) { + exitProcess(); + return; + } + + execFunction(main.teardown, main, [], exitProcess, exitProcess); +} + +function exitProcess() { + // Clean up open handles so the process ideally exits gracefully + process.removeListener('message', messageListener); +} + +function execMethod(method, args) { + const main = require(file); + + let fn; + + if (method === 'default') { + fn = main.__esModule ? main['default'] : main; + } else { + fn = main[method]; + } + + function execHelper() { + execFunction(fn, main, args, reportSuccess, reportClientError); + } + + if (initialized || !main.setup) { + execHelper(); + return; + } + + initialized = true; + execFunction(main.setup, main, setupArgs, execHelper, reportInitializeError); +} + +const isPromise = obj => + !!obj && + (typeof obj === 'object' || typeof obj === 'function') && + typeof obj.then === 'function'; + +function execFunction(fn, ctx, args, onResult, onError) { + let result; + + try { + result = fn.apply(ctx, args); + } catch (err) { + onError(err); + return; + } + + if (isPromise(result)) { + result.then(onResult, onError); + } else { + onResult(result); + } +} diff --git a/node_modules/jest-worker/build/workers/threadChild.js b/node_modules/jest-worker/build/workers/threadChild.js new file mode 100644 index 0000000..7431bcf --- /dev/null +++ b/node_modules/jest-worker/build/workers/threadChild.js @@ -0,0 +1,173 @@ +'use strict'; + +function _worker_threads() { + const data = require('worker_threads'); + + _worker_threads = function () { + return data; + }; + + return data; +} + +var _types = require('../types'); + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +let file = null; +let setupArgs = []; +let initialized = false; +/** + * This file is a small bootstrapper for workers. It sets up the communication + * between the worker and the parent process, interpreting parent messages and + * sending results back. + * + * The file loaded will be lazily initialized the first time any of the workers + * is called. This is done for optimal performance: if the farm is initialized, + * but no call is made to it, child Node processes will be consuming the least + * possible amount of memory. + * + * If an invalid message is detected, the child will exit (by throwing) with a + * non-zero exit code. + */ + +const messageListener = request => { + switch (request[0]) { + case _types.CHILD_MESSAGE_INITIALIZE: + const init = request; + file = init[2]; + setupArgs = request[3]; + process.env.JEST_WORKER_ID = request[4]; + break; + + case _types.CHILD_MESSAGE_CALL: + const call = request; + execMethod(call[2], call[3]); + break; + + case _types.CHILD_MESSAGE_END: + end(); + break; + + case _types.CHILD_MESSAGE_MEM_USAGE: + reportMemoryUsage(); + break; + + default: + throw new TypeError( + `Unexpected request from parent process: ${request[0]}` + ); + } +}; + +_worker_threads().parentPort.on('message', messageListener); + +function reportMemoryUsage() { + if (_worker_threads().isMainThread) { + throw new Error('Child can only be used on a forked process'); + } + + const msg = [_types.PARENT_MESSAGE_MEM_USAGE, process.memoryUsage().heapUsed]; + + _worker_threads().parentPort.postMessage(msg); +} + +function reportSuccess(result) { + if (_worker_threads().isMainThread) { + throw new Error('Child can only be used on a forked process'); + } + + _worker_threads().parentPort.postMessage([_types.PARENT_MESSAGE_OK, result]); +} + +function reportClientError(error) { + return reportError(error, _types.PARENT_MESSAGE_CLIENT_ERROR); +} + +function reportInitializeError(error) { + return reportError(error, _types.PARENT_MESSAGE_SETUP_ERROR); +} + +function reportError(error, type) { + if (_worker_threads().isMainThread) { + throw new Error('Child can only be used on a forked process'); + } + + if (error == null) { + error = new Error('"null" or "undefined" thrown'); + } + + _worker_threads().parentPort.postMessage([ + type, + error.constructor && error.constructor.name, + error.message, + error.stack, + typeof error === 'object' ? {...error} : error + ]); +} + +function end() { + const main = require(file); + + if (!main.teardown) { + exitProcess(); + return; + } + + execFunction(main.teardown, main, [], exitProcess, exitProcess); +} + +function exitProcess() { + // Clean up open handles so the worker ideally exits gracefully + _worker_threads().parentPort.removeListener('message', messageListener); +} + +function execMethod(method, args) { + const main = require(file); + + let fn; + + if (method === 'default') { + fn = main.__esModule ? main['default'] : main; + } else { + fn = main[method]; + } + + function execHelper() { + execFunction(fn, main, args, reportSuccess, reportClientError); + } + + if (initialized || !main.setup) { + execHelper(); + return; + } + + initialized = true; + execFunction(main.setup, main, setupArgs, execHelper, reportInitializeError); +} + +const isPromise = obj => + !!obj && + (typeof obj === 'object' || typeof obj === 'function') && + typeof obj.then === 'function'; + +function execFunction(fn, ctx, args, onResult, onError) { + let result; + + try { + result = fn.apply(ctx, args); + } catch (err) { + onError(err); + return; + } + + if (isPromise(result)) { + result.then(onResult, onError); + } else { + onResult(result); + } +} diff --git a/node_modules/jest-worker/node_modules/supports-color/browser.js b/node_modules/jest-worker/node_modules/supports-color/browser.js new file mode 100644 index 0000000..f097aec --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/browser.js @@ -0,0 +1,24 @@ +/* eslint-env browser */ +'use strict'; + +function getChromeVersion() { + const matches = /(Chrome|Chromium)\/(?\d+)\./.exec(navigator.userAgent); + + if (!matches) { + return; + } + + return Number.parseInt(matches.groups.chromeVersion, 10); +} + +const colorSupport = getChromeVersion() >= 69 ? { + level: 1, + hasBasic: true, + has256: false, + has16m: false +} : false; + +module.exports = { + stdout: colorSupport, + stderr: colorSupport +}; diff --git a/node_modules/jest-worker/node_modules/supports-color/index.js b/node_modules/jest-worker/node_modules/supports-color/index.js new file mode 100644 index 0000000..2dd2fcb --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/index.js @@ -0,0 +1,152 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let flagForceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + flagForceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + flagForceColor = 1; +} + +function envForceColor() { + if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + return 1; + } + + if (env.FORCE_COLOR === 'false') { + return 0; + } + + return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + + if (forceColor === 0) { + return 0; + } + + if (sniffFlags) { + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream, options = {}) { + const level = supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options + }); + + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel({isTTY: tty.isatty(1)}), + stderr: getSupportLevel({isTTY: tty.isatty(2)}) +}; diff --git a/node_modules/jest-worker/node_modules/supports-color/license b/node_modules/jest-worker/node_modules/supports-color/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jest-worker/node_modules/supports-color/package.json b/node_modules/jest-worker/node_modules/supports-color/package.json new file mode 100644 index 0000000..2131c4c --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/package.json @@ -0,0 +1,90 @@ +{ + "_from": "supports-color@^8.0.0", + "_id": "supports-color@8.1.1", + "_inBundle": false, + "_integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "_location": "/jest-worker/supports-color", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "supports-color@^8.0.0", + "name": "supports-color", + "escapedName": "supports-color", + "rawSpec": "^8.0.0", + "saveSpec": null, + "fetchSpec": "^8.0.0" + }, + "_requiredBy": [ + "/jest-worker" + ], + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "_shasum": "cd6fc17e28500cff56c1b86c0a7fd4a54a73005c", + "_spec": "supports-color@^8.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest-worker", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/chalk/supports-color/issues" + }, + "bundleDependencies": false, + "dependencies": { + "has-flag": "^4.0.0" + }, + "deprecated": false, + "description": "Detect whether a terminal supports color", + "devDependencies": { + "ava": "^2.4.0", + "import-fresh": "^3.2.2", + "xo": "^0.35.0" + }, + "engines": { + "node": ">=10" + }, + "exports": { + "node": "./index.js", + "default": "./browser.js" + }, + "files": [ + "index.js", + "browser.js" + ], + "funding": "https://github.com/chalk/supports-color?sponsor=1", + "homepage": "https://github.com/chalk/supports-color#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "license": "MIT", + "name": "supports-color", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/supports-color.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "8.1.1" +} diff --git a/node_modules/jest-worker/node_modules/supports-color/readme.md b/node_modules/jest-worker/node_modules/supports-color/readme.md new file mode 100644 index 0000000..3eedd1c --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/readme.md @@ -0,0 +1,77 @@ +# supports-color + +> Detect whether a terminal supports color + +## Install + +``` +$ npm install supports-color +``` + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + +### `require('supports-color').supportsColor(stream, options?)` + +Additionally, `supports-color` exposes the `.supportsColor()` function that takes an arbitrary write stream (e.g. `process.stdout`) and an optional options object to (re-)evaluate color support for an arbitrary stream. + +For example, `require('supports-color').stdout` is the equivalent of `require('supports-color').supportsColor(process.stdout)`. + +The options object supports a single boolean property `sniffFlags`. By default it is `true`, which instructs `supportsColor()` to sniff `process.argv` for the multitude of `--color` flags (see _Info_ below). If `false`, then `process.argv` is not considered when determining color support. + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- diff --git a/node_modules/jest-worker/package.json b/node_modules/jest-worker/package.json new file mode 100644 index 0000000..0111d19 --- /dev/null +++ b/node_modules/jest-worker/package.json @@ -0,0 +1,74 @@ +{ + "_from": "jest-worker@^29.0.1", + "_id": "jest-worker@29.0.1", + "_inBundle": false, + "_integrity": "sha512-+B/2/8WW7goit7qVezG9vnI1QP3dlmuzi2W0zxazAQQ8dcDIA63dDn6j4pjOGBARha/ZevcwYQtNIzCySbS7fQ==", + "_location": "/jest-worker", + "_phantomChildren": { + "has-flag": "4.0.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-worker@^29.0.1", + "name": "jest-worker", + "escapedName": "jest-worker", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/@jest/reporters", + "/jest-haste-map", + "/jest-runner" + ], + "_resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.0.1.tgz", + "_shasum": "fb42ff7e05e0573f330ec0cf781fc545dcd11a31", + "_spec": "jest-worker@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@jest/reporters", + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "deprecated": false, + "description": "Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers.", + "devDependencies": { + "@tsd/typescript": "~4.7.4", + "@types/merge-stream": "^1.1.2", + "@types/supports-color": "^8.1.0", + "get-stream": "^6.0.0", + "jest-leak-detector": "^29.0.1", + "tsd-lite": "^0.6.0", + "worker-farm": "^1.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://github.com/facebook/jest#readme", + "license": "MIT", + "main": "./build/index.js", + "name": "jest-worker", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-worker" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest/LICENSE b/node_modules/jest/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest/README.md b/node_modules/jest/README.md new file mode 100644 index 0000000..9c3d31e --- /dev/null +++ b/node_modules/jest/README.md @@ -0,0 +1,11 @@ +# Jest + +🃏 Delightful JavaScript Testing + +- **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project. + +- **🏃🏽 Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files. + +- **📸 Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing) of React trees or other serializable values to simplify UI testing. + +Read More: https://jestjs.io/ diff --git a/node_modules/jest/bin/jest.js b/node_modules/jest/bin/jest.js new file mode 100755 index 0000000..4a82888 --- /dev/null +++ b/node_modules/jest/bin/jest.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const importLocal = require('import-local'); + +if (!importLocal(__filename)) { + require('jest-cli/bin/jest'); +} diff --git a/node_modules/jest/build/index.d.ts b/node_modules/jest/build/index.d.ts new file mode 100644 index 0000000..da6592c --- /dev/null +++ b/node_modules/jest/build/index.d.ts @@ -0,0 +1,26 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config as Config_2} from '@jest/types'; +import {createTestScheduler} from '@jest/core'; +import {getVersion} from '@jest/core'; +import {run} from 'jest-cli'; +import {runCLI} from '@jest/core'; +import {SearchSource} from '@jest/core'; + +export declare type Config = Config_2.InitialOptions; + +export {createTestScheduler}; + +export {getVersion}; + +export {run}; + +export {runCLI}; + +export {SearchSource}; + +export {}; diff --git a/node_modules/jest/build/index.js b/node_modules/jest/build/index.js new file mode 100644 index 0000000..860bb4c --- /dev/null +++ b/node_modules/jest/build/index.js @@ -0,0 +1,55 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'SearchSource', { + enumerable: true, + get: function () { + return _core().SearchSource; + } +}); +Object.defineProperty(exports, 'createTestScheduler', { + enumerable: true, + get: function () { + return _core().createTestScheduler; + } +}); +Object.defineProperty(exports, 'getVersion', { + enumerable: true, + get: function () { + return _core().getVersion; + } +}); +Object.defineProperty(exports, 'run', { + enumerable: true, + get: function () { + return _jestCli().run; + } +}); +Object.defineProperty(exports, 'runCLI', { + enumerable: true, + get: function () { + return _core().runCLI; + } +}); + +function _core() { + const data = require('@jest/core'); + + _core = function () { + return data; + }; + + return data; +} + +function _jestCli() { + const data = require('jest-cli'); + + _jestCli = function () { + return data; + }; + + return data; +} diff --git a/node_modules/jest/node_modules/.bin/jest b/node_modules/jest/node_modules/.bin/jest new file mode 120000 index 0000000..3d9fe5c --- /dev/null +++ b/node_modules/jest/node_modules/.bin/jest @@ -0,0 +1 @@ +../jest-cli/bin/jest.js \ No newline at end of file diff --git a/node_modules/jest/node_modules/jest-cli/LICENSE b/node_modules/jest/node_modules/jest-cli/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/jest/node_modules/jest-cli/README.md b/node_modules/jest/node_modules/jest-cli/README.md new file mode 100644 index 0000000..9c3d31e --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/README.md @@ -0,0 +1,11 @@ +# Jest + +🃏 Delightful JavaScript Testing + +- **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project. + +- **🏃🏽 Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files. + +- **📸 Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing) of React trees or other serializable values to simplify UI testing. + +Read More: https://jestjs.io/ diff --git a/node_modules/jest/node_modules/jest-cli/bin/jest.js b/node_modules/jest/node_modules/jest-cli/bin/jest.js new file mode 100755 index 0000000..146fb2c --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/bin/jest.js @@ -0,0 +1,17 @@ +#!/usr/bin/env node +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const importLocal = require('import-local'); + +if (!importLocal(__filename)) { + if (process.env.NODE_ENV == null) { + process.env.NODE_ENV = 'test'; + } + + require('..').run(); +} diff --git a/node_modules/jest/node_modules/jest-cli/build/cli/args.js b/node_modules/jest/node_modules/jest-cli/build/cli/args.js new file mode 100644 index 0000000..d9fff6d --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/cli/args.js @@ -0,0 +1,716 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.check = check; +exports.usage = exports.options = exports.docs = void 0; + +function _jestConfig() { + const data = require('jest-config'); + + _jestConfig = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +function check(argv) { + if ( + argv.runInBand && + Object.prototype.hasOwnProperty.call(argv, 'maxWorkers') + ) { + throw new Error( + 'Both --runInBand and --maxWorkers were specified, but these two ' + + 'options do not make sense together. Which is it?' + ); + } + + for (const key of [ + 'onlyChanged', + 'lastCommit', + 'changedFilesWithAncestor', + 'changedSince' + ]) { + if (argv[key] && argv.watchAll) { + throw new Error( + `Both --${key} and --watchAll were specified, but these two ` + + 'options do not make sense together. Try the --watch option which ' + + 'reruns only tests related to changed files.' + ); + } + } + + if (argv.onlyFailures && argv.watchAll) { + throw new Error( + 'Both --onlyFailures and --watchAll were specified, but these two ' + + 'options do not make sense together.' + ); + } + + if (argv.findRelatedTests && argv._.length === 0) { + throw new Error( + 'The --findRelatedTests option requires file paths to be specified.\n' + + 'Example usage: jest --findRelatedTests ./src/source.js ' + + './src/index.js.' + ); + } + + if ( + Object.prototype.hasOwnProperty.call(argv, 'maxWorkers') && + argv.maxWorkers === undefined + ) { + throw new Error( + 'The --maxWorkers (-w) option requires a number or string to be specified.\n' + + 'Example usage: jest --maxWorkers 2\n' + + 'Example usage: jest --maxWorkers 50%\n' + + 'Or did you mean --watch?' + ); + } + + if (argv.selectProjects && argv.selectProjects.length === 0) { + throw new Error( + 'The --selectProjects option requires the name of at least one project to be specified.\n' + + 'Example usage: jest --selectProjects my-first-project my-second-project' + ); + } + + if (argv.ignoreProjects && argv.ignoreProjects.length === 0) { + throw new Error( + 'The --ignoreProjects option requires the name of at least one project to be specified.\n' + + 'Example usage: jest --ignoreProjects my-first-project my-second-project' + ); + } + + if ( + argv.config && + !(0, _jestConfig().isJSONString)(argv.config) && + !argv.config.match( + new RegExp( + `\\.(${_jestConfig() + .constants.JEST_CONFIG_EXT_ORDER.map(e => e.substring(1)) + .join('|')})$`, + 'i' + ) + ) + ) { + throw new Error( + `The --config option requires a JSON string literal, or a file path with one of these extensions: ${_jestConfig().constants.JEST_CONFIG_EXT_ORDER.join( + ', ' + )}.\nExample usage: jest --config ./jest.config.js` + ); + } + + return true; +} + +const usage = 'Usage: $0 [--config=] [TestPathPattern]'; +exports.usage = usage; +const docs = 'Documentation: https://jestjs.io/'; // The default values are all set in jest-config + +exports.docs = docs; +const options = { + all: { + description: + 'The opposite of `onlyChanged`. If `onlyChanged` is set by ' + + 'default, running jest with `--all` will force Jest to run all tests ' + + 'instead of running only tests related to changed files.', + type: 'boolean' + }, + automock: { + description: 'Automock all files by default.', + type: 'boolean' + }, + bail: { + alias: 'b', + description: + 'Exit the test suite immediately after `n` number of failing tests.', + type: 'boolean' + }, + cache: { + description: + 'Whether to use the transform cache. Disable the cache ' + + 'using --no-cache.', + type: 'boolean' + }, + cacheDirectory: { + description: + 'The directory where Jest should store its cached ' + + ' dependency information.', + type: 'string' + }, + changedFilesWithAncestor: { + description: + 'Runs tests related to the current changes and the changes made in the ' + + 'last commit. Behaves similarly to `--onlyChanged`.', + type: 'boolean' + }, + changedSince: { + description: + 'Runs tests related to the changes since the provided branch. If the ' + + 'current branch has diverged from the given branch, then only changes ' + + 'made locally will be tested. Behaves similarly to `--onlyChanged`.', + nargs: 1, + type: 'string' + }, + ci: { + description: + 'Whether to run Jest in continuous integration (CI) mode. ' + + 'This option is on by default in most popular CI environments. It will ' + + 'prevent snapshots from being written unless explicitly requested.', + type: 'boolean' + }, + clearCache: { + description: + 'Clears the configured Jest cache directory and then exits. ' + + 'Default directory can be found by calling jest --showConfig', + type: 'boolean' + }, + clearMocks: { + description: + 'Automatically clear mock calls, instances, contexts and results before every test. ' + + 'Equivalent to calling jest.clearAllMocks() before each test.', + type: 'boolean' + }, + collectCoverage: { + description: 'Alias for --coverage.', + type: 'boolean' + }, + collectCoverageFrom: { + description: + 'A glob pattern relative to matching the files that coverage ' + + 'info needs to be collected from.', + type: 'string' + }, + color: { + description: + 'Forces test results output color highlighting (even if ' + + 'stdout is not a TTY). Set to false if you would like to have no colors.', + type: 'boolean' + }, + colors: { + description: 'Alias for `--color`.', + type: 'boolean' + }, + config: { + alias: 'c', + description: + 'The path to a jest config file specifying how to find ' + + 'and execute tests. If no rootDir is set in the config, the directory ' + + 'containing the config file is assumed to be the rootDir for the project. ' + + 'This can also be a JSON encoded value which Jest will use as configuration.', + type: 'string' + }, + coverage: { + description: + 'Indicates that test coverage information should be ' + + 'collected and reported in the output.', + type: 'boolean' + }, + coverageDirectory: { + description: 'The directory where Jest should output its coverage files.', + type: 'string' + }, + coveragePathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all file paths before executing the test. If the file path ' + + 'matches any of the patterns, coverage information will be skipped.', + string: true, + type: 'array' + }, + coverageProvider: { + choices: ['babel', 'v8'], + description: 'Select between Babel and V8 to collect coverage' + }, + coverageReporters: { + description: + 'A list of reporter names that Jest uses when writing ' + + 'coverage reports. Any istanbul reporter can be used.', + string: true, + type: 'array' + }, + coverageThreshold: { + description: + 'A JSON string with which will be used to configure ' + + 'minimum threshold enforcement for coverage results', + type: 'string' + }, + debug: { + description: 'Print debugging info about your jest config.', + type: 'boolean' + }, + detectLeaks: { + description: + '**EXPERIMENTAL**: Detect memory leaks in tests. After executing a ' + + 'test, it will try to garbage collect the global object used, and fail ' + + 'if it was leaked', + type: 'boolean' + }, + detectOpenHandles: { + description: + 'Print out remaining open handles preventing Jest from exiting at the ' + + 'end of a test run. Implies `runInBand`.', + type: 'boolean' + }, + env: { + description: + 'The test environment used for all tests. This can point to ' + + 'any file or node module. Examples: `jsdom`, `node` or ' + + '`path/to/my-environment.js`', + type: 'string' + }, + errorOnDeprecated: { + description: 'Make calling deprecated APIs throw helpful error messages.', + type: 'boolean' + }, + expand: { + alias: 'e', + description: 'Use this flag to show full diffs instead of a patch.', + type: 'boolean' + }, + filter: { + description: + 'Path to a module exporting a filtering function. This method receives ' + + 'a list of tests which can be manipulated to exclude tests from ' + + 'running. Especially useful when used in conjunction with a testing ' + + 'infrastructure to filter known broken tests.', + type: 'string' + }, + findRelatedTests: { + description: + 'Find related tests for a list of source files that were ' + + 'passed in as arguments. Useful for pre-commit hook integration to run ' + + 'the minimal amount of tests necessary.', + type: 'boolean' + }, + forceExit: { + description: + 'Force Jest to exit after all tests have completed running. ' + + 'This is useful when resources set up by test code cannot be ' + + 'adequately cleaned up.', + type: 'boolean' + }, + globalSetup: { + description: 'The path to a module that runs before All Tests.', + type: 'string' + }, + globalTeardown: { + description: 'The path to a module that runs after All Tests.', + type: 'string' + }, + globals: { + description: + 'A JSON string with map of global variables that need ' + + 'to be available in all test environments.', + type: 'string' + }, + haste: { + description: + 'A JSON string with map of variables for the haste module system', + type: 'string' + }, + ignoreProjects: { + description: + 'Ignore the tests of the specified projects. ' + + 'Jest uses the attribute `displayName` in the configuration to identify each project.', + string: true, + type: 'array' + }, + init: { + description: 'Generate a basic configuration file', + type: 'boolean' + }, + injectGlobals: { + description: 'Should Jest inject global variables or not', + type: 'boolean' + }, + json: { + description: + 'Prints the test results in JSON. This mode will send all ' + + 'other test output and user messages to stderr.', + type: 'boolean' + }, + lastCommit: { + description: + 'Run all tests affected by file changes in the last commit made. ' + + 'Behaves similarly to `--onlyChanged`.', + type: 'boolean' + }, + listTests: { + description: + 'Lists all tests Jest will run given the arguments and ' + + 'exits. Most useful in a CI system together with `--findRelatedTests` ' + + 'to determine the tests Jest will run based on specific files', + type: 'boolean' + }, + logHeapUsage: { + description: + 'Logs the heap usage after every test. Useful to debug ' + + 'memory leaks. Use together with `--runInBand` and `--expose-gc` in ' + + 'node.', + type: 'boolean' + }, + maxConcurrency: { + description: + 'Specifies the maximum number of tests that are allowed to run ' + + 'concurrently. This only affects tests using `test.concurrent`.', + type: 'number' + }, + maxWorkers: { + alias: 'w', + description: + 'Specifies the maximum number of workers the worker-pool ' + + 'will spawn for running tests. This defaults to the number of the ' + + 'cores available on your machine. (its usually best not to override ' + + 'this default)', + type: 'string' + }, + moduleDirectories: { + description: + 'An array of directory names to be searched recursively ' + + "up from the requiring module's location.", + string: true, + type: 'array' + }, + moduleFileExtensions: { + description: + 'An array of file extensions your modules use. If you ' + + 'require modules without specifying a file extension, these are the ' + + 'extensions Jest will look for.', + string: true, + type: 'array' + }, + moduleNameMapper: { + description: + 'A JSON string with a map from regular expressions to ' + + 'module names or to arrays of module names that allow to stub ' + + 'out resources, like images or styles with a single module', + type: 'string' + }, + modulePathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all module paths before those paths are to be considered ' + + '"visible" to the module loader.', + string: true, + type: 'array' + }, + modulePaths: { + description: + 'An alternative API to setting the NODE_PATH env variable, ' + + 'modulePaths is an array of absolute paths to additional locations to ' + + 'search when resolving modules.', + string: true, + type: 'array' + }, + noStackTrace: { + description: 'Disables stack trace in test results output', + type: 'boolean' + }, + notify: { + description: 'Activates notifications for test results.', + type: 'boolean' + }, + notifyMode: { + description: 'Specifies when notifications will appear for test results.', + type: 'string' + }, + onlyChanged: { + alias: 'o', + description: + 'Attempts to identify which tests to run based on which ' + + "files have changed in the current repository. Only works if you're " + + 'running tests in a git or hg repository at the moment.', + type: 'boolean' + }, + onlyFailures: { + alias: 'f', + description: 'Run tests that failed in the previous execution.', + type: 'boolean' + }, + outputFile: { + description: + 'Write test results to a file when the --json option is ' + + 'also specified.', + type: 'string' + }, + passWithNoTests: { + description: + 'Will not fail if no tests are found (for example while using `--testPathPattern`.)', + type: 'boolean' + }, + preset: { + description: "A preset that is used as a base for Jest's configuration.", + type: 'string' + }, + prettierPath: { + description: 'The path to the "prettier" module used for inline snapshots.', + type: 'string' + }, + projects: { + description: + 'A list of projects that use Jest to run all tests of all ' + + 'projects in a single instance of Jest.', + string: true, + type: 'array' + }, + reporters: { + description: 'A list of custom reporters for the test suite.', + string: true, + type: 'array' + }, + resetMocks: { + description: + 'Automatically reset mock state before every test. ' + + 'Equivalent to calling jest.resetAllMocks() before each test.', + type: 'boolean' + }, + resetModules: { + description: + 'If enabled, the module registry for every test file will ' + + 'be reset before running each individual test.', + type: 'boolean' + }, + resolver: { + description: 'A JSON string which allows the use of a custom resolver.', + type: 'string' + }, + restoreMocks: { + description: + 'Automatically restore mock state and implementation before every test. ' + + 'Equivalent to calling jest.restoreAllMocks() before each test.', + type: 'boolean' + }, + rootDir: { + description: + 'The root directory that Jest should scan for tests and ' + + 'modules within.', + type: 'string' + }, + roots: { + description: + 'A list of paths to directories that Jest should use to ' + + 'search for files in.', + string: true, + type: 'array' + }, + runInBand: { + alias: 'i', + description: + 'Run all tests serially in the current process (rather than ' + + 'creating a worker pool of child processes that run tests). This ' + + 'is sometimes useful for debugging, but such use cases are pretty ' + + 'rare.', + type: 'boolean' + }, + runTestsByPath: { + description: + 'Used when provided patterns are exact file paths. This avoids ' + + 'converting them into a regular expression and matching it against ' + + 'every single file.', + type: 'boolean' + }, + runner: { + description: + "Allows to use a custom runner instead of Jest's default test runner.", + type: 'string' + }, + selectProjects: { + description: + 'Run the tests of the specified projects. ' + + 'Jest uses the attribute `displayName` in the configuration to identify each project.', + string: true, + type: 'array' + }, + setupFiles: { + description: + 'A list of paths to modules that run some code to configure or ' + + 'set up the testing environment before each test.', + string: true, + type: 'array' + }, + setupFilesAfterEnv: { + description: + 'A list of paths to modules that run some code to configure or ' + + 'set up the testing framework before each test', + string: true, + type: 'array' + }, + shard: { + description: + 'Shard tests and execute only the selected shard, specify in ' + + 'the form "current/all". 1-based, for example "3/5".', + type: 'string' + }, + showConfig: { + description: 'Print your jest config and then exits.', + type: 'boolean' + }, + silent: { + description: 'Prevent tests from printing messages through the console.', + type: 'boolean' + }, + skipFilter: { + description: + 'Disables the filter provided by --filter. Useful for CI jobs, or ' + + 'local enforcement when fixing tests.', + type: 'boolean' + }, + snapshotSerializers: { + description: + 'A list of paths to snapshot serializer modules Jest should ' + + 'use for snapshot testing.', + string: true, + type: 'array' + }, + testEnvironment: { + description: 'Alias for --env', + type: 'string' + }, + testEnvironmentOptions: { + description: + 'A JSON string with options that will be passed to the `testEnvironment`. ' + + 'The relevant options depend on the environment.', + type: 'string' + }, + testFailureExitCode: { + description: 'Exit code of `jest` command if the test run failed', + type: 'string' // number + }, + testLocationInResults: { + description: 'Add `location` information to the test results', + type: 'boolean' + }, + testMatch: { + description: 'The glob patterns Jest uses to detect test files.', + string: true, + type: 'array' + }, + testNamePattern: { + alias: 't', + description: 'Run only tests with a name that matches the regex pattern.', + type: 'string' + }, + testPathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all test paths before executing the test. If the test path ' + + 'matches any of the patterns, it will be skipped.', + string: true, + type: 'array' + }, + testPathPattern: { + description: + 'A regexp pattern string that is matched against all tests ' + + 'paths before executing the test.', + string: true, + type: 'array' + }, + testRegex: { + description: + 'A string or array of string regexp patterns that Jest uses to detect test files.', + string: true, + type: 'array' + }, + testResultsProcessor: { + description: + 'Allows the use of a custom results processor. ' + + 'This processor must be a node module that exports ' + + 'a function expecting as the first argument the result object.', + type: 'string' + }, + testRunner: { + description: + 'Allows to specify a custom test runner. The default is' + + ' `jest-circus/runner`. A path to a custom test runner can be provided:' + + ' `/path/to/testRunner.js`.', + type: 'string' + }, + testSequencer: { + description: + 'Allows to specify a custom test sequencer. The default is ' + + '`@jest/test-sequencer`. A path to a custom test sequencer can be ' + + 'provided: `/path/to/testSequencer.js`', + type: 'string' + }, + testTimeout: { + description: 'This option sets the default timeouts of test cases.', + type: 'number' + }, + transform: { + description: + 'A JSON string which maps from regular expressions to paths ' + + 'to transformers.', + type: 'string' + }, + transformIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all source file paths before transformation.', + string: true, + type: 'array' + }, + unmockedModulePathPatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all modules before the module loader will automatically ' + + 'return a mock for them.', + string: true, + type: 'array' + }, + updateSnapshot: { + alias: 'u', + description: + 'Use this flag to re-record snapshots. ' + + 'Can be used together with a test suite pattern or with ' + + '`--testNamePattern` to re-record snapshot for test matching ' + + 'the pattern', + type: 'boolean' + }, + useStderr: { + description: 'Divert all output to stderr.', + type: 'boolean' + }, + verbose: { + description: + 'Display individual test results with the test suite hierarchy.', + type: 'boolean' + }, + watch: { + description: + 'Watch files for changes and rerun tests related to ' + + 'changed files. If you want to re-run all tests when a file has ' + + 'changed, use the `--watchAll` option.', + type: 'boolean' + }, + watchAll: { + description: + 'Watch files for changes and rerun all tests. If you want ' + + 'to re-run only the tests related to the changed files, use the ' + + '`--watch` option.', + type: 'boolean' + }, + watchPathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all paths before trigger test re-run in watch mode. ' + + 'If the test path matches any of the patterns, it will be skipped.', + string: true, + type: 'array' + }, + watchman: { + description: + 'Whether to use watchman for file crawling. Disable using ' + + '--no-watchman.', + type: 'boolean' + } +}; +exports.options = options; diff --git a/node_modules/jest/node_modules/jest-cli/build/cli/index.js b/node_modules/jest/node_modules/jest-cli/build/cli/index.js new file mode 100644 index 0000000..6b4b810 --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/cli/index.js @@ -0,0 +1,264 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.buildArgv = buildArgv; +exports.run = run; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function _exit() { + const data = _interopRequireDefault(require('exit')); + + _exit = function () { + return data; + }; + + return data; +} + +function _yargs() { + const data = _interopRequireDefault(require('yargs')); + + _yargs = function () { + return data; + }; + + return data; +} + +function _core() { + const data = require('@jest/core'); + + _core = function () { + return data; + }; + + return data; +} + +function _jestConfig() { + const data = require('jest-config'); + + _jestConfig = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +function _jestValidate() { + const data = require('jest-validate'); + + _jestValidate = function () { + return data; + }; + + return data; +} + +var _init = _interopRequireDefault(require('../init')); + +var args = _interopRequireWildcard(require('./args')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +async function run(maybeArgv, project) { + try { + const argv = await buildArgv(maybeArgv); + + if (argv.init) { + await (0, _init.default)(); + return; + } + + const projects = getProjectListFromCLIArgs(argv, project); + const {results, globalConfig} = await (0, _core().runCLI)(argv, projects); + readResultsAndExit(results, globalConfig); + } catch (error) { + (0, _jestUtil().clearLine)(process.stderr); + (0, _jestUtil().clearLine)(process.stdout); + + if (error?.stack) { + console.error(_chalk().default.red(error.stack)); + } else { + console.error(_chalk().default.red(error)); + } + + (0, _exit().default)(1); + throw error; + } +} + +async function buildArgv(maybeArgv) { + const version = + (0, _core().getVersion)() + + (__dirname.includes(`packages${path().sep}jest-cli`) ? '-dev' : ''); + const rawArgv = maybeArgv || process.argv.slice(2); + const argv = await (0, _yargs().default)(rawArgv) + .usage(args.usage) + .version(version) + .alias('help', 'h') + .options(args.options) + .epilogue(args.docs) + .check(args.check).argv; + (0, _jestValidate().validateCLIOptions)( + argv, + {...args.options, deprecationEntries: _jestConfig().deprecationEntries}, // strip leading dashes + Array.isArray(rawArgv) + ? rawArgv.map(rawArgv => rawArgv.replace(/^--?/, '')) + : Object.keys(rawArgv) + ); // strip dashed args + + return Object.keys(argv).reduce( + (result, key) => { + if (!key.includes('-')) { + result[key] = argv[key]; + } + + return result; + }, + { + $0: argv.$0, + _: argv._ + } + ); +} + +const getProjectListFromCLIArgs = (argv, project) => { + const projects = argv.projects ? argv.projects : []; + + if (project) { + projects.push(project); + } + + if (!projects.length && process.platform === 'win32') { + try { + projects.push((0, _jestUtil().tryRealpath)(process.cwd())); + } catch { + // do nothing, just catch error + // process.binding('fs').realpath can throw, e.g. on mapped drives + } + } + + if (!projects.length) { + projects.push(process.cwd()); + } + + return projects; +}; + +const readResultsAndExit = (result, globalConfig) => { + const code = !result || result.success ? 0 : globalConfig.testFailureExitCode; // Only exit if needed + + process.on('exit', () => { + if (typeof code === 'number' && code !== 0) { + process.exitCode = code; + } + }); + + if (globalConfig.forceExit) { + if (!globalConfig.detectOpenHandles) { + console.warn( + `${_chalk().default.bold( + 'Force exiting Jest: ' + )}Have you considered using \`--detectOpenHandles\` to detect ` + + 'async operations that kept running after all tests finished?' + ); + } + + (0, _exit().default)(code); + } else if (!globalConfig.detectOpenHandles) { + setTimeout(() => { + console.warn( + _chalk().default.yellow.bold( + 'Jest did not exit one second after the test run has completed.\n\n' + ) + + _chalk().default.yellow( + 'This usually means that there are asynchronous operations that ' + + "weren't stopped in your tests. Consider running Jest with " + + '`--detectOpenHandles` to troubleshoot this issue.' + ) + ); + }, 1000).unref(); + } +}; diff --git a/node_modules/jest/node_modules/jest-cli/build/index.d.ts b/node_modules/jest/node_modules/jest-cli/build/index.d.ts new file mode 100644 index 0000000..2e38204 --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/index.d.ts @@ -0,0 +1,12 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare function run( + maybeArgv?: Array, + project?: string, +): Promise; + +export {}; diff --git a/node_modules/jest/node_modules/jest-cli/build/index.js b/node_modules/jest/node_modules/jest-cli/build/index.js new file mode 100644 index 0000000..fdfb92e --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/index.js @@ -0,0 +1,13 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'run', { + enumerable: true, + get: function () { + return _cli.run; + } +}); + +var _cli = require('./cli'); diff --git a/node_modules/jest/node_modules/jest-cli/build/init/errors.js b/node_modules/jest/node_modules/jest-cli/build/init/errors.js new file mode 100644 index 0000000..340522c --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/init/errors.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.NotFoundPackageJsonError = exports.MalformedPackageJsonError = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +class NotFoundPackageJsonError extends Error { + constructor(rootDir) { + super(`Could not find a "package.json" file in ${rootDir}`); + this.name = ''; // eslint-disable-next-line @typescript-eslint/no-empty-function + + Error.captureStackTrace(this, () => {}); + } +} + +exports.NotFoundPackageJsonError = NotFoundPackageJsonError; + +class MalformedPackageJsonError extends Error { + constructor(packageJsonPath) { + super( + `There is malformed json in ${packageJsonPath}\n` + + 'Fix it, and then run "jest --init"' + ); + this.name = ''; // eslint-disable-next-line @typescript-eslint/no-empty-function + + Error.captureStackTrace(this, () => {}); + } +} + +exports.MalformedPackageJsonError = MalformedPackageJsonError; diff --git a/node_modules/jest/node_modules/jest-cli/build/init/generateConfigFile.js b/node_modules/jest/node_modules/jest-cli/build/init/generateConfigFile.js new file mode 100644 index 0000000..e553d11 --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/init/generateConfigFile.js @@ -0,0 +1,98 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +function _jestConfig() { + const data = require('jest-config'); + + _jestConfig = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const stringifyOption = (option, map, linePrefix = '') => { + const optionDescription = ` // ${_jestConfig().descriptions[option]}`; + const stringifiedObject = `${option}: ${JSON.stringify( + map[option], + null, + 2 + )}`; + return `${optionDescription}\n${stringifiedObject + .split('\n') + .map(line => ` ${linePrefix}${line}`) + .join('\n')},\n`; +}; + +const generateConfigFile = (results, generateEsm = false) => { + const {useTypescript, coverage, coverageProvider, clearMocks, environment} = + results; + const overrides = {}; + + if (coverage) { + Object.assign(overrides, { + collectCoverage: true, + coverageDirectory: 'coverage' + }); + } + + if (coverageProvider === 'v8') { + Object.assign(overrides, { + coverageProvider: 'v8' + }); + } + + if (environment === 'jsdom') { + Object.assign(overrides, { + testEnvironment: 'jsdom' + }); + } + + if (clearMocks) { + Object.assign(overrides, { + clearMocks: true + }); + } + + const overrideKeys = Object.keys(overrides); + const properties = []; + + for (const option in _jestConfig().descriptions) { + const opt = option; + + if (overrideKeys.includes(opt)) { + properties.push(stringifyOption(opt, overrides)); + } else { + properties.push(stringifyOption(opt, _jestConfig().defaults, '// ')); + } + } + + const configHeaderMessage = `/* + * For a detailed explanation regarding each configuration property${ + useTypescript ? ' and type check' : '' + }, visit: + * https://jestjs.io/docs/configuration + */ + +`; + return `${ + configHeaderMessage + + (useTypescript || generateEsm + ? 'export default {\n' + : 'module.exports = {\n') + + properties.join('\n') + }};\n`; +}; + +var _default = generateConfigFile; +exports.default = _default; diff --git a/node_modules/jest/node_modules/jest-cli/build/init/index.js b/node_modules/jest/node_modules/jest-cli/build/init/index.js new file mode 100644 index 0000000..839c659 --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/init/index.js @@ -0,0 +1,246 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = init; + +function path() { + const data = _interopRequireWildcard(require('path')); + + path = function () { + return data; + }; + + return data; +} + +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + + _chalk = function () { + return data; + }; + + return data; +} + +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + + fs = function () { + return data; + }; + + return data; +} + +function _prompts() { + const data = _interopRequireDefault(require('prompts')); + + _prompts = function () { + return data; + }; + + return data; +} + +function _jestConfig() { + const data = require('jest-config'); + + _jestConfig = function () { + return data; + }; + + return data; +} + +function _jestUtil() { + const data = require('jest-util'); + + _jestUtil = function () { + return data; + }; + + return data; +} + +var _errors = require('./errors'); + +var _generateConfigFile = _interopRequireDefault( + require('./generateConfigFile') +); + +var _modifyPackageJson = _interopRequireDefault(require('./modifyPackageJson')); + +var _questions = _interopRequireWildcard(require('./questions')); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const { + JEST_CONFIG_BASE_NAME, + JEST_CONFIG_EXT_MJS, + JEST_CONFIG_EXT_JS, + JEST_CONFIG_EXT_TS, + JEST_CONFIG_EXT_ORDER, + PACKAGE_JSON +} = _jestConfig().constants; + +const getConfigFilename = ext => JEST_CONFIG_BASE_NAME + ext; + +async function init(rootDir = (0, _jestUtil().tryRealpath)(process.cwd())) { + // prerequisite checks + const projectPackageJsonPath = path().join(rootDir, PACKAGE_JSON); + + if (!fs().existsSync(projectPackageJsonPath)) { + throw new _errors.NotFoundPackageJsonError(rootDir); + } + + const questions = _questions.default.slice(0); + + let hasJestProperty = false; + let projectPackageJson; + + try { + projectPackageJson = JSON.parse( + fs().readFileSync(projectPackageJsonPath, 'utf-8') + ); + } catch { + throw new _errors.MalformedPackageJsonError(projectPackageJsonPath); + } + + if (projectPackageJson.jest) { + hasJestProperty = true; + } + + const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext => + fs().existsSync(path().join(rootDir, getConfigFilename(ext))) + ); + + if (hasJestProperty || existingJestConfigExt) { + const result = await (0, _prompts().default)({ + initial: true, + message: + 'It seems that you already have a jest configuration, do you want to override it?', + name: 'continue', + type: 'confirm' + }); + + if (!result.continue) { + console.log(); + console.log('Aborting...'); + return; + } + } // Add test script installation only if needed + + if ( + !projectPackageJson.scripts || + projectPackageJson.scripts.test !== 'jest' + ) { + questions.unshift(_questions.testScriptQuestion); + } // Start the init process + + console.log(); + console.log( + _chalk().default.underline( + 'The following questions will help Jest to create a suitable configuration for your project\n' + ) + ); + let promptAborted = false; // @ts-expect-error: Return type cannot be object - faulty typings + + const results = await (0, _prompts().default)(questions, { + onCancel: () => { + promptAborted = true; + } + }); + + if (promptAborted) { + console.log(); + console.log('Aborting...'); + return; + } // Determine if Jest should use JS or TS for the config file + + const jestConfigFileExt = results.useTypescript + ? JEST_CONFIG_EXT_TS + : projectPackageJson.type === 'module' + ? JEST_CONFIG_EXT_MJS + : JEST_CONFIG_EXT_JS; // Determine Jest config path + + const jestConfigPath = existingJestConfigExt + ? getConfigFilename(existingJestConfigExt) + : path().join(rootDir, getConfigFilename(jestConfigFileExt)); + const shouldModifyScripts = results.scripts; + + if (shouldModifyScripts || hasJestProperty) { + const modifiedPackageJson = (0, _modifyPackageJson.default)({ + projectPackageJson, + shouldModifyScripts + }); + fs().writeFileSync(projectPackageJsonPath, modifiedPackageJson); + console.log(''); + console.log( + `✏️ Modified ${_chalk().default.cyan(projectPackageJsonPath)}` + ); + } + + const generatedConfig = (0, _generateConfigFile.default)( + results, + projectPackageJson.type === 'module' || + jestConfigPath.endsWith(JEST_CONFIG_EXT_MJS) + ); + fs().writeFileSync(jestConfigPath, generatedConfig); + console.log(''); + console.log( + `📝 Configuration file created at ${_chalk().default.cyan(jestConfigPath)}` + ); +} diff --git a/node_modules/jest/node_modules/jest-cli/build/init/modifyPackageJson.js b/node_modules/jest/node_modules/jest-cli/build/init/modifyPackageJson.js new file mode 100644 index 0000000..3548f0e --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/init/modifyPackageJson.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const modifyPackageJson = ({projectPackageJson, shouldModifyScripts}) => { + if (shouldModifyScripts) { + projectPackageJson.scripts + ? (projectPackageJson.scripts.test = 'jest') + : (projectPackageJson.scripts = { + test: 'jest' + }); + } + + delete projectPackageJson.jest; + return `${JSON.stringify(projectPackageJson, null, 2)}\n`; +}; + +var _default = modifyPackageJson; +exports.default = _default; diff --git a/node_modules/jest/node_modules/jest-cli/build/init/questions.js b/node_modules/jest/node_modules/jest-cli/build/init/questions.js new file mode 100644 index 0000000..966b0cc --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/init/questions.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.testScriptQuestion = exports.default = void 0; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const defaultQuestions = [ + { + initial: false, + message: 'Would you like to use Typescript for the configuration file?', + name: 'useTypescript', + type: 'confirm' + }, + { + choices: [ + { + title: 'node', + value: 'node' + }, + { + title: 'jsdom (browser-like)', + value: 'jsdom' + } + ], + initial: 0, + message: 'Choose the test environment that will be used for testing', + name: 'environment', + type: 'select' + }, + { + initial: false, + message: 'Do you want Jest to add coverage reports?', + name: 'coverage', + type: 'confirm' + }, + { + choices: [ + { + title: 'v8', + value: 'v8' + }, + { + title: 'babel', + value: 'babel' + } + ], + initial: 0, + message: 'Which provider should be used to instrument code for coverage?', + name: 'coverageProvider', + type: 'select' + }, + { + initial: false, + message: + 'Automatically clear mock calls, instances, contexts and results before every test?', + name: 'clearMocks', + type: 'confirm' + } +]; +var _default = defaultQuestions; +exports.default = _default; +const testScriptQuestion = { + initial: true, + message: + 'Would you like to use Jest when running "test" script in "package.json"?', + name: 'scripts', + type: 'confirm' +}; +exports.testScriptQuestion = testScriptQuestion; diff --git a/node_modules/jest/node_modules/jest-cli/build/init/types.js b/node_modules/jest/node_modules/jest-cli/build/init/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/build/init/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest/node_modules/jest-cli/package.json b/node_modules/jest/node_modules/jest-cli/package.json new file mode 100644 index 0000000..a6d96a0 --- /dev/null +++ b/node_modules/jest/node_modules/jest-cli/package.json @@ -0,0 +1,114 @@ +{ + "_from": "jest-cli@^29.0.1", + "_id": "jest-cli@29.0.1", + "_inBundle": false, + "_integrity": "sha512-XozBHtoJCS6mnjCxNESyGm47Y4xSWzNlBJj4tix9nGrG6m068B83lrTWKtjYAenYSfOqyYVpQCkyqUp35IT+qA==", + "_location": "/jest/jest-cli", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jest-cli@^29.0.1", + "name": "jest-cli", + "escapedName": "jest-cli", + "rawSpec": "^29.0.1", + "saveSpec": null, + "fetchSpec": "^29.0.1" + }, + "_requiredBy": [ + "/jest" + ], + "_resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.0.1.tgz", + "_shasum": "6633c2ab97337ac5207910bd6b0aba2ef0900110", + "_spec": "jest-cli@^29.0.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/jest", + "bin": { + "jest": "bin/jest.js" + }, + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/core": "^29.0.1", + "@jest/test-result": "^29.0.1", + "@jest/types": "^29.0.1", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "import-local": "^3.0.2", + "jest-config": "^29.0.1", + "jest-util": "^29.0.1", + "jest-validate": "^29.0.1", + "prompts": "^2.0.1", + "yargs": "^17.3.1" + }, + "deprecated": false, + "description": "Delightful JavaScript Testing.", + "devDependencies": { + "@types/exit": "^0.1.30", + "@types/graceful-fs": "^4.1.3", + "@types/prompts": "^2.0.1", + "@types/yargs": "^17.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json", + "./bin/jest": "./bin/jest.js" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://jestjs.io/", + "keywords": [ + "ava", + "babel", + "coverage", + "easy", + "expect", + "facebook", + "immersive", + "instant", + "jasmine", + "jest", + "jsdom", + "mocha", + "mocking", + "painless", + "qunit", + "runner", + "sandboxed", + "snapshot", + "tap", + "tape", + "test", + "testing", + "typescript", + "watch" + ], + "license": "MIT", + "main": "./build/index.js", + "name": "jest-cli", + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest-cli" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/jest/package.json b/node_modules/jest/package.json new file mode 100644 index 0000000..d4f5292 --- /dev/null +++ b/node_modules/jest/package.json @@ -0,0 +1,118 @@ +{ + "_from": "jest", + "_id": "jest@29.0.1", + "_inBundle": false, + "_integrity": "sha512-liHkwzaW6iwQyhRBFj0A4ZYKcsQ7ers1s62CCT95fPeNzoxT/vQRWwjTT4e7jpSCwrvPP2t1VESuy7GrXcr2ug==", + "_location": "/jest", + "_phantomChildren": { + "@jest/core": "29.0.1", + "@jest/test-result": "29.0.1", + "@jest/types": "29.0.1", + "chalk": "4.1.2", + "exit": "0.1.2", + "graceful-fs": "4.2.10", + "import-local": "3.1.0", + "jest-config": "29.0.1", + "jest-util": "29.0.1", + "jest-validate": "29.0.1", + "prompts": "2.4.2", + "yargs": "17.5.1" + }, + "_requested": { + "type": "tag", + "registry": true, + "raw": "jest", + "name": "jest", + "escapedName": "jest", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#DEV:/", + "#USER" + ], + "_resolved": "https://registry.npmjs.org/jest/-/jest-29.0.1.tgz", + "_shasum": "4a1c48d79fada0a47c686a111ed9411fd41cd584", + "_spec": "jest", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter", + "bin": { + "jest": "bin/jest.js" + }, + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@jest/core": "^29.0.1", + "@jest/types": "^29.0.1", + "import-local": "^3.0.2", + "jest-cli": "^29.0.1" + }, + "deprecated": false, + "description": "Delightful JavaScript Testing.", + "devDependencies": { + "@tsd/typescript": "~4.7.4", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json", + "./bin/jest": "./bin/jest.js" + }, + "gitHead": "b959a3d3bdf324ed1c7358f76ab238a8b0b0cf93", + "homepage": "https://jestjs.io/", + "keywords": [ + "ava", + "babel", + "coverage", + "easy", + "expect", + "facebook", + "immersive", + "instant", + "jasmine", + "jest", + "jsdom", + "mocha", + "mocking", + "painless", + "qunit", + "runner", + "sandboxed", + "snapshot", + "tap", + "tape", + "test", + "testing", + "typescript", + "watch" + ], + "license": "MIT", + "main": "./build/index.js", + "name": "jest", + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/facebook/jest.git", + "directory": "packages/jest" + }, + "types": "./build/index.d.ts", + "version": "29.0.1" +} diff --git a/node_modules/js-tokens/CHANGELOG.md b/node_modules/js-tokens/CHANGELOG.md new file mode 100644 index 0000000..755e6f6 --- /dev/null +++ b/node_modules/js-tokens/CHANGELOG.md @@ -0,0 +1,151 @@ +### Version 4.0.0 (2018-01-28) ### + +- Added: Support for ES2018. The only change needed was recognizing the `s` + regex flag. +- Changed: _All_ tokens returned by the `matchToToken` function now have a + `closed` property. It is set to `undefined` for the tokens where “closed” + doesn’t make sense. This means that all tokens objects have the same shape, + which might improve performance. + +These are the breaking changes: + +- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but + `['/a/s']`. (There are of course other variations of this.) +- Code that rely on some token objects not having the `closed` property could + now behave differently. + + +### Version 3.0.2 (2017-06-28) ### + +- No code changes. Just updates to the readme. + + +### Version 3.0.1 (2017-01-30) ### + +- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched + correctly. + + +### Version 3.0.0 (2017-01-11) ### + +This release contains one breaking change, that should [improve performance in +V8][v8-perf]: + +> So how can you, as a JavaScript developer, ensure that your RegExps are fast? +> If you are not interested in hooking into RegExp internals, make sure that +> neither the RegExp instance, nor its prototype is modified in order to get the +> best performance: +> +> ```js +> var re = /./g; +> re.exec(''); // Fast path. +> re.new_property = 'slow'; +> ``` + +This module used to export a single regex, with `.matchToToken` bolted +on, just like in the above example. This release changes the exports of +the module to avoid this issue. + +Before: + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens") +var matchToToken = jsTokens.matchToToken +``` + +After: + +```js +import jsTokens, {matchToToken} from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +var matchToToken = require("js-tokens").matchToToken +``` + +[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html + + +### Version 2.0.0 (2016-06-19) ### + +- Added: Support for ES2016. In other words, support for the `**` exponentiation + operator. + +These are the breaking changes: + +- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`. +- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`. + + +### Version 1.0.3 (2016-03-27) ### + +- Improved: Made the regex ever so slightly smaller. +- Updated: The readme. + + +### Version 1.0.2 (2015-10-18) ### + +- Improved: Limited npm package contents for a smaller download. Thanks to + @zertosh! + + +### Version 1.0.1 (2015-06-20) ### + +- Fixed: Declared an undeclared variable. + + +### Version 1.0.0 (2015-02-26) ### + +- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That + type is now equivalent to the Punctuator token in the ECMAScript + specification. (Backwards-incompatible change.) +- Fixed: A `-` followed by a number is now correctly matched as a punctuator + followed by a number. It used to be matched as just a number, but there is no + such thing as negative number literals. (Possibly backwards-incompatible + change.) + + +### Version 0.4.1 (2015-02-21) ### + +- Added: Support for the regex `u` flag. + + +### Version 0.4.0 (2015-02-21) ### + +- Improved: `jsTokens.matchToToken` performance. +- Added: Support for octal and binary number literals. +- Added: Support for template strings. + + +### Version 0.3.1 (2015-01-06) ### + +- Fixed: Support for unicode spaces. They used to be allowed in names (which is + very confusing), and some unicode newlines were wrongly allowed in strings and + regexes. + + +### Version 0.3.0 (2014-12-19) ### + +- Changed: The `jsTokens.names` array has been replaced with the + `jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no + longer part of the public API; instead use said function. See this [gist] for + an example. (Backwards-incompatible change.) +- Changed: The empty string is now considered an “invalid” token, instead an + “empty” token (its own group). (Backwards-incompatible change.) +- Removed: component support. (Backwards-incompatible change.) + +[gist]: https://gist.github.com/lydell/be49dbf80c382c473004 + + +### Version 0.2.0 (2014-06-19) ### + +- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own + category (“functionArrow”), for simplicity. (Backwards-incompatible change.) +- Added: ES6 splats (`...`) are now matched as an operator (instead of three + punctuations). (Backwards-incompatible change.) + + +### Version 0.1.0 (2014-03-08) ### + +- Initial release. diff --git a/node_modules/js-tokens/LICENSE b/node_modules/js-tokens/LICENSE new file mode 100644 index 0000000..54aef52 --- /dev/null +++ b/node_modules/js-tokens/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/js-tokens/README.md b/node_modules/js-tokens/README.md new file mode 100644 index 0000000..00cdf16 --- /dev/null +++ b/node_modules/js-tokens/README.md @@ -0,0 +1,240 @@ +Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) +======== + +A regex that tokenizes JavaScript. + +```js +var jsTokens = require("js-tokens").default + +var jsString = "var foo=opts.foo;\n..." + +jsString.match(jsTokens) +// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] +``` + + +Installation +============ + +`npm install js-tokens` + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +``` + + +Usage +===== + +### `jsTokens` ### + +A regex with the `g` flag that matches JavaScript tokens. + +The regex _always_ matches, even invalid JavaScript and the empty string. + +The next match is always directly after the previous. + +### `var token = matchToToken(match)` ### + +```js +import {matchToToken} from "js-tokens" +// or: +var matchToToken = require("js-tokens").matchToToken +``` + +Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: +String, value: String}` object. The following types are available: + +- string +- comment +- regex +- number +- name +- punctuator +- whitespace +- invalid + +Multi-line comments and strings also have a `closed` property indicating if the +token was closed or not (see below). + +Comments and strings both come in several flavors. To distinguish them, check if +the token starts with `//`, `/*`, `'`, `"` or `` ` ``. + +Names are ECMAScript IdentifierNames, that is, including both identifiers and +keywords. You may use [is-keyword-js] to tell them apart. + +Whitespace includes both line terminators and other whitespace. + +[is-keyword-js]: https://github.com/crissdev/is-keyword-js + + +ECMAScript support +================== + +The intention is to always support the latest ECMAScript version whose feature +set has been finalized. + +If adding support for a newer version requires changes, a new version with a +major verion bump will be released. + +Currently, ECMAScript 2018 is supported. + + +Invalid code handling +===================== + +Unterminated strings are still matched as strings. JavaScript strings cannot +contain (unescaped) newlines, so unterminated strings simply end at the end of +the line. Unterminated template strings can contain unescaped newlines, though, +so they go on to the end of input. + +Unterminated multi-line comments are also still matched as comments. They +simply go on to the end of the input. + +Unterminated regex literals are likely matched as division and whatever is +inside the regex. + +Invalid ASCII characters have their own capturing group. + +Invalid non-ASCII characters are treated as names, to simplify the matching of +names (except unicode spaces which are treated as whitespace). Note: See also +the [ES2018](#es2018) section. + +Regex literals may contain invalid regex syntax. They are still matched as +regex literals. They may also contain repeated regex flags, to keep the regex +simple. + +Strings may contain invalid escape sequences. + + +Limitations +=========== + +Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be +perfect. But that’s not the point either. + +You may compare jsTokens with [esprima] by using `esprima-compare.js`. +See `npm run esprima-compare`! + +[esprima]: http://esprima.org/ + +### Template string interpolation ### + +Template strings are matched as single tokens, from the starting `` ` `` to the +ending `` ` ``, including interpolations (whose tokens are not matched +individually). + +Matching template string interpolations requires recursive balancing of `{` and +`}`—something that JavaScript regexes cannot do. Only one level of nesting is +supported. + +### Division and regex literals collision ### + +Consider this example: + +```js +var g = 9.82 +var number = bar / 2/g + +var regex = / 2/g +``` + +A human can easily understand that in the `number` line we’re dealing with +division, and in the `regex` line we’re dealing with a regex literal. How come? +Because humans can look at the whole code to put the `/` characters in context. +A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also +look backwards. See the [ES2018](#es2018) section). + +When the `jsTokens` regex scans throught the above, it will see the following +at the end of both the `number` and `regex` rows: + +```js +/ 2/g +``` + +It is then impossible to know if that is a regex literal, or part of an +expression dealing with division. + +Here is a similar case: + +```js +foo /= 2/g +foo(/= 2/g) +``` + +The first line divides the `foo` variable with `2/g`. The second line calls the +`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only +sees forwards, it cannot tell the two cases apart. + +There are some cases where we _can_ tell division and regex literals apart, +though. + +First off, we have the simple cases where there’s only one slash in the line: + +```js +var foo = 2/g +foo /= 2 +``` + +Regex literals cannot contain newlines, so the above cases are correctly +identified as division. Things are only problematic when there are more than +one non-comment slash in a single line. + +Secondly, not every character is a valid regex flag. + +```js +var number = bar / 2/e +``` + +The above example is also correctly identified as division, because `e` is not a +valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` +(any letter) as flags, but it is not worth it since it increases the amount of +ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are +allowed. This means that the above example will be identified as division as +long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 +characters long. + +Lastly, we can look _forward_ for information. + +- If the token following what looks like a regex literal is not valid after a + regex literal, but is valid in a division expression, then the regex literal + is treated as division instead. For example, a flagless regex cannot be + followed by a string, number or name, but all of those three can be the + denominator of a division. +- Generally, if what looks like a regex literal is followed by an operator, the + regex literal is treated as division instead. This is because regexes are + seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division + could likely be part of such an expression. + +Please consult the regex source and the test cases for precise information on +when regex or division is matched (should you need to know). In short, you +could sum it up as: + +If the end of a statement looks like a regex literal (even if it isn’t), it +will be treated as one. Otherwise it should work as expected (if you write sane +code). + +### ES2018 ### + +ES2018 added some nice regex improvements to the language. + +- [Unicode property escapes] should allow telling names and invalid non-ASCII + characters apart without blowing up the regex size. +- [Lookbehind assertions] should allow matching telling division and regex + literals apart in more cases. +- [Named capture groups] might simplify some things. + +These things would be nice to do, but are not critical. They probably have to +wait until the oldest maintained Node.js LTS release supports those features. + +[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html +[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html +[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html + + +License +======= + +[MIT](LICENSE). diff --git a/node_modules/js-tokens/index.js b/node_modules/js-tokens/index.js new file mode 100644 index 0000000..b23a4a0 --- /dev/null +++ b/node_modules/js-tokens/index.js @@ -0,0 +1,23 @@ +// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell +// License: MIT. (See LICENSE.) + +Object.defineProperty(exports, "__esModule", { + value: true +}) + +// This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g + +exports.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined} + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) + else if (match[ 5]) token.type = "comment" + else if (match[ 6]) token.type = "comment", token.closed = !!match[7] + else if (match[ 8]) token.type = "regex" + else if (match[ 9]) token.type = "number" + else if (match[10]) token.type = "name" + else if (match[11]) token.type = "punctuator" + else if (match[12]) token.type = "whitespace" + return token +} diff --git a/node_modules/js-tokens/package.json b/node_modules/js-tokens/package.json new file mode 100644 index 0000000..0b0bb5f --- /dev/null +++ b/node_modules/js-tokens/package.json @@ -0,0 +1,64 @@ +{ + "_from": "js-tokens@^4.0.0", + "_id": "js-tokens@4.0.0", + "_inBundle": false, + "_integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "_location": "/js-tokens", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "js-tokens@^4.0.0", + "name": "js-tokens", + "escapedName": "js-tokens", + "rawSpec": "^4.0.0", + "saveSpec": null, + "fetchSpec": "^4.0.0" + }, + "_requiredBy": [ + "/@babel/highlight" + ], + "_resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "_shasum": "19203fb59991df98e3a287050d4647cdeaf32499", + "_spec": "js-tokens@^4.0.0", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@babel/highlight", + "author": { + "name": "Simon Lydell" + }, + "bugs": { + "url": "https://github.com/lydell/js-tokens/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A regex that tokenizes JavaScript.", + "devDependencies": { + "coffeescript": "2.1.1", + "esprima": "4.0.0", + "everything.js": "1.0.3", + "mocha": "5.0.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/lydell/js-tokens#readme", + "keywords": [ + "JavaScript", + "js", + "token", + "tokenize", + "regex" + ], + "license": "MIT", + "name": "js-tokens", + "repository": { + "type": "git", + "url": "git+https://github.com/lydell/js-tokens.git" + }, + "scripts": { + "build": "node generate-index.js", + "dev": "npm run build && npm test", + "esprima-compare": "node esprima-compare ./index.js everything.js/es5.js", + "test": "mocha --ui tdd" + }, + "version": "4.0.0" +} diff --git a/node_modules/js-yaml/CHANGELOG.md b/node_modules/js-yaml/CHANGELOG.md new file mode 100644 index 0000000..b4baa4e --- /dev/null +++ b/node_modules/js-yaml/CHANGELOG.md @@ -0,0 +1,557 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [3.14.1] - 2020-12-07 +### Security +- Fix possible code execution in (already unsafe) `.load()` (in &anchor). + + +## [3.14.0] - 2020-05-22 +### Changed +- Support `safe/loadAll(input, options)` variant of call. +- CI: drop outdated nodejs versions. +- Dev deps bump. + +### Fixed +- Quote `=` in plain scalars #519. +- Check the node type for `!` tag in case user manually specifies it. +- Verify that there are no null-bytes in input. +- Fix wrong quote position when writing condensed flow, #526. + + +## [3.13.1] - 2019-04-05 +### Security +- Fix possible code execution in (already unsafe) `.load()`, #480. + + +## [3.13.0] - 2019-03-20 +### Security +- Security fix: `safeLoad()` can hang when arrays with nested refs + used as key. Now throws exception for nested arrays. #475. + + +## [3.12.2] - 2019-02-26 +### Fixed +- Fix `noArrayIndent` option for root level, #468. + + +## [3.12.1] - 2019-01-05 +### Added +- Added `noArrayIndent` option, #432. + + +## [3.12.0] - 2018-06-02 +### Changed +- Support arrow functions without a block statement, #421. + + +## [3.11.0] - 2018-03-05 +### Added +- Add arrow functions suport for `!!js/function`. + +### Fixed +- Fix dump in bin/octal/hex formats for negative integers, #399. + + +## [3.10.0] - 2017-09-10 +### Fixed +- Fix `condenseFlow` output (quote keys for sure, instead of spaces), #371, #370. +- Dump astrals as codepoints instead of surrogate pair, #368. + + +## [3.9.1] - 2017-07-08 +### Fixed +- Ensure stack is present for custom errors in node 7.+, #351. + + +## [3.9.0] - 2017-07-08 +### Added +- Add `condenseFlow` option (to create pretty URL query params), #346. + +### Fixed +- Support array return from safeLoadAll/loadAll, #350. + + +## [3.8.4] - 2017-05-08 +### Fixed +- Dumper: prevent space after dash for arrays that wrap, #343. + + +## [3.8.3] - 2017-04-05 +### Fixed +- Should not allow numbers to begin and end with underscore, #335. + + +## [3.8.2] - 2017-03-02 +### Fixed +- Fix `!!float 123` (integers) parse, #333. +- Don't allow leading zeros in floats (except 0, 0.xxx). +- Allow positive exponent without sign in floats. + + +## [3.8.1] - 2017-02-07 +### Changed +- Maintenance: update browserified build. + + +## [3.8.0] - 2017-02-07 +### Fixed +- Fix reported position for `duplicated mapping key` errors. + Now points to block start instead of block end. + (#243, thanks to @shockey). + + +## [3.7.0] - 2016-11-12 +### Added +- Support polymorphism for tags (#300, thanks to @monken). + +### Fixed +- Fix parsing of quotes followed by newlines (#304, thanks to @dplepage). + + +## [3.6.1] - 2016-05-11 +### Fixed +- Fix output cut on a pipe, #286. + + +## [3.6.0] - 2016-04-16 +### Fixed +- Dumper rewrite, fix multiple bugs with trailing `\n`. + Big thanks to @aepsilon! +- Loader: fix leading/trailing newlines in block scalars, @aepsilon. + + +## [3.5.5] - 2016-03-17 +### Fixed +- Date parse fix: don't allow dates with on digit in month and day, #268. + + +## [3.5.4] - 2016-03-09 +### Added +- `noCompatMode` for dumper, to disable quoting YAML 1.1 values. + + +## [3.5.3] - 2016-02-11 +### Changed +- Maintenance release. + + +## [3.5.2] - 2016-01-11 +### Changed +- Maintenance: missed comma in bower config. + + +## [3.5.1] - 2016-01-11 +### Changed +- Removed `inherit` dependency, #239. +- Better browserify workaround for esprima load. +- Demo rewrite. + + +## [3.5.0] - 2016-01-10 +### Fixed +- Dumper. Fold strings only, #217. +- Dumper. `norefs` option, to clone linked objects, #229. +- Loader. Throw a warning for duplicate keys, #166. +- Improved browserify support (mark `esprima` & `Buffer` excluded). + + +## [3.4.6] - 2015-11-26 +### Changed +- Use standalone `inherit` to keep browserified files clear. + + +## [3.4.5] - 2015-11-23 +### Added +- Added `lineWidth` option to dumper. + + +## [3.4.4] - 2015-11-21 +### Fixed +- Fixed floats dump (missed dot for scientific format), #220. +- Allow non-printable characters inside quoted scalars, #192. + + +## [3.4.3] - 2015-10-10 +### Changed +- Maintenance release - deps bump (esprima, argparse). + + +## [3.4.2] - 2015-09-09 +### Fixed +- Fixed serialization of duplicated entries in sequences, #205. + Thanks to @vogelsgesang. + + +## [3.4.1] - 2015-09-05 +### Fixed +- Fixed stacktrace handling in generated errors, for browsers (FF/IE). + + +## [3.4.0] - 2015-08-23 +### Changed +- Don't throw on warnings anymore. Use `onWarning` option to catch. +- Throw error on unknown tags (was warning before). +- Reworked internals of error class. + +### Fixed +- Fixed multiline keys dump, #197. Thanks to @tcr. +- Fixed heading line breaks in some scalars (regression). + + +## [3.3.1] - 2015-05-13 +### Added +- Added `.sortKeys` dumper option, thanks to @rjmunro. + +### Fixed +- Fixed astral characters support, #191. + + +## [3.3.0] - 2015-04-26 +### Changed +- Significantly improved long strings formatting in dumper, thanks to @isaacs. +- Strip BOM if exists. + + +## [3.2.7] - 2015-02-19 +### Changed +- Maintenance release. +- Updated dependencies. +- HISTORY.md -> CHANGELOG.md + + +## [3.2.6] - 2015-02-07 +### Fixed +- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE). +- Fixed demo dates dump (#113, thanks to @Hypercubed). + + +## [3.2.5] - 2014-12-28 +### Fixed +- Fixed resolving of all built-in types on empty nodes. +- Fixed invalid warning on empty lines within quoted scalars and flow collections. +- Fixed bug: Tag on an empty node didn't resolve in some cases. + + +## [3.2.4] - 2014-12-19 +### Fixed +- Fixed resolving of !!null tag on an empty node. + + +## [3.2.3] - 2014-11-08 +### Fixed +- Implemented dumping of objects with circular and cross references. +- Partially fixed aliasing of constructed objects. (see issue #141 for details) + + +## [3.2.2] - 2014-09-07 +### Fixed +- Fixed infinite loop on unindented block scalars. +- Rewritten base64 encode/decode in binary type, to keep code licence clear. + + +## [3.2.1] - 2014-08-24 +### Fixed +- Nothig new. Just fix npm publish error. + + +## [3.2.0] - 2014-08-24 +### Added +- Added input piping support to CLI. + +### Fixed +- Fixed typo, that could cause hand on initial indent (#139). + + +## [3.1.0] - 2014-07-07 +### Changed +- 1.5x-2x speed boost. +- Removed deprecated `require('xxx.yml')` support. +- Significant code cleanup and refactoring. +- Internal API changed. If you used custom types - see updated examples. + Others are not affected. +- Even if the input string has no trailing line break character, + it will be parsed as if it has one. +- Added benchmark scripts. +- Moved bower files to /dist folder +- Bugfixes. + + +## [3.0.2] - 2014-02-27 +### Fixed +- Fixed bug: "constructor" string parsed as `null`. + + +## [3.0.1] - 2013-12-22 +### Fixed +- Fixed parsing of literal scalars. (issue #108) +- Prevented adding unnecessary spaces in object dumps. (issue #68) +- Fixed dumping of objects with very long (> 1024 in length) keys. + + +## [3.0.0] - 2013-12-16 +### Changed +- Refactored code. Changed API for custom types. +- Removed output colors in CLI, dump json by default. +- Removed big dependencies from browser version (esprima, buffer). Load `esprima` manually, if `!!js/function` needed. `!!bin` now returns Array in browser +- AMD support. +- Don't quote dumped strings because of `-` & `?` (if not first char). +- __Deprecated__ loading yaml files via `require()`, as not recommended + behaviour for node. + + +## [2.1.3] - 2013-10-16 +### Fixed +- Fix wrong loading of empty block scalars. + + +## [2.1.2] - 2013-10-07 +### Fixed +- Fix unwanted line breaks in folded scalars. + + +## [2.1.1] - 2013-10-02 +### Fixed +- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1 +- Fixed reader bug in JSON-like sequences/mappings. + + +## [2.1.0] - 2013-06-05 +### Added +- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`), + JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`). +- Add `skipInvalid` dumper option. + +### Changed +- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA` + and `SAFE_SCHEMA` to `DEFAULT_SAFE_SCHEMA`. +- Use `safeLoad` for `require` extension. + +### Fixed +- Bug fix: export `NIL` constant from the public interface. + + +## [2.0.5] - 2013-04-26 +### Security +- Close security issue in !!js/function constructor. + Big thanks to @nealpoole for security audit. + + +## [2.0.4] - 2013-04-08 +### Changed +- Updated .npmignore to reduce package size + + +## [2.0.3] - 2013-02-26 +### Fixed +- Fixed dumping of empty arrays ans objects. ([] and {} instead of null) + + +## [2.0.2] - 2013-02-15 +### Fixed +- Fixed input validation: tabs are printable characters. + + +## [2.0.1] - 2013-02-09 +### Fixed +- Fixed error, when options not passed to function cass + + +## [2.0.0] - 2013-02-09 +### Changed +- Full rewrite. New architecture. Fast one-stage parsing. +- Changed custom types API. +- Added YAML dumper. + + +## [1.0.3] - 2012-11-05 +### Fixed +- Fixed utf-8 files loading. + + +## [1.0.2] - 2012-08-02 +### Fixed +- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44. +- Fix timstamps incorectly parsed in local time when no time part specified. + + +## [1.0.1] - 2012-07-07 +### Fixed +- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong. +- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46. + + +## [1.0.0] - 2012-07-01 +### Changed +- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore. + Fixes #42. +- `require(filename)` now returns a single document and throws an Error if + file contains more than one document. +- CLI was merged back from js-yaml.bin + + +## [0.3.7] - 2012-02-28 +### Fixed +- Fix export of `addConstructor()`. Closes #39. + + +## [0.3.6] - 2012-02-22 +### Changed +- Removed AMD parts - too buggy to use. Need help to rewrite from scratch + +### Fixed +- Removed YUI compressor warning (renamed `double` variable). Closes #40. + + +## [0.3.5] - 2012-01-10 +### Fixed +- Workagound for .npmignore fuckup under windows. Thanks to airportyh. + + +## [0.3.4] - 2011-12-24 +### Fixed +- Fixes str[] for oldIEs support. +- Adds better has change support for browserified demo. +- improves compact output of Error. Closes #33. + + +## [0.3.3] - 2011-12-20 +### Added +- adds `compact` stringification of Errors. + +### Changed +- jsyaml executable moved to separate module. + + +## [0.3.2] - 2011-12-16 +### Added +- Added jsyaml executable. +- Added !!js/function support. Closes #12. + +### Fixed +- Fixes ug with block style scalars. Closes #26. +- All sources are passing JSLint now. +- Fixes bug in Safari. Closes #28. +- Fixes bug in Opers. Closes #29. +- Improves browser support. Closes #20. + + +## [0.3.1] - 2011-11-18 +### Added +- Added AMD support for browserified version. +- Added permalinks for online demo YAML snippets. Now we have YPaste service, lol. +- Added !!js/regexp and !!js/undefined types. Partially solves #12. + +### Changed +- Wrapped browserified js-yaml into closure. + +### Fixed +- Fixed the resolvement of non-specific tags. Closes #17. +- Fixed !!set mapping. +- Fixed month parse in dates. Closes #19. + + +## [0.3.0] - 2011-11-09 +### Added +- Added browserified version. Closes #13. +- Added live demo of browserified version. +- Ported some of the PyYAML tests. See #14. + +### Fixed +- Removed JS.Class dependency. Closes #3. +- Fixed timestamp bug when fraction was given. + + +## [0.2.2] - 2011-11-06 +### Fixed +- Fixed crash on docs without ---. Closes #8. +- Fixed multiline string parse +- Fixed tests/comments for using array as key + + +## [0.2.1] - 2011-11-02 +### Fixed +- Fixed short file read (<4k). Closes #9. + + +## [0.2.0] - 2011-11-02 +### Changed +- First public release + + +[3.14.1]: https://github.com/nodeca/js-yaml/compare/3.14.0...3.14.1 +[3.14.0]: https://github.com/nodeca/js-yaml/compare/3.13.1...3.14.0 +[3.13.1]: https://github.com/nodeca/js-yaml/compare/3.13.0...3.13.1 +[3.13.0]: https://github.com/nodeca/js-yaml/compare/3.12.2...3.13.0 +[3.12.2]: https://github.com/nodeca/js-yaml/compare/3.12.1...3.12.2 +[3.12.1]: https://github.com/nodeca/js-yaml/compare/3.12.0...3.12.1 +[3.12.0]: https://github.com/nodeca/js-yaml/compare/3.11.0...3.12.0 +[3.11.0]: https://github.com/nodeca/js-yaml/compare/3.10.0...3.11.0 +[3.10.0]: https://github.com/nodeca/js-yaml/compare/3.9.1...3.10.0 +[3.9.1]: https://github.com/nodeca/js-yaml/compare/3.9.0...3.9.1 +[3.9.0]: https://github.com/nodeca/js-yaml/compare/3.8.4...3.9.0 +[3.8.4]: https://github.com/nodeca/js-yaml/compare/3.8.3...3.8.4 +[3.8.3]: https://github.com/nodeca/js-yaml/compare/3.8.2...3.8.3 +[3.8.2]: https://github.com/nodeca/js-yaml/compare/3.8.1...3.8.2 +[3.8.1]: https://github.com/nodeca/js-yaml/compare/3.8.0...3.8.1 +[3.8.0]: https://github.com/nodeca/js-yaml/compare/3.7.0...3.8.0 +[3.7.0]: https://github.com/nodeca/js-yaml/compare/3.6.1...3.7.0 +[3.6.1]: https://github.com/nodeca/js-yaml/compare/3.6.0...3.6.1 +[3.6.0]: https://github.com/nodeca/js-yaml/compare/3.5.5...3.6.0 +[3.5.5]: https://github.com/nodeca/js-yaml/compare/3.5.4...3.5.5 +[3.5.4]: https://github.com/nodeca/js-yaml/compare/3.5.3...3.5.4 +[3.5.3]: https://github.com/nodeca/js-yaml/compare/3.5.2...3.5.3 +[3.5.2]: https://github.com/nodeca/js-yaml/compare/3.5.1...3.5.2 +[3.5.1]: https://github.com/nodeca/js-yaml/compare/3.5.0...3.5.1 +[3.5.0]: https://github.com/nodeca/js-yaml/compare/3.4.6...3.5.0 +[3.4.6]: https://github.com/nodeca/js-yaml/compare/3.4.5...3.4.6 +[3.4.5]: https://github.com/nodeca/js-yaml/compare/3.4.4...3.4.5 +[3.4.4]: https://github.com/nodeca/js-yaml/compare/3.4.3...3.4.4 +[3.4.3]: https://github.com/nodeca/js-yaml/compare/3.4.2...3.4.3 +[3.4.2]: https://github.com/nodeca/js-yaml/compare/3.4.1...3.4.2 +[3.4.1]: https://github.com/nodeca/js-yaml/compare/3.4.0...3.4.1 +[3.4.0]: https://github.com/nodeca/js-yaml/compare/3.3.1...3.4.0 +[3.3.1]: https://github.com/nodeca/js-yaml/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/nodeca/js-yaml/compare/3.2.7...3.3.0 +[3.2.7]: https://github.com/nodeca/js-yaml/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/nodeca/js-yaml/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/nodeca/js-yaml/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/nodeca/js-yaml/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/nodeca/js-yaml/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/nodeca/js-yaml/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/nodeca/js-yaml/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/nodeca/js-yaml/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/nodeca/js-yaml/compare/3.0.2...3.1.0 +[3.0.2]: https://github.com/nodeca/js-yaml/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/nodeca/js-yaml/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/nodeca/js-yaml/compare/2.1.3...3.0.0 +[2.1.3]: https://github.com/nodeca/js-yaml/compare/2.1.2...2.1.3 +[2.1.2]: https://github.com/nodeca/js-yaml/compare/2.1.1...2.1.2 +[2.1.1]: https://github.com/nodeca/js-yaml/compare/2.1.0...2.1.1 +[2.1.0]: https://github.com/nodeca/js-yaml/compare/2.0.5...2.1.0 +[2.0.5]: https://github.com/nodeca/js-yaml/compare/2.0.4...2.0.5 +[2.0.4]: https://github.com/nodeca/js-yaml/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/nodeca/js-yaml/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/nodeca/js-yaml/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/nodeca/js-yaml/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/js-yaml/compare/1.0.3...2.0.0 +[1.0.3]: https://github.com/nodeca/js-yaml/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/js-yaml/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/js-yaml/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/js-yaml/compare/0.3.7...1.0.0 +[0.3.7]: https://github.com/nodeca/js-yaml/compare/0.3.6...0.3.7 +[0.3.6]: https://github.com/nodeca/js-yaml/compare/0.3.5...0.3.6 +[0.3.5]: https://github.com/nodeca/js-yaml/compare/0.3.4...0.3.5 +[0.3.4]: https://github.com/nodeca/js-yaml/compare/0.3.3...0.3.4 +[0.3.3]: https://github.com/nodeca/js-yaml/compare/0.3.2...0.3.3 +[0.3.2]: https://github.com/nodeca/js-yaml/compare/0.3.1...0.3.2 +[0.3.1]: https://github.com/nodeca/js-yaml/compare/0.3.0...0.3.1 +[0.3.0]: https://github.com/nodeca/js-yaml/compare/0.2.2...0.3.0 +[0.2.2]: https://github.com/nodeca/js-yaml/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/nodeca/js-yaml/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/nodeca/js-yaml/releases/tag/0.2.0 diff --git a/node_modules/js-yaml/LICENSE b/node_modules/js-yaml/LICENSE new file mode 100644 index 0000000..09d3a29 --- /dev/null +++ b/node_modules/js-yaml/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2011-2015 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/js-yaml/README.md b/node_modules/js-yaml/README.md new file mode 100644 index 0000000..246e563 --- /dev/null +++ b/node_modules/js-yaml/README.md @@ -0,0 +1,299 @@ +JS-YAML - YAML 1.2 parser / writer for JavaScript +================================================= + +[![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) +[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) + +__[Online Demo](http://nodeca.github.com/js-yaml/)__ + + +This is an implementation of [YAML](http://yaml.org/), a human-friendly data +serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was +completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. + + +Installation +------------ + +### YAML module for node.js + +``` +npm install js-yaml +``` + + +### CLI executable + +If you want to inspect your YAML files from CLI, install js-yaml globally: + +``` +npm install -g js-yaml +``` + +#### Usage + +``` +usage: js-yaml [-h] [-v] [-c] [-t] file + +Positional arguments: + file File with YAML document(s) + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -c, --compact Display errors in compact mode + -t, --trace Show stack trace on error +``` + + +### Bundled YAML library for browsers + +``` html + + + + +``` + +Browser support was done mostly for the online demo. If you find any errors - feel +free to send pull requests with fixes. Also note, that IE and other old browsers +needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. + +Notes: + +1. We have no resources to support browserified version. Don't expect it to be + well tested. Don't expect fast fixes if something goes wrong there. +2. `!!js/function` in browser bundle will not work by default. If you really need + it - load `esprima` parser first (via amd or directly). +3. `!!bin` in browser will return `Array`, because browsers do not support + node.js `Buffer` and adding Buffer shims is completely useless on practice. + + +API +--- + +Here we cover the most 'useful' methods. If you need advanced details (creating +your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and +[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more +info. + +``` javascript +const yaml = require('js-yaml'); +const fs = require('fs'); + +// Get document, or throw exception on error +try { + const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); + console.log(doc); +} catch (e) { + console.log(e); +} +``` + + +### safeLoad (string [ , options ]) + +**Recommended loading way.** Parses `string` as single YAML document. Returns either a +plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does +not support regexps, functions and undefined. This method is safe for untrusted data. + +options: + +- `filename` _(default: null)_ - string to be used as a file path in + error/warning messages. +- `onWarning` _(default: null)_ - function to call on warning messages. + Loader will call this function with an instance of `YAMLException` for each warning. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. + - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: + http://www.yaml.org/spec/1.2/spec.html#id2802346 + - `JSON_SCHEMA` - all JSON-supported types: + http://www.yaml.org/spec/1.2/spec.html#id2803231 + - `CORE_SCHEMA` - same as `JSON_SCHEMA`: + http://www.yaml.org/spec/1.2/spec.html#id2804923 + - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones + (`!!js/undefined`, `!!js/regexp` and `!!js/function`): + http://yaml.org/type/ + - `DEFAULT_FULL_SCHEMA` - all supported YAML types. +- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. + +NOTE: This function **does not** understand multi-document sources, it throws +exception on those. + +NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. +So, the JSON schema is not as strictly defined in the YAML specification. +It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. +The core schema also has no such restrictions. It allows binary notation for integers. + + +### load (string [ , options ]) + +**Use with care with untrusted sources**. The same as `safeLoad()` but uses +`DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: +`!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you +must additionally validate object structure to avoid injections: + +``` javascript +const untrusted_code = '"toString": ! "function (){very_evil_thing();}"'; + +// I'm just converting that string, what could possibly go wrong? +require('js-yaml').load(untrusted_code) + '' +``` + + +### safeLoadAll (string [, iterator] [, options ]) + +Same as `safeLoad()`, but understands multi-document sources. Applies +`iterator` to each document if specified, or returns array of documents. + +``` javascript +const yaml = require('js-yaml'); + +yaml.safeLoadAll(data, function (doc) { + console.log(doc); +}); +``` + + +### loadAll (string [, iterator] [ , options ]) + +Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. + + +### safeDump (object [ , options ]) + +Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will +throw an exception if you try to dump regexps or functions. However, you can +disable exceptions by setting the `skipInvalid` option to `true`. + +options: + +- `indent` _(default: 2)_ - indentation width to use (in spaces). +- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements +- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function + in the safe schema) and skip pairs and single values with such types. +- `flowLevel` (default: -1) - specifies level of nesting, when to switch from + block to flow style for collections. -1 means block style everwhere +- `styles` - "tag" => "style" map. Each tag may have own set of styles. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. +- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a + function, use the function to sort the keys. +- `lineWidth` _(default: `80`)_ - set max line width. +- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references +- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older + yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 +- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. + +The following table show availlable styles (e.g. "canonical", +"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml +output is shown on the right side after `=>` (default setting) or `->`: + +``` none +!!null + "canonical" -> "~" + "lowercase" => "null" + "uppercase" -> "NULL" + "camelcase" -> "Null" + +!!int + "binary" -> "0b1", "0b101010", "0b1110001111010" + "octal" -> "01", "052", "016172" + "decimal" => "1", "42", "7290" + "hexadecimal" -> "0x1", "0x2A", "0x1C7A" + +!!bool + "lowercase" => "true", "false" + "uppercase" -> "TRUE", "FALSE" + "camelcase" -> "True", "False" + +!!float + "lowercase" => ".nan", '.inf' + "uppercase" -> ".NAN", '.INF' + "camelcase" -> ".NaN", '.Inf' +``` + +Example: + +``` javascript +safeDump (object, { + 'styles': { + '!!null': 'canonical' // dump null as ~ + }, + 'sortKeys': true // sort object keys +}); +``` + +### dump (object [ , options ]) + +Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). + + +Supported YAML types +-------------------- + +The list of standard YAML tags and corresponding JavaScipt types. See also +[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and +[YAML types repository](http://yaml.org/type/). + +``` +!!null '' # null +!!bool 'yes' # bool +!!int '3...' # number +!!float '3.14...' # number +!!binary '...base64...' # buffer +!!timestamp 'YYYY-...' # date +!!omap [ ... ] # array of key-value pairs +!!pairs [ ... ] # array or array pairs +!!set { ... } # array of objects with given keys and null values +!!str '...' # string +!!seq [ ... ] # array +!!map { ... } # object +``` + +**JavaScript-specific tags** + +``` +!!js/regexp /pattern/gim # RegExp +!!js/undefined '' # Undefined +!!js/function 'function () {...}' # Function +``` + +Caveats +------- + +Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects +or arrays as keys, and stringifies (by calling `toString()` method) them at the +moment of adding them. + +``` yaml +--- +? [ foo, bar ] +: - baz +? { foo: bar } +: - baz + - baz +``` + +``` javascript +{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } +``` + +Also, reading of properties on implicit block mapping keys is not supported yet. +So, the following YAML document cannot be loaded. + +``` yaml +&anchor foo: + foo: bar + *anchor: duplicate key + baz: bat + *anchor: duplicate key +``` + + +js-yaml for enterprise +---------------------- + +Available as part of the Tidelift Subscription + +The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/js-yaml/bin/js-yaml.js b/node_modules/js-yaml/bin/js-yaml.js new file mode 100755 index 0000000..e79186b --- /dev/null +++ b/node_modules/js-yaml/bin/js-yaml.js @@ -0,0 +1,132 @@ +#!/usr/bin/env node + + +'use strict'; + +/*eslint-disable no-console*/ + + +// stdlib +var fs = require('fs'); + + +// 3rd-party +var argparse = require('argparse'); + + +// internal +var yaml = require('..'); + + +//////////////////////////////////////////////////////////////////////////////// + + +var cli = new argparse.ArgumentParser({ + prog: 'js-yaml', + version: require('../package.json').version, + addHelp: true +}); + + +cli.addArgument([ '-c', '--compact' ], { + help: 'Display errors in compact mode', + action: 'storeTrue' +}); + + +// deprecated (not needed after we removed output colors) +// option suppressed, but not completely removed for compatibility +cli.addArgument([ '-j', '--to-json' ], { + help: argparse.Const.SUPPRESS, + dest: 'json', + action: 'storeTrue' +}); + + +cli.addArgument([ '-t', '--trace' ], { + help: 'Show stack trace on error', + action: 'storeTrue' +}); + +cli.addArgument([ 'file' ], { + help: 'File to read, utf-8 encoded without BOM', + nargs: '?', + defaultValue: '-' +}); + + +//////////////////////////////////////////////////////////////////////////////// + + +var options = cli.parseArgs(); + + +//////////////////////////////////////////////////////////////////////////////// + +function readFile(filename, encoding, callback) { + if (options.file === '-') { + // read from stdin + + var chunks = []; + + process.stdin.on('data', function (chunk) { + chunks.push(chunk); + }); + + process.stdin.on('end', function () { + return callback(null, Buffer.concat(chunks).toString(encoding)); + }); + } else { + fs.readFile(filename, encoding, callback); + } +} + +readFile(options.file, 'utf8', function (error, input) { + var output, isYaml; + + if (error) { + if (error.code === 'ENOENT') { + console.error('File not found: ' + options.file); + process.exit(2); + } + + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + + try { + output = JSON.parse(input); + isYaml = false; + } catch (err) { + if (err instanceof SyntaxError) { + try { + output = []; + yaml.loadAll(input, function (doc) { output.push(doc); }, {}); + isYaml = true; + + if (output.length === 0) output = null; + else if (output.length === 1) output = output[0]; + + } catch (e) { + if (options.trace && err.stack) console.error(e.stack); + else console.error(e.toString(options.compact)); + + process.exit(1); + } + } else { + console.error( + options.trace && err.stack || + err.message || + String(err)); + + process.exit(1); + } + } + + if (isYaml) console.log(JSON.stringify(output, null, ' ')); + else console.log(yaml.dump(output)); +}); diff --git a/node_modules/js-yaml/dist/js-yaml.js b/node_modules/js-yaml/dist/js-yaml.js new file mode 100644 index 0000000..7878320 --- /dev/null +++ b/node_modules/js-yaml/dist/js-yaml.js @@ -0,0 +1,3989 @@ +/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; + +},{"./common":2,"./exception":4,"./schema/default_full":9,"./schema/default_safe":10}],4:[function(require,module,exports){ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; + +},{}],5:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; + +},{"./common":2,"./exception":4,"./mark":6,"./schema/default_full":9,"./schema/default_safe":10}],6:[function(require,module,exports){ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; + +},{"./common":2}],7:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; + +},{"./common":2,"./exception":4,"./type":13}],8:[function(require,module,exports){ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); + +},{"../schema":7,"./json":12}],9:[function(require,module,exports){ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); + +},{"../schema":7,"../type/js/function":18,"../type/js/regexp":19,"../type/js/undefined":20,"./default_safe":10}],10:[function(require,module,exports){ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); + +},{"../schema":7,"../type/binary":14,"../type/merge":22,"../type/omap":24,"../type/pairs":25,"../type/set":27,"../type/timestamp":29,"./core":8}],11:[function(require,module,exports){ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); + +},{"../schema":7,"../type/map":21,"../type/seq":26,"../type/str":28}],12:[function(require,module,exports){ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); + +},{"../schema":7,"../type/bool":15,"../type/float":16,"../type/int":17,"../type/null":23,"./failsafe":11}],13:[function(require,module,exports){ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; + +},{"./exception":4}],14:[function(require,module,exports){ +'use strict'; + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +},{"../type":13}],15:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":13}],16:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +},{"../common":2,"../type":13}],17:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +},{"../common":2,"../type":13}],18:[function(require,module,exports){ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); + +},{"../../type":13}],19:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + +},{"../../type":13}],20:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); + +},{"../../type":13}],21:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +},{"../type":13}],22:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +},{"../type":13}],23:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":13}],24:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +},{"../type":13}],25:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +},{"../type":13}],26:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +},{"../type":13}],27:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +},{"../type":13}],28:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +},{"../type":13}],29:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +},{"../type":13}],"/":[function(require,module,exports){ +'use strict'; + + +var yaml = require('./lib/js-yaml.js'); + + +module.exports = yaml; + +},{"./lib/js-yaml.js":1}]},{},[])("/") +}); diff --git a/node_modules/js-yaml/dist/js-yaml.min.js b/node_modules/js-yaml/dist/js-yaml.min.js new file mode 100644 index 0000000..1b6ecc1 --- /dev/null +++ b/node_modules/js-yaml/dist/js-yaml.min.js @@ -0,0 +1 @@ +/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsyaml=e()}(function(){return function i(r,o,a){function s(t,e){if(!o[t]){if(!r[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(c)return c(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=o[t]={exports:{}},r[t][0].call(n.exports,function(e){return s(r[t][1][e]||e)},n,n.exports,i,r,o,a)}return o[t].exports}for(var c="function"==typeof require&&require,e=0;e=i.flowLevel;switch(V(r,n,i.indent,t,function(e){return function(e,t){for(var n=0,i=e.implicitTypes.length;n"+z(r,i.indent)+J(U(function(t,n){var e,i=/(\n+)([^\n]*)/g,r=function(){var e=-1!==(e=t.indexOf("\n"))?e:t.length;return i.lastIndex=e,Q(t.slice(0,e),n)}(),o="\n"===t[0]||" "===t[0];for(;e=i.exec(t);){var a=e[1],s=e[2];e=" "===s[0],r+=a+(o||e||""===s?"":"\n")+Q(s,n),o=e}return r}(r,t),e));case G:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+o+'" style');i=r.represent[o](t,o)}e.dump=i}return 1}}function ee(e,t,n,i,r,o){e.tag=null,e.dump=n,X(e,n,!1)||X(e,n,!0);var a=l.call(e.dump);i=i&&(e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return 1}function te(e,t){var n,i,r=[],o=[];for(!function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;o>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else S(u)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}}function K(e,t){var n,i,r=e.tag,o=e.anchor,a=[],s=!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&45===i&&O(e.input.charCodeAt(e.position+1));)if(s=!0,e.position++,Y(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,P(e,t,x,!1,!0),a.push(e.result),Y(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt)&&(P(e,t,A,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentc&&(c=e.lineIndent),S(p))u++;else{if(e.lineIndent=t){a=!0,f=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),I(f)||(o=e.position+1),f=e.input.charCodeAt(++e.position)}if(L(e,r,o,!1),e.result)return 1;e.kind=l,e.result=p}}(e,i,g===n)&&(d=!0,null===e.tag&&(e.tag="?")):(d=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===p&&(d=s&&K(e,r))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&N(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||d}function $(e,t){t=t||{},0!==(e=String(e)).length&&(10!==e.charCodeAt(e.length-1)&&13!==e.charCodeAt(e.length-1)&&(e+="\n"),65279===e.charCodeAt(0)&&(e=e.slice(1)));var n=new F(e,t),e=e.indexOf("\0");for(-1!==e&&(n.position=e,N(n,"null byte is not allowed in input")),n.input+="\0";32===n.input.charCodeAt(n.position);)n.lineIndent+=1,n.position+=1;for(;n.positiont/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t="";return this.name&&(t+='in "'+this.name+'" '),t+="at line "+(this.line+1)+", column "+(this.column+1),e||(e=this.getSnippet())&&(t+=":\n"+e),t},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var r=e("./common"),o=e("./exception"),a=e("./type");function s(e,t,i){var r=[];return e.include.forEach(function(e){i=s(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function c(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=s(this,"implicit",[]),this.compiledExplicit=s(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),o.push(r>>8&255),o.push(255&r)),r=r<<6|i.indexOf(t.charAt(a));return 0==(e=n%4*6)?(o.push(r>>16&255),o.push(r>>8&255),o.push(255&r)):18==e?(o.push(r>>10&255),o.push(r>>2&255)):12==e&&o.push(r>>4&255),s?s.from?s.from(o):new s(o):o},predicate:function(e){return s&&s.isBuffer(e)},represent:function(e){for(var t,n="",i=0,r=e.length,o=c,a=0;a>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]),i=(i<<8)+e[a];return 0==(t=r%3)?(n+=o[i>>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]):2==t?(n+=o[i>>10&63],n+=o[i>>4&63],n+=o[i<<2&63],n+=o[64]):1==t&&(n+=o[i>>2&63],n+=o[i<<4&63],n+=o[64],n+=o[64]),n}})},{"../type":13}],15:[function(e,t,n){"use strict";e=e("../type");t.exports=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type"),r=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var o=/^[-+]?[0-9]+e/;t.exports=new e("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!r.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n=e.replace(/_/g,"").toLowerCase(),e="-"===n[0]?-1:1,i=[];return 0<="+-".indexOf(n[0])&&(n=n.slice(1)),".inf"===n?1==e?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===n?NaN:0<=n.indexOf(":")?(n.split(":").forEach(function(e){i.unshift(parseFloat(e,10))}),n=0,t=1,i.forEach(function(e){n+=e*t,t*=60}),e*n):e*parseFloat(n,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return e=e.toString(10),o.test(e)?e.replace("e",".e"):e},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type");t.exports=new e("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; diff --git a/node_modules/js-yaml/lib/js-yaml/exception.js b/node_modules/js-yaml/lib/js-yaml/exception.js new file mode 100644 index 0000000..b744a1e --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/exception.js @@ -0,0 +1,43 @@ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; diff --git a/node_modules/js-yaml/lib/js-yaml/loader.js b/node_modules/js-yaml/lib/js-yaml/loader.js new file mode 100644 index 0000000..d7484a5 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/loader.js @@ -0,0 +1,1644 @@ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; diff --git a/node_modules/js-yaml/lib/js-yaml/mark.js b/node_modules/js-yaml/lib/js-yaml/mark.js new file mode 100644 index 0000000..47b265c --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/mark.js @@ -0,0 +1,76 @@ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; diff --git a/node_modules/js-yaml/lib/js-yaml/schema.js b/node_modules/js-yaml/lib/js-yaml/schema.js new file mode 100644 index 0000000..ca7cf47 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema.js @@ -0,0 +1,108 @@ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; diff --git a/node_modules/js-yaml/lib/js-yaml/schema/core.js b/node_modules/js-yaml/lib/js-yaml/schema/core.js new file mode 100644 index 0000000..206daab --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/core.js @@ -0,0 +1,18 @@ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/default_full.js b/node_modules/js-yaml/lib/js-yaml/schema/default_full.js new file mode 100644 index 0000000..a55ef42 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/default_full.js @@ -0,0 +1,25 @@ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js b/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js new file mode 100644 index 0000000..11d89bb --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js @@ -0,0 +1,28 @@ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js b/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js new file mode 100644 index 0000000..b7a33eb --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js @@ -0,0 +1,17 @@ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/json.js b/node_modules/js-yaml/lib/js-yaml/schema/json.js new file mode 100644 index 0000000..5be3dbf --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/json.js @@ -0,0 +1,25 @@ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type.js b/node_modules/js-yaml/lib/js-yaml/type.js new file mode 100644 index 0000000..90b702a --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type.js @@ -0,0 +1,61 @@ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; diff --git a/node_modules/js-yaml/lib/js-yaml/type/binary.js b/node_modules/js-yaml/lib/js-yaml/type/binary.js new file mode 100644 index 0000000..10b1875 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/binary.js @@ -0,0 +1,138 @@ +'use strict'; + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/bool.js b/node_modules/js-yaml/lib/js-yaml/type/bool.js new file mode 100644 index 0000000..cb77459 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/bool.js @@ -0,0 +1,35 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/float.js b/node_modules/js-yaml/lib/js-yaml/type/float.js new file mode 100644 index 0000000..127671b --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/float.js @@ -0,0 +1,116 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/int.js b/node_modules/js-yaml/lib/js-yaml/type/int.js new file mode 100644 index 0000000..ba61c5f --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/int.js @@ -0,0 +1,173 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/js/function.js b/node_modules/js-yaml/lib/js-yaml/type/js/function.js new file mode 100644 index 0000000..8fab8c4 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/js/function.js @@ -0,0 +1,93 @@ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js b/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js new file mode 100644 index 0000000..43fa470 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js @@ -0,0 +1,60 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js b/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js new file mode 100644 index 0000000..95b5569 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js @@ -0,0 +1,28 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/map.js b/node_modules/js-yaml/lib/js-yaml/type/map.js new file mode 100644 index 0000000..f327bee --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/map.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/merge.js b/node_modules/js-yaml/lib/js-yaml/type/merge.js new file mode 100644 index 0000000..ae08a86 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/merge.js @@ -0,0 +1,12 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/null.js b/node_modules/js-yaml/lib/js-yaml/type/null.js new file mode 100644 index 0000000..6874daa --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/null.js @@ -0,0 +1,34 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/omap.js b/node_modules/js-yaml/lib/js-yaml/type/omap.js new file mode 100644 index 0000000..b2b5323 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/omap.js @@ -0,0 +1,44 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/pairs.js b/node_modules/js-yaml/lib/js-yaml/type/pairs.js new file mode 100644 index 0000000..74b5240 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/pairs.js @@ -0,0 +1,53 @@ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/seq.js b/node_modules/js-yaml/lib/js-yaml/type/seq.js new file mode 100644 index 0000000..be8f77f --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/seq.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/set.js b/node_modules/js-yaml/lib/js-yaml/type/set.js new file mode 100644 index 0000000..f885a32 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/set.js @@ -0,0 +1,29 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/str.js b/node_modules/js-yaml/lib/js-yaml/type/str.js new file mode 100644 index 0000000..27acc10 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/str.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/timestamp.js b/node_modules/js-yaml/lib/js-yaml/type/timestamp.js new file mode 100644 index 0000000..8fa9c58 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/timestamp.js @@ -0,0 +1,88 @@ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); diff --git a/node_modules/js-yaml/package.json b/node_modules/js-yaml/package.json new file mode 100644 index 0000000..af555c1 --- /dev/null +++ b/node_modules/js-yaml/package.json @@ -0,0 +1,95 @@ +{ + "_from": "js-yaml@^3.13.1", + "_id": "js-yaml@3.14.1", + "_inBundle": false, + "_integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "_location": "/js-yaml", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "js-yaml@^3.13.1", + "name": "js-yaml", + "escapedName": "js-yaml", + "rawSpec": "^3.13.1", + "saveSpec": null, + "fetchSpec": "^3.13.1" + }, + "_requiredBy": [ + "/@istanbuljs/load-nyc-config" + ], + "_resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "_shasum": "dae812fdb3825fa306609a8717383c50c36a0537", + "_spec": "js-yaml@^3.13.1", + "_where": "/Users/jasonoconal/dev/src/github-pr-linter/node_modules/@istanbuljs/load-nyc-config", + "author": { + "name": "Vladimir Zapparov", + "email": "dervus.grim@gmail.com" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + }, + "bugs": { + "url": "https://github.com/nodeca/js-yaml/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Aleksey V Zapparov", + "email": "ixti@member.fsf.org", + "url": "http://www.ixti.net/" + }, + { + "name": "Vitaly Puzrin", + "email": "vitaly@rcdesign.ru", + "url": "https://github.com/puzrin" + }, + { + "name": "Martin Grenfell", + "email": "martin.grenfell@gmail.com", + "url": "http://got-ravings.blogspot.com" + } + ], + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "deprecated": false, + "description": "YAML 1.2 parser and serializer", + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "browserify": "^16.2.2", + "codemirror": "^5.13.4", + "eslint": "^7.0.0", + "fast-check": "^1.24.2", + "istanbul": "^0.4.5", + "mocha": "^7.1.2", + "uglify-js": "^3.0.1" + }, + "files": [ + "index.js", + "lib/", + "bin/", + "dist/" + ], + "homepage": "https://github.com/nodeca/js-yaml", + "jsdelivr": "dist/js-yaml.min.js", + "keywords": [ + "yaml", + "parser", + "serializer", + "pyyaml" + ], + "license": "MIT", + "name": "js-yaml", + "repository": { + "type": "git", + "url": "git+https://github.com/nodeca/js-yaml.git" + }, + "scripts": { + "test": "make test" + }, + "unpkg": "dist/js-yaml.min.js", + "version": "3.14.1" +} diff --git a/node_modules/jsesc/LICENSE-MIT.txt b/node_modules/jsesc/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/jsesc/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jsesc/README.md b/node_modules/jsesc/README.md new file mode 100644 index 0000000..aae2b13 --- /dev/null +++ b/node_modules/jsesc/README.md @@ -0,0 +1,421 @@ +# jsesc [![Build status](https://travis-ci.org/mathiasbynens/jsesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/jsesc) [![Code coverage status](https://coveralls.io/repos/mathiasbynens/jsesc/badge.svg)](https://coveralls.io/r/mathiasbynens/jsesc) [![Dependency status](https://gemnasium.com/mathiasbynens/jsesc.svg)](https://gemnasium.com/mathiasbynens/jsesc) + +Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except: + +1. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets; +2. it offers [many options](#api) to customize the output; +3. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed. + +For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Here’s an online demo.](https://mothereff.in/js-escapes) + +jsesc’s output can be used instead of `JSON.stringify`’s to avoid [mojibake](https://en.wikipedia.org/wiki/Mojibake) and other encoding issues, or even to [avoid errors](https://twitter.com/annevk/status/380000829643571200) when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder. + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install jsesc +``` + +In [Node.js](https://nodejs.org/): + +```js +const jsesc = require('jsesc'); +``` + +## API + +### `jsesc(value, options)` + +This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in JavaScript strings](https://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings: + +```js +jsesc('Ich ♥ Bücher'); +// → 'Ich \\u2665 B\\xFCcher' + +jsesc('foo 𝌆 bar'); +// → 'foo \\uD834\\uDF06 bar' +``` + +Instead of a string, the `value` can also be an array, an object, a map, a set, or a buffer. In such cases, `jsesc` returns a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way. + +```js +// Escaping an array +jsesc([ + 'Ich ♥ Bücher', 'foo 𝌆 bar' +]); +// → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']' + +// Escaping an object +jsesc({ + 'Ich ♥ Bücher': 'foo 𝌆 bar' +}); +// → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}' +``` + +The optional `options` argument accepts an object with the following options: + +#### `quotes` + +The default value for the `quotes` option is `'single'`. This means that any occurrences of `'` in the input string are escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes. + +```js +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.'); +// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' + +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'single' +}); +// → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.' +// → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc." +``` + +If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`. + +```js +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'double' +}); +// → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.' +// → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc." +``` + +If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the `quotes` option to `'backtick'`. + +```js +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'backtick' +}); +// → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.' +// → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc." +// → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.` +``` + +This setting also affects the output for arrays and objects: + +```js +jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { + 'quotes': 'double' +}); +// → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}' + +jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { + 'quotes': 'double' +}); +// → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]' +``` + +#### `numbers` + +The default value for the `numbers` option is `'decimal'`. This means that any numeric values are represented using decimal integer literals. Other valid options are `binary`, `octal`, and `hexadecimal`, which result in binary integer literals, octal integer literals, and hexadecimal integer literals, respectively. + +```js +jsesc(42, { + 'numbers': 'binary' +}); +// → '0b101010' + +jsesc(42, { + 'numbers': 'octal' +}); +// → '0o52' + +jsesc(42, { + 'numbers': 'decimal' +}); +// → '42' + +jsesc(42, { + 'numbers': 'hexadecimal' +}); +// → '0x2A' +``` + +#### `wrap` + +The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. + +```js +jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'single', + 'wrap': true +}); +// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' +// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" + +jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'double', + 'wrap': true +}); +// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' +// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" +``` + +#### `es6` + +The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input are escaped using [ECMAScript 6 Unicode code point escape sequences](https://mathiasbynens.be/notes/javascript-escapes#unicode-code-point) instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, don’t enable this setting. If the `json` setting is enabled, the value for the `es6` setting is ignored (as if it was `false`). + +```js +// By default, the `es6` option is disabled: +jsesc('foo 𝌆 bar 💩 baz'); +// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' + +// To explicitly disable it: +jsesc('foo 𝌆 bar 💩 baz', { + 'es6': false +}); +// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' + +// To enable it: +jsesc('foo 𝌆 bar 💩 baz', { + 'es6': true +}); +// → 'foo \\u{1D306} bar \\u{1F4A9} baz' +``` + +#### `escapeEverything` + +The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output are escaped — even printable ASCII symbols. + +```js +jsesc('lolwat"foo\'bar', { + 'escapeEverything': true +}); +// → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72' +// → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72" +``` + +This setting also affects the output for string literals within arrays and objects. + +#### `minimal` + +The `minimal` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, only a limited set of symbols in the output are escaped: + +* U+0000 `\0` +* U+0008 `\b` +* U+0009 `\t` +* U+000A `\n` +* U+000C `\f` +* U+000D `\r` +* U+005C `\\` +* U+2028 `\u2028` +* U+2029 `\u2029` +* whatever symbol is being used for wrapping string literals (based on [the `quotes` option](#quotes)) + +Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe. + +```js +jsesc('foo\u2029bar\nbaz©qux𝌆flops', { + 'minimal': false +}); +// → 'foo\\u2029bar\\nbaz©qux𝌆flops' +``` + +#### `isScriptContext` + +The `isScriptContext` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, occurrences of [`` or `